Main.cpp 2.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700
  1. #include <cfenv>
  2. #include <juce_gui_basics/juce_gui_basics.h>
  3. #include "engine/AraHost.h"
  4. #include "engine/FileSort.h"
  5. #include "platform/Paths.h"
  6. #include "core/SectionOps.h" // round 190ol (P1: the Sections lane)
  7. #include "core/SignatureEdit.h" // round 190ol (P6)
  8. #include "ui/SectionsLane190ol.h" // round 190ol (P1: the shot route drives the lane)
  9. #include "ui/ChordLane190pf.h" // round 190pf (P13: the shot route drives the lane)
  10. #include "ui/SmartTempo190pf.h" // round 190pf (P12)
  11. #include "core/SmartTempo.h"
  12. #include "core/Offline.h"
  13. #include "core/GrooveAudio.h"
  14. #include "core/SmartDisableTip.h" // (round 190ok: --smarttipshot190ok)
  15. #include "core/SimpleTracks.h" // (round 190ot: --simpleduck190otshot)
  16. #include "core/TrackImport.h" // (round 190pe: --tracks190peshot, --selftest tracks190pe)
  17. #include "core/TrackVersions.h"
  18. #include "ui/TrackImportDialog.h"
  19. #include "core/EditorScale.h"
  20. #include "core/SimplePads.h"
  21. #include "core/SimSynth.h" // (round 190om: the selftest's SimSynth channel)
  22. #include "core/ClipEnvelope.h"
  23. #include "core/ClipWarp.h"
  24. #include "core/KeyGuess.h"
  25. #include "core/EditorPolish.h"
  26. #include "core/FlpExport.h"
  27. #include "core/FruityBasicFx.h" // (round 190my: Fruity Balance in --details190myshot)
  28. #include "core/TrackClips.h"
  29. #include "core/TrackStates.h"
  30. #include "core/RangeEdit.h" // round 190pa (P14)
  31. #include "core/AutomationModes.h" // round 190pa (P21)
  32. #include "core/Groove.h"
  33. #include "core/DrawMode.h"
  34. #include "core/SessionOps.h"
  35. #include "ui/ClipGridComponent.h"
  36. #include "ui/ArticulatorTools.h"
  37. #include "ui/ExternalDrag.h"
  38. #include "ui/LabelFont.h"
  39. #include "ui/SessionMixer.h"
  40. #include "core/FlSamplers.h"
  41. #include "core/ArrangeOps.h"
  42. #include "core/ClipSample.h"
  43. #include "core/WarpModes.h"
  44. #include "ui/ClipAudioPanel.h"
  45. #include "core/DetailChain.h"
  46. #include "core/SessionMixer.h"
  47. #include "core/PlaylistOps.h"
  48. #include "core/LastTweaked.h"
  49. #include "core/ClipOps.h"
  50. #include "core/TransportEdit.h" // (round 190jz: --issueshot190jz)
  51. #include "core/SamplerPage.h"
  52. #include "core/FlTrackMenus.h"
  53. #include "core/FlClipMenu.h"
  54. #include "core/OneClickRec.h"
  55. #include "core/WarpTools.h"
  56. #include "core/Comping.h"
  57. #include "core/ExportSilence.h"
  58. #include "core/Drumaxx.h"
  59. #include "core/PatternBlocks.h"
  60. #include "core/LoadTrace.h"
  61. #include "core/ProjectSafety.h"
  62. #include "core/Patcher.h"
  63. #include "core/Rack.h"
  64. #include "ui/RackEditor.h"
  65. #include "ui/HelixEditor.h"
  66. #include "ui/LynxModelEditor.h"
  67. #include "core/physmod/LynxModel.h"
  68. #include "core/PluginCatalog.h"
  69. #include "engine/GeneratorCatalog.h"
  70. #include "core/AlsDevices.h"
  71. #include "core/XmlLite.h"
  72. #include "ui/DrumRackShot.h"
  73. #include "ui/GroovePoolComponent.h"
  74. #include "core/Patcherize.h"
  75. #include "core/Performance.h"
  76. #include "core/VideoPlayer.h"
  77. #include "core/Effects.h"
  78. #include "core/MixSuite.h"
  79. #include "core/LowLifterFl.h" // (rollup step 12: the 0.1.28 copy item)
  80. #include "core/HardwareInsert.h"
  81. #include "core/EchoSuite.h"
  82. #include "core/LuxeVerb.h"
  83. #include "core/LynxVerbs.h"
  84. #include "core/LynxTune.h"
  85. #include "core/FlEffects.h"
  86. #include "core/FlpImport.h"
  87. #include "core/NoteEdit.h"
  88. #include "core/PlaylistTrackOps.h" // round 190jf (FoldersShot190jf.inc)
  89. #include "ui/DawProjectExport.h" // round 190jf (--dawprojcheck190jf)
  90. #include "ui/FlmExportDialog.h" // round 190og (--export-flm, --flmexportshot)
  91. #include "core/NoteNames.h"
  92. #include "core/MaximusFx.h"
  93. #include "core/ChainPresets.h"
  94. #include "core/GoalKnobs.h"
  95. #include "core/MasterLooks.h"
  96. #include "core/Harmor.h"
  97. #include "core/KiloheartsDsp.h" // (rollup step 14: the copy for 0.1.28 self-test)
  98. #include "core/ThreeOsc.h" // (rollup 0.1.32 step 1: the copy for 0.1.31 self-test)
  99. #include "core/WavetableSynth.h" // (round 190oc: the copy for 0.1.30 self-test)
  100. #include "core/AutoLook.h" // (rollup 0.1.31 step 4: the copy for 0.1.30 self-test)
  101. #include "flp/Flp.h"
  102. #include "flp/FlpWrite.h" // round 190qs (issue #282 self-test)
  103. #include "core/DemoSongs.h"
  104. #include "core/FirstSongTour.h"
  105. #include "core/PerfProjects.h"
  106. #include "core/ShowcaseSong.h"
  107. #include "core/RenderAhead.h"
  108. #include "core/SynthPresets.h"
  109. #include "core/FlWrapper.h"
  110. #include "engine/AudioEngine.h"
  111. #include "engine/ProjectDowngrade.h"
  112. #include "engine/RemoteNotes.h" // (round 190pm: --selftest repeats190pm)
  113. #include "core/NoteConditions.h" // (round 190pm)
  114. #include "ui/TouchInput.h" // (round 190pm)
  115. #include "ui/TrackerComponent.h"
  116. #include "core/ClipLauncher.h"
  117. #include "core/SimpleSteps.h"
  118. #include "core/DirectWaveState.h"
  119. #include "core/MixSnapshots.h"
  120. #include "core/VoiceShift.h"
  121. #include "core/PeakShapes.h" // rollup step 7: the copy for 0.1.28 self-test
  122. #include "core/DynamicsSuite.h"
  123. #include "core/TempoMarkers.h"
  124. #include "engine/RemoteControl.h"
  125. #include "engine/RemoteError.h"
  126. #include "ui/RemoteControlSettings.h"
  127. #include "engine/PreviewPlayer.h"
  128. #include "engine/Metronome.h"
  129. #include "engine/AudioLogger.h"
  130. #include "engine/DllAsioDevice.h"
  131. #include "engine/PipeWireDevice.h"
  132. #include "platform/LinuxRealtime.h"
  133. #include "engine/PowerHints.h"
  134. #include "engine/Exporter.h"
  135. #include "engine/AacEncoder.h"
  136. #include "engine/FlStudioExport.h"
  137. #include "engine/MidiFileIo.h"
  138. #include "core/MidiPreview.h" // round 190qi
  139. #include "core/PluginPicks.h" // round 190qi
  140. #include "engine/PluginHost.h"
  141. #include "engine/Vst3NoteTuning.h"
  142. #include "engine/PluginSandbox.h"
  143. #include "engine/Bridge32Test.h"
  144. #include "engine/ClapFormat.h"
  145. #include "engine/JsfxFormat.h"
  146. #include "engine/ClapTeardownTest.h"
  147. #include "engine/RenderAgainTest.h"
  148. #include "engine/Determinism190poTest.h"
  149. #include "ui/TiltViewport.h"
  150. #if JUCE_LINUX
  151. #include <dlfcn.h> // (round 190ou: --hwheel254test presses X11 buttons through XTest)
  152. #include <sys/prctl.h> // (round 190ou: --multieditor255test LYNX_ME_PTRACE=1)
  153. #include <sys/socket.h> // (round 190rf: --qa190rfchild display)
  154. #include <unistd.h>
  155. #endif
  156. #include "engine/HostingTests.h"
  157. #include "engine/Modulators190oxTest.h"
  158. #include "ui/ModRing.h"
  159. #include "core/EdisonFx.h"
  160. #include "engine/ProjectFile.h"
  161. #include "ui/RemoteControl.h"
  162. #include "core/FlControlMenus.h"
  163. #include "core/PlaylistOps.h"
  164. #include "core/Sha256.h"
  165. #include "engine/SessionPack.h"
  166. #include "engine/LiveSessions.h"
  167. #include "engine/LiveTest.h"
  168. #include "engine/ShortExportTest.h"
  169. #include "core/SessionIds.h"
  170. #include "core/SessionParts.h"
  171. #include "engine/SampleLibrary.h"
  172. #include "engine/Text.h"
  173. #include "platform/FileTypes.h"
  174. #include "platform/Package.h"
  175. #include "core/AlsExport.h"
  176. #include "core/AlsImport.h"
  177. #include "core/LiveScaleControl.h" // round 190oo (--design190ooshot)
  178. #include "core/PlaylistViewOptions.h"
  179. #include "core/PianoRollScript.h"
  180. #include "ui/ScriptPanel.h"
  181. #include "ui/AlsExportDialog.h"
  182. #include "ui/LiveRemoteUi.h"
  183. #include "ui/GamepadInput.h"
  184. #include "ui/SettingsPages.h"
  185. #include "core/ExtrasDefaults.h" // round 190qk (--selftest extras190qk)
  186. #include "ui/ExtendedHintPanel.h"
  187. #include "core/FlSettings.h"
  188. #include "ui/OtherAppsExport.h"
  189. #include "ui/TimerWhileShowing.h"
  190. #include "ui/MixerBasicsCheck.h"
  191. #include "ui/VideoPlayerView.h"
  192. #include "ui/VideoMedia.h"
  193. #include "ui/VideoTracks.h"
  194. #include "ui/AdrWindow.h"
  195. #include "ui/PluginPicker.h"
  196. #include "ui/PlaylistComponent.h"
  197. #include "ui/PictureCheck.h"
  198. #include "ui/PatternBlocksView.h"
  199. #include "ui/PaintAB.h"
  200. #include <typeinfo>
  201. #include "ui/PatcherEditor.h"
  202. #include "ui/VisualEditors.h"
  203. #include "ui/FlExtraEditors.h"
  204. #include "ui/VisualGl.h"
  205. #include "ui/DanceView.h"
  206. #include "ui/PluginPresetMenu.h"
  207. #include "ui/GeneratorPresetMenu.h"
  208. #include "core/GeneratorPresets.h"
  209. #include "ui/PluginWindow.h"
  210. #include "platform/NativeEmbed.h"
  211. #include "ui/Motion.h"
  212. #include "ui/ShotShowing.h"
  213. #include "ui/SimpleLook.h"
  214. #include "ui/NativeChild.h"
  215. #include "ui/FrameTicker.h"
  216. #include "ui/DockPaintCheck.h"
  217. #include "ui/Workspace.h"
  218. #include "ui/PluginThumbs.h"
  219. #include "ui/ClipProperties.h"
  220. #include "ui/NewProjectDialog.h"
  221. #include "ui/PluginMonitorWindow.h"
  222. #include "ui/TouchKeyboard.h"
  223. #include "ui/AutomationUi.h"
  224. #include "core/GrossBeatLocator.h"
  225. #include "ui/PluginSkin.h"
  226. #include "ui/ChannelSettings.h"
  227. #include "ui/TempoDetectionDialog.h"
  228. #include "ui/AudioClipboard.h"
  229. #include "ui/FlVoicePanel.h"
  230. #include "ui/SlicexEditor.h"
  231. #include "ui/DirectWaveEditor.h"
  232. #include "ui/FruitySlicerEditor.h"
  233. #include "core/GrossBeat.h"
  234. #include "core/LynxBanks.h"
  235. #include "core/NativeEngines.h"
  236. #include "ui/ControllerEditors.h"
  237. #include "ui/NewtoneEditor.h"
  238. #include "core/NewtoneFx.h"
  239. #include "core/FormulaController.h"
  240. #include "core/MidiControls.h"
  241. #include "core/FlSynths.h"
  242. #include "core/SoundFont.h"
  243. #include "core/Sfz.h"
  244. #include "core/Slicex.h"
  245. #include "ui/Dialogs.h"
  246. #include "ui/DialogFrame.h"
  247. #include "ui/FileChoosers.h"
  248. #include "ui/TrackIcons.h"
  249. #include "core/MeterScale.h"
  250. #include "core/RackOps.h"
  251. #include "core/RackAutomation.h" // round 190oo (PAT-7, --selftest rackauto190oo)
  252. #include "core/Layer.h"
  253. #include "core/XyController.h"
  254. #include "core/FlCurve.h"
  255. #include "core/ControlSurface.h"
  256. #include "core/VoltageController.h"
  257. #include "ui/Controllers164.h"
  258. #include "core/StandIns.h"
  259. #include "ui/ExportDialog.h"
  260. #include "ui/QuickAddPalette.h"
  261. #include "ui/I18n.h"
  262. #include "ui/KeyFocus.h"
  263. #include "core/TrackIconScale.h"
  264. #include "core/EscClose.h"
  265. #include "ui/MainComponent.h"
  266. #include "ui/LynxWindows.h" // --tabs2test190nz (issue #232 stage 2)
  267. #include "ui/WindowClipboard.h"
  268. #include "ui/SimpleDock.h"
  269. #include "core/ScaleKeys.h"
  270. #include "core/KeyFollow.h"
  271. #include "core/SoundLibrary.h"
  272. #include "ui/MidiToolsPanel.h"
  273. #include "ui/FrameProbe.h"
  274. #include "ui/MotionOverlay.h"
  275. #include "ui/UiTrace.h"
  276. #include "core/MixerOps.h"
  277. #include "ui/QuickPick.h"
  278. #include "core/FolderWatcher.h"
  279. #include "core/FruityDynamics.h"
  280. #include "core/PluginDbFolder.h"
  281. #include "core/NoteTools.h"
  282. #include "engine/ProjectPackage.h"
  283. #include "ui/SetupWizard.h"
  284. #include "ui/DemoMode.h" // (round 190np)
  285. #if JUCE_LINUX || JUCE_WINDOWS // (rollup 0.1.31 step 2: Windows too, so --onboard190npshot runs its async callbacks there)
  286. namespace juce::detail { bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages); } // juce_Messaging_linux / _windows.cpp (--onboard190npshot)
  287. #endif
  288. #include "ui/Onboarding.h"
  289. #include "engine/FlStudio.h"
  290. #include "ui/HistoryPanel.h"
  291. #include "ui/VersionsPanel.h"
  292. #include "ui/CleanVoiceMenu.h"
  293. #include "ui/LyricsPanel.h"
  294. #include "ui/ReferenceMatchPanel.h"
  295. #include "ui/StartFromPanel.h"
  296. #include "ui/FirstSongTour.h"
  297. #include "ui/PluginsOffPanel.h"
  298. #include "ui/MissingFilesDialog.h"
  299. #include "ui/SettingsDialog.h"
  300. #include "ui/PluginManager.h"
  301. #include "ui/ShortcutManager.h"
  302. #include "ui/NoteToolDialogs.h"
  303. #include "ui/ChordStripView.h" // round 190kd (--prchord190kd)
  304. #include "ui/ChordHelper.h" // round 190mc (--modal190mc)
  305. #include "core/KeyRegions.h" // round chord2_190nu (--selftest, --keys190nu)
  306. #include "core/TransistorBass.h" // round 190mc (--modal190mc)
  307. #include "core/ModelParams.h" // round 190mc (--modal190mc)
  308. #include "ui/EventEditor.h"
  309. #include "ui/AudioEditor.h"
  310. #include "ui/SampleProperties.h"
  311. #include "ui/TempoTapper.h"
  312. #include "ui/ProjectPickerView.h" // (round 190my)
  313. #include "ui/WindowPlaces.h" // (round 190oa)
  314. #include "ui/HintBar.h" // (round 190oa)
  315. #include "core/EventEdit.h"
  316. #include "core/FacetEq.h"
  317. #include "core/LimiterLaw.h" // (rollup step 9: the copy for 0.1.28 self-test)
  318. #include "core/ApexLimiter.h" // (rollup step 10: likewise)
  319. #include "core/Reeverb2.h"
  320. #include "core/VoiceTools.h"
  321. #include "platform/ThreadInstructions.h" // (rollup step 9: --paintbench counts instructions)
  322. #include "ui/FacetEqEditor.h"
  323. #include "core/RackRenderer.h"
  324. #include "ui/ProEditors.h"
  325. #include "ui/ParametricEqEditor.h"
  326. #include "ui/PluginEditors.h"
  327. #include "core/PluginLayout.h"
  328. #include "core/EffectPresets.h"
  329. #include "ui/PluginHeader.h"
  330. #include "core/Vfx.h"
  331. #include "core/TransistorBass.h"
  332. #include "ui/Splash.h"
  333. #include "core/ExportDone.h" // round 190qr (#280)
  334. #include "core/StartupSound.h" // round 190qr (#280)
  335. #include "core/ClipHandle.h" // round 190qr (#274)
  336. #include "core/ZoomAnchor.h" // round 190qr (#276)
  337. #include "ui/Theme.h"
  338. #include "ui/ThemeSettings.h"
  339. #include "ui/AutoLookEditor.h" // (round 190od, issue #239)
  340. #include "core/StartPage.h" // (round 190oq, issue #252)
  341. #include "core/MuteKeys.h"
  342. #include "core/AraRegions.h"
  343. #include "ui/StartPage.h"
  344. #include "ui/DeleteFade.h"
  345. #include "ui/AraMenu.h"
  346. #include "ui/WaveformView.h"
  347. #include "ui/WindowOwner.h"
  348. #include "ui/PluginKeysTest.h"
  349. #include "ui/ZOrder191Test.h"
  350. #include "ui/Toolbar.h"
  351. #include "ui/ToolWindow.h"
  352. #include "core/Details190mv.h" // (round 190mv)
  353. #include "platform/CrashGuard.h"
  354. #include "ui/CrashReporter.h"
  355. #include "ui/Updater.h"
  356. #include "ui/AudioCheck.h"
  357. #include "ui/StemExtract.h"
  358. #include "core/RegionLoop.h" // round 190jr: --bandlab190jrshot
  359. #include "core/FactoryContent.h" // round 190ke: --simplegb190keshot
  360. #include "core/KeyFollow.h" // round 190kx: --loopinfo190kxshot
  361. #include "core/LoopAnalysis.h"
  362. #include "../tests/LoopCorpus190kx.h" // (LYNX's own synthetic loops, written for the shot)
  363. #include "core/SongFade.h"
  364. #include "core/SoundLibrary.h"
  365. #include "core/SynthParams.h"
  366. #include "core/GoalKnobs.h"
  367. #include "core/DetailChain.h"
  368. #include "ui/FinishDock.h"
  369. #include "ui/SimpleDock.h"
  370. #include "ui/SimpleTuner.h"
  371. #include "ui/AudioToMidi.h"
  372. #include "ui/PolyEditor.h"
  373. #include "core/PolyEdit.h"
  374. #include "ui/ShotScale.h"
  375. #include "core/LaneView.h" // round 190iu
  376. #include "core/PlaylistTrackOps.h"
  377. #include "core/MidiDrop.h"
  378. #include "core/TakeCleanup.h"
  379. #include "core/TrackOnly.h"
  380. #include "core/WheelZones.h"
  381. #include "ui/WorkflowExtras.h"
  382. #include "core/Links.h"
  383. #include <algorithm>
  384. #include <set> // (round 190jf: --dawprojcheck190jf)
  385. #include <atomic>
  386. #include <exception>
  387. #include <chrono>
  388. #include <cstdio>
  389. #include <ctime>
  390. #include <cstdlib>
  391. #include <future>
  392. #include <mutex>
  393. #include <thread>
  394. namespace
  395. {
  396. lynx::AudioEngine* crashEngine = nullptr;
  397. // Startup trace (REA round 116): with LYNX_TRACE_STARTUP set, the time of each startup step since the C++ runtime
  398. // started is written to %APPDATA%\LYNX\startup.log (the loader's own time before that is not included).
  399. struct StartupTrace
  400. {
  401. using clock = std::chrono::steady_clock;
  402. const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
  403. const std::chrono::system_clock::time_point t0System = std::chrono::system_clock::now(); // (round 190hd: vs the process's creation)
  404. // (round 190go: always kept, as a field-readable start-up timeline; written to startup.log 5 s and 15 s after the
  405. // window — with LYNX_TRACE_STARTUP set, at every step as before, so a start that hangs still leaves its last step)
  406. const bool on = true;
  407. const bool eachStep = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
  408. juce::String text;
  409. clock::time_point last = t0;
  410. std::int64_t lastPrivate = 0;
  411. double seconds() const { return std::chrono::duration<double> (clock::now() - t0).count(); } // since the process started
  412. void mark (const char* step)
  413. {
  414. if (! on)
  415. return;
  416. const auto now = clock::now();
  417. const auto ms = [] (clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); };
  418. // (round 190gd: the process's memory after each step too, so the log says where the megabytes of a start go)
  419. const auto mb = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1).paddedLeft (' ', 7); };
  420. const auto priv = lynx::toolbar::PerformanceMeter::processPrivateBytes();
  421. const auto ws = lynx::toolbar::PerformanceMeter::processMemoryBytes();
  422. text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7)
  423. << " private " << mb (priv) << " MB (+" << mb (priv - lastPrivate).trim() << ") ws " << mb (ws) << " MB " << step << "\n";
  424. lastPrivate = priv;
  425. last = now;
  426. if (eachStep)
  427. write();
  428. }
  429. void write() const { lynx::platform::settingsFile ("startup.log").replaceWithText (text); }
  430. };
  431. StartupTrace startupTrace;
  432. void startupMarkHook (const char* step) { startupTrace.mark (step); }
  433. // Round 190rb: a sanitizer build (-DLYNX_SANITIZE) leaves SIGSEGV / SIGBUS / SIGFPE / SIGABRT to ASan and UBSan (their
  434. // report names the bad access and where the memory came from); LYNX_CRASHGUARD=1 installs LYNX's handlers anyway
  435. bool sanitizerOwnsSignals()
  436. {
  437. #if defined(LYNX_SANITIZER_BUILD)
  438. return juce::SystemStats::getEnvironmentVariable ("LYNX_CRASHGUARD", {}) != "1";
  439. #else
  440. return false;
  441. #endif
  442. }
  443. juce::File crashFolderForTest; // --faulttest: where the crash file goes instead of the settings' autosave folder
  444. // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
  445. void onCrash (void* exceptionPointers)
  446. {
  447. // round 190oh (Windows): a fault on a hosted plugin's own thread that nothing handled — that thread waits for good
  448. // inside this call and the main window's timer switches the plugin off (crashguard::parkFaultingPluginThread)
  449. if (lynx::crashguard::parkFaultingPluginThread (exceptionPointers))
  450. return;
  451. // (round 190ci: once. The hook for stacks Windows cannot walk, crashguard::setUnwalkableFaultHandler, may have run
  452. // this before the top-level filter does)
  453. static std::atomic<bool> reported { false };
  454. if (reported.exchange (true))
  455. return;
  456. // rollup 0.1.30 step 12 (owner decision after round 190mo): whatever follows, the process ends within the watchdog's
  457. // time (60 s): after a heap corruption everything below that allocates can wait for ever on the allocator's lock
  458. lynx::crashguard::armCrashWatchdog (exceptionPointers);
  459. // ... and after the C library's (or Windows') heap-corruption abort, nothing that allocates runs at all: a crash file
  460. // written without the heap, no session note, no emergency save (the project in memory may be what was broken)
  461. if (lynx::crashguard::heapCorruptionCrash (exceptionPointers))
  462. {
  463. lynx::crashguard::writeHeapCrashFile (exceptionPointers);
  464. return;
  465. }
  466. const auto folder = crashFolderForTest != juce::File() ? crashFolderForTest : lynx::platform::settingsFile ("autosave");
  467. folder.createDirectory();
  468. const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
  469. // JUCE's backtrace (named frames only), then every frame of the faulting thread as module+offset (round 157a: a
  470. // release LYNX.exe has no symbols, so its own frames were missing from the file)
  471. folder.getChildFile ("crash " + stamp + ".txt").replaceWithText (juce::SystemStats::getStackBacktrace() + "\n--- frames (module+offset)\n"
  472. + juce::String::fromUTF8 (lynx::crashguard::exceptionBacktrace (exceptionPointers).c_str()));
  473. lynx::crashguard::note (("crashed: backtrace in autosave\\crash " + stamp + ".txt").toStdString());
  474. if (lynx::crashguard::hangInCrashHandlerForTest()) // (--faulttest hang: a handler that never returns; the watchdog ends it)
  475. for (;;)
  476. std::this_thread::sleep_for (std::chrono::seconds (1));
  477. if (crashEngine != nullptr)
  478. {
  479. juce::String error;
  480. lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
  481. }
  482. }
  483. // Round 190rf (Linux): the X server went away (crashguard::watchDisplayConnection): the project in memory is saved as a
  484. // recovered project, as after a crash, before the process ends (it cannot go on without a display)
  485. void onDisplayLost()
  486. {
  487. if (crashEngine == nullptr)
  488. return;
  489. const auto folder = lynx::platform::settingsFile ("autosave");
  490. folder.createDirectory();
  491. juce::String error;
  492. lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S")
  493. + lynx::ProjectFile::extension), error);
  494. }
  495. juce::File sessionsFolder()
  496. {
  497. return lynx::PluginHost::settingsFolder().getChildFile ("sessions");
  498. }
  499. // Sessions of earlier runs whose process is gone without closing (a fail-fast, a crash, a forced end): each is appended
  500. // to %APPDATA%\LYNX\crash-history.log and its file removed. Returns the last step of the newest one ("" when none).
  501. juce::StringArray uncleanSteps; // the newest unclean session's steps (without their times)
  502. juce::String uncleanSessionText; // the newest unclean session's whole file (round 159: the crash report reads it)
  503. // What the newest unclean session tells (round 157a): the plugin whose editor was opening / shown when it ended, and
  504. // whether its crash file blames a graphics driver
  505. struct UncleanCause
  506. {
  507. juce::String editorPlugin; // the last steps were that plugin's editor
  508. bool gpuDriver = false; // the crash file's top frames are in a GPU driver / Direct3D / Direct2D module
  509. juce::String driverModule;
  510. };
  511. UncleanCause uncleanCause()
  512. {
  513. UncleanCause cause;
  514. juce::File crashFile;
  515. for (int i = uncleanSteps.size(); --i >= 0 && i >= uncleanSteps.size() - 4;)
  516. {
  517. const auto& step = uncleanSteps[i];
  518. if (step.startsWith ("crashed: backtrace in "))
  519. crashFile = lynx::platform::settingsFolder().getChildFile (step.fromFirstOccurrenceOf ("backtrace in ", false, false).replaceCharacter ('\\', '/'));
  520. for (const auto* prefix : { "opening the editor of ", "editor open: ", "editor shown: " })
  521. if (cause.editorPlugin.isEmpty() && step.startsWith (prefix))
  522. cause.editorPlugin = step.fromFirstOccurrenceOf (prefix, false, false).trim();
  523. if (step.startsWith ("closing the editor of ") || step.startsWith ("loaded plugin") || step.startsWith ("opening project"))
  524. break; // older steps than these did not end the session
  525. }
  526. // issue #32 (round 174a): a plugin whose editor already faulted in this session (caught, LYNX went on) is the
  527. // likely cause when the session then ended without a word: offer it a separate process too
  528. for (int i = uncleanSteps.size(); --i >= 0 && cause.editorPlugin.isEmpty();)
  529. if (const auto editor = lynx::crashreport::parseEditorCrashStep (uncleanSteps[i].toStdString()); ! editor.plugin.empty())
  530. cause.editorPlugin = juce::String::fromUTF8 (editor.plugin.c_str());
  531. if (crashFile.existsAsFile())
  532. {
  533. // the first frames after the crash handler's own (the "--- frames" part lists the faulting thread)
  534. auto text = crashFile.loadFileAsString();
  535. if (text.contains ("--- frames"))
  536. text = text.fromFirstOccurrenceOf ("--- frames", false, false);
  537. auto lines = juce::StringArray::fromLines (text);
  538. int looked = 0;
  539. for (const auto& line : lines)
  540. {
  541. const auto module = line.fromFirstOccurrenceOf (": ", false, false).upToFirstOccurrenceOf ("+", false, false).trim().toLowerCase();
  542. if (module.isEmpty() || ! module.endsWith (".dll"))
  543. continue;
  544. if (++looked > 12)
  545. break;
  546. for (const auto* driver : { "igd", "ig9icd", "ig7icd", "igxelp", "nvwgf2um", "nvoglv", "nvd3dum", "atidxx", "atio6axx", "amdxx", "aticfx",
  547. "d3d11.dll", "d3d10warp", "dxgi.dll", "d2d1.dll", "opengl32.dll", "dcomp.dll" })
  548. if (module.startsWith (driver))
  549. {
  550. cause.gpuDriver = true;
  551. cause.driverModule = module;
  552. break;
  553. }
  554. if (cause.gpuDriver)
  555. break;
  556. }
  557. }
  558. return cause;
  559. }
  560. juce::String collectUncleanSessions()
  561. {
  562. juce::String lastStep;
  563. juce::Time newest;
  564. for (const auto& file : sessionsFolder().findChildFiles (juce::File::findFiles, false, "session-*.txt"))
  565. {
  566. const auto text = file.loadFileAsString();
  567. juce::StringPairArray values;
  568. juce::StringArray steps;
  569. for (const auto& line : juce::StringArray::fromLines (text))
  570. {
  571. if (line.startsWith ("step="))
  572. steps.add (line.fromFirstOccurrenceOf ("=", false, false));
  573. else if (line.contains ("="))
  574. values.set (line.upToFirstOccurrenceOf ("=", false, false), line.fromFirstOccurrenceOf ("=", false, false));
  575. }
  576. const auto pid = (std::uint32_t) values["pid"].getLargeIntValue();
  577. const auto start = (std::uint64_t) values["start"].getLargeIntValue();
  578. if (pid == lynx::crashguard::processId() || lynx::crashguard::processRunning (pid, start))
  579. continue; // this run, or another LYNX window still open
  580. lynx::PluginHost::settingsFolder().getChildFile ("crash-history.log")
  581. .appendText (juce::Time::getCurrentTime().toISO8601 (true) + " previous session ended without closing\n" + text + "\n");
  582. file.deleteFile();
  583. if (const auto modified = file.getLastModificationTime(); lastStep.isEmpty() || modified > newest)
  584. {
  585. newest = modified;
  586. lastStep = steps.isEmpty() ? juce::String ("start-up") : steps[steps.size() - 1].fromFirstOccurrenceOf (" ", false, false);
  587. uncleanSessionText = text;
  588. uncleanSteps.clear();
  589. for (const auto& step : steps)
  590. uncleanSteps.add (step.fromFirstOccurrenceOf (" ", false, false));
  591. }
  592. }
  593. return lastStep;
  594. }
  595. } // namespace
  596. // --uiperf (round 173f, discussion #10): a mixer fader dragged up and down with the mouse while the pattern plays. A
  597. // high-resolution timer delivers 125 moves a second to the message thread through the window's own mouse path
  598. // (ComponentPeer::handleMouseEvent), at most one waiting at a time as Windows does with WM_MOUSEMOVE; every frame the
  599. // window paints tells whether it covered the fader. Measured: how long a move waited for the message thread, the time
  600. // from a move to the first frame that shows the fader after it (input → paint), and whether the value stays put when
  601. // the mouse is released.
  602. #if JUCE_WINDOWS
  603. namespace juce
  604. {
  605. extern int lynxD2DPresents; // (cmake/LynxPatchJuce.cmake, round 190gv: every Direct2D window present)
  606. }
  607. #endif
  608. // round 190jy: --uiperf's presents per second (190kb's cycles line reads it too)
  609. static int uiPerfPresents()
  610. {
  611. #if JUCE_WINDOWS
  612. return juce::lynxD2DPresents;
  613. #else
  614. return 0;
  615. #endif
  616. }
  617. struct UiPerfDrag final : public std::enable_shared_from_this<UiPerfDrag>,
  618. private juce::HighResolutionTimer
  619. {
  620. ~UiPerfDrag() override { stopTimer(); }
  621. void start (juce::Component& windowIn, juce::Component& strips, juce::Rectangle<int> rail, lynx::AudioEngine* engineIn, int trackIn)
  622. {
  623. window = &windowIn;
  624. engine = engineIn;
  625. track = trackIn;
  626. railInWindow = window->getLocalArea (&strips, rail);
  627. watch = railInWindow.expanded (6, 40); // the cap, its tip above and the dB read-out below
  628. visible = strips.isShowing() && window->getLocalArea (&strips, strips.getLocalBounds()).contains (railInWindow.getCentre());
  629. const auto volume = engine->getSong().mixer[(std::size_t) track].volume;
  630. x = (float) railInWindow.getCentreX();
  631. startY = (float) railInWindow.getBottom() - volume * (float) railInWindow.getHeight(); // on the cap: no jump
  632. amplitude = 0.4f * (float) railInWindow.getHeight();
  633. centreY = juce::jlimit ((float) railInWindow.getY() + amplitude, (float) railInWindow.getBottom() - amplitude, startY);
  634. t0 = juce::Time::getMillisecondCounterHiRes();
  635. inject (x, startY, false);
  636. juce::ModifierKeys::currentModifiers = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  637. inject (x, startY, true);
  638. active = true;
  639. startTimer (8);
  640. }
  641. // message thread
  642. void framePainted (double now, juce::Rectangle<int> area)
  643. {
  644. if (pending.empty() || ! area.intersects (watch))
  645. return;
  646. for (const auto t : pending)
  647. latencies.push_back (now - t);
  648. pending.clear();
  649. ++framesOverFader;
  650. }
  651. // the moves end; as in the reporter's clip, the song is stopped while the button is still down
  652. juce::String stop()
  653. {
  654. stopTimer();
  655. active = false;
  656. valueAtRelease = engine->getSong().mixer[(std::size_t) track].volume;
  657. engine->stop();
  658. juce::String text;
  659. text << " drag of insert " << track << "'s fader" << (visible ? "" : " (NOT VISIBLE)") << ": " << moves << " moves handled, " << dropped
  660. << " folded into the next (the message thread still busy with the previous one)\n"
  661. << " move waited for the message thread: " << describe (queueDelays) << "\n"
  662. << " input -> paint (move to the first frame over the fader): " << describe (latencies) << ", " << framesOverFader
  663. << " frames over the fader\n";
  664. return text;
  665. }
  666. juce::String release()
  667. {
  668. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  669. juce::ModifierKeys::currentModifiers = {};
  670. inject (x, lastY, false);
  671. return " song stopped, button still down: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " at the last move) "
  672. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  673. }
  674. juce::String released() const
  675. {
  676. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  677. return " after the release: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " when released) "
  678. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  679. }
  680. private:
  681. juce::Component* window = nullptr;
  682. lynx::AudioEngine* engine = nullptr;
  683. int track = 1;
  684. juce::Rectangle<int> railInWindow, watch;
  685. bool visible = false;
  686. float x = 0.0f, startY = 0.0f, centreY = 0.0f, amplitude = 0.0f, lastY = 0.0f;
  687. double t0 = 0.0;
  688. std::atomic<bool> active { false }, posted { false };
  689. std::atomic<int> dropped { 0 };
  690. int moves = 0, framesOverFader = 0;
  691. float valueAtRelease = 0.0f;
  692. std::vector<double> pending, latencies, queueDelays;
  693. static juce::String describe (std::vector<double> v)
  694. {
  695. if (v.empty())
  696. return "none";
  697. std::sort (v.begin(), v.end());
  698. const auto at = [&v] (double q) { return v[std::min (v.size() - 1, (std::size_t) (q * (double) v.size()))]; };
  699. return "p50 " + juce::String (at (0.5), 1) + " / p95 " + juce::String (at (0.95), 1) + " / p99 " + juce::String (at (0.99), 1) + " / max "
  700. + juce::String (v.back(), 1) + " ms";
  701. }
  702. void inject (float px, float py, bool down)
  703. {
  704. lastY = py;
  705. if (auto* peer = window != nullptr ? window->getPeer() : nullptr)
  706. {
  707. const auto local = peer->globalToLocal (window->localPointToGlobal (juce::Point<float> (px, py)));
  708. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local,
  709. down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys(),
  710. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation,
  711. juce::Time::currentTimeMillis());
  712. }
  713. }
  714. void hiResTimerCallback() override
  715. {
  716. if (! active.load())
  717. return;
  718. if (posted.exchange (true))
  719. {
  720. ++dropped;
  721. return;
  722. }
  723. const auto postedAt = juce::Time::getMillisecondCounterHiRes();
  724. juce::MessageManager::callAsync ([self = shared_from_this(), postedAt] {
  725. self->posted = false;
  726. if (! self->active.load())
  727. return;
  728. const auto now = juce::Time::getMillisecondCounterHiRes();
  729. self->queueDelays.push_back (now - postedAt);
  730. // up and down ~1.3 times a second, like the reporter's hand
  731. const auto y = self->centreY + self->amplitude * (float) std::sin (2.0 * juce::MathConstants<double>::pi * 1.3 * (now - self->t0) / 1000.0);
  732. self->inject (self->x, y, true);
  733. self->pending.push_back (postedAt);
  734. ++self->moves;
  735. });
  736. }
  737. };
  738. class LynxApplication final : public juce::JUCEApplication
  739. {
  740. public:
  741. const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
  742. const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
  743. // the plugin scan runs copies of LYNX as child processes
  744. bool moreThanOneInstanceAllowed() override { return true; }
  745. // A file handed to the running application. macOS does this for every Finder double-click, "Open With" and Dock drop,
  746. // also the one that starts LYNX (its argv has no file). On Windows and Linux a second start is a second process
  747. // (moreThanOneInstanceAllowed) with the file as an argument, so this is not called there. Only the first file of a
  748. // multiple selection opens: a project replaces the one before it. (D#92, round 180a)
  749. void anotherInstanceStarted (const juce::String& commandLine) override
  750. {
  751. const auto files = lynx::safety::filesInCommandLine (commandLine.toStdString());
  752. if (files.empty())
  753. return;
  754. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile (juce::String::fromUTF8 (files.front().c_str()));
  755. if (! startupFileHandled) // still starting: openStartupFile takes it, nothing to ask about yet
  756. {
  757. fileToOpen = file;
  758. return;
  759. }
  760. if (mainWindow != nullptr)
  761. {
  762. mainWindow->toFront (true);
  763. mainWindow->getContent().openFileRequest (file);
  764. }
  765. }
  766. void initialise (const juce::String& commandLine) override
  767. {
  768. // round 190nx: --offline (or LYNX_OFFLINE=1) = no network connection of LYNX's own, before anything can start one
  769. if (juce::StringArray::fromTokens (commandLine, true).contains ("--offline"))
  770. lynx::offline::set (true);
  771. // round 166b: the copy of LYNX.exe that installs an update (ui/Updater.h) waits, installs, starts LYNX again
  772. if (commandLine.contains ("--apply-update") && lynx::updater::runApplyHelper (juce::StringArray::fromTokens (commandLine, true)))
  773. {
  774. updateHelper = true;
  775. quit();
  776. return;
  777. }
  778. // Windows, LYNX.exe in a folder with accents: run again from its ASCII short path (Waves editors crash otherwise)
  779. if (int code = 0; lynx::platform::relaunchFromAsciiPath (code))
  780. {
  781. relaunched = true;
  782. setApplicationReturnValue (code);
  783. quit();
  784. return;
  785. }
  786. // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave. A sanitizer build
  787. // (-DLYNX_SANITIZE, round 190rb) leaves the fault signals to ASan / UBSan, whose reports name the bad access,
  788. // unless LYNX_CRASHGUARD=1 asks for LYNX's own handlers (their tests)
  789. if (! sanitizerOwnsSignals())
  790. juce::SystemStats::setApplicationCrashHandler (onCrash);
  791. // rollup step 12: the crash handler's watchdog and its allocation-free crash file (platform/CrashGuard.h)
  792. lynx::crashguard::prepareCrashWatchdog (lynx::platform::settingsFile ("autosave").getFullPathName().toStdString());
  793. // rollup 0.1.28 (REA 190hb action 4, FL's "Init DWM"): the compositor on MMCSS, steadier frames under CPU load
  794. // (Windows; LYNX_DWM_MMCSS=0 leaves it off)
  795. lynx::powerhints::enableCompositorMmcss();
  796. // round als190ka (issue #193): a video's sound track for the sample library (a Live set's video clips)
  797. lynx::SampleLibrary::setVideoSoundDecoder ([] (const juce::File& video) { return lynx::videotracks::soundTrackWav (video); });
  798. // round 190ci: also for a fault on a stack Windows cannot walk, which never reaches that handler (Windows)
  799. lynx::crashguard::setUnwalkableFaultHandler (onCrash);
  800. if (const auto args = juce::StringArray::fromTokens (commandLine, true); args.contains ("--faulttest"))
  801. {
  802. // LYNX.exe --faulttest plain|unwalkable <folder> (round 190ci): ends by an access violation on purpose,
  803. // before any window, so that --selftest can check that the crash file gets written (into <folder>)
  804. const auto i = args.indexOf ("--faulttest");
  805. crashFolderForTest = juce::File (args[i + 2].unquoted());
  806. lynx::crashguard::setCrashFolder (crashFolderForTest.getFullPathName().toStdString());
  807. lynx::crashguard::quietCrashReports();
  808. // rollup step 12: heap = the C library's heap-corruption abort (no recovered project may be written: an
  809. // engine is set for the emergency save on purpose); hang = a crash handler that never returns (the watchdog
  810. // must end the process: LYNX_CRASH_WATCHDOG_S makes the test short)
  811. if (args[i + 1] == "heap" || args[i + 1] == "hang")
  812. {
  813. static lynx::AudioEngine* engine = new lynx::AudioEngine (false);
  814. crashEngine = engine;
  815. if (args[i + 1] == "heap")
  816. lynx::crashguard::heapCorruptionForTest();
  817. lynx::crashguard::setHangInCrashHandlerForTest();
  818. lynx::crashguard::faultForTest (false);
  819. }
  820. // round 190dt: guarded / guarded-libc = LYNX's own fault inside a guarded plugin call (Linux / macOS): it must
  821. // reach the crash handler like any other; a return means the guard swallowed it
  822. // round 190gg: thread / thread-libc = a fault on a thread of LYNX's own, with LYNX's executable watched as
  823. // a plugin's module: it must not be parked as a plugin's thread
  824. if (args[i + 1].startsWith ("thread"))
  825. {
  826. lynx::crashguard::faultOnOwnThreadForTest (args[i + 1] == "thread-libc");
  827. crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText ("parked");
  828. lynx::crashguard::exitNow (4);
  829. }
  830. if (args[i + 1].startsWith ("guarded"))
  831. {
  832. const auto code = lynx::crashguard::faultInGuardedCallForTest (args[i + 1] == "guarded-libc");
  833. crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText (lynx::crashguard::describe (code));
  834. lynx::crashguard::exitNow (4);
  835. }
  836. lynx::crashguard::faultForTest (args[i + 1] == "unwalkable");
  837. }
  838. if (! sanitizerOwnsSignals())
  839. lynx::crashguard::hardenSignals(); // issue #115: stack overflows and SIGTERM / SIGHUP leave a trace (Linux / macOS)
  840. // SFZ instruments (round 167o): their FLAC / OGG / AIFF / MP3 samples through JUCE's readers
  841. lynx::sfz::setDecoder ([] (const std::string& path, lynx::sfz::Audio& out) {
  842. juce::AudioFormatManager formats;
  843. formats.registerBasicFormats();
  844. std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (juce::File (juce::String::fromUTF8 (path.c_str()))));
  845. if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (1 << 28) || reader->numChannels == 0)
  846. return false;
  847. const auto frames = (int) reader->lengthInSamples;
  848. juce::AudioBuffer<float> buffer ((int) std::min (2u, reader->numChannels), frames);
  849. if (! reader->read (&buffer, 0, frames, 0, true, buffer.getNumChannels() > 1))
  850. return false;
  851. out.channels.clear();
  852. for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
  853. out.channels.emplace_back (buffer.getReadPointer (ch), buffer.getReadPointer (ch) + frames);
  854. out.sampleRate = reader->sampleRate;
  855. out.loopStart = out.loopEnd = -1;
  856. return true;
  857. });
  858. // child process of a sandboxed plugin: no window or audio of its own
  859. if (lynx::runPluginSandboxWorker (commandLine))
  860. {
  861. lynx::crashguard::quietCrashReports();
  862. sandboxChild = true;
  863. return;
  864. }
  865. // --shot-scale <v> / --shot-suffix <text> (round 190bi, ui/ShotScale.h): the pixel scale and file-name suffix of every
  866. // picture route, taken out here so the routes' own arguments keep their places
  867. const auto args = lynx::shot::takeArguments (juce::StringArray::fromTokens (commandLine, true));
  868. // round 190np: whether this profile already had LYNX's UI settings before this start (an upgrade keeps what it had:
  869. // no welcome card), and --demo (ui/DemoMode.h: the tutorial-video pipeline's automation mode)
  870. lynx::onboardui::profileExistedAtStart() = lynx::PluginHost::settingsFolder().getChildFile ("ui-options.txt").existsAsFile();
  871. if (args.contains ("--demo"))
  872. lynx::demo::setActive (true);
  873. // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
  874. lynx::i18n::initialise (args);
  875. // interface font: saved in Settings › General; --uifont "Name" overrides it for this run
  876. const auto uiFontArg = args.indexOf ("--uifont");
  877. lookAndFeel.applyInterfaceFont (lynx::i18n::current(), uiFontArg >= 0 ? args[uiFontArg + 1].unquoted() : juce::String());
  878. // text size (issue #189): saved in Settings › General; --textsize 125 overrides it for this run
  879. const auto textSizeArg = args.indexOf ("--textsize");
  880. lynx::theme::setTextSize (textSizeArg >= 0 ? args[textSizeArg + 1].getIntValue() : lynx::theme::savedTextSize());
  881. // bold text (round 190jp): saved in Settings › General; --boldtext 1 (labels) or 2 (all) overrides it for this run
  882. const auto boldTextArg = args.indexOf ("--boldtext");
  883. lynx::theme::setBoldText (boldTextArg >= 0 ? args[boldTextArg + 1].getIntValue() : lynx::theme::savedBoldText());
  884. // round 190je: FL-style condensed labels (Settings › General); --condensedlabels for one run. --menustyle flClassic: FL's
  885. // light menus for one run (Settings › Theme keeps the saved choice)
  886. lynx::theme::setCondensedLabels (args.contains ("--condensedlabels") || lynx::theme::savedCondensedLabels());
  887. if (const auto menuStyleArg = args.indexOf ("--menustyle"); menuStyleArg >= 0)
  888. {
  889. lynx::theme::menus::setStyle (lynx::themes::menuStyleFromId (args[menuStyleArg + 1].unquoted().toStdString()));
  890. lookAndFeel.refreshColours();
  891. }
  892. if (args.contains ("--showcase"))
  893. {
  894. // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
  895. const auto i = args.indexOf ("--showcase");
  896. runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
  897. return;
  898. }
  899. if (args.contains ("--demosongs"))
  900. {
  901. // round 190dv: LYNX's two short genre demos (core/DemoSongs.h) as .lynx files: --demosongs <folder>
  902. // (resources/demos/ in the repository)
  903. const auto i = args.indexOf ("--demosongs");
  904. runDemoSongs (args[i + 1].unquoted());
  905. return;
  906. }
  907. if (args.contains ("--perfgen"))
  908. {
  909. // round perfgate190id: the big-project performance gate's synthetic projects (core/PerfProjects.h) as .lynx
  910. // files with their WAVs: --perfgen <folder> [report.txt] [name,name...]; the save and load times in the report
  911. const auto i = args.indexOf ("--perfgen");
  912. const auto report = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  913. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  914. runPerfGen (args[i + 1].unquoted(), report, only);
  915. return;
  916. }
  917. if (args.contains ("--sandboxtest"))
  918. {
  919. const auto i = args.indexOf ("--sandboxtest");
  920. runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  921. return;
  922. }
  923. // round 190jg (BUILD-LIST 11 + 18, engine/HostingTests.h): grouped plugin processes, CLAP extensions, timing
  924. if (args.contains ("--sandboxgrouptest") || args.contains ("--sandboxbench") || args.contains ("--clapext")
  925. || args.contains ("--automationtimingtest") || args.contains ("--pluginbench"))
  926. {
  927. const auto value = [&args] (const char* name, int fallback) {
  928. return args.contains (name) ? args[args.indexOf (name) + 1].getIntValue() : fallback;
  929. };
  930. auto code = 1;
  931. if (const auto i = args.indexOf ("--sandboxgrouptest"); i >= 0)
  932. code = lynx::runSandboxGroupTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  933. args.contains ("--crash") ? args[args.indexOf ("--crash") + 1].unquoted() : juce::String());
  934. else if (const auto b = args.indexOf ("--sandboxbench"); b >= 0)
  935. code = lynx::runSandboxBench (args[b + 1].unquoted(), args[b + 2].unquoted(), value ("--plugins", 8), value ("--block", 256),
  936. args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 5.0);
  937. else if (const auto pb = args.indexOf ("--pluginbench"); pb >= 0) // round 190of: per-plugin cost (engine/HostingTests.h)
  938. code = lynx::runPluginBench (args[pb + 1].unquoted(), args[pb + 2].unquoted(), value ("--block", 256),
  939. args.contains ("--rate") ? args[args.indexOf ("--rate") + 1].getDoubleValue() : 48000.0,
  940. args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 4.0, value ("--types", 8),
  941. args.contains ("--names") ? args[args.indexOf ("--names") + 1].unquoted() : juce::String(),
  942. args.contains ("--editors"));
  943. else if (const auto c = args.indexOf ("--clapext"); c >= 0)
  944. code = lynx::runClapExtTest (args[c + 1].unquoted(), args[c + 2].unquoted());
  945. else if (const auto t = args.indexOf ("--automationtimingtest"); t >= 0)
  946. code = lynx::runAutomationTimingTest (args[t + 1].unquoted(), args[t + 2].unquoted());
  947. setApplicationReturnValue (code);
  948. quit();
  949. return;
  950. }
  951. if (args.contains ("--bridge32test"))
  952. {
  953. // LYNX.exe --bridge32test "LYNX Test Synth 32.dll" report.txt [--compare "LYNX Test Synth.dll"] (round 176a):
  954. // the 32-bit plugin bridge (engine/Bridge32Test.cpp)
  955. const auto i = args.indexOf ("--bridge32test");
  956. const auto compare = args.contains ("--compare") ? args[args.indexOf ("--compare") + 1].unquoted() : juce::String();
  957. setApplicationReturnValue (lynx::runBridge32Test (args[i + 1].unquoted(), args[i + 2].unquoted(), compare));
  958. quit();
  959. return;
  960. }
  961. if (args.contains ("--rtstress"))
  962. {
  963. // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--type "driver type"] [--device "output"]
  964. // [--no-window] [--record take.wav]: the real app (window, audio device) plays the project and reports the callbacks
  965. // that missed their deadline (REA round 87); --type/--device pick another driver for this run only (round 97);
  966. // --record also records the input during the run, like Rec + Play, and moves the take to take.wav (round 106)
  967. const auto i = args.indexOf ("--rtstress");
  968. const auto seconds = args[i + 3].getDoubleValue();
  969. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  970. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  971. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  972. runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer,
  973. option ("--type"), option ("--device"), option ("--record"));
  974. return;
  975. }
  976. if (args.contains ("--renderaheadtest"))
  977. {
  978. // LYNX --renderaheadtest report.txt [project.flp|.lynx ...] [--buffer N] [--seconds S] (round 190gq): the engine's
  979. // own device callback (a stand-in device driven block by block, as --cliplooptest) plays the showcase song (from
  980. // the start, round a loop region that wraps mid-block, in Pattern mode) and each project with Options › Audio
  981. // settings › "Render ahead" off, then on. The two outputs must be the same to the bit, nothing rendered ahead
  982. // may be dropped, and most blocks must come from the ring. No window, no audio device.
  983. const auto i = args.indexOf ("--renderaheadtest");
  984. juce::StringArray projects;
  985. for (int k = i + 2; k < args.size() && ! args[k].startsWith ("--"); ++k)
  986. projects.add (args[k].unquoted());
  987. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 128;
  988. const auto seconds = args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 12.0;
  989. runRenderAheadTest (juce::File (args[i + 1].unquoted()), projects, juce::jlimit (16, 2048, buffer), seconds > 0.0 ? seconds : 12.0);
  990. return;
  991. }
  992. if (args.contains ("--cliplooptest"))
  993. {
  994. // LYNX --cliplooptest report.txt [export.wav] (round 167q, issue #25: 0.1.21 drew the repeats of a stretched
  995. // pattern clip but played the pattern once). The real engine's device callback (a stand-in device, driven
  996. // block by block) plays a synth's 1-bar pattern in a 4-bar clip: every repeat must sound as bar 1, also
  997. // starting inside a repeat, after a jump mid-clip and in a loop region; the WAV export (written to
  998. // export.wav and read back) the same. With the LYNX extra off, bars 2-4 must be silent (FL's behaviour).
  999. const auto i = args.indexOf ("--cliplooptest");
  1000. runClipLoopTest (juce::File (args[i + 1].unquoted()), args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File());
  1001. return;
  1002. }
  1003. if (args.contains ("--devicechangetest"))
  1004. {
  1005. // LYNX --devicechangetest report.txt [switches] [--plugin file]... (round 190c, issue #134: changing the
  1006. // output device with a project open crashed LYNX). The engine plays a project of every instrument and effect
  1007. // it can make here on stand-in devices with real callback threads, while the output device, its sample
  1008. // rate and its buffer size change the way Settings > Audio changes them (8 kHz mono to 192 kHz, buffers of
  1009. // 32 to 16384 samples, a device plugged in, the open one unplugged, one that refuses to open). After every
  1010. // change the song must sound, finite, at the new rate. No window, no real audio or MIDI device.
  1011. const auto i = args.indexOf ("--devicechangetest");
  1012. const juce::File report (args[i + 1].unquoted());
  1013. const auto switches = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  1014. juce::StringArray plugins;
  1015. for (int k = 0; k + 1 < args.size(); ++k)
  1016. if (args[k] == "--plugin")
  1017. plugins.add (args[k + 1].unquoted());
  1018. auto text = std::make_shared<juce::String>();
  1019. // --quick: the selftest's handful of instruments and effects instead of every one
  1020. const auto result = lynx::AudioEngine::deviceChangeSelfTest (switches > 0 ? switches : 40, ! args.contains ("--quick"), plugins, [report, text] (const juce::String& line) {
  1021. *text << line << "\n";
  1022. report.replaceWithText (*text + "(running)\n"); // what was reached, if it crashes
  1023. });
  1024. *text << "device_change=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1025. report.replaceWithText (*text);
  1026. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1027. quit();
  1028. return;
  1029. }
  1030. if (args.contains ("--exportlivetest"))
  1031. {
  1032. // LYNX --exportlivetest report.txt [--plugin file]... (round 190jb): exports with the live plugin instances (as
  1033. // FL renders) against playback on a stand-in device, the plugins given back afterwards. No window.
  1034. const auto i = args.indexOf ("--exportlivetest");
  1035. const juce::File report (args[i + 1].unquoted());
  1036. juce::StringArray files;
  1037. for (int k = 0; k + 1 < args.size(); ++k)
  1038. if (args[k] == "--plugin")
  1039. files.add (args[k + 1].unquoted());
  1040. juce::String text;
  1041. const auto result = lynx::AudioEngine::exportLiveSelfTest ([&text] (const juce::String& line) { text << line << "\n"; }, files);
  1042. text << "export_live=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1043. report.replaceWithText (text);
  1044. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1045. quit();
  1046. return;
  1047. }
  1048. if (args.contains ("--sharetest"))
  1049. {
  1050. // LYNX --sharetest <folder> <case> report.txt (round 190ks): the memory 8 identical SoundFont / Sampler channels
  1051. // cost (LYNX_CONTENT_SHARE=0: byte copies held separately, as before). No window.
  1052. const auto i = args.indexOf ("--sharetest");
  1053. const auto result = lynx::AudioEngine::shareMemorySelfTest (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted());
  1054. juce::File (args[i + 3].unquoted()).replaceWithText ("share=" + result + "\nresult=" + (result.startsWith ("OK") ? "OK" : "FAILED") + "\n");
  1055. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1056. quit();
  1057. return;
  1058. }
  1059. if (args.contains ("--padrectest"))
  1060. {
  1061. // LYNX --padrectest "<LYNX Test Pads.vst3>" report.txt (round 190ks, GitHub #198): a take records the notes a
  1062. // hosted plugin plays from its own window (the live engine on a stand-in device). No window.
  1063. const auto i = args.indexOf ("--padrectest");
  1064. const auto result = lynx::AudioEngine::padRecordSelfTest (args[i + 1].unquoted());
  1065. juce::File (args[i + 2].unquoted()).replaceWithText ("pad_record=" + result + "\nresult=" + (result.startsWith ("OK") ? "OK" : "FAILED") + "\n");
  1066. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1067. quit();
  1068. return;
  1069. }
  1070. if (args.contains ("--midiouttest"))
  1071. {
  1072. // LYNX --midiouttest report.txt (round 190jl): MIDI Out channels to the hardware MIDI outputs on their port
  1073. // (the sender's dry run and the live engine on a stand-in device). No window.
  1074. const auto i = args.indexOf ("--midiouttest");
  1075. const auto result = lynx::AudioEngine::midiOutPortSelfTest();
  1076. juce::File (args[i + 1].unquoted()).replaceWithText ("midi_out_ports=" + result + "\nresult=" + (result.startsWith ("OK") ? "OK" : "FAILED") + "\n");
  1077. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1078. quit();
  1079. return;
  1080. }
  1081. if (args.contains ("--aratest"))
  1082. {
  1083. // LYNX --aratest <plugin.vst3> <audio.wav> <out folder> [project.lynx] (round 190kx, engine/AraTest.cpp): ARA 2
  1084. // hosting end to end (a plain clip vs the clip in the ARA plugin, the document archived and restored). No window.
  1085. const auto i = args.indexOf ("--aratest");
  1086. const juce::File out (args[i + 3].unquoted());
  1087. juce::String text;
  1088. const auto result = lynx::araSelfTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), out,
  1089. args.size() > i + 4 ? juce::File (args[i + 4].unquoted()) : juce::File(),
  1090. [&text, out] (const juce::String& line) {
  1091. text << line << "\n";
  1092. out.getChildFile ("aratest.txt").replaceWithText (text + "(running)\n");
  1093. });
  1094. text << "ara=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1095. out.getChildFile ("aratest.txt").replaceWithText (text);
  1096. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1097. quit();
  1098. return;
  1099. }
  1100. if (args.contains ("--exportparitytest") || args.contains ("--midihotplugtest"))
  1101. {
  1102. // LYNX --exportparitytest report.txt (round 190gh, B7): the export against playback through a stand-in audio
  1103. // device, stems adding up to the mix with one length, the PDC trim. LYNX --midihotplugtest report.txt (B8):
  1104. // MIDI devices plugged in and out (stand-in device lists) while messages arrive. No window.
  1105. const auto parity = args.contains ("--exportparitytest");
  1106. const auto i = args.indexOf (parity ? "--exportparitytest" : "--midihotplugtest");
  1107. const juce::File report (args[i + 1].unquoted());
  1108. juce::String text;
  1109. const auto result = parity ? lynx::AudioEngine::exportParitySelfTest ([&text] (const juce::String& line) { text << line << "\n"; })
  1110. : lynx::AudioEngine::midiHotplugSelfTest();
  1111. text << (parity ? "export_parity=" : "midi_hotplug=") << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1112. report.replaceWithText (text);
  1113. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1114. quit();
  1115. return;
  1116. }
  1117. if (args.contains ("--shortexportstress"))
  1118. {
  1119. // LYNX --shortexportstress report.txt [count] [--seed N] [--no-realtime] [--plugin file] (round 190hn, issue #138): `count`
  1120. // random export settings over short sounds at the very start of the song, each exported again a bar later; a
  1121. // file that comes out silent or quieter fails (engine/ShortExportTest.h). No window.
  1122. const auto i = args.indexOf ("--shortexportstress");
  1123. const juce::File report (args[i + 1].unquoted());
  1124. const auto count = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 200;
  1125. const auto s = args.indexOf ("--seed");
  1126. const auto seed = s >= 0 && s + 1 < args.size() ? args[s + 1].getLargeIntValue() : juce::Time::currentTimeMillis();
  1127. auto text = std::make_shared<juce::String>();
  1128. const auto pl = args.indexOf ("--plugin");
  1129. lynx::shortexport::stress (count, seed, ! args.contains ("--no-realtime"), pl >= 0 && pl + 1 < args.size() ? args[pl + 1].unquoted() : juce::String(),
  1130. [report, text] (const juce::String& line) {
  1131. *text << line << "\n";
  1132. report.replaceWithText (*text + "(running)\n");
  1133. },
  1134. [this, report, text] (juce::String result) {
  1135. *text << "short_export_stress=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1136. report.replaceWithText (*text);
  1137. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1138. quit();
  1139. });
  1140. return;
  1141. }
  1142. if (args.contains ("--shortexporttest"))
  1143. {
  1144. // LYNX --shortexporttest report.txt [repeats] [--plugin file]... (round 190c, issue #138: a short note at
  1145. // the very start of the Playlist exported quiet). Every instrument LYNX can make here, and a synth with
  1146. // effects, tail modes, normalising and other rates, exported through the Export window's path (the job
  1147. // made on the message thread, run on its own thread, the message loop running) with a 2-second note at
  1148. // tick 0 and again with it at bar 2: the note must come out the same. No window.
  1149. const auto i = args.indexOf ("--shortexporttest");
  1150. const juce::File report (args[i + 1].unquoted());
  1151. const auto repeats = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  1152. juce::StringArray plugins;
  1153. for (int k = 0; k + 1 < args.size(); ++k)
  1154. if (args[k] == "--plugin")
  1155. plugins.add (args[k + 1].unquoted());
  1156. auto text = std::make_shared<juce::String>();
  1157. lynx::shortexport::run (! args.contains ("--quick"), repeats > 0 ? repeats : 3, plugins, // (--quick: a handful of instruments, round 190hn)
  1158. [report, text] (const juce::String& line) {
  1159. *text << line << "\n";
  1160. report.replaceWithText (*text + "(running)\n");
  1161. },
  1162. [this, report, text] (juce::String result) {
  1163. *text << "short_export=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1164. report.replaceWithText (*text);
  1165. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1166. quit();
  1167. });
  1168. return;
  1169. }
  1170. if (args.contains ("--slicexedittest"))
  1171. {
  1172. // LYNX --slicexedittest project script.txt report.txt [png-prefix] (round 190aj): the Slicex editor of the
  1173. // project's first Slicex channel, off screen, driven by the script's commands (ui/SlicexEditor.h; mouse
  1174. // gestures at fractions of the deck's width, the menu entries, shortcuts). The report holds each command
  1175. // and what the state held after it; "shot <name>" writes <png-prefix><name>.png.
  1176. const auto i = args.indexOf ("--slicexedittest");
  1177. runSlicexEditTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
  1178. args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
  1179. return;
  1180. }
  1181. if (args.contains ("--dwedittest"))
  1182. {
  1183. // LYNX --dwedittest project script.txt report.txt [png-prefix] (round 190hz): the DirectWave editor of the
  1184. // project's first DirectWave channel, off screen, driven by the script's commands (ui/DirectWaveEditor.h);
  1185. // "shot <name>" writes <png-prefix><name>.png. A project path "new" makes a new DirectWave channel.
  1186. const auto i = args.indexOf ("--dwedittest");
  1187. runDirectWaveEditTest (args[i + 1].unquoted(), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
  1188. args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
  1189. return;
  1190. }
  1191. if (args.contains ("--slicexkeytest"))
  1192. {
  1193. // LYNX --slicexkeytest report.txt (round 190ac): what a click on the Slicex editor's keyboard sends
  1194. // (AudioEngine::sendLiveNote on the channel, velocity 100/128) through the real engine's device callback
  1195. // (a stand-in device, driven block by block): the key's region must sound, on the channel's mixer meter
  1196. // too, another key must play another region, and the note-off must end it.
  1197. runSlicexKeyTest (juce::File (args[args.indexOf ("--slicexkeytest") + 1].unquoted()));
  1198. return;
  1199. }
  1200. if (args.contains ("--countinrectest"))
  1201. {
  1202. // LYNX --countinrectest report.txt (round 170d, the Busy Works video: the chord on the downbeat after the
  1203. // pre-count was lost). The real engine's device callback (a stand-in device: 48 kHz, blocks of 512, 256
  1204. // samples of output latency) records a Song-mode take from bar 3 with a 1-bar count-in. Pass 1 finds where
  1205. // the metronome's bar-3 click is heard; pass 2 plays MIDI notes stamped at the times they are heard around
  1206. // it (a chord 15 ms early, a note in the count-in, one 3 ms after beat 2, one a bar for 6 bars) through
  1207. // LYNX's MIDI input. Every note must land on the tick it was heard at (the chord on bar 3).
  1208. const auto i = args.indexOf ("--countinrectest");
  1209. runCountInRecordTest (juce::File (args[i + 1].unquoted()));
  1210. return;
  1211. }
  1212. if (args.contains ("--bendrectest"))
  1213. {
  1214. // LYNX --bendrectest report.txt [song|pattern] (round 167a, issue #12): pitch bend recording end to end. A
  1215. // controller's pitch wheel is injected into LYNX's MIDI input (as a device would send it) while recording
  1216. // plays: a held note and a wheel sweep 0 → full up → full down → centre. The recorded lane (pattern mode) or
  1217. // automation clip (song mode) of the channel's pitch bend must follow the sweep.
  1218. const auto i = args.indexOf ("--bendrectest");
  1219. const auto songMode = args.size() > i + 2 && args[i + 2] == "song";
  1220. runBendRecordTest (juce::File (args[i + 1].unquoted()), songMode);
  1221. return;
  1222. }
  1223. if (args.contains ("--rectest"))
  1224. {
  1225. // LYNX --rectest report.txt [seconds] [--type T] [--device D] [--input I] [--loop] [--buffer N]
  1226. // (round 163): records a click track through a loopback (cable, interface loopback or PipeWire's
  1227. // pw-loopback): pings the round trip, plays a click on every beat from an audio clip, records it on Insert 1,
  1228. // stops, and checks every recorded click's song position on the Playlist against its beat (samples).
  1229. // --loop: loop recording over bars 2-4 (take lanes). --punch: punch in/out on bars 3-4 with 1 bar of pre-roll
  1230. // and 1 of post-roll (playback stops by itself after the post-roll).
  1231. const auto i = args.indexOf ("--rectest");
  1232. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  1233. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  1234. runRecordTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 20.0, option ("--type"), option ("--device"), option ("--input"),
  1235. args.contains ("--loop") ? 1 : args.contains ("--punch") ? 2 : 0, option ("--pdc").getIntValue(), option ("--buffer").getIntValue());
  1236. return;
  1237. }
  1238. if (args.contains ("--hwinserttest"))
  1239. {
  1240. // LYNX --hwinserttest report.txt [seconds] [--type T] [--device D] [--input I] [--buffer N] (round 164d): a
  1241. // hardware insert through a loopback cable (output pair 1-2 -> input pair 1-2; the Master plays nowhere, so
  1242. // the cable carries the send only). The same click track plays on two inserts: Insert 1 through the
  1243. // hardware insert (panned left), Insert 2 dry (panned right). The insert's own ping measures the round
  1244. // trip, PDC delays the dry path by it, and every click of the Master's left side must sit on the same
  1245. // sample as the right side's.
  1246. const auto i = args.indexOf ("--hwinserttest");
  1247. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  1248. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 10.0;
  1249. // round 165c: --patcher puts the insert inside a Patcher on Insert 1; --bounce file.wav then exports the song in real
  1250. // time through the device (Export › "Render through the hardware in real time") and offline, and compares them
  1251. runHwInsertTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 10.0, option ("--type"), option ("--device"), option ("--input"),
  1252. option ("--buffer").getIntValue(), args.contains ("--patcher"),
  1253. args.contains ("--bounce") ? juce::File (option ("--bounce")) : juce::File());
  1254. return;
  1255. }
  1256. if (args.contains ("--uiperf"))
  1257. {
  1258. // LYNX --uiperf project.(flp|lynx) report.txt: the heavy UI cases in the real window, every frame timed (round 161)
  1259. const auto i = args.indexOf ("--uiperf");
  1260. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1261. runUiPerf (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1262. return;
  1263. }
  1264. if (args.contains ("--cachetest"))
  1265. {
  1266. // LYNX --cachetest project.(flp|lynx) report.txt (round 174f): the Playlist's cached picture against exact
  1267. // paints after zooms, scrolls and repaints, off screen (no window)
  1268. const auto i = args.indexOf ("--cachetest");
  1269. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1270. runCacheTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1271. return;
  1272. }
  1273. if (args.contains ("--picturetest"))
  1274. {
  1275. // LYNX --picturetest report.txt [project.(flp|lynx)] (round 190bm): the Playlist and the Mixer drawn through
  1276. // their cached pictures at 100-300 %, into native and software targets, against straight paints; off
  1277. // screen (no window)
  1278. const auto i = args.indexOf ("--picturetest");
  1279. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1280. runPictureTest (juce::File (args[i + 1].unquoted()), i + 2 < args.size() ? juce::File (args[i + 2].unquoted()) : juce::File());
  1281. return;
  1282. }
  1283. if (args.contains ("--paintcachetest"))
  1284. {
  1285. // LYNX --paintcachetest report.txt (round 190ki): --selftest's paint_caches item alone (the shape tiles, the
  1286. // cached FL toolbar tiles; LYNX_TILE_DEBUG=<folder> keeps the tiles' pictures as PNGs), off screen
  1287. const auto i = args.indexOf ("--paintcachetest");
  1288. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1289. auto result = lynx::theme::paintCacheSelfTest();
  1290. const auto tiles = lynx::flTileCacheSelfTest();
  1291. juce::File (args[i + 1].unquoted()).replaceWithText ("paint_caches=" + result + "\nfl_tiles=" + tiles + "\n");
  1292. setApplicationReturnValue (result.startsWith ("OK") && tiles == "OK" ? 0 : 1);
  1293. quit();
  1294. return;
  1295. }
  1296. if (args.contains ("--timertest"))
  1297. {
  1298. // LYNX --timertest report.txt (round 174f): ui::TimerWhileShowing through hide / show / minimise (opens a small window)
  1299. runTimerTest (juce::File (args[args.indexOf ("--timertest") + 1].unquoted()));
  1300. return;
  1301. }
  1302. if (args.contains ("--livepeer"))
  1303. {
  1304. // LYNX --livepeer host|guest|rejoin <folder> [--relay URL] [--code CODE|@file]: one computer's side of a live
  1305. // session between two real computers, no window (round 190ah)
  1306. setApplicationReturnValue (lynx::livetest::runPeer (args));
  1307. quit();
  1308. return;
  1309. }
  1310. if (args.contains ("--offlinetest"))
  1311. {
  1312. // LYNX --offlinetest report.txt [--offline] (round 190nx): with LYNX_OFFLINE=1 or --offline every place that
  1313. // would use the network refuses and says so. The test script runs it under `unshare -rn` with strace and counts
  1314. // the connect() calls of internet sockets: zero (tests/offline-network-test.sh)
  1315. const auto report = juce::File::getCurrentWorkingDirectory().getChildFile (args[args.indexOf ("--offlinetest") + 1].unquoted());
  1316. juce::String log;
  1317. bool ok = true;
  1318. auto check = [&] (bool good, const juce::String& what) {
  1319. ok = ok && good;
  1320. log << (good ? "ok " : "FAIL ") << what << "\n";
  1321. };
  1322. check (lynx::offline::enabled(), "offline mode is on");
  1323. {
  1324. std::string why;
  1325. check (! lynx::livelink::Connection::available (&why) && why.find ("offline") != std::string::npos, "live link unavailable: " + juce::String (why));
  1326. check (lynx::livelink::http ("GET", "https://relay.lynx-share.com/v1/health", {}, {}, "LYNX-test", 2).status == 0, "relay HTTP gives no answer, no connection tried");
  1327. }
  1328. {
  1329. lynx::AudioEngine offlineEngine (false);
  1330. lynx::LiveSessionManager live (offlineEngine);
  1331. lynx::LiveSessionManager::Options o;
  1332. o.relay = "https://relay.lynx-share.com";
  1333. o.name = "Offline test";
  1334. o.inlineWork = true;
  1335. live.start (o);
  1336. check (live.getState() == lynx::LiveSessionManager::State::ended && ! live.isActive(), "Start live session refused: " + live.getStatus());
  1337. lynx::LiveSessionManager joiner (offlineEngine);
  1338. joiner.join ("LYNX-AAAA-AAAA-AAAA-AAAA-AAAA", o);
  1339. check (joiner.getState() == lynx::LiveSessionManager::State::ended && ! joiner.isActive(), "Join live session refused: " + joiner.getStatus());
  1340. }
  1341. {
  1342. const auto err = lynx::crashreporter::sendNow ("{\"offline\":\"test\"}");
  1343. check (err.containsIgnoreCase ("offline"), "crash report upload refused: " + err);
  1344. }
  1345. lynx::updater::startAutomaticCheck();
  1346. lynx::updater::checkNow();
  1347. lynx::updater::goBack();
  1348. check (true, "update check, update dialog and go-back opened no connection (see strace)");
  1349. log << (ok ? "RESULT OK\n" : "RESULT FAIL\n");
  1350. report.replaceWithText (log);
  1351. setApplicationReturnValue (ok ? 0 : 1);
  1352. quit();
  1353. return;
  1354. }
  1355. if (args.contains ("--livetest"))
  1356. {
  1357. // LYNX --livetest report.txt [--relay URL]: a live session of four peers over the relay (round 169b)
  1358. setApplicationReturnValue (lynx::livetest::run (args));
  1359. quit();
  1360. return;
  1361. }
  1362. if (args.contains ("--selftest"))
  1363. {
  1364. const auto i = args.indexOf ("--selftest");
  1365. // round 190mo: a temp folder of this run alone (two runs at once shared the fixed temp names of its items),
  1366. // and on Linux room for its main-thread stack (it reached 7.4 of the usual 8 MB: AudioEngines on the stack)
  1367. selfTestTemp = lynx::platform::useOwnTempFolder ("lynx-selftest");
  1368. lynx::platform::allowMainThreadStack ((std::size_t) 64 << 20);
  1369. runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1370. return;
  1371. }
  1372. if (args.contains ("--scan-one"))
  1373. {
  1374. // child process of the plugin scan (see PluginHost::scan)
  1375. const auto i = args.indexOf ("--scan-one");
  1376. // no crash dialogs from the plugin being examined; and once the result is written, the process ends without
  1377. // unloading it: a Waves shell crashed in its own teardown at exit (Intel GPU driver fail-fast, 0xC0000409),
  1378. // which showed Windows' crash dialog and made the scan reject the whole shell (round 111)
  1379. lynx::crashguard::quietCrashReports();
  1380. lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
  1381. lynx::crashguard::exitNow (0);
  1382. }
  1383. if (args.contains ("--splashshot"))
  1384. {
  1385. // LYNX --splashshot <folder> (round 190hd): the splash card drawn as the JUCE card is and as the card on its own
  1386. // thread is (ui/Splash.h), side by side; no window
  1387. const auto shots = lynx::writeSplashShots (juce::File (args[args.indexOf ("--splashshot") + 1].unquoted()));
  1388. setApplicationReturnValue (shots.size() == 20 ? 0 : 1);
  1389. quit();
  1390. return;
  1391. }
  1392. if (args.contains ("--browser-indexer"))
  1393. {
  1394. // round 190hd: the Browser's indexer, a low-priority child of the LYNX window (BrowserComponent.h): no window,
  1395. // no session, no audio; it ends with its parent
  1396. lynx::crashguard::quietCrashReports();
  1397. lynx::crashguard::exitNow (lynx::BrowserComponent::runIndexerProcess (args));
  1398. }
  1399. if (args.contains ("--packageinfo"))
  1400. {
  1401. // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
  1402. // workflow runs it inside the installed test package
  1403. juce::File (args[args.indexOf ("--packageinfo") + 1].unquoted()).replaceWithText (lynx::platform::packageReport());
  1404. quit();
  1405. return;
  1406. }
  1407. if (args.contains ("--paths"))
  1408. {
  1409. // diagnostics: folders LYNX searches
  1410. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  1411. juce::String report;
  1412. report << "programs=" << programs.getFullPathName() << "\n";
  1413. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  1414. report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
  1415. juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
  1416. quit();
  1417. return;
  1418. }
  1419. if (args.contains ("--fldb"))
  1420. {
  1421. // diagnostics: LYNX.exe --fldb report.txt [project.flp]: the FL Studio installation, its plugin database,
  1422. // the suggested plugin folders and, for a project, how each of its plugins resolves (read-only)
  1423. const auto i = args.indexOf ("--fldb");
  1424. const auto fl = lynx::findFlStudio();
  1425. lynx::PluginHost host (false);
  1426. juce::String report;
  1427. report << "install=" << fl.installDir.getFullPathName() << "\nuserdata=" << fl.userData.getFullPathName() << "\n";
  1428. for (const auto& f : fl.vstFolders)
  1429. report << "flvstfolder=" << f << "\n";
  1430. report << "dbfiles=" << host.flPluginDatabaseFiles() << " entries=" << (int) host.flPluginDatabase().entries().size() << "\n";
  1431. for (const auto& e : host.flPluginDatabase().entries())
  1432. report << " entry: " << juce::String::fromUTF8 (e.name.c_str()) << " | " << juce::String::fromUTF8 (e.path.c_str()) << " | role=" << e.role << "\n";
  1433. const auto suggested = host.suggestedFolders();
  1434. for (int k = 0; k < suggested.getNumPaths(); ++k)
  1435. report << "folder=" << suggested[k].getFullPathName() << "\n";
  1436. if (const juce::File project (args[i + 2].unquoted()); project.existsAsFile())
  1437. {
  1438. juce::MemoryBlock data;
  1439. project.loadFileAsData (data);
  1440. try
  1441. {
  1442. for (const auto& use : lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })))
  1443. {
  1444. juce::String how;
  1445. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  1446. const auto* entry = host.flPluginDatabase().match (use.plugin, use.instrument);
  1447. report << "plugin: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  1448. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known"))
  1449. << (entry != nullptr ? " | fl db: " + juce::String::fromUTF8 (entry->path.c_str()) : juce::String()) << "\n";
  1450. }
  1451. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  1452. const auto candidates = host.filesToScanFor (uses);
  1453. report << "scan_candidates=" << candidates.joinIntoString (";") << "\n";
  1454. if (args.contains ("--scan"))
  1455. {
  1456. // the targeted scan an open would run (child processes; the user's plugin list is not touched)
  1457. report << "scanned_new=" << host.scanFiles (candidates, {}) << "\n";
  1458. for (const auto& use : uses)
  1459. {
  1460. juce::String how;
  1461. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  1462. report << "after_scan: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  1463. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known")) << "\n";
  1464. }
  1465. }
  1466. }
  1467. catch (const flp::Error& e)
  1468. {
  1469. report << "error=" << e.what() << "\n";
  1470. }
  1471. }
  1472. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1473. quit();
  1474. return;
  1475. }
  1476. if (args.contains ("--midisync-test"))
  1477. {
  1478. // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
  1479. const auto i = args.indexOf ("--midisync-test");
  1480. const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1481. const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1482. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
  1483. quit();
  1484. return;
  1485. }
  1486. if (args.contains ("--linktest"))
  1487. {
  1488. // LYNX --linktest report.txt [seconds] [peer] (round 190gl): Ableton Link with simulated audio callbacks; with
  1489. // "peer" a second Link peer in this process, else a peer on the network (Ableton's LinkHut) is expected
  1490. const auto i = args.indexOf ("--linktest");
  1491. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  1492. const auto ownPeer = args.contains ("peer");
  1493. juce::File (args[i + 1].unquoted()).replaceWithText (juce::String (lynx::AbletonLink::selfTest (seconds > 0.0 ? seconds : 20.0, ownPeer)));
  1494. quit();
  1495. return;
  1496. }
  1497. if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
  1498. {
  1499. // diagnostics: driver types and output devices JUCE offers (without opening any)
  1500. juce::AudioDeviceManager manager;
  1501. juce::String report;
  1502. manager.getAvailableDeviceTypes();
  1503. if (auto pipeWire = lynx::makePipeWireDeviceType()) // Linux: LYNX's own PipeWire client (round 161)
  1504. manager.addAudioDeviceType (std::move (pipeWire));
  1505. #if JUCE_LINUX
  1506. report << lynx::describePipeWire() << "\n";
  1507. #endif
  1508. for (auto* type : manager.getAvailableDeviceTypes())
  1509. {
  1510. type->scanForDevices();
  1511. report << "type=" << type->getTypeName() << "\n";
  1512. for (const auto& name : type->getDeviceNames (false))
  1513. report << " output=" << name << "\n";
  1514. for (const auto& name : type->getDeviceNames (true))
  1515. report << " input=" << name << "\n";
  1516. }
  1517. for (const auto& d : juce::MidiInput::getAvailableDevices())
  1518. report << "midi-in=" << d.name << "\n";
  1519. for (const auto& d : juce::MidiOutput::getAvailableDevices())
  1520. report << "midi-out=" << d.name << "\n";
  1521. const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
  1522. juce::File (args[flag + 1].unquoted()).replaceWithText (report);
  1523. quit();
  1524. return;
  1525. }
  1526. if (args.contains ("--devicetest"))
  1527. {
  1528. // LYNX.exe --devicetest "type" "device" report.txt ["input device"] [--buffer N] [--roundtrip]: opens that output device (and, with the
  1529. // 4th argument, an input: "*" = the same device / the driver's default input), receives 1 s of callbacks
  1530. // writing silence, closes it and reports rate, block size, latency, callbacks and the input channels with
  1531. // their peak level (driver check, no sound). --roundtrip: clicks out, found again on input 1 through a loopback
  1532. // cable / PipeWire link: the round-trip latency (3 s)
  1533. const auto i = args.indexOf ("--devicetest");
  1534. const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
  1535. auto inputName = args.size() > i + 4 && ! args[i + 4].startsWith ("--") ? args[i + 4].unquoted() : juce::String();
  1536. const auto wantInput = inputName.isNotEmpty();
  1537. juce::String report;
  1538. const juce::File reportFile (args[i + 3].unquoted());
  1539. auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
  1540. step ("step=start");
  1541. juce::AudioDeviceManager manager;
  1542. manager.getAvailableDeviceTypes();
  1543. if (auto pipeWire = lynx::makePipeWireDeviceType())
  1544. manager.addAudioDeviceType (std::move (pipeWire));
  1545. std::unique_ptr<juce::AudioIODevice> device;
  1546. for (auto* type : manager.getAvailableDeviceTypes())
  1547. if (type->getTypeName() == typeName)
  1548. {
  1549. type->scanForDevices();
  1550. if (wantInput && type->hasSeparateInputsAndOutputs())
  1551. {
  1552. const auto inputs = type->getDeviceNames (true);
  1553. if (inputName == "*" || ! inputs.contains (inputName))
  1554. {
  1555. const auto index = type->getDefaultDeviceIndex (true);
  1556. inputName = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  1557. }
  1558. for (const auto& n : inputs)
  1559. step ("input_device=" + n);
  1560. step ("input_chosen=" + inputName);
  1561. }
  1562. else if (wantInput)
  1563. inputName = deviceName;
  1564. step ("step=create");
  1565. device.reset (type->createDevice (deviceName, type->hasSeparateInputsAndOutputs() ? inputName : juce::String()));
  1566. step ("step=created");
  1567. }
  1568. struct Silence final : juce::AudioIODeviceCallback
  1569. {
  1570. std::atomic<int> calls { 0 }, inputs { 0 };
  1571. std::array<std::atomic<float>, 64> peaks {};
  1572. // --roundtrip (round 161): a click every quarter second on the outputs, found again on input 1 through a
  1573. // loopback; the delays in samples
  1574. bool roundtrip = false;
  1575. int period = 12000;
  1576. std::int64_t position = 0, lastClick = -1;
  1577. std::vector<int> delays;
  1578. void audioDeviceIOCallbackWithContext (const float* const* in, int numIn, float* const* out, int channels, int n,
  1579. const juce::AudioIODeviceCallbackContext&) override
  1580. {
  1581. for (int c = 0; c < channels; ++c)
  1582. if (out[c] != nullptr)
  1583. juce::FloatVectorOperations::clear (out[c], n);
  1584. if (roundtrip)
  1585. {
  1586. for (int i = 0; i < n; ++i)
  1587. {
  1588. if (numIn > 0 && in[0] != nullptr && lastClick >= 0 && std::abs (in[0][i]) > 0.5f)
  1589. {
  1590. if (delays.size() < delays.capacity())
  1591. delays.push_back ((int) (position + i - lastClick));
  1592. lastClick = -1;
  1593. }
  1594. if ((position + i) % period == 0 && position + i > 0)
  1595. {
  1596. for (int c = 0; c < channels; ++c)
  1597. if (out[c] != nullptr)
  1598. out[c][i] = 0.9f;
  1599. lastClick = position + i;
  1600. }
  1601. }
  1602. position += n;
  1603. }
  1604. inputs.store (numIn);
  1605. for (int c = 0; c < juce::jmin (numIn, 64); ++c)
  1606. if (in[c] != nullptr)
  1607. {
  1608. const auto range = juce::FloatVectorOperations::findMinAndMax (in[c], n);
  1609. const auto peak = juce::jmax (std::abs (range.getStart()), std::abs (range.getEnd()));
  1610. if (peak > peaks[(std::size_t) c].load())
  1611. peaks[(std::size_t) c].store (peak);
  1612. }
  1613. ++calls;
  1614. }
  1615. void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
  1616. void audioDeviceStopped() override {}
  1617. } silence;
  1618. bool ok = false;
  1619. if (device == nullptr)
  1620. step ("error=device not found");
  1621. else
  1622. {
  1623. step ("step=open");
  1624. juce::BigInteger outputs;
  1625. outputs.setRange (0, 2, true);
  1626. const auto rates = device->getAvailableSampleRates();
  1627. const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
  1628. : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
  1629. step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
  1630. juce::BigInteger inputs;
  1631. if (wantInput)
  1632. {
  1633. const auto names = device->getInputChannelNames();
  1634. step ("input_channels=" + juce::String (names.size()));
  1635. for (int c = 0; c < names.size(); ++c)
  1636. step (" in" + juce::String (c + 1) + "=" + names[c]);
  1637. inputs.setRange (0, juce::jmin (64, names.size()), true);
  1638. }
  1639. // --buffer N: ask for that block size (REA round 97 latency survey); default: the driver's default
  1640. const auto wantedBlock = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  1641. const auto error = device->open (inputs, outputs, rate, wantedBlock > 0 ? wantedBlock : device->getDefaultBufferSize());
  1642. if (error.isNotEmpty())
  1643. step ("error=" + error);
  1644. else
  1645. {
  1646. step ("step=start_callbacks");
  1647. silence.roundtrip = args.contains ("--roundtrip");
  1648. silence.period = juce::jmax (1, (int) (rate / 4));
  1649. silence.delays.reserve (64);
  1650. device->start (&silence);
  1651. juce::Thread::sleep (silence.roundtrip ? 3000 : 1000);
  1652. device->stop();
  1653. if (silence.roundtrip)
  1654. {
  1655. auto d = silence.delays;
  1656. std::sort (d.begin(), d.end());
  1657. report << "roundtrip_clicks=" << (int) d.size() << "\n";
  1658. if (! d.empty())
  1659. report << "roundtrip_samples=min " << d.front() << " median " << d[d.size() / 2] << " max " << d.back() << "\n"
  1660. << "roundtrip_ms=" << juce::String (1000.0 * d[d.size() / 2] / device->getCurrentSampleRate(), 2) << "\n";
  1661. }
  1662. report << "rate=" << device->getCurrentSampleRate() << "\n"
  1663. << "block=" << device->getCurrentBufferSizeSamples() << "\n"
  1664. << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
  1665. << "callbacks=" << silence.calls.load() << "\n";
  1666. if (wantInput)
  1667. {
  1668. report << "input_latency=" << device->getInputLatencyInSamples() << "\n"
  1669. << "active_inputs=" << device->getActiveInputChannels().countNumberOfSetBits() << "\n"
  1670. << "callback_inputs=" << silence.inputs.load() << "\n";
  1671. for (int c = 0; c < juce::jmin (64, silence.inputs.load()); ++c)
  1672. report << " peak_in" << (c + 1) << "=" << juce::Decibels::gainToDecibels (silence.peaks[(std::size_t) c].load(), -150.0f) << " dB\n";
  1673. }
  1674. ok = silence.calls.load() > 0 && (! wantInput || silence.inputs.load() > 0);
  1675. device->close();
  1676. }
  1677. }
  1678. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  1679. setApplicationReturnValue (ok ? 0 : 1);
  1680. quit();
  1681. return;
  1682. }
  1683. if (args.contains ("--pickertime"))
  1684. {
  1685. // LYNX.exe --pickertime report.txt (issue #209): the plugin lists' opening times with the profile's plugin
  1686. // list (LYNX_PROFILE_MAIN samples the message thread meanwhile)
  1687. const auto i = args.indexOf ("--pickertime");
  1688. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1689. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  1690. lynx::crashguard::startMainProfiler (profile.toStdString());
  1691. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1692. lynx::AudioEngine offline (false);
  1693. const auto engineMs = juce::Time::getMillisecondCounterHiRes() - t0;
  1694. const auto report = "engine_ms=" + juce::String (engineMs) + "\n" + lynx::pluginPickerTimings (offline);
  1695. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1696. lynx::crashguard::stopMainProfiler();
  1697. setApplicationReturnValue (0);
  1698. quit();
  1699. return;
  1700. }
  1701. if (args.contains ("--plusmenutime"))
  1702. {
  1703. // LYNX --plusmenutime report.txt [watched] (round 190mf): the Channel rack "+" menu's build time (as
  1704. // showAddChannelMenu builds it, without showing it) with the profile's plugin list and Plugin database
  1705. // folder: the first one, then each one after the old two-second throttle ran out; then one after the
  1706. // folder was marked changed. "watched": as the app (a folder watcher), else as before round 190mf.
  1707. const auto i = args.indexOf ("--plusmenutime");
  1708. const auto watched = i + 2 < args.size() && args[i + 2] == "watched";
  1709. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1710. lynx::AudioEngine offline (false);
  1711. lynx::quickpick::installPluginDatabase (offline);
  1712. std::unique_ptr<lynx::folderwatch::Watcher> watcher;
  1713. if (watched)
  1714. {
  1715. const auto root = lynx::quickpick::pluginDatabaseFolder();
  1716. watcher = std::make_unique<lynx::folderwatch::Watcher> (
  1717. std::vector<std::string> { root.getChildFile ("Effects").getFullPathName().toStdString(), root.getChildFile ("Generators").getFullPathName().toStdString() },
  1718. [] { juce::MessageManager::callAsync ([] { lynx::quickpick::markPluginDatabaseChanged(); }); });
  1719. lynx::quickpick::setPluginDatabaseWatched (true);
  1720. }
  1721. juce::String report;
  1722. report << "types=" << offline.getPluginHost().getKnownPlugins().getNumTypes() << " watched=" << (watched ? 1 : 0) << "\n";
  1723. auto build = [&offline] (int& items) {
  1724. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1725. juce::PopupMenu menu;
  1726. auto picks = lynx::quickpick::renamedGenerators (offline, [] (lynx::ChannelDef) {});
  1727. lynx::quickpick::addPicks (menu, picks);
  1728. lynx::quickpick::addGeneratorMenu (menu, offline, [] (lynx::ChannelDef) {}, [] {}, nullptr, nullptr);
  1729. lynx::quickpick::addFolderViewItems (menu, offline);
  1730. items = menu.getNumItems();
  1731. return juce::Time::getMillisecondCounterHiRes() - t0;
  1732. };
  1733. auto line = [&report, &build] (const juce::String& what) {
  1734. const auto readsBefore = lynx::quickpick::lastRefreshTimes().reads;
  1735. int items = 0;
  1736. const auto ms = build (items);
  1737. const auto t = lynx::quickpick::lastRefreshTimes();
  1738. const auto read = t.reads != readsBefore;
  1739. report << what << " menu_ms=" << juce::String (ms, 2) << " items=" << items << " folder_read=" << (read ? 1 : 0);
  1740. if (read)
  1741. report << " list_ms=" << juce::String (t.listMs, 2) << " read_ms=" << juce::String (t.readMs, 2);
  1742. report << "\n";
  1743. };
  1744. line ("first");
  1745. for (int k = 1; k <= 5; ++k)
  1746. {
  1747. juce::Thread::sleep (2100);
  1748. line ("again" + juce::String (k));
  1749. }
  1750. for (int k = 1; k <= 3; ++k)
  1751. line ("quick" + juce::String (k));
  1752. lynx::quickpick::markPluginDatabaseChanged();
  1753. line ("marked");
  1754. line ("after");
  1755. lynx::quickpick::setPluginDatabaseWatched (false);
  1756. watcher.reset();
  1757. lynx::plugindb::finishInstalledWrites();
  1758. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1759. setApplicationReturnValue (0);
  1760. quit();
  1761. return;
  1762. }
  1763. if (args.contains ("--scantest"))
  1764. {
  1765. // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
  1766. const auto i = args.indexOf ("--scantest");
  1767. lynx::PluginHost host (false);
  1768. const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
  1769. juce::String report;
  1770. report << "found=" << found << "\n";
  1771. for (const auto& t : host.getKnownPlugins().getTypes())
  1772. report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
  1773. for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
  1774. report << " blacklisted: " << f << "\n";
  1775. juce::File (args[i + 2].unquoted()).replaceWithText (report);
  1776. setApplicationReturnValue (found > 0 ? 0 : 1);
  1777. quit();
  1778. return;
  1779. }
  1780. if (args.contains ("--wrappermiditest"))
  1781. {
  1782. // LYNX.exe --wrappermiditest plugin.dll report.txt (round 181c), with LYNX_TEST_VST2_MIDILOG set: what a
  1783. // hosted plugin receives after a wrapper MIDI option changes while it runs
  1784. const auto i = args.indexOf ("--wrappermiditest");
  1785. runWrapperMidiTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1786. return;
  1787. }
  1788. if (args.contains ("--wrappershot190oh"))
  1789. {
  1790. // LYNX --wrappershot190oh plugin <folder> [--open] (round 190oh, P3: FL's wrapper Settings › GUI): the
  1791. // plugin (any format; an effect on insert 1) and its wrapper Settings tab drawn offscreen at 100 % and 150 %,
  1792. // with FL's defaults and with "DPI aware" off + "Scale editor dimensions" on; --open also opens its editor
  1793. // with each setting (a real window: Windows reports the editor windows' DPI awareness) -> report.txt
  1794. const auto i = args.indexOf ("--wrappershot190oh");
  1795. runWrapperShot190oh (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--open"));
  1796. return;
  1797. }
  1798. if (args.contains ("--hotfixui190qp"))
  1799. {
  1800. // LYNX --hotfixui190qp <prefix> [--plugin file]... (hotfix 0.1.31.1, round 190qp): the Clip-launch Arrangement's
  1801. // track selection reaching the Device View, and channel / plugin windows opened and closed again and again
  1802. // (src/HotfixUi190qp.inc); <prefix>-checks.txt, result=OK
  1803. const auto i = args.indexOf ("--hotfixui190qp");
  1804. juce::StringArray plugins;
  1805. for (int k = 0; k + 1 < args.size(); ++k)
  1806. if (args[k] == "--plugin")
  1807. plugins.add (args[k + 1].unquoted());
  1808. runHotfixUi190qp (args[i + 1].unquoted(), plugins);
  1809. return;
  1810. }
  1811. if (args.contains ("--pertabshot259"))
  1812. {
  1813. // LYNX --pertabshot259 <prefix> [--plugin file]... [--shot-scale 1.5 --shot-suffix @150] (round 190pw, PR #259:
  1814. // channel and plugin windows the size of the tab they show): src/PerTabShot259.inc
  1815. const auto i = args.indexOf ("--pertabshot259");
  1816. juce::StringArray plugins;
  1817. for (int k = 0; k + 1 < args.size(); ++k)
  1818. if (args[k] == "--plugin")
  1819. plugins.add (args[k + 1].unquoted());
  1820. runPerTabShot259 (args[i + 1].unquoted(), plugins);
  1821. return;
  1822. }
  1823. if (args.contains ("--wrappershot"))
  1824. {
  1825. const auto i = args.indexOf ("--wrappershot");
  1826. runWrapperShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1827. return;
  1828. }
  1829. if (args.contains ("--multiouttest"))
  1830. {
  1831. const auto i = args.indexOf ("--multiouttest");
  1832. runMultiOutTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1833. return;
  1834. }
  1835. if (args.contains ("--vstitest"))
  1836. {
  1837. // LYNX --vstitest plugin folder [project.lynx] (round 190fw, issue #162): an instrument plugin (Image-Line's
  1838. // "FL Studio VSTi") on a channel: notes in, audio out, its state through a saved project, its outputs and
  1839. // the host tempo it follows. See runVstiTest.
  1840. const auto i = args.indexOf ("--vstitest");
  1841. const auto project = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1842. runVstiTest (args[i + 1].unquoted(), args[i + 2].unquoted(), project);
  1843. return;
  1844. }
  1845. if (args.contains ("--vst2test"))
  1846. {
  1847. const auto i = args.indexOf ("--vst2test");
  1848. runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
  1849. return;
  1850. }
  1851. if (args.contains ("--issuesshot190qr"))
  1852. {
  1853. // --issuesshot190qr <prefix> (round 190qr, issues #274-#281): src/IssuesShot190qr.inc
  1854. setApplicationReturnValue (runIssuesShot190qr (args[args.indexOf ("--issuesshot190qr") + 1].unquoted()) ? 0 : 1);
  1855. quit();
  1856. return;
  1857. }
  1858. if (args.contains ("--issuesshot190ll"))
  1859. {
  1860. // --issuesshot190ll <prefix> (round 190ll, issues #200 / #203): src/IssuesShot190ll.inc
  1861. setApplicationReturnValue (runIssuesShot190ll (args[args.indexOf ("--issuesshot190ll") + 1].unquoted()) ? 0 : 1);
  1862. quit();
  1863. return;
  1864. }
  1865. if (args.contains ("--hostplaytest190ll"))
  1866. {
  1867. // LYNX --hostplaytest190ll report.txt "<LYNX Test Synth.vst3>" [--buffer N] (round 190ll, issue #199): src/HostPlay190ll.inc
  1868. const auto i = args.indexOf ("--hostplaytest190ll");
  1869. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 1024;
  1870. runHostPlayTest190ll (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), juce::jlimit (16, 4096, buffer));
  1871. return;
  1872. }
  1873. if (args.contains ("--vst3noteidtest"))
  1874. {
  1875. const auto i = args.indexOf ("--vst3noteidtest");
  1876. runVst3NoteIdTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1877. return;
  1878. }
  1879. if (args.contains ("--lv2scantest"))
  1880. {
  1881. runLv2ScanTest (args[args.indexOf ("--lv2scantest") + 1].unquoted());
  1882. return;
  1883. }
  1884. if (args.contains ("--wrappertest"))
  1885. {
  1886. const auto i = args.indexOf ("--wrappertest");
  1887. runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1888. return;
  1889. }
  1890. if (args.contains ("--plugintest"))
  1891. {
  1892. const auto i = args.indexOf ("--plugintest");
  1893. // optional 3rd argument: the plugin's name inside a shell (e.g. "CLA-2A Stereo" in a WaveShell)
  1894. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1895. runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  1896. return;
  1897. }
  1898. if (args.contains ("--crashguardtest"))
  1899. {
  1900. // LYNX --crashguardtest "LYNX Test Crash.vst3|.clap" report.txt [process|memcpy] (round 190dt,
  1901. // tools/testplugin/lynx_test_crash*.{c,cpp}): the plugin crashes in its 40th block on insert 1; LYNX must
  1902. // catch it, mark the slot, keep playing the other inserts, save the project, reload the plugin; then the
  1903. // saved project opens with the plugin crashing on its state; and LYNX's own faults are still crashes
  1904. const auto i = args.indexOf ("--crashguardtest");
  1905. runCrashGuardTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1906. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("process"));
  1907. return;
  1908. }
  1909. if (args.contains ("--claprestarttest"))
  1910. {
  1911. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c)
  1912. const auto i = args.indexOf ("--claprestarttest");
  1913. runClapRestartTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1914. return;
  1915. }
  1916. if (args.contains ("--multieditor255test"))
  1917. {
  1918. // LYNX --multieditor255test report.txt <plugin>[::Name] ... (round 190ou, issue #255): several plugin editors open
  1919. // and in use while a keyboard plays; the audio must keep running (src/MultiEditor255Test.inc)
  1920. const auto i = args.indexOf ("--multieditor255test");
  1921. juce::StringArray plugins;
  1922. for (int k = i + 2; k < args.size() && ! args[k].startsWith ("--"); ++k)
  1923. plugins.add (args[k].unquoted());
  1924. runMultiEditor255Test (args[i + 1].unquoted(), plugins);
  1925. return;
  1926. }
  1927. if (args.contains ("--issue258test"))
  1928. {
  1929. // LYNX --issue258test report.txt (round 190pv, issue #258): a cloned channel's own automation clip drives its
  1930. // sound, through the app's engine with render-ahead off and on (src/Issue258Test.inc; Transistor Bass needs
  1931. // FL Studio, LYNX_FL_INSTALL on Linux)
  1932. runIssue258Test (args[args.indexOf ("--issue258test") + 1].unquoted());
  1933. return;
  1934. }
  1935. if (args.contains ("--autolive190qp"))
  1936. {
  1937. // LYNX --autolive190qp <project.flp|.lynx> report.txt [--per-kind N] [--all-modes] (round 190qp, issue #253): the
  1938. // project's automated mixer volumes, send levels and effect parameters heard and shown through the app's engine
  1939. // (src/Hotfix190qpTest.inc)
  1940. const auto i = args.indexOf ("--autolive190qp");
  1941. const auto perKind = args.contains ("--per-kind") ? args[args.indexOf ("--per-kind") + 1].getIntValue() : 2;
  1942. runAutoLive190qpTest (args[i + 1].unquoted(), args[i + 2].unquoted(), perKind, args.contains ("--all-modes"));
  1943. return;
  1944. }
  1945. if (args.contains ("--feel190qetest"))
  1946. {
  1947. // LYNX --feel190qetest report.txt [shot prefix [project]] (round 190qe, TOP-NEXT R1): edge scroll, view stack, zoom
  1948. // glide and anchor, Restore selection, Keep labels on screen, off screen (src/Feel190qeTest.inc)
  1949. const auto i = args.indexOf ("--feel190qetest");
  1950. const auto arg = [&args] (int k) { return k < args.size() && ! args[k].startsWith ("--") ? args[k].unquoted() : juce::String(); };
  1951. setApplicationReturnValue (runFeel190qeTest (arg (i + 1), arg (i + 2), arg (i + 3)) ? 0 : 1);
  1952. quit();
  1953. return;
  1954. }
  1955. if (args.contains ("--qa190rfchild"))
  1956. {
  1957. // LYNX --qa190rfchild exit|display <folder> (round 190rf; --qa190rbtest starts it): a process with the hang
  1958. // watch's thread running that ends through exit() ("exit": exit code 3 expected; the static hang watch's
  1959. // destructor called std::terminate before) or whose display connection breaks ("display", Linux: exit code 1
  1960. // through crashguard::watchDisplayConnection, its session file names the lost display)
  1961. const auto i = args.indexOf ("--qa190rfchild");
  1962. const auto mode = args[i + 1];
  1963. const juce::File folder (args[i + 2].unquoted());
  1964. folder.createDirectory();
  1965. lynx::crashguard::beginSession (folder.getChildFile ("session.txt").getFullPathName().toStdString(), "LYNX session\n");
  1966. lynx::crashguard::startHangWatch (folder.getFullPathName().toStdString());
  1967. if (mode == "exit")
  1968. std::exit (3);
  1969. #if JUCE_LINUX
  1970. if (mode == "display")
  1971. if (auto* xlib = dlopen ("libX11.so.6", RTLD_LAZY | RTLD_LOCAL))
  1972. {
  1973. using OpenDisplay = void* (*) (const char*);
  1974. using ConnectionNumber = int (*) (void*);
  1975. using Sync = int (*) (void*, int);
  1976. const auto open = (OpenDisplay) dlsym (xlib, "XOpenDisplay");
  1977. const auto number = (ConnectionNumber) dlsym (xlib, "XConnectionNumber");
  1978. const auto sync = (Sync) dlsym (xlib, "XSync");
  1979. if (auto* display = open != nullptr && number != nullptr && sync != nullptr ? open (nullptr) : nullptr)
  1980. {
  1981. lynx::crashguard::watchDisplayConnection (nullptr);
  1982. ::shutdown (number (display), SHUT_RDWR); // (the server "went away")
  1983. sync (display, 0);
  1984. }
  1985. }
  1986. #endif
  1987. std::_Exit (2); // (not reached when the display part ran)
  1988. }
  1989. if (args.contains ("--qa190rbtest"))
  1990. {
  1991. // LYNX --qa190rbtest report.txt (round 190rb, the 0.1.32 quality round's crash / memory fixes; also in
  1992. // --selftest): src/Qa190rbCheck.inc
  1993. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1994. juce::String log;
  1995. const auto result = qa190rbCheck (log);
  1996. juce::File (args[args.indexOf ("--qa190rbtest") + 1].unquoted()).replaceWithText (log + "qa190rb=" + result + "\n");
  1997. setApplicationReturnValue (result == "OK" ? 0 : 1);
  1998. quit();
  1999. return;
  2000. }
  2001. if (args.contains ("--issues190qrtest"))
  2002. {
  2003. // LYNX --issues190qrtest report.txt (round 190qr, issues #274-#281; also in --selftest): src/Issues190qrCheck.inc
  2004. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2005. juce::String log;
  2006. const auto result = issues190qrCheck (log);
  2007. juce::File (args[args.indexOf ("--issues190qrtest") + 1].unquoted()).replaceWithText (log + "issues190qr=" + result + "\n");
  2008. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2009. quit();
  2010. return;
  2011. }
  2012. if (args.contains ("--hwheel254test"))
  2013. {
  2014. // LYNX --hwheel254test report.txt (round 190ou, issue #254): the horizontal wheel in the Playlist (three layouts),
  2015. // Piano roll, Mixer and Browser, off screen (src/HWheel254Test.inc)
  2016. const auto i = args.indexOf ("--hwheel254test");
  2017. setApplicationReturnValue (runHWheel254Test (args[i + 1].unquoted()) ? 0 : 1);
  2018. quit();
  2019. return;
  2020. }
  2021. if (args.contains ("--determinismtest190po"))
  2022. {
  2023. // LYNX --determinismtest190po report.txt (round 190po, engine/Determinism190poTest.cpp): a render is the same
  2024. // bit for bit on one thread and on several, and two exports have one hash (Windows: the x87 precision)
  2025. const auto i = args.indexOf ("--determinismtest190po");
  2026. juce::String lines;
  2027. const auto result = lynx::determinism190po::check ([&lines] (const juce::String& line) { lines << line << "\n"; });
  2028. juce::File (args[i + 1].unquoted()).replaceWithText (lines + "determinism190po=" + result + "\n");
  2029. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  2030. quit();
  2031. return;
  2032. }
  2033. if (args.contains ("--renderagaintest"))
  2034. {
  2035. // LYNX --renderagaintest report.txt (round 190ou, engine/RenderAgainTest.cpp): offline renders made again
  2036. const auto i = args.indexOf ("--renderagaintest");
  2037. juce::String lines;
  2038. const auto result = lynx::renderagain::check ([&lines] (const juce::String& line) { lines << line << "\n"; });
  2039. juce::File (args[i + 1].unquoted()).replaceWithText (lines + "renderagain190ou=" + result + "\n");
  2040. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  2041. quit();
  2042. return;
  2043. }
  2044. if (args.contains ("--jsfxtest") || args.contains ("--jsfxbench"))
  2045. {
  2046. // LYNX --jsfxtest <folder>: the JSFX format end to end (round 190pj, issue #241; also in --selftest), report in
  2047. // <folder>/jsfx-selftest.txt. LYNX --jsfxbench <out.txt>: CPU per instance of every bundled script.
  2048. const auto test = args.contains ("--jsfxtest");
  2049. const auto i = args.indexOf (test ? "--jsfxtest" : "--jsfxbench");
  2050. const juce::File out (args[i + 1].unquoted());
  2051. juce::String result;
  2052. if (test)
  2053. {
  2054. out.createDirectory();
  2055. result = lynx::jsfx::selfTest (out);
  2056. out.getChildFile ("report.txt").replaceWithText ("jsfx190pj=" + result + "\n");
  2057. }
  2058. else
  2059. result = lynx::jsfx::bench (out);
  2060. std::cout << result << std::endl;
  2061. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  2062. quit();
  2063. return;
  2064. }
  2065. if (args.contains ("--clapteardowntest"))
  2066. {
  2067. // LYNX.exe --clapteardowntest "LYNX Test Restart.clap" report.txt (round 190az, engine/ClapTeardownTest.cpp)
  2068. const auto i = args.indexOf ("--clapteardowntest");
  2069. lynx::runClapTeardownTest (args[i + 1].unquoted(), args[i + 2].unquoted(), [this] (int code) {
  2070. setApplicationReturnValue (code);
  2071. quit();
  2072. });
  2073. return;
  2074. }
  2075. if (args.contains ("--mpetest"))
  2076. {
  2077. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108)
  2078. const auto i = args.indexOf ("--mpetest");
  2079. runMpeTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  2080. return;
  2081. }
  2082. if (args.contains ("--mpeplaytest190hy"))
  2083. {
  2084. // LYNX --mpeplaytest190hy plugin.(clap|vst3) report.txt (round 190hy, issue #108): a song note with a pitch
  2085. // curve played by a hosted plugin with MPE on, through the whole song path (scheduler, renderer, the wrapper's
  2086. // MPE / CLAP note expressions), rendered offline; the pitch heard is measured (report.txt, report.wav)
  2087. const auto i = args.indexOf ("--mpeplaytest190hy");
  2088. runMpePlayTest190hy (args[i + 1].unquoted(), args[i + 2].unquoted());
  2089. return;
  2090. }
  2091. if (args.contains ("--editortest"))
  2092. {
  2093. // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
  2094. // seconds, then closes it (a plugin whose UI crashes the host ends the process before the report says OK)
  2095. const auto i = args.indexOf ("--editortest");
  2096. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2097. runEditorTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  2098. return;
  2099. }
  2100. if (args.contains ("--editorcrashtest"))
  2101. {
  2102. // LYNX.exe --editorcrashtest "LYNX Test Crash.clap" report.txt (issue #32, round 174a; Windows): the test
  2103. // plugin's editor faults in its own window procedure (LYNX_TEST_CRASH=editor). LYNX must catch it, close
  2104. // that editor, record the trace and keep running its message loop.
  2105. const auto i = args.indexOf ("--editorcrashtest");
  2106. runEditorCrashTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  2107. return;
  2108. }
  2109. if (args.contains ("--reloadtest"))
  2110. {
  2111. // LYNX --reloadtest plugin report.txt [shots folder] [--wait-kill]: round 190ao (reload a crashed plugin).
  2112. // Hosts the plugin in a separate process (a channel for an instrument, insert 1 for an effect) in an offline
  2113. // engine, crashes its process (--wait-kill: writes <report>.pid and waits for the process to be killed
  2114. // from outside), checks that nothing reloads by itself, reloads it on request and checks the new process,
  2115. // the state captured last, the untouched song and undo history; twice. With a shots folder: PNGs of the
  2116. // plugin window's crash notice and of the prompt.
  2117. const auto i = args.indexOf ("--reloadtest");
  2118. runReloadTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  2119. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String(), args.contains ("--wait-kill"));
  2120. return;
  2121. }
  2122. if (args.contains ("--pluginoptionstest"))
  2123. {
  2124. // LYNX --pluginoptionstest plugin report.txt [shots folder]: round 190ao. Hosts the plugin inside LYNX (a
  2125. // channel for an instrument, insert 1 for an effect) in an offline engine, opens its window and checks
  2126. // LYNX's own plugin-window options: Pin on top (set, kept above another window, saved with the plugin,
  2127. // back when the window opens again). With a shots folder: PNGs of each state. The window is on screen.
  2128. const auto i = args.indexOf ("--pluginoptionstest");
  2129. runPluginOptionsTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  2130. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String());
  2131. return;
  2132. }
  2133. if (args.contains ("--plugwintest"))
  2134. {
  2135. // LYNX --plugwintest plugin report.txt ["name"] [seconds]: round 162d. Puts the plugin in a channel (an
  2136. // instrument) or on insert 1 (an effect) of an offline engine, opens its plugin window (wrapper header,
  2137. // presets), checks a preset round trip, keeps the window `seconds` on screen (default 15: time for xdotool /
  2138. // screenshots), then removes the plugin from the song and reports whether its window closed by itself.
  2139. const auto i = args.indexOf ("--plugwintest");
  2140. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") && ! args[i + 3].containsOnly ("0123456789") ? args[i + 3].unquoted() : juce::String();
  2141. auto seconds = 15;
  2142. for (int k = i + 3; k < juce::jmin (args.size(), i + 5); ++k)
  2143. if (args[k].containsOnly ("0123456789"))
  2144. seconds = args[k].getIntValue();
  2145. runPlugWinTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only, seconds);
  2146. return;
  2147. }
  2148. if (args.contains ("--zorder191test"))
  2149. {
  2150. // LYNX --zorder191test report.txt [plugin.vst3]: issue #191 (round 190mx), ui/ZOrder191Test.h
  2151. const auto i = args.indexOf ("--zorder191test");
  2152. const auto plugin = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2153. lynx::runZOrder191Test (args[i + 1].unquoted(), plugin, &lookAndFeel, [this] (bool ok) {
  2154. setApplicationReturnValue (ok ? 0 : 1);
  2155. quit();
  2156. });
  2157. return;
  2158. }
  2159. if (args.contains ("--fittest"))
  2160. {
  2161. // LYNX.exe --fittest report.txt [percent]: round 163 — at that UI zoom (default 150) a window taller than
  2162. // the screen and a big resizable window that grows with a zoom change keep their title bar and close
  2163. // button on the screen. The windows show for about two seconds.
  2164. const auto i = args.indexOf ("--fittest");
  2165. runFitTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].getIntValue() : 150);
  2166. return;
  2167. }
  2168. if (args.contains ("--windowtest"))
  2169. {
  2170. // LYNX.exe --windowtest report.txt: opens the Quick-add palette, the Audio editor, a plugin-like window and a name dialog
  2171. // over the main window and checks that each one stays in front, owned by the main window, with the
  2172. // keyboard focus (issue #4). The windows appear on screen for a few seconds.
  2173. runWindowTest (args[args.indexOf ("--windowtest") + 1].unquoted());
  2174. return;
  2175. }
  2176. if (args.contains ("--minimizeclicktest"))
  2177. {
  2178. // LYNX --minimizeclicktest report.txt (issue #188, round 190ir): a tool window over the main window is
  2179. // minimised (through the window manager), the main window comes to the front, and a click where the tool
  2180. // window was must reach the main window's component. Run it under a window manager (openbox on a private
  2181. // Xvfb); exit code 0 = OK.
  2182. runMinimizeClickTest (args[args.indexOf ("--minimizeclicktest") + 1].unquoted());
  2183. return;
  2184. }
  2185. if (args.contains ("--focustest"))
  2186. {
  2187. // LYNX --focustest report.txt (issue #161): the main window with the Playlist and the Piano roll (native
  2188. // child windows with docking on). For each: LYNX goes to the background (the main window loses the focus),
  2189. // the user comes back with a click in the panel, then presses Space: playback must start. Also: a text
  2190. // field's focus comes back with the window, and inside the active window the click's answer is unchanged.
  2191. // Shows a window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  2192. runFocusTest (args[args.indexOf ("--focustest") + 1].unquoted());
  2193. return;
  2194. }
  2195. if (args.contains ("--simplekeytest"))
  2196. {
  2197. // LYNX --simplekeytest report.txt (round 190fc, 0.1.27 RC H2): the main window in the Simple layout; after a
  2198. // demo opened from Welcome › Start from and after clicks in the dock, its tabs, the Lyrics button, a track
  2199. // header and the grid, Space must start playback (a text field clicked into keeps its typing keys). Shows a
  2200. // window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  2201. runSimpleKeyTest (args[args.indexOf ("--simplekeytest") + 1].unquoted());
  2202. return;
  2203. }
  2204. if (args.contains ("--pluginstyle")) // round 126: force one style for this run (glow, neon, hardware, vivid; auto = per plugin)
  2205. {
  2206. const auto i = args.indexOf ("--pluginstyle");
  2207. if (i + 1 < args.size())
  2208. {
  2209. const auto name = args[i + 1].unquoted();
  2210. lynx::skin::setForcedStyle (name.equalsIgnoreCase ("auto") ? -1 : (int) lynx::skin::styleFromName (name));
  2211. }
  2212. }
  2213. if (args.contains ("--gfxprobe"))
  2214. {
  2215. // LYNX.exe --gfxprobe report.txt (round 170c, issue #11): renderer checks on this platform's native images —
  2216. // text drawn with a gradient fill (a word with a space in it) and an empty path filled with a gradient must
  2217. // stay inside their shapes. JUCE 8.0.4's CoreGraphics renderer (macOS) clipped to an empty glyph or path as
  2218. // "no clip" and flooded the whole component (Facet EQ's blank pink window).
  2219. const auto i = args.indexOf ("--gfxprobe");
  2220. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::skin::rendererProbeReport());
  2221. quit();
  2222. return;
  2223. }
  2224. if (args.contains ("--steppertest"))
  2225. {
  2226. // LYNX.exe --steppertest <report.txt>: round 170c (#14) — every value stepper of every generated effect editor
  2227. // driven by synthetic input (arrows, click on the value, drag, wheel, trackpad); ends with result=OK / FAIL
  2228. const auto i = args.indexOf ("--steppertest");
  2229. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2230. juce::String report;
  2231. int fails = 0, count = 0, skips = 0;
  2232. {
  2233. lynx::AudioEngine offline (false);
  2234. auto kinds = lynx::plugui::flLayoutKinds();
  2235. for (const auto own : lynx::plugui::ownLayoutKinds())
  2236. kinds.push_back (own);
  2237. // FL's Default preset when the installation has one (the state-backed controls need FL's state)
  2238. const auto roots = lynx::findFlStudioRoots();
  2239. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  2240. for (const auto kind : kinds)
  2241. {
  2242. auto fx = lynx::makeEffectSlot (kind);
  2243. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  2244. {
  2245. juce::MemoryBlock data;
  2246. const auto file = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str())).getChildFile ("Default.fst");
  2247. if (file.existsAsFile() && file.loadFileAsData (data))
  2248. {
  2249. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  2250. if (auto loaded = lynx::effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), 130.0, lynx::natives::flDataReader (lynx::flStudioAccess())); loaded && loaded->kind == kind)
  2251. fx = *loaded;
  2252. }
  2253. break;
  2254. }
  2255. lynx::Song song;
  2256. song.mixer.resize (2);
  2257. song.mixer[0].name = "Master";
  2258. song.mixer[1].name = "Insert 1";
  2259. song.mixer[1].effects.push_back (fx);
  2260. offline.setSong (std::move (song));
  2261. offline.dispatchPendingMessages();
  2262. const auto lines = lynx::stepperSelfTest (offline, 1, 0, (int) lynx::plugui::layoutFor (kind).pages.size());
  2263. for (const auto& line : juce::StringArray::fromLines (lines))
  2264. if (line.isNotEmpty())
  2265. {
  2266. ++count;
  2267. fails += line.contains (": FAIL") ? 1 : 0;
  2268. skips += line.contains (": SKIP") ? 1 : 0;
  2269. }
  2270. report << lines;
  2271. juce::PopupMenu::dismissAllActiveMenus();
  2272. offline.dispatchPendingMessages();
  2273. }
  2274. }
  2275. report << "steppers=" << count << " failures=" << fails << " skipped=" << skips << "\nresult=" << (fails == 0 && count > 0 ? "OK" : "FAIL") << "\n";
  2276. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  2277. quit();
  2278. return;
  2279. }
  2280. if (args.contains ("--design190inshot"))
  2281. {
  2282. // LYNX --design190inshot prefix [project.flp]: round 190in off screen (no desktop window, no audio device) —
  2283. // the channel window as it shows docked (FL's ▸, two-tone title, presets in the title bar, the 46 px strip
  2284. // with icon tabs, LED, knobs, RANGE / TRACK badges) on each tab, the floating strip, and FL's ▸ menu
  2285. const auto i = args.indexOf ("--design190inshot");
  2286. runDesign190inShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String());
  2287. quit();
  2288. return;
  2289. }
  2290. if (args.contains ("--plugui"))
  2291. {
  2292. // LYNX.exe --plugui <folder>: the native effect editors at FL's size (one PNG per editor and page), each
  2293. // loaded with the FL plugin's Default preset when the FL installation has one
  2294. const auto i = args.indexOf ("--plugui");
  2295. runPluginEditorSnapshots (args[i + 1].unquoted());
  2296. return;
  2297. }
  2298. if (args.contains ("--parityshot"))
  2299. {
  2300. // LYNX.exe --parityshot <out.png> <effect name> [<params file>]: one built-in effect's editor with the given
  2301. // parameters ("index value" lines, tools/fxrender --dump), its displays fed by the demo song — the LYNX side
  2302. // of the third-party parity pictures (round tp172b)
  2303. const auto i = args.indexOf ("--parityshot");
  2304. runParityShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  2305. if (parityShotFailed)
  2306. setApplicationReturnValue (2);
  2307. if (parityShow == nullptr)
  2308. quit();
  2309. return;
  2310. }
  2311. if (args.contains ("--design168rshot"))
  2312. {
  2313. // LYNX.exe --design168rshot <folder>: round 168r's editors (FL effects that had a generated page and LYNX's own
  2314. // simple built-ins) at 100 % and 200 %, with their default settings and, when they have one, the first
  2315. // preset of LYNX's own bank. "--design168rshot <folder> generated": the generated pages they had before
  2316. const auto i = args.indexOf ("--design168rshot");
  2317. if (i + 2 < args.size() && args[i + 2] == "generated")
  2318. lynx::plugui::showGeneratedLayoutsOnly (true);
  2319. runDesign168rShots (args[i + 1].unquoted());
  2320. quit();
  2321. return;
  2322. }
  2323. if (args.contains ("--eq166fshot"))
  2324. {
  2325. // LYNX.exe --eq166fshot <folder>: round 166f's pictures (issue #16) — Parametric EQ 2's spectrum and heatmap
  2326. // (flat, a +12 dB band, a -12 dB band, Top position) and Facet EQ's comparative EQ (listening to the target,
  2327. // its spectrum over the source's), each fed by the demo song rendered offline
  2328. const auto i = args.indexOf ("--eq166fshot");
  2329. runEq166fShots (args[i + 1].unquoted());
  2330. quit();
  2331. return;
  2332. }
  2333. if (args.contains ("--editorcpu"))
  2334. {
  2335. // LYNX.exe --editorcpu report.txt: opens built-in plugin editors one at a time in a small window (no audio
  2336. // device: a silent, idle editor) and writes the process CPU each costs while idle and while its display
  2337. // animates (demo signal) — round 122's check that an idle editor burns no CPU
  2338. const auto i = args.indexOf ("--editorcpu");
  2339. runEditorCpu (args[i + 1].unquoted());
  2340. return;
  2341. }
  2342. if (args.contains ("--precomputeshot"))
  2343. {
  2344. // LYNX.exe --precomputeshot project.(flp|lynx) <prefix>: round 167h — <prefix>-precompute.png (channel 1's
  2345. // Precomputed effects panel) and <prefix>-project.png (Options › Project with "Fast declick for cut groups")
  2346. const auto i = args.indexOf ("--precomputeshot");
  2347. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2348. lynx::AudioEngine shotEngine (false);
  2349. const juce::File input (args[i + 1].unquoted());
  2350. const auto prefix = args[i + 2].unquoted();
  2351. juce::String error;
  2352. bool ok = false;
  2353. if (input.hasFileExtension ("flp"))
  2354. ok = shotEngine.importFlpFile (input, error);
  2355. else if (auto song = lynx::ProjectFile::load (input, error))
  2356. shotEngine.setSong (std::move (*song)), ok = true;
  2357. shotEngine.dispatchPendingMessages();
  2358. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  2359. if (c == nullptr)
  2360. return false;
  2361. if (c->getWidth() <= 0)
  2362. c->setSize (520, 600);
  2363. savePng (lynx::shot::snapshot (*c), prefix + name);
  2364. return true;
  2365. };
  2366. ok = ok && shoot (lynx::makeChannelPrecomputePanel (shotEngine, 0), "-precompute.png");
  2367. ok = ok && shoot (lynx::makeSettingsPanel (shotEngine, lynx::SettingsPage::project), "-project.png");
  2368. setApplicationReturnValue (ok ? 0 : 1);
  2369. quit();
  2370. return;
  2371. }
  2372. if (args.contains ("--pluginthumbs"))
  2373. {
  2374. // LYNX.exe --pluginthumbs <folder> [key,key...]: the Plugin picker's pictures of LYNX's own plugins (round 171c,
  2375. // ui/PluginThumbs.h), each editor drawn off-screen and kept as <folder>/<name>.png; the picker starts this in
  2376. // the background when pictures are missing. One line per plugin on stdout.
  2377. const auto i = args.indexOf ("--pluginthumbs");
  2378. lynx::crashguard::quietCrashReports();
  2379. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2380. juce::StringArray only;
  2381. if (i + 2 < args.size() && ! args[i + 2].startsWith ("--"))
  2382. only.addTokens (args[i + 2].unquoted(), ",", "");
  2383. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  2384. // round 190bi: with --shot-scale / LYNX_SHOT_SCALE each plugin's whole editor at that scale, not the picker's
  2385. // small thumbnail (never for the picker's own cache folder, whatever the environment says)
  2386. const juce::File folder (args[i + 1].unquoted());
  2387. const auto full = lynx::shot::given() && folder != lynx::pluginthumbs::nativeFolder() ? lynx::shot::scale() : 0.0f;
  2388. const auto drawn = lynx::pluginthumbs::renderNative (folder, only, [] (const juce::String& line) {
  2389. std::printf ("%s\n", line.toRawUTF8());
  2390. std::fflush (stdout);
  2391. }, full);
  2392. std::printf ("drawn %d in %.0f ms\n", drawn, juce::Time::getMillisecondCounterHiRes() - t0);
  2393. setApplicationReturnValue (0);
  2394. quit();
  2395. return;
  2396. }
  2397. if (args.contains ("--jsonroundtrip"))
  2398. {
  2399. // LYNX.exe --jsonroundtrip <folder>: round 183c's finding — a project saved, loaded and saved again: both texts
  2400. // (a.json, b.json) and the first lines that differ (diff.txt) for the default song, with and without a Patcher
  2401. const auto i = args.indexOf ("--jsonroundtrip");
  2402. const juce::File out (args[i + 1].unquoted());
  2403. out.createDirectory();
  2404. juce::String report;
  2405. auto check = [&] (const lynx::Song& song, const juce::String& name) {
  2406. const auto a = lynx::ProjectFile::toJson (song);
  2407. juce::String error;
  2408. const auto back = lynx::ProjectFile::fromJson (a, error);
  2409. const auto b = back ? lynx::ProjectFile::toJson (*back) : juce::String ("(not loaded: " + error + ")");
  2410. out.getChildFile (name + "-a.json").replaceWithText (a);
  2411. out.getChildFile (name + "-b.json").replaceWithText (b);
  2412. juce::StringArray la, lb;
  2413. la.addLines (a);
  2414. lb.addLines (b);
  2415. report << name << ": " << (a == b ? "stable" : "DIFFERS") << " (" << la.size() << " / " << lb.size() << " lines)\n";
  2416. int shown = 0;
  2417. for (int k = 0; k < juce::jmax (la.size(), lb.size()) && shown < 12; ++k)
  2418. if (la[k] != lb[k])
  2419. {
  2420. report << " line " << (k + 1) << "\n a: " << la[k].trim().substring (0, 200) << "\n b: " << lb[k].trim().substring (0, 200) << "\n";
  2421. ++shown;
  2422. }
  2423. };
  2424. auto song = lynx::Song::makeDefault();
  2425. check (song, "default");
  2426. song.mixer.resize (3);
  2427. song.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::patcher) };
  2428. check (song, "patcher");
  2429. song.mixer[1].effects = { lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect) };
  2430. check (song, "rack");
  2431. out.getChildFile ("diff.txt").replaceWithText (report);
  2432. setApplicationReturnValue (0);
  2433. quit();
  2434. return;
  2435. }
  2436. // --prshot190jv <folder> (round 190jv: Piano roll › Scale highlighting › Automatic): src/PrShot190jv.inc
  2437. if (args.contains ("--prshot190jv"))
  2438. {
  2439. setApplicationReturnValue (runPrShot190jv (juce::File (args[args.indexOf ("--prshot190jv") + 1].unquoted())) ? 0 : 1);
  2440. quit();
  2441. return;
  2442. }
  2443. // --prchord190kd <folder> (round 190kd: FL's chord tool strip, scale shading, rack name alignment): src/PrChordShot190kd.inc
  2444. if (args.contains ("--prchord190kd"))
  2445. {
  2446. setApplicationReturnValue (runPrChordShot190kd (juce::File (args[args.indexOf ("--prchord190kd") + 1].unquoted())) ? 0 : 1);
  2447. quit();
  2448. return;
  2449. }
  2450. // --keys190nu <folder> (round chord2_190nu: key regions, the Scale degree chord, pinned Chord helper relationships)
  2451. if (args.contains ("--keys190nu"))
  2452. {
  2453. setApplicationReturnValue (runKeysShot190nu (juce::File (args[args.indexOf ("--keys190nu") + 1].unquoted())) ? 0 : 1);
  2454. quit();
  2455. return;
  2456. }
  2457. // --modal190mc <folder> (round 190mc: the Chord helper, Transistor Bass's program row): src/ModalShot190mc.inc
  2458. if (args.contains ("--modal190mc"))
  2459. {
  2460. setApplicationReturnValue (runModalShot190mc (juce::File (args[args.indexOf ("--modal190mc") + 1].unquoted())) ? 0 : 1);
  2461. quit();
  2462. return;
  2463. }
  2464. // --trimshot190jv <folder> (round 190jv: Mixer menu › Trim unused tracks): src/TrimShot190jv.inc
  2465. if (args.contains ("--trimshot190jv"))
  2466. {
  2467. setApplicationReturnValue (runTrimShot190jv (juce::File (args[args.indexOf ("--trimshot190jv") + 1].unquoted())) ? 0 : 1);
  2468. quit();
  2469. return;
  2470. }
  2471. // --undogesture190jv <report.txt> (round 190jv, queue item 73: one undo step per drag): src/UndoGesture190jv.inc
  2472. if (args.contains ("--undogesture190jv"))
  2473. {
  2474. setApplicationReturnValue (runUndoGesture190jv (juce::File (args[args.indexOf ("--undogesture190jv") + 1].unquoted())) ? 0 : 1);
  2475. quit();
  2476. return;
  2477. }
  2478. // --simplegb190keshot <folder> (round 190ke: tuner, fade-out, Controls tab, LYNX content): src/SimpleGbShot190ke.inc
  2479. if (args.contains ("--simplegb190keshot"))
  2480. {
  2481. setApplicationReturnValue (runSimpleGbShot190ke (juce::File (args[args.indexOf ("--simplegb190keshot") + 1].unquoted())) ? 0 : 1);
  2482. quit();
  2483. return;
  2484. }
  2485. // --browsershot190iz <folder> (round 190iz: FL's tabs, tags, Live's browser): src/BrowserShot190iz.inc
  2486. // --qarest190lcshot <folder> [Live set] (rollup step 7: QA-8's View menu submenu, QA-2's take lanes in Simple):
  2487. // src/QaRest190lcShot.inc
  2488. if (args.contains ("--qarest190lcshot"))
  2489. {
  2490. const auto i = args.indexOf ("--qarest190lcshot");
  2491. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2492. setApplicationReturnValue (runQaRest190lcShot (juce::File (args[i + 1].unquoted()), set) ? 0 : 1);
  2493. quit();
  2494. return;
  2495. }
  2496. // --loopinfo190kxshot <folder> (round 190kx: loop key / tempo in the Simple rows, the Loop Browser, the clip menu)
  2497. if (args.contains ("--loopinfo190kxshot"))
  2498. {
  2499. setApplicationReturnValue (runLoopInfoShot190kx (juce::File (args[args.indexOf ("--loopinfo190kxshot") + 1].unquoted())) ? 0 : 1);
  2500. quit();
  2501. return;
  2502. }
  2503. // --loopshot190kf <folder> (round gaps190kf: the Loop Browser): src/LoopShot190kf.inc
  2504. if (args.contains ("--loopshot190kf"))
  2505. {
  2506. setApplicationReturnValue (runLoopShot190kf (juce::File (args[args.indexOf ("--loopshot190kf") + 1].unquoted())) ? 0 : 1);
  2507. quit();
  2508. return;
  2509. }
  2510. if (args.contains ("--lynxmodelshot190ni"))
  2511. {
  2512. // LYNX --lynxmodelshot190ni prefix: round 190ni, LYNX Model's window per preset, its Browser entry, checks
  2513. setApplicationReturnValue (runLynxModelShot190ni (args[args.indexOf ("--lynxmodelshot190ni") + 1].unquoted()) ? 0 : 1);
  2514. quit();
  2515. return;
  2516. }
  2517. if (args.contains ("--browsershot190iz"))
  2518. {
  2519. setApplicationReturnValue (runBrowserShot190iz (juce::File (args[args.indexOf ("--browsershot190iz") + 1].unquoted())) ? 0 : 1);
  2520. quit();
  2521. return;
  2522. }
  2523. if (args.contains ("--rackshot"))
  2524. {
  2525. // LYNX.exe --rackshot <folder>: round 183c's Rack view drawn off-screen (no window), for the LYNX | Live pairs:
  2526. // rack-deviceview.png (an Audio Effect Rack laid out as in Live's reference shot), rack-mapmode.png (Map mode
  2527. // with the mapping list), rack-instrument.png (an Instrument Rack with its key zones)
  2528. const auto i = args.indexOf ("--rackshot");
  2529. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2530. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2531. setApplicationReturnValue (runRackShots (juce::File (args[i + 1].unquoted()), set) ? 0 : 1);
  2532. quit();
  2533. return;
  2534. }
  2535. if (args.contains ("--artshot"))
  2536. {
  2537. // LYNX.exe --artshot <folder> [before|after] [name,name...]: every editor with art of its own (round 170j/170k: the
  2538. // Themed style; or only the named ones, e.g. "sakura,facet-eq") drawn off-screen at 100 % and 200 % as
  2539. // <folder>/<plugin>-<before|after>-<scale>.png. "before" draws each in the style it had before the Themed style
  2540. const auto i = args.indexOf ("--artshot");
  2541. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2542. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  2543. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  2544. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  2545. setApplicationReturnValue (runArtShots (juce::File (args[i + 1].unquoted()), mode == "before") ? 0 : 1);
  2546. quit();
  2547. return;
  2548. }
  2549. if (args.contains ("--artgui"))
  2550. {
  2551. // LYNX.exe --artgui <folder> [before|after|still] [name,name...]: the same editors in REAL windows on the desktop, one at a
  2552. // time (always on top, no focus taken), each held while an outside script screenshots it (it writes
  2553. // <folder>/<plugin>.ready with the window's bounds and waits up to 10 s for <folder>/<plugin>.done), then the
  2554. // process CPU it costs over 6 s is written to <folder>/cpu-<mode>.txt. "still": Themed with the motion off
  2555. const auto i = args.indexOf ("--artgui");
  2556. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2557. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  2558. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  2559. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  2560. runArtGui (juce::File (args[i + 1].unquoted()), mode);
  2561. return;
  2562. }
  2563. if (args.contains ("--instrumentshot"))
  2564. {
  2565. // LYNX.exe --instrumentshot <folder> <engine,engine...|banks> [lynx|fl]: round 168n — the channel window of
  2566. // each engine (its Plugin tab) at 100 %, 150 % and 200 %, as <folder>/<engine>-<source>-<scale>.png. Source
  2567. // "lynx" starts from the engine's LYNX bank (what a PC without FL gets), "fl" from FL's Default preset.
  2568. const auto i = args.indexOf ("--instrumentshot");
  2569. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2570. const auto source = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("lynx");
  2571. setApplicationReturnValue (runInstrumentShots (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted(), source) ? 0 : 1);
  2572. quit();
  2573. return;
  2574. }
  2575. if (args.contains ("--flextrashot"))
  2576. {
  2577. // LYNX.exe --flextrashot <folder>: pictures of the editors of round 165g (Big Clock, Tuner, HTML NoteBook, Mute 2, Scratcher, Transmitter) + round 167n Transporter
  2578. const auto i = args.indexOf ("--flextrashot");
  2579. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2580. lynx::AudioEngine shotEngine (false);
  2581. const auto ok = lynx::runFlExtraShots (shotEngine, juce::File (args[i + 1].unquoted()));
  2582. setApplicationReturnValue (ok ? 0 : 1);
  2583. quit();
  2584. return;
  2585. }
  2586. if (args.contains ("--visualtest"))
  2587. {
  2588. // LYNX.exe --visualtest <folder> [project.flp]: the visual plugins (round 164c) — the audio path's CPU, every
  2589. // Wave Candy mode and Visualizer scene drawn from a test signal (PNG + the editor's CPU each), and the video
  2590. // export of a project (default: FL's first ZGameEditor demo) with ffmpeg and as images. Writes report.txt.
  2591. const auto i = args.indexOf ("--visualtest");
  2592. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2593. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File();
  2594. lynx::runVisualTest (juce::File (args[i + 1].unquoted()), project, [this] (bool ok) {
  2595. setApplicationReturnValue (ok ? 0 : 1);
  2596. quit();
  2597. });
  2598. return;
  2599. }
  2600. if (args.contains ("--menu-entry"))
  2601. {
  2602. // LYNX.AppImage --menu-entry on|off: puts the AppImage in the applications menu (and .lynx files on it) or
  2603. // takes it out again, without opening a window; the same as the switch in Options › General (round 161)
  2604. const auto i = args.indexOf ("--menu-entry");
  2605. const auto on = args[i + 1].unquoted() != "off";
  2606. const auto ok = lynx::runningAsAppImage() && lynx::setAppImageMenuEntry (on);
  2607. std::fprintf (ok ? stdout : stderr, "%s\n", ok ? (on ? "LYNX SHARE added to the applications menu" : "LYNX SHARE removed from the applications menu")
  2608. : "only the LYNX SHARE AppImage on Linux can do this");
  2609. setApplicationReturnValue (ok ? 0 : 1);
  2610. quit();
  2611. return;
  2612. }
  2613. if (args.contains ("--leftovers190nrtest"))
  2614. {
  2615. // round 190nr: going back to an older version removes what newer versions added to the install folder
  2616. // (the --apply-update helper's step after the installer). Prints "result=OK" or the failing check.
  2617. const auto root = juce::File::createTempFile ("lynx-leftovers190nr");
  2618. juce::StringArray fails;
  2619. auto run = [&] (const juce::String& version, bool licensesGone, bool listGone) {
  2620. root.deleteRecursively();
  2621. root.getChildFile ("install/licenses").createDirectory();
  2622. root.getChildFile ("install/licenses/onnxruntime-LICENSE.txt").replaceWithText ("x");
  2623. root.getChildFile ("install/LYNX.exe").replaceWithText ("x");
  2624. root.getChildFile ("install/installed-files.txt").replaceWithText ("LYNX.exe\r\nlicenses\r\n");
  2625. root.getChildFile ("install/My notes.txt").replaceWithText ("x");
  2626. root.getChildFile ("update/installing.txt").create();
  2627. if (version.isNotEmpty())
  2628. root.getChildFile ("update/installing.txt").replaceWithText ("from=0.1.31\nrollback=1\nversion=" + version + "\n");
  2629. const auto removed = lynx::updater::removeNewerLeftovers (root.getChildFile ("install"), root.getChildFile ("update/installing.txt"));
  2630. const auto in = root.getChildFile ("install");
  2631. if (in.getChildFile ("licenses").exists() == licensesGone) fails.add (version + ": licenses");
  2632. if (in.getChildFile ("installed-files.txt").exists() == listGone) fails.add (version + ": installed-files.txt");
  2633. if (! in.getChildFile ("LYNX.exe").existsAsFile() || ! in.getChildFile ("My notes.txt").existsAsFile()) fails.add (version + ": removed too much");
  2634. std::printf ("%s -> removed [%s]\n", version.toRawUTF8(), removed.joinIntoString (", ").toRawUTF8());
  2635. };
  2636. run ("0.1.29-alpha", true, true); // going back to 0.1.29: both newer entries go
  2637. run ("0.1.28.1-alpha", true, true);
  2638. run ("0.1.30-alpha", false, true); // 0.1.30 installs licenses itself
  2639. run ("0.1.31-alpha", false, false); // same or newer: nothing goes
  2640. run ("0.1.32", false, false);
  2641. run ("", false, false); // unreadable note: nothing goes
  2642. root.deleteRecursively();
  2643. std::printf ("result=%s%s\n", fails.isEmpty() ? "OK" : "FAILED ", fails.joinIntoString ("; ").toRawUTF8());
  2644. setApplicationReturnValue (fails.isEmpty() ? 0 : 1);
  2645. quit();
  2646. return;
  2647. }
  2648. if (args.contains ("--send-test-report"))
  2649. {
  2650. // LYNX.exe --send-test-report out.txt [--dry]: builds a crash report marked "test" from the newest crash /
  2651. // hang file and this computer's facts, writes its JSON to out.txt.json and (without --dry) sends it to
  2652. // lynx-share.com (LYNX_CRASH_ENDPOINT overrides); out.txt gets "id=…" and "result=OK" or the error (round 159)
  2653. const auto i = args.indexOf ("--send-test-report");
  2654. const juce::File out (args[i + 1].unquoted());
  2655. lynx::crashreporter::Session session;
  2656. session.version = getApplicationVersion();
  2657. for (const auto* pattern : { "crash *.txt", "hang *.txt" })
  2658. {
  2659. auto files = lynx::platform::settingsFile ("autosave").findChildFiles (juce::File::findFiles, false, pattern);
  2660. lynx::filesort::byTime (files, lynx::filesort::By::modificationTime, true);
  2661. if (! files.isEmpty())
  2662. (juce::String (pattern).startsWith ("crash") ? session.crashFile : session.hangFile) = files[0];
  2663. }
  2664. session.steps = { "00:00:01 test report (LYNX.exe --send-test-report)", "00:00:02 opening project " + out.getFileName() };
  2665. auto input = lynx::crashreporter::makeInput (session, session.crashFile.existsAsFile() ? "crash" : "manual", nullptr);
  2666. input.test = true;
  2667. const auto json = lynx::crashreporter::buildJson (input, false);
  2668. out.withFileExtension (out.getFileExtension() + ".json").replaceWithText (json);
  2669. const auto error = args.contains ("--dry") ? juce::String() : lynx::crashreporter::sendNow (json);
  2670. out.replaceWithText ("id=" + juce::String::fromUTF8 (input.id.c_str()) + "\nendpoint=" + lynx::crashreporter::endpoint() + "\nbytes="
  2671. + juce::String (json.getNumBytesAsUTF8()) + "\nresult=" + (error.isEmpty() ? juce::String ("OK") : error) + "\n");
  2672. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  2673. quit();
  2674. return;
  2675. }
  2676. if (args.contains ("--symbolize"))
  2677. {
  2678. // LYNX.exe --symbolize "crash … .txt" out.txt: names the LYNX.exe+offset frames of a user's crash / hang file
  2679. // (needs this build's LYNX.pdb next to LYNX.exe — the release's "LYNX-symbols" CI artifact; round 157a)
  2680. const auto i = args.indexOf ("--symbolize");
  2681. const auto text = juce::File (args[i + 1].unquoted()).loadFileAsString();
  2682. juce::File (args[i + 2].unquoted()).replaceWithText (juce::String::fromUTF8 (lynx::crashguard::symbolizeOwnFrames (text.toStdString()).c_str()));
  2683. quit();
  2684. return;
  2685. }
  2686. if (args.contains ("--opentest"))
  2687. {
  2688. // LYNX.exe --opentest report.txt [--visible]: every built-in effect and instrument window opened as the mixer /
  2689. // Channel rack open them, with default, extreme, random and old-project states; a watchdog fails the test on
  2690. // a hang (round 157a: opening the Parametric EQ froze LYNX). Windows stay off-screen without --visible.
  2691. const auto i = args.indexOf ("--opentest");
  2692. runOpenTest (args[i + 1].unquoted(), args.contains ("--visible"), [this] (bool ok) {
  2693. setApplicationReturnValue (ok ? 0 : 1);
  2694. quit();
  2695. });
  2696. return;
  2697. }
  2698. if (args.contains ("--fxfuzz"))
  2699. {
  2700. // LYNX.exe --fxfuzz report.txt [rounds] [--drags]: every built-in effect in its editor, parameters swept (and
  2701. // dragged with the mouse), audio rendered at several rates; a crash ends the process (round 111)
  2702. const auto i = args.indexOf ("--fxfuzz");
  2703. const auto rounds = args.size() > i + 2 ? juce::jmax (1, args[i + 2].getIntValue()) : 6;
  2704. // --drags: also mouse drags over the editors (their menus may flash on screen: not for the selftest)
  2705. const auto ok = runEffectFuzz (rounds, args[i + 1].unquoted(), args.contains ("--drags"));
  2706. setApplicationReturnValue (ok ? 0 : 1);
  2707. quit();
  2708. return;
  2709. }
  2710. if (args.contains ("--controllershot"))
  2711. {
  2712. // LYNX.exe --controllershot prefix: the built-in controllers' editors (round 133) as PNGs
  2713. const auto i = args.indexOf ("--controllershot");
  2714. runControllerShot (args[i + 1].unquoted());
  2715. quit();
  2716. return;
  2717. }
  2718. if (args.contains ("--edisonshot"))
  2719. {
  2720. // LYNX.exe --edisonshot prefix [audio.wav]: the audio editor's Edison tool windows (round 165l) and the
  2721. // editor before / after some of them, as PNGs (a synthetic drum loop without a file)
  2722. const auto i = args.indexOf ("--edisonshot");
  2723. runEdisonShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2724. quit();
  2725. return;
  2726. }
  2727. if (args.contains ("--arashot190kx"))
  2728. {
  2729. // LYNX --arashot190kx prefix (round 190kx): the Playlist's audio clip menu with its "Edit in ARA plugin" submenu
  2730. // (a stand-in Melodyne entry in this engine's plugin list, as a scan lists the installed one), before and after the
  2731. // clip's channel is edited in it
  2732. const auto i = args.indexOf ("--arashot190kx");
  2733. runAraShot190kx (args[i + 1].unquoted());
  2734. quit();
  2735. return;
  2736. }
  2737. if (args.contains ("--polyshot190lj") && args.indexOf ("--polyshot190lj") + 2 < args.size())
  2738. {
  2739. // LYNX --polyshot190lj prefix audio.wav [bends.wav] (round 190lj): "Convert to MIDI (polyphonic)" — the audio
  2740. // clip menu (Pattern and Simple layouts), the options dialog, Edison's Tools menu, and the result of a
  2741. // conversion (Playlist, Piano roll; with bends on the second file), plus <prefix>-checks.txt (OK / FAIL)
  2742. const auto i = args.indexOf ("--polyshot190lj");
  2743. const auto ok = runPolyShot190lj (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String());
  2744. setApplicationReturnValue (ok ? 0 : 1);
  2745. quit();
  2746. return;
  2747. }
  2748. if (args.contains ("--newtoneshot190li"))
  2749. {
  2750. // LYNX --newtoneshot190li prefix audio.wav (round 190li): Newtone with the natural engine (a new slot), as
  2751. // analysed and after Correct pitch 100 / 100 (centre and drift; the vibrato kept), and its Edit menu with the
  2752. // round's items, for the Melodyne | LYNX pairs (with --shot-scale 1.5 for @150)
  2753. const auto i = args.indexOf ("--newtoneshot190li");
  2754. runNewtoneShot190li (args[i + 1].unquoted(), args[i + 2].unquoted());
  2755. quit();
  2756. return;
  2757. }
  2758. if (args.contains ("--polyeditshot190lk") && args.indexOf ("--polyeditshot190lk") + 2 < args.size())
  2759. {
  2760. // LYNX --polyeditshot190lk prefix audio.wav [key] (round 190lk): "Edit notes (polyphonic)" — the audio clip menu,
  2761. // the editor as analysed and after one note (the one nearest `key`, default 64 = E4) moved down a semitone,
  2762. // at 100 % and 150 %, plus <prefix>-checks.txt (OK / FAIL, timings) and <prefix>-notes.txt
  2763. const auto i = args.indexOf ("--polyeditshot190lk");
  2764. const auto ok = runPolyEditShot190lk (args[i + 1].unquoted(), args[i + 2].unquoted(),
  2765. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].getDoubleValue() : 64.0);
  2766. setApplicationReturnValue (ok ? 0 : 1);
  2767. quit();
  2768. return;
  2769. }
  2770. if (args.contains ("--polyeditshot190lo") && args.indexOf ("--polyeditshot190lo") + 2 < args.size())
  2771. {
  2772. // LYNX --polyeditshot190lo prefix audio.wav [key] (round 190lo): the polyphonic note editor's round-2 tools —
  2773. // note assignment, rubber band and moving several notes, stretch handles, modulation / drift / drawn pitch,
  2774. // a dragged note's preview, Edison's buffer mode and its undo, "Prepare edited clips when a project opens" —
  2775. // at 100 % and 150 %, plus <prefix>-checks.txt and <prefix>-notes.txt
  2776. const auto i = args.indexOf ("--polyeditshot190lo");
  2777. const auto ok = runPolyEditShot190lo (args[i + 1].unquoted(), args[i + 2].unquoted(),
  2778. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].getDoubleValue() : 64.0);
  2779. setApplicationReturnValue (ok ? 0 : 1);
  2780. quit();
  2781. return;
  2782. }
  2783. if (args.contains ("--newtoneshot190kx"))
  2784. {
  2785. // LYNX --newtoneshot190kx prefix audio.wav (round 190kx): Newtone with FL's analysis and with "Separate close
  2786. // notes", each as analysed and after Center 100 % (Melodyne's Correct Pitch), for the Melodyne | LYNX pairs
  2787. const auto i = args.indexOf ("--newtoneshot190kx");
  2788. runNewtoneShot190kx (args[i + 1].unquoted(), args[i + 2].unquoted());
  2789. quit();
  2790. return;
  2791. }
  2792. if (args.contains ("--newtoneshot"))
  2793. {
  2794. // LYNX --newtoneshot prefix audio.wav (round natives190kj): FL's Newtone window with the sample analysed, in a
  2795. // few states (-plain, -selected, -advanced, -cut, -timesel, -moved) and the paint time of the FL look against
  2796. // the round-165g layout (-paint.txt)
  2797. const auto i = args.indexOf ("--newtoneshot");
  2798. runNewtoneShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2799. quit();
  2800. return;
  2801. }
  2802. if (args.contains ("--edisonslottest"))
  2803. {
  2804. // LYNX.exe --edisonslottest folder [project.flp]: round 190cd — the audio editor as a mixer-slot plugin through
  2805. // the engine and the project file (report.txt: one "name=ok|FAIL" per check), its window as slot-*.png, and
  2806. // the Edison slots of an FL project (what was read of each)
  2807. const auto i = args.indexOf ("--edisonslottest");
  2808. const auto ok = runEdisonSlotTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2809. setApplicationReturnValue (ok ? 0 : 1);
  2810. quit();
  2811. return;
  2812. }
  2813. if (args.contains ("--danceshot"))
  2814. {
  2815. // LYNX.exe --danceshot prefix: LYNX Dance (round 165e) — every move as a contact sheet, the channel's editor,
  2816. // and a demo project with two dance channels (for --snapshot)
  2817. const auto i = args.indexOf ("--danceshot");
  2818. runDanceShot (args[i + 1].unquoted());
  2819. quit();
  2820. return;
  2821. }
  2822. if (args.contains ("--videoshot") && args.indexOf ("--videoshot") + 2 < args.size())
  2823. {
  2824. // LYNX.exe --videoshot prefix video: the Video Player's editor (round 165g) at a few song positions, with
  2825. // the user's ffmpeg, as PNGs + report.txt (frames decoded, the sound track)
  2826. const auto i = args.indexOf ("--videoshot");
  2827. runVideoShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2828. return;
  2829. }
  2830. if (args.contains ("--videotrackshot") && args.indexOf ("--videotrackshot") + 2 < args.size())
  2831. {
  2832. // LYNX.exe --videotrackshot prefix video [video2]: round 174d — the Playlist with video tracks (filmstrips,
  2833. // timecode row) and the video window at a few song positions, as PNGs + report.txt (the decoder, the
  2834. // frame shown for each wanted time: frame accuracy, frames dropped)
  2835. const auto i = args.indexOf ("--videotrackshot");
  2836. runVideoTrackShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  2837. return;
  2838. }
  2839. if (args.contains ("--vfxshot"))
  2840. {
  2841. // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
  2842. const auto i = args.indexOf ("--vfxshot");
  2843. runVfxShot (args[i + 1].unquoted());
  2844. quit();
  2845. return;
  2846. }
  2847. if (args.contains ("--patchershot"))
  2848. {
  2849. // LYNX.exe --patchershot prefix [project]: every Patcher's editor (round 141) as PNGs (a demo one without a project)
  2850. const auto i = args.indexOf ("--patchershot");
  2851. runPatcherShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2852. quit();
  2853. return;
  2854. }
  2855. if (args.contains ("--audioxshot"))
  2856. {
  2857. // LYNX.exe --audioxshot prefix (round 190aq): the pre-fader send, the "Low latency while recording" mark on a
  2858. // bypassed slot and the Browser's "Preview in time", drawn off-screen
  2859. runAudioXShot (args[args.indexOf ("--audioxshot") + 1].unquoted());
  2860. quit();
  2861. return;
  2862. }
  2863. if (args.contains ("--comp177shot"))
  2864. {
  2865. // LYNX.exe --comp177shot prefix project (round 177c): a project of loop takes in the maximised
  2866. // Playlist as it opened; every group after "Comp these takes", with a swipe on the first; the track and record menus
  2867. const auto i = args.indexOf ("--comp177shot");
  2868. runComp177Shot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2869. quit();
  2870. return;
  2871. }
  2872. if (args.contains ("--evpaneshot"))
  2873. {
  2874. // LYNX --evpaneshot prefix [project] (round 190fz): the Piano roll's event editor divider driven with the mouse
  2875. // handlers (drag, right-click = alternate size and back, middle-click = default, a drag into the snap zone),
  2876. // a picture of each state and prefix-report.txt with the heights and the remembered settings file
  2877. const auto i = args.indexOf ("--evpaneshot");
  2878. setApplicationReturnValue (runEvPaneShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2879. quit();
  2880. return;
  2881. }
  2882. if (args.contains ("--feat166shot"))
  2883. {
  2884. // LYNX.exe --feat166shot prefix [project]: round 166d (issue #14) — the Piano Roll with a scale, folded to
  2885. // it, with one ghost channel, the ghost channels menu, and the Mixer filled to 500 inserts (its start and
  2886. // its end, and the time a full repaint takes)
  2887. const auto i = args.indexOf ("--feat166shot");
  2888. runFeat166Shot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2889. quit();
  2890. return;
  2891. }
  2892. if (args.contains ("--pickerdropshot"))
  2893. {
  2894. // LYNX --pickerdropshot prefix: round 190hm (issue #177) — Picker panel entries dropped on the Playlist as FL
  2895. // places them (plain drop: one track per entry at the snapped time; Shift: one after another), off-screen,
  2896. // with <prefix>-checks.txt (OK / FAIL per placement)
  2897. setApplicationReturnValue (runPickerDropShot (args[args.indexOf ("--pickerdropshot") + 1].unquoted()) ? 0 : 1);
  2898. quit();
  2899. return;
  2900. }
  2901. if (args.contains ("--trackmodeshot"))
  2902. {
  2903. // LYNX --trackmodeshot prefix: rollup 190cv (UI gate of PR #151) — Playlist track header › Track mode › Audio
  2904. // track, off-screen, in three states of FL's live check 190cu (q1-01 fresh, q1-02 one insert linked
  2905. // elsewhere and one renamed, q1-07 the full state), plus a report that compares each list with FL's
  2906. setApplicationReturnValue (runTrackModeShot (args[args.indexOf ("--trackmodeshot") + 1].unquoted()) ? 0 : 1);
  2907. quit();
  2908. return;
  2909. }
  2910. if (args.contains ("--curveshot"))
  2911. {
  2912. // LYNX.exe --curveshot prefix: round 190bw — an automation clip with one segment per FL curve mode in the
  2913. // point editor and in the Playlist, and FL's point menu, off-screen
  2914. runCurveShot (args[args.indexOf ("--curveshot") + 1].unquoted());
  2915. quit();
  2916. return;
  2917. }
  2918. if (args.contains ("--remoteshot"))
  2919. {
  2920. // LYNX.exe --remoteshot prefix: Online Sessions P5-A1 (round 190ai) — the host's "Share plugins with guests"
  2921. // list and a guest's parameter editor of a plugin the host plays, off-screen with sample data
  2922. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2923. lynx::liveui::saveRemoteShots (args[args.indexOf ("--remoteshot") + 1].unquoted());
  2924. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  2925. quit();
  2926. return;
  2927. }
  2928. if (args.contains ("--settingsshot") && ! args.contains ("--rtstress")) // (--rtstress has its own --settingsshot file.png option, round 161)
  2929. {
  2930. // LYNX.exe --settingsshot prefix: round 190bx — every Settings page off-screen at the window's size, in a
  2931. // small window (390 x 390) and, for the long pages, whole (see runSettingsShot)
  2932. runSettingsShot (args[args.indexOf ("--settingsshot") + 1].unquoted());
  2933. quit();
  2934. return;
  2935. }
  2936. if (args.contains ("--perfshot"))
  2937. {
  2938. // LYNX.exe --perfshot prefix project: the Playlist in Performance mode with a few clips launched and waiting,
  2939. // then the project patcherized (every insert's effects, the first channels) saved as prefix-patcherized.lynx
  2940. // for --patchershot (round 165m)
  2941. const auto i = args.indexOf ("--perfshot");
  2942. runPerfShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2943. quit();
  2944. return;
  2945. }
  2946. if (args.contains ("--freezetest"))
  2947. {
  2948. // LYNX.exe --freezetest prefix [project]: round 190ay's Freeze end to end, off-screen (see runFreezeTest)
  2949. const auto i = args.indexOf ("--freezetest");
  2950. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2951. // a word after the project: "keep" = freeze, save prefix-frozen.lynx and stop (the audio stays);
  2952. // "measure" = only load and render the project, for the memory and time of a process of its own
  2953. const auto mode = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2954. setApplicationReturnValue (runFreezeTest (args[i + 1].unquoted(), project, mode) ? 0 : 1);
  2955. quit();
  2956. return;
  2957. }
  2958. if (args.contains ("--trackfreezetest"))
  2959. {
  2960. // LYNX --trackfreezetest prefix: round 190ff's Freeze Track, Flatten / Bounce Track in Place, Bounce to New
  2961. // Track and Consolidate end to end in the Clip-launch workflow, off-screen (see runTrackFreezeTest)
  2962. const auto i = args.indexOf ("--trackfreezetest");
  2963. setApplicationReturnValue (runTrackFreezeTest (args[i + 1].unquoted()) ? 0 : 1);
  2964. quit();
  2965. return;
  2966. }
  2967. if (args.contains ("--details190ihshot"))
  2968. {
  2969. // LYNX --details190ihshot prefix: round 190ih's live states off screen (no window, no audio device) — Gross
  2970. // Beat's locator and slots from its real engine, the rack's activity light, Play / Pause, the Record blink,
  2971. // the "Note on" hint, the save reminder, the Simple dock's input level, the Envelope Controller's key line
  2972. const auto i = args.indexOf ("--details190ihshot");
  2973. runDetails190ihShot (args[i + 1].unquoted());
  2974. quit();
  2975. return;
  2976. }
  2977. if (args.contains ("--paintbench"))
  2978. {
  2979. // LYNX --paintbench project.(flp|lynx|als) report.txt (round 190ge): each main view drawn off screen, whole, many
  2980. // times (the message thread's CPU per frame), with the playhead mid-song; no window, no audio device
  2981. const auto i = args.indexOf ("--paintbench");
  2982. runPaintBench (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  2983. quit();
  2984. return;
  2985. }
  2986. if (args.contains ("--design190igshot"))
  2987. {
  2988. // LYNX --design190igshot prefix project.flp: round 190ig off-screen (design190ia slice 3) — the Pattern layout's
  2989. // Playlist with FL's clip and header look: the song at FL's default zoom (26 px tracks, 15.6 px a bar, bar 21),
  2990. // at FL's "zoom 17" (50 px tracks, 39.75 px a bar), and playing (the activity column), as FL's reference shots
  2991. const auto i = args.indexOf ("--design190igshot");
  2992. runDesign190igShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2993. quit();
  2994. return;
  2995. }
  2996. if (args.contains ("--cliplaunch190kcshot"))
  2997. {
  2998. // LYNX --cliplaunch190kcshot prefix set.als: round 190kc off screen (Live's return tracks, Sends rows, Pre / Post,
  2999. // the crossfader, the map modes' crossfader positions and relative strip, Commit / Extract on audio); prefix-checks.txt
  3000. const auto i = args.indexOf ("--cliplaunch190kcshot");
  3001. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3002. runClipLaunch190kcShot (args[i + 1].unquoted(), set);
  3003. quit();
  3004. return;
  3005. }
  3006. if (args.contains ("--livelook190jnshot"))
  3007. {
  3008. // LYNX --livelook190jnshot prefix [set.als]: round 190jn off screen (design190ia slices 13, 17, 18, 19, 25: the
  3009. // Clip-launch layout in Live's look, and the classic look); prefix-checks.txt
  3010. const auto i = args.indexOf ("--livelook190jnshot");
  3011. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3012. runLiveLook190jnShot (args[i + 1].unquoted(), set);
  3013. quit();
  3014. return;
  3015. }
  3016. if (args.contains ("--fllook190joshot"))
  3017. {
  3018. // LYNX --fllook190joshot prefix project.flp: round 190jo off screen (design190ia slices 12, 21, 23): the Pattern
  3019. // toolbar's tiles in every state, time / tempo / hint / menu bar, at 1920 / 1600 / 1366 / 1280; the Piano roll
  3020. // (FL's rows, notes, keys, grid, ghosts); the audio editor in Edison's layout with FL's "DL Breaker.wav";
  3021. // prefix-checks.txt (note label contrast)
  3022. const auto i = args.indexOf ("--fllook190joshot");
  3023. runFllook190joShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String());
  3024. quit();
  3025. return;
  3026. }
  3027. if (args.contains ("--capfix190jjshot"))
  3028. {
  3029. // LYNX --capfix190jjshot prefix project.flp [set.als]: round 190jj off screen (capture190ji's changes: Simple
  3030. // capsule states, master meter, pads press, held keys, drop lane ghosts; Live's control bar; FL's C-11 drop ghost
  3031. // and the picker's playing mark); prefix-checks.txt
  3032. const auto i = args.indexOf ("--capfix190jjshot");
  3033. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  3034. runCapfix190jjShot (args[i + 1].unquoted(), args[i + 2].unquoted(), set);
  3035. quit();
  3036. return;
  3037. }
  3038. if (args.contains ("--demo190plcheck"))
  3039. {
  3040. // LYNX --demo190plcheck prefix: round 190pl, the --demo operations of tutorial batch 2 (src/Demo190plCheck.inc)
  3041. const auto i = args.indexOf ("--demo190plcheck");
  3042. setApplicationReturnValue (runDemoCheck190pl (args[i + 1].unquoted()) ? 0 : 1);
  3043. quit();
  3044. return;
  3045. }
  3046. if (args.contains ("--demo190pgcheck"))
  3047. {
  3048. // LYNX --demo190pgcheck prefix project.lynx: round 190pg, the --demo operations of the tutorial videos (src/Demo190pgCheck.inc)
  3049. const auto i = args.indexOf ("--demo190pgcheck");
  3050. setApplicationReturnValue (runDemoCheck190pg (args[i + 1].unquoted(), juce::File (i + 2 < args.size() ? args[i + 2].unquoted() : juce::String())) ? 0 : 1);
  3051. quit();
  3052. return;
  3053. }
  3054. if (args.contains ("--onboard190npshot"))
  3055. {
  3056. // LYNX --onboard190npshot prefix: round 190np off screen (src/OnboardShot190np.inc): the welcome card, the choices,
  3057. // the Next-3 card, the empty-state hints, the tips and the Help menu, 100 % and @150, with <prefix>-checks.txt
  3058. const auto i = args.indexOf ("--onboard190npshot");
  3059. setApplicationReturnValue (runOnboardShot190np (args[i + 1].unquoted()) ? 0 : 1);
  3060. quit();
  3061. return;
  3062. }
  3063. if (args.contains ("--details190oashot"))
  3064. {
  3065. // LYNX --details190oashot prefix project.flp: round 190oa off screen (src/DetailsShot190oa.inc)
  3066. const auto i = args.indexOf ("--details190oashot");
  3067. setApplicationReturnValue (runDetailsShot190oa (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3068. quit();
  3069. return;
  3070. }
  3071. if (args.contains ("--details190myshot"))
  3072. {
  3073. // LYNX --details190myshot prefix project.flp: round 190my off screen (src/DetailsShot190my.inc)
  3074. const auto i = args.indexOf ("--details190myshot");
  3075. setApplicationReturnValue (runDetailsShot190my (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3076. quit();
  3077. return;
  3078. }
  3079. if (args.contains ("--details190mvshot"))
  3080. {
  3081. // LYNX --details190mvshot prefix project.flp: round 190mv off screen (src/DetailsShot190mv.inc)
  3082. const auto i = args.indexOf ("--details190mvshot");
  3083. setApplicationReturnValue (runDetailsShot190mv (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3084. quit();
  3085. return;
  3086. }
  3087. if (args.contains ("--details190mrshot"))
  3088. {
  3089. // LYNX --details190mrshot prefix project.flp: round 190mr off screen (src/DetailsShot190mr.inc)
  3090. const auto i = args.indexOf ("--details190mrshot");
  3091. setApplicationReturnValue (runDetailsShot190mr (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3092. quit();
  3093. return;
  3094. }
  3095. if (args.contains ("--rack190ncshot") && args.indexOf ("--rack190ncshot") + 1 < args.size())
  3096. {
  3097. // LYNX --rack190ncshot prefix: round 190nc off screen (src/RackShot190nc.inc): Live's rack with its devices
  3098. // inline and the Macro Map overlay (DL-95), the Session mixer's Solo / Cue (DL-110)
  3099. setApplicationReturnValue (runRackShot190nc (args[args.indexOf ("--rack190ncshot") + 1].unquoted()) ? 0 : 1);
  3100. quit();
  3101. return;
  3102. }
  3103. if (args.contains ("--details190mpshot"))
  3104. {
  3105. // LYNX --details190mpshot prefix project.flp: round 190mp off screen (src/DetailsShot190mp.inc)
  3106. const auto i = args.indexOf ("--details190mpshot");
  3107. setApplicationReturnValue (runDetailsShot190mp (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3108. quit();
  3109. return;
  3110. }
  3111. if (args.contains ("--details190mkshot"))
  3112. {
  3113. // LYNX --details190mkshot prefix project.flp: round 190mk off screen (src/DetailsShot190mk.inc)
  3114. const auto i = args.indexOf ("--details190mkshot");
  3115. setApplicationReturnValue (runDetailsShot190mk (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3116. quit();
  3117. return;
  3118. }
  3119. if (args.contains ("--details190mfshot"))
  3120. {
  3121. // LYNX --details190mfshot prefix project.flp: round 190mf off screen (src/DetailsShot190mf.inc)
  3122. const auto i = args.indexOf ("--details190mfshot");
  3123. setApplicationReturnValue (runDetailsShot190mf (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3124. quit();
  3125. return;
  3126. }
  3127. if (args.contains ("--details190lxshot"))
  3128. {
  3129. // LYNX --details190lxshot prefix project.flp [set.als]: round 190lx off screen (src/DetailsShot190lx.inc)
  3130. const auto i = args.indexOf ("--details190lxshot");
  3131. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  3132. setApplicationReturnValue (runDetailsShot190lx (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  3133. quit();
  3134. return;
  3135. }
  3136. if (args.contains ("--details190lrshot"))
  3137. {
  3138. // LYNX --details190lrshot prefix project.flp [set.als]: round 190lr off screen (src/DetailsShot190lr.inc)
  3139. const auto i = args.indexOf ("--details190lrshot");
  3140. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  3141. setApplicationReturnValue (runDetailsShot190lr (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  3142. quit();
  3143. return;
  3144. }
  3145. if (args.contains ("--details190ldshot"))
  3146. {
  3147. // LYNX --details190ldshot prefix project.flp [set.als]: round 190ld off screen (src/DetailsShot190ld.inc)
  3148. const auto i = args.indexOf ("--details190ldshot");
  3149. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  3150. setApplicationReturnValue (runDetailsShot190ld (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  3151. quit();
  3152. return;
  3153. }
  3154. if (args.contains ("--details190knshot"))
  3155. {
  3156. // LYNX --details190knshot prefix project.flp [set.als]: round 190kn off screen (src/DetailsShot190kn.inc)
  3157. const auto i = args.indexOf ("--details190knshot");
  3158. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  3159. setApplicationReturnValue (runDetailsShot190kn (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  3160. quit();
  3161. return;
  3162. }
  3163. if (args.contains ("--details190imshot"))
  3164. {
  3165. // LYNX --details190imshot prefix project.flp [set.als]: round 190im off-screen (details190if R1, R5, R6, R11, R12,
  3166. // R13, R15) — the automation hints, the Playlist playing (picker marks, glow, overview, activity levels), a drop
  3167. // preview, Follow's pause, the Sampler's handles, and with the Live set the grid's one-shot / follow / queued
  3168. // scene / deactivated clip / hints and the Clip View's launched position; prefix-checks.txt
  3169. const auto i = args.indexOf ("--details190imshot");
  3170. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  3171. runDetails190imShot (args[i + 1].unquoted(), args[i + 2].unquoted(), set);
  3172. quit();
  3173. return;
  3174. }
  3175. if (args.contains ("--toolbarshot190qg"))
  3176. {
  3177. // LYNX --toolbarshot190qg prefix [project]: round 190qg off screen — the toolbar walk (every preset, icon size,
  3178. // Interface size and window width: each item on the toolbar or in its overflow), every preset's toolbar at
  3179. // 80-175 % on 1280 / 1920 px screens, the overflow menus; exit 0 = the walk passed (src/ToolbarShot190qg.inc)
  3180. const auto i = args.indexOf ("--toolbarshot190qg");
  3181. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3182. setApplicationReturnValue (runToolbarShot190qg (args[i + 1].unquoted(), project) ? 0 : 1);
  3183. quit();
  3184. return;
  3185. }
  3186. if (args.contains ("--toolbarshot190iv"))
  3187. {
  3188. // LYNX --toolbarshot190iv prefix [project.als]: round 190iv off screen — the toolbar of each layout style (Pattern,
  3189. // Simple, Clip-launch) at 1920 / 1366 / 1280, the Simple transport capsule idle / hover / pressed / playing /
  3190. // recording, the "Last saved" status in its four states, Live's control bar with every button idle / hover /
  3191. // pressed / lit, the "⋯" menus, and a report of the parts' bounds
  3192. const auto i = args.indexOf ("--toolbarshot190iv");
  3193. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3194. runToolbarShot190iv (args[i + 1].unquoted(), project);
  3195. quit();
  3196. return;
  3197. }
  3198. if (args.contains ("--gridshot"))
  3199. {
  3200. // LYNX.exe --gridshot prefix [project]: the Clip-launch workflow's layout off-screen, with a grid of sample
  3201. // clips, some playing and waiting, at the size of LYNX_SNAPSHOT_SIZE (round 181a); with a project (.lynx,
  3202. // .flp, .als), that project's grid instead (round 181c: a Live set's Session view as LYNX imports it)
  3203. const auto i = args.indexOf ("--gridshot");
  3204. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3205. runGridShot (args[i + 1].unquoted(), project);
  3206. quit();
  3207. return;
  3208. }
  3209. if (args.contains ("--tour190dvshot"))
  3210. {
  3211. // LYNX.exe --tour190dvshot prefix: round 190dv off-screen — the Simple workflow's Welcome screen, every step of
  3212. // the first-song tour done with its "Do it for me" (a loop dropped for the loop step), the end card, Back /
  3213. // Next / close, the Help menu, the chooser's tour button, Start from with the three demo songs, a demo
  3214. // opened in Simple — and a text report of the checks (incl. resources/demos/*.lynx = the generated songs)
  3215. const auto i = args.indexOf ("--tour190dvshot");
  3216. runTour190dvShot (args[i + 1].unquoted());
  3217. quit();
  3218. return;
  3219. }
  3220. if (args.contains ("--donateshot"))
  3221. {
  3222. // LYNX --donateshot prefix: round 190fq off-screen (no window) — Help › Support LYNX SHARE... in the three
  3223. // layouts, the Support window, the About window's Support button, the start-up support note in the main
  3224. // window, and the note's rules end to end on its saved state (run it with LYNX_PROFILE_DIR: it writes
  3225. // support-note.txt there, and puts the old one back at the end); report prefix-report.txt, exit 0 = OK
  3226. const auto i = args.indexOf ("--donateshot");
  3227. setApplicationReturnValue (runDonateShot (args[i + 1].unquoted()) ? 0 : 1);
  3228. quit();
  3229. return;
  3230. }
  3231. if (args.contains ("--simpleclosetest"))
  3232. {
  3233. // LYNX --simpleclosetest <report.txt>: round 190fc off-screen (no window) — the main window in the Simple
  3234. // layout with Welcome, the tour, Start from, a demo, the dock's tabs, Finish and Lyrics open, then closed as at
  3235. // shutdown (the 0.1.27 RC crashed on every such close); exit code 0 = OK
  3236. const auto i = args.indexOf ("--simpleclosetest");
  3237. setApplicationReturnValue (runSimpleCloseTest (args[i + 1].unquoted()) ? 0 : 1);
  3238. quit();
  3239. return;
  3240. }
  3241. if (args.contains ("--patterns190ea"))
  3242. {
  3243. // LYNX --patterns190ea <report.txt>: round 190ea off-screen (no window) — a song with no pattern at all
  3244. // reaching the engine in every layout (the Simple dock's Editor tab, the Piano roll panel of the Pattern
  3245. // layout, the Clip-launch layout), the last pattern deleted, all patterns cleared by an edit, undo / redo,
  3246. // a live session's remote song and an out-of-range current pattern; each must leave one pattern and not crash
  3247. const auto i = args.indexOf ("--patterns190ea");
  3248. setApplicationReturnValue (runPatterns190ea (args[i + 1].unquoted()) ? 0 : 1);
  3249. quit();
  3250. return;
  3251. }
  3252. if (args.contains ("--reabl190foshot"))
  3253. {
  3254. // LYNX --reabl190foshot prefix: round 190fo off-screen — the Simple Sampler track's 16 pads in the dock, its
  3255. // menus and kits, the typing keys, the .lynx round trip, a folder of stems and MIDI files — and a report
  3256. const auto i = args.indexOf ("--reabl190foshot");
  3257. runReabl190foShot (args[i + 1].unquoted());
  3258. quit();
  3259. return;
  3260. }
  3261. if (args.contains ("--simple190dsshot"))
  3262. {
  3263. // LYNX.exe --simple190dsshot prefix: round 190ds off-screen, at 1x and 2x — loops dropped in the Simple
  3264. // workflow following the project key (the dock's switch, the clip menu), the docked Piano roll in the Editor
  3265. // tab, the keyboard's modes Keys / Scale keys / Chord pad with the scale selector — and a text report
  3266. const auto i = args.indexOf ("--simple190dsshot");
  3267. runSimple190dsShot (args[i + 1].unquoted());
  3268. quit();
  3269. return;
  3270. }
  3271. if (args.contains ("--simple190dgshot"))
  3272. {
  3273. // LYNX.exe --simple190dgshot prefix: round 190dg's additions to the Simple dock off-screen, at 1x and 2x —
  3274. // the Effects tab with all eight one-knob cards and each card alone, a chain preset with Blend, the
  3275. // favourites in the Preset menu, the sound picker (a search, My plugins with a made-up plugin list) — and a
  3276. // text report of the checks
  3277. const auto i = args.indexOf ("--simple190dgshot");
  3278. runSimple190dgShot (args[i + 1].unquoted());
  3279. quit();
  3280. return;
  3281. }
  3282. if (args.contains ("--simplefxshot"))
  3283. {
  3284. // LYNX.exe --simplefxshot prefix: round 190bu's track dock of the Simple workflow off-screen, at 1x and 2x —
  3285. // the Instrument tab (LYNX sounds, My SoundFonts), the Effects tab (empty, a preset, its menus), and a text
  3286. // report: the dock's edits, a user preset saved and loaded, the same slots in the Pattern workflow's Mixer
  3287. const auto i = args.indexOf ("--simplefxshot");
  3288. runSimpleFxShot (args[i + 1].unquoted());
  3289. quit();
  3290. return;
  3291. }
  3292. if (args.contains ("--simple190jcshot"))
  3293. {
  3294. // LYNX.exe --simple190jcshot prefix: round 190jc's Simple layout look (design190ia slices 5, 14, 15, 22, 24 and
  3295. // Large controls) off-screen, at 1x and 2x, with a text report
  3296. const auto i = args.indexOf ("--simple190jcshot");
  3297. runSimple190jcShot (args[i + 1].unquoted());
  3298. quit();
  3299. return;
  3300. }
  3301. if (args.contains ("--simpleshot"))
  3302. {
  3303. // LYNX.exe --simpleshot prefix: round 184a's Simple workflow off-screen — View › Layout style with each style
  3304. // chosen, Settings › General (Pattern, then Simple selected) with its style list, the window in Pattern, then
  3305. // Simple, then Pattern again, and how many Simple workflow objects existed before and after (0 before)
  3306. const auto i = args.indexOf ("--simpleshot");
  3307. runSimpleShot (args[i + 1].unquoted());
  3308. quit();
  3309. return;
  3310. }
  3311. // --versionsshot <prefix> (round 190ap): the Versions panel, File's new items, a project opened without its
  3312. // third-party plugins (window, list, File menu) and the Export window's additions, offscreen
  3313. if (args.contains ("--versionsshot"))
  3314. {
  3315. runVersionsShot (args[args.indexOf ("--versionsshot") + 1].unquoted());
  3316. quit();
  3317. return;
  3318. }
  3319. // --linkshot <prefix> (round 190bt): FL's Remote control settings / Global link settings windows, the control
  3320. // menu with "Link to controller...", the formula presets and controller menus and the Multilink items,
  3321. // offscreen; prefix-checks.txt holds the round's checks of the engine, the project file and the settings
  3322. if (args.contains ("--linkshot"))
  3323. {
  3324. setApplicationReturnValue (runLinkShot (args[args.indexOf ("--linkshot") + 1].unquoted()) ? 0 : 1);
  3325. quit();
  3326. return;
  3327. }
  3328. // --flctlshot <prefix> (round 190df): FL's multilink menu (on / off), the plugin menu's A/B and "Link all
  3329. // parameters...", the sampler's File row with its Sample history, and the Envelope / instrument page of a sampler
  3330. // running FL's voice with its envelope presets, offscreen; prefix-checks.txt holds the checks
  3331. if (args.contains ("--flctlshot"))
  3332. {
  3333. setApplicationReturnValue (runFlCtlShot (args[args.indexOf ("--flctlshot") + 1].unquoted()) ? 0 : 1);
  3334. quit();
  3335. return;
  3336. }
  3337. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen (shots and checks in prefix-checks.txt)
  3338. if (args.contains ("--samplerpageshot"))
  3339. {
  3340. setApplicationReturnValue (runSamplerPageShot (args[args.indexOf ("--samplerpageshot") + 1].unquoted()) ? 0 : 1);
  3341. quit();
  3342. return;
  3343. }
  3344. // --flplshot <prefix> (round 190dx): the audio clip menu (Preview, Automate › Panning / Volume), the Playlist's "+"
  3345. // and its menu, Track mode › Instrument track, the Channel rack's "Assign to new instrument track", Tools › One-click
  3346. // audio recording and Mixer › Disk recording › Latency compensation, offscreen; prefix-checks.txt holds the checks
  3347. // --hdrshot190ft <prefix> (round 190ft, issues #163 / #164): FL's track-header selection and resize rules driven
  3348. // with synthetic mouse events on the Playlist headers and the mixer strips, offscreen; prefix-checks.txt
  3349. if (args.contains ("--hdrshot190ft"))
  3350. {
  3351. setApplicationReturnValue (runHdrShot190ft (args[args.indexOf ("--hdrshot190ft") + 1].unquoted()) ? 0 : 1);
  3352. quit();
  3353. return;
  3354. }
  3355. // --dawprojcheck190jf <prefix> <project> (round 190jf, slice B22): export to DAWproject and open it again
  3356. if (args.contains ("--dawprojcheck190jf") && args.indexOf ("--dawprojcheck190jf") + 2 < args.size())
  3357. {
  3358. const auto at = args.indexOf ("--dawprojcheck190jf");
  3359. setApplicationReturnValue (runDawProjectCheck190jf (args[at + 1].unquoted(), juce::File (args[at + 2].unquoted())) ? 0 : 1);
  3360. quit();
  3361. return;
  3362. }
  3363. // --foldersshot190jf <prefix> <thief.flp> (round 190jf, slice B17): the Playlist's folders; prefix-checks.txt
  3364. if (args.contains ("--foldersshot190jf") && args.indexOf ("--foldersshot190jf") + 2 < args.size())
  3365. {
  3366. const auto at = args.indexOf ("--foldersshot190jf");
  3367. setApplicationReturnValue (runFoldersShot190jf (args[at + 1].unquoted(), juce::File (args[at + 2].unquoted())) ? 0 : 1);
  3368. quit();
  3369. return;
  3370. }
  3371. // --userfixshot190ib <prefix> (round 190ib): issue #182's type-to-jump in a real popup menu (the Playlist's Edit menu
  3372. // of the issue's screenshot, typed into), #183's Piano roll item, #181's Ctrl+, through the main window's keys;
  3373. // prefix-checks.txt
  3374. if (args.contains ("--userfixshot190ib"))
  3375. {
  3376. setApplicationReturnValue (runUserFixShot190ib (args[args.indexOf ("--userfixshot190ib") + 1].unquoted()) ? 0 : 1);
  3377. quit();
  3378. return;
  3379. }
  3380. // --issuesshot190ht <prefix> (round 190ht): issue #127's other tools on Pattern Blocks (Mute, Select + group move,
  3381. // Slice, Zoom) and issue #154's insert effects list on linked headers, driven with synthetic mouse events,
  3382. // offscreen; prefix-checks.txt and pictures
  3383. if (args.contains ("--issuesshot190ht"))
  3384. {
  3385. setApplicationReturnValue (runIssuesShot190ht (args[args.indexOf ("--issuesshot190ht") + 1].unquoted()) ? 0 : 1);
  3386. quit();
  3387. return;
  3388. }
  3389. // --chordlane190pfshot <prefix> (round 190pf, research190oe P13 / P12): src/ChordLaneShot190pf.inc
  3390. if (args.contains ("--chordlane190pfshot"))
  3391. {
  3392. setApplicationReturnValue (runChordLaneShot190pf (args[args.indexOf ("--chordlane190pfshot") + 1].unquoted()) ? 0 : 1);
  3393. quit();
  3394. return;
  3395. }
  3396. // --sections190olshot <prefix> (round 190ol, research190oe P1 / P6): src/SectionsShot190ol.inc
  3397. if (args.contains ("--sections190olshot"))
  3398. {
  3399. setApplicationReturnValue (runSectionsShot190ol (args[args.indexOf ("--sections190olshot") + 1].unquoted()) ? 0 : 1);
  3400. quit();
  3401. return;
  3402. }
  3403. // --playlistshot190jq <prefix> (round 190jq, issues #164 and #191): src/PlaylistShot190jq.inc
  3404. if (args.contains ("--playlistshot190jq"))
  3405. {
  3406. setApplicationReturnValue (runPlaylistShot190jq (args[args.indexOf ("--playlistshot190jq") + 1].unquoted()) ? 0 : 1);
  3407. quit();
  3408. return;
  3409. }
  3410. // --focus218shot190ng <prefix> (round 190ng, issue #218): src/Focus218Shot190ng.inc
  3411. if (args.contains ("--focus218shot190ng"))
  3412. {
  3413. setApplicationReturnValue (runFocus218Shot190ng (args[args.indexOf ("--focus218shot190ng") + 1].unquoted()) ? 0 : 1);
  3414. quit();
  3415. return;
  3416. }
  3417. // --mixerqolshot190qh <prefix> [project.flp] (round 190qh, research190qa R5 Mixer QoL): src/MixerQolShot190qh.inc
  3418. if (args.contains ("--mixerqolshot190qh"))
  3419. {
  3420. const auto i = args.indexOf ("--mixerqolshot190qh");
  3421. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3422. setApplicationReturnValue (runMixerQolShot190qh (args[i + 1].unquoted(), project) ? 0 : 1);
  3423. quit();
  3424. return;
  3425. }
  3426. // --slots260shot <prefix> (round 190qf, PR #260: FL 2026.2's mixer slots): src/Slots260Shot190qf.inc
  3427. if (args.contains ("--slots260shot"))
  3428. {
  3429. setApplicationReturnValue (runSlots260Shot (args[args.indexOf ("--slots260shot") + 1].unquoted()) ? 0 : 1);
  3430. quit();
  3431. return;
  3432. }
  3433. // --mixer221shot190ng <prefix> (round 190ng, issue #221): src/Mixer221Shot190ng.inc
  3434. if (args.contains ("--mixer221shot190ng"))
  3435. {
  3436. setApplicationReturnValue (runMixer221Shot190ng (args[args.indexOf ("--mixer221shot190ng") + 1].unquoted()) ? 0 : 1);
  3437. quit();
  3438. return;
  3439. }
  3440. // --research190onshot <prefix> (round 190on: research190oe P2, P8, P10): src/Research190onShot.inc
  3441. if (args.contains ("--research190onshot"))
  3442. {
  3443. setApplicationReturnValue (runResearchShot190on (args[args.indexOf ("--research190onshot") + 1].unquoted()) ? 0 : 1);
  3444. quit();
  3445. return;
  3446. }
  3447. // --issuesshot190nq <prefix> (round 190nq, issues #193, #225-#230): src/IssuesShot190nq.inc
  3448. if (args.contains ("--issuesshot190nq"))
  3449. {
  3450. setApplicationReturnValue (runIssuesShot190nq (args[args.indexOf ("--issuesshot190nq") + 1].unquoted()) ? 0 : 1);
  3451. quit();
  3452. return;
  3453. }
  3454. // --design190ojshot <prefix> [project] (round 190oj, design review): src/Design190ojShot.inc
  3455. if (args.contains ("--design190ojshot"))
  3456. {
  3457. const auto i = args.indexOf ("--design190ojshot");
  3458. setApplicationReturnValue (runDesign190ojShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3459. quit();
  3460. return;
  3461. }
  3462. // --rackauto190owshot <prefix> [project.flp] [probe.flp] (round 190ow, PAT-7 rest / DE-123): src/RackAuto190owShot.inc
  3463. if (args.contains ("--rackauto190owshot"))
  3464. {
  3465. const auto i = args.indexOf ("--rackauto190owshot");
  3466. const auto arg = [&args] (int k) { return k < args.size() && ! args[k].startsWith ("--") ? args[k].unquoted() : juce::String(); };
  3467. setApplicationReturnValue (runRackAuto190owShot (args[i + 1].unquoted(), arg (i + 2), arg (i + 3)) ? 0 : 1);
  3468. quit();
  3469. return;
  3470. }
  3471. // --extras190qkshot <prefix> (round 190qk: the LYNX extras on by default, FL-exact / Recommended): src/Extras190qkShot.inc
  3472. if (args.contains ("--extras190qkshot"))
  3473. {
  3474. setApplicationReturnValue (runExtras190qkShot (args[args.indexOf ("--extras190qkshot") + 1].unquoted()) ? 0 : 1);
  3475. quit();
  3476. return;
  3477. }
  3478. // --design190ooshot <prefix> [project] (round 190oo, design review 2): src/Design190ooShot.inc
  3479. if (args.contains ("--design190ooshot"))
  3480. {
  3481. const auto i = args.indexOf ("--design190ooshot");
  3482. setApplicationReturnValue (runDesign190ooShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3483. quit();
  3484. return;
  3485. }
  3486. // --rollup031s3shot <prefix> (rollup 0.1.31 step 3, round 190ny): src/Rollup031S3Shot.inc
  3487. if (args.contains ("--rollup031s3shot"))
  3488. {
  3489. setApplicationReturnValue (runRollup031S3Shot (args[args.indexOf ("--rollup031s3shot") + 1].unquoted()) ? 0 : 1);
  3490. quit();
  3491. return;
  3492. }
  3493. // --tabs2test190nz <a|b> <folder> (round 190nz, issue #232 stage 2: copy and paste between two LYNX windows):
  3494. // src/Tabs2Test190nz.inc
  3495. if (args.contains ("--tabs2test190nz"))
  3496. {
  3497. const auto i = args.indexOf ("--tabs2test190nz");
  3498. setApplicationReturnValue (runTabs2Test190nz (args[i + 1].unquoted(), juce::File (args[i + 2].unquoted())) ? 0 : 1);
  3499. quit();
  3500. return;
  3501. }
  3502. // --headergearshot248 <prefix> (rollup 0.1.31 step 7, PRs #248 / #256): src/HeaderGearShot248.inc
  3503. if (args.contains ("--headergearshot248"))
  3504. {
  3505. setApplicationReturnValue (runHeaderGearShot (args[args.indexOf ("--headergearshot248") + 1].unquoted()) ? 0 : 1);
  3506. quit();
  3507. return;
  3508. }
  3509. // --hotfix190qpwfshot <prefix> (round 190qp, 0.1.31.1 hotfix): src/Hotfix190qpWf.inc, its checks and pictures
  3510. if (args.contains ("--hotfix190qpwfshot"))
  3511. {
  3512. const auto prefix = args[args.indexOf ("--hotfix190qpwfshot") + 1].unquoted();
  3513. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3514. const auto r = hotfix190qpWfCheck (prefix);
  3515. juce::File (prefix + "-checks.txt").replaceWithText ("hotfix190qp_wf=" + r + "\n");
  3516. setApplicationReturnValue (r == "OK" ? 0 : 1);
  3517. quit();
  3518. return;
  3519. }
  3520. // --pickerpaint190qi <report> (round 190qi): the plugin lists' and the Browser's paint cost, src/PickerPaintBench190qi.inc
  3521. if (args.contains ("--pickerpaint190qi"))
  3522. {
  3523. runPickerPaint190qi (juce::File (args[args.indexOf ("--pickerpaint190qi") + 1].unquoted()));
  3524. setApplicationReturnValue (0);
  3525. quit();
  3526. return;
  3527. }
  3528. // --picker190qishot <folder> (round 190qi, picker and Browser quality of life): src/Picker190qiShot.inc
  3529. if (args.contains ("--picker190qishot"))
  3530. {
  3531. setApplicationReturnValue (runPicker190qiShot (juce::File (args[args.indexOf ("--picker190qishot") + 1].unquoted())) ? 0 : 1);
  3532. quit();
  3533. return;
  3534. }
  3535. // --issuesshot190qo <prefix> (round 190qo, issues #239, #215, #251, #270): src/IssuesShot190qo.inc
  3536. if (args.contains ("--issuesshot190qo"))
  3537. {
  3538. setApplicationReturnValue (runIssuesShot190qo (args[args.indexOf ("--issuesshot190qo") + 1].unquoted()) ? 0 : 1);
  3539. quit();
  3540. return;
  3541. }
  3542. // --issuesshot190qb <prefix> (round 190qb, follow-ups of issues #206 and #215): src/IssuesShot190qb.inc
  3543. if (args.contains ("--issuesshot190qb"))
  3544. {
  3545. setApplicationReturnValue (runIssuesShot190qb (args[args.indexOf ("--issuesshot190qb") + 1].unquoted()) ? 0 : 1);
  3546. quit();
  3547. return;
  3548. }
  3549. // --issuesshot190oq <prefix> (round 190oq, issues #243-#252): src/IssuesShot190oq.inc
  3550. if (args.contains ("--issuesshot190oq"))
  3551. {
  3552. setApplicationReturnValue (runIssuesShot190oq (args[args.indexOf ("--issuesshot190oq") + 1].unquoted()) ? 0 : 1);
  3553. quit();
  3554. return;
  3555. }
  3556. // --issuesshot190od <prefix> (round 190od, issues #236-#242): src/IssuesShot190od.inc
  3557. if (args.contains ("--issuesshot190od"))
  3558. {
  3559. setApplicationReturnValue (runIssuesShot190od (args[args.indexOf ("--issuesshot190od") + 1].unquoted()) ? 0 : 1);
  3560. quit();
  3561. return;
  3562. }
  3563. // --issuesshot190ns <prefix> (round 190ns, issues #231-#235): src/IssuesShot190ns.inc
  3564. if (args.contains ("--issuesshot190ns"))
  3565. {
  3566. setApplicationReturnValue (runIssuesShot190ns (args[args.indexOf ("--issuesshot190ns") + 1].unquoted()) ? 0 : 1);
  3567. quit();
  3568. return;
  3569. }
  3570. // --issuesshot190ng <prefix> (round 190ng, issues #215, #217, #219, #220, #222): src/IssuesShot190ng.inc
  3571. if (args.contains ("--issuesshot190ng"))
  3572. {
  3573. setApplicationReturnValue (runIssuesShot190ng (args[args.indexOf ("--issuesshot190ng") + 1].unquoted()) ? 0 : 1);
  3574. quit();
  3575. return;
  3576. }
  3577. // --tracker190nwshot <prefix> [module] (round 190nw, 0.1.31: the built-in tracker): src/TrackerShot190nw.inc
  3578. if (args.contains ("--tracker190nwshot"))
  3579. {
  3580. const auto i = args.indexOf ("--tracker190nwshot");
  3581. setApplicationReturnValue (runTrackerShot190nw (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3582. quit();
  3583. return;
  3584. }
  3585. // --automodes190pashot <prefix> (round 190pa, 0.1.32: automation write modes, range edits on chosen tracks): src/AutoModesShot190pa.inc
  3586. if (args.contains ("--automodes190pashot"))
  3587. {
  3588. setApplicationReturnValue (runAutoModesShot190pa (args[args.indexOf ("--automodes190pashot") + 1].unquoted()) ? 0 : 1);
  3589. quit();
  3590. return;
  3591. }
  3592. // --trackstates190opshot <prefix> (round 190op, 0.1.31: Hide / Deactivate tracks, Capture automation): src/TrackStatesShot190op.inc
  3593. // --tracks190peshot <prefix> (round 190pe, 0.1.32: Track versions, Import tracks from another project): src/Tracks190peShot.inc
  3594. if (args.contains ("--tracks190peshot"))
  3595. {
  3596. setApplicationReturnValue (runTracks190peShot (args[args.indexOf ("--tracks190peshot") + 1].unquoted()) ? 0 : 1);
  3597. quit();
  3598. return;
  3599. }
  3600. if (args.contains ("--trackstates190opshot"))
  3601. {
  3602. setApplicationReturnValue (runTrackStatesShot190op (args[args.indexOf ("--trackstates190opshot") + 1].unquoted()) ? 0 : 1);
  3603. quit();
  3604. return;
  3605. }
  3606. // --trackclips190neshot <prefix> (round 190ne, 0.1.31: track clips): src/TrackClipsShot190ne.inc
  3607. if (args.contains ("--trackclips190neshot"))
  3608. {
  3609. setApplicationReturnValue (runTrackClipsShot190ne (args[args.indexOf ("--trackclips190neshot") + 1].unquoted()) ? 0 : 1);
  3610. quit();
  3611. return;
  3612. }
  3613. // --issueshot190mq <prefix> (round 190mq, issues #211, #212, #213): src/IssuesShot190mq.inc
  3614. if (args.contains ("--issueshot190mq"))
  3615. {
  3616. setApplicationReturnValue (runIssuesShot190mq (args[args.indexOf ("--issueshot190mq") + 1].unquoted()) ? 0 : 1);
  3617. quit();
  3618. return;
  3619. }
  3620. // --issueshot190lw <prefix> (round 190lw, issues #205, #206, #207): src/IssuesShot190lw.inc
  3621. if (args.contains ("--issueshot190lw"))
  3622. {
  3623. setApplicationReturnValue (runIssuesShot190lw (args[args.indexOf ("--issueshot190lw") + 1].unquoted()) ? 0 : 1);
  3624. quit();
  3625. return;
  3626. }
  3627. // --issueshot190jz <prefix> (round 190jz, issues #192, #194, #195): src/IssuesShot190jz.inc
  3628. if (args.contains ("--issueshot190jz"))
  3629. {
  3630. setApplicationReturnValue (runIssuesShot190jz (args[args.indexOf ("--issueshot190jz") + 1].unquoted()) ? 0 : 1);
  3631. quit();
  3632. return;
  3633. }
  3634. // --workflowshot190iu <prefix> (round 190iu, issues #186 and #191): src/WorkflowShot190iu.inc
  3635. if (args.contains ("--workflowshot190iu"))
  3636. {
  3637. setApplicationReturnValue (runWorkflowShot190iu (args[args.indexOf ("--workflowshot190iu") + 1].unquoted()) ? 0 : 1);
  3638. quit();
  3639. return;
  3640. }
  3641. // --trackautoshot190gz <prefix> (round 190gz, issue #170): LYNX's "Link Playlist tracks to mixer tracks" — the
  3642. // switch, the linked headers' M / S / volume / pan driven with synthetic mouse events, row sizes, undo and the
  3643. // .lynx round trip, offscreen; prefix-checks.txt
  3644. if (args.contains ("--trackautoshot190gz"))
  3645. {
  3646. setApplicationReturnValue (runTrackAutoShot190gz (args[args.indexOf ("--trackautoshot190gz") + 1].unquoted()) ? 0 : 1);
  3647. quit();
  3648. return;
  3649. }
  3650. if (args.contains ("--flplshot"))
  3651. {
  3652. setApplicationReturnValue (runFlPlShot (args[args.indexOf ("--flplshot") + 1].unquoted()) ? 0 : 1);
  3653. quit();
  3654. return;
  3655. }
  3656. // --genpresetshot <prefix> (round 190fs): the channel window's preset box with the user's own presets (Save
  3657. // preset..., Your presets, Delete preset, Show the presets folder) for Fruity DX10, 3x Osc and LYNX's synth, the
  3658. // name box, a load (one undo step) and the Browser's new channel, offscreen; prefix-checks.txt holds the checks
  3659. if (args.contains ("--genpresetshot"))
  3660. {
  3661. setApplicationReturnValue (runGenPresetShot (args[args.indexOf ("--genpresetshot") + 1].unquoted()) ? 0 : 1);
  3662. quit();
  3663. return;
  3664. }
  3665. // --flfixshot <prefix> (round 190ey): what the live FL session 190ew found different (the Sampler page, the
  3666. // Multilink menu, the Playlist, issue #152's question), offscreen; prefix-checks.txt holds the checks
  3667. if (args.contains ("--flfixshot"))
  3668. {
  3669. setApplicationReturnValue (runFlFixShot (args[args.indexOf ("--flfixshot") + 1].unquoted()) ? 0 : 1);
  3670. quit();
  3671. return;
  3672. }
  3673. // --flclipshot <prefix> (round 190dz): FL's audio clip menu layout (two columns, FL's sections, LYNX's own items at
  3674. // the end) and the channel's Misc › Levels adjustment, offscreen; prefix-checks.txt holds the checks
  3675. if (args.contains ("--flclipshot"))
  3676. {
  3677. setApplicationReturnValue (runFlClipShot (args[args.indexOf ("--flclipshot") + 1].unquoted()) ? 0 : 1);
  3678. quit();
  3679. return;
  3680. }
  3681. if (args.contains ("--warpshot"))
  3682. {
  3683. // LYNX.exe --warpshot prefix: round 190cg's pictures (warp commands in the audio editor, the Clip page's
  3684. // Audio panel, the arrangement with the loop switched off, a folded track, signature changes), off-screen
  3685. const auto i = args.indexOf ("--warpshot");
  3686. runWarpShot (args[i + 1].unquoted());
  3687. quit();
  3688. return;
  3689. }
  3690. // --bandlab190jrshot <prefix> (round 190jr): a .blx imported as Simple tracks, the region loop handle, the Simple
  3691. // automation view and its menu, the Extract stems form; <prefix>-report.txt with ok / FAIL lines
  3692. if (args.contains ("--bandlab190jrshot"))
  3693. {
  3694. runBandlab190jrShot (args[args.indexOf ("--bandlab190jrshot") + 1].unquoted());
  3695. quit();
  3696. return;
  3697. }
  3698. // --bandlabshot <prefix> (round 190ch): Lyrics / Notes, Reference match, Start from and Clean voice, offscreen
  3699. if (args.contains ("--bandlabshot"))
  3700. {
  3701. runBandlabShot (args[args.indexOf ("--bandlabshot") + 1].unquoted());
  3702. quit();
  3703. return;
  3704. }
  3705. if (args.contains ("--mpeshot190hy"))
  3706. {
  3707. // LYNX --mpeshot190hy prefix: round 190hy (issue #108, MPE stage 2) off-screen: the Piano roll's MPE lanes (pitch
  3708. // bend, slide, pressure) over notes with curves in Pattern workflow, then the Clip-launch layout's Clip page with
  3709. // its Notes and MPE tabs. Writes prefix-checks.txt.
  3710. runMpeShot190hy (args[args.indexOf ("--mpeshot190hy") + 1].unquoted());
  3711. quit();
  3712. return;
  3713. }
  3714. if (args.contains ("--detailshot"))
  3715. {
  3716. // LYNX.exe --detailshot prefix: the Clip-launch workflow's detail view off-screen (round 183a): a track's chain
  3717. // (instrument, effects, one off, one folded), its clip page, and Pattern workflow before / after, at
  3718. // LYNX_SNAPSHOT_SIZE. Writes prefix-counts.txt with what the chain shows.
  3719. const auto i = args.indexOf ("--detailshot");
  3720. runDetailShot (args[i + 1].unquoted());
  3721. quit();
  3722. return;
  3723. }
  3724. if (args.contains ("--meldshot190ko"))
  3725. {
  3726. // LYNX.exe --meldshot190ko prefix meld.adv spectraltime.adv spectralresonator.adv: round 190ko off-screen, in the
  3727. // Clip-launch layout: a track whose instrument is what a Live Meld preset imports onto (Braid) and whose insert
  3728. // holds what Spectral Time and Spectral Resonator presets import onto (Timeprism, Harmonia), on the Device View.
  3729. // Writes prefix-devices.png and prefix-checks.txt.
  3730. const auto i = args.indexOf ("--meldshot190ko");
  3731. runMeldShot190ko (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].unquoted(), args[i + 4].unquoted());
  3732. quit();
  3733. return;
  3734. }
  3735. if (args.contains ("--livedevshot190kk"))
  3736. {
  3737. // LYNX.exe --livedevshot190kk prefix: round 190kk off-screen, in the Clip-launch layout: a track whose insert holds
  3738. // what Live's Erosion, Vinyl Distortion and Corpus (Core Library presets) import onto — Corrode, Platter,
  3739. // Soundboard — on the Device View as ordinary effect cards. Writes prefix-devices.png and prefix-checks.txt.
  3740. runLiveDevShot190kk (args[args.indexOf ("--livedevshot190kk") + 1].unquoted());
  3741. quit();
  3742. return;
  3743. }
  3744. if (args.contains ("--liverackshot190hr"))
  3745. {
  3746. // LYNX.exe --liverackshot190hr prefix: round 190hr off-screen, in the Ableton-style layout: the Device View's
  3747. // instrument menu with Group / Ungroup, an instrument grouped into an Instrument Rack and back, a rack's Save
  3748. // Preset button and drop area (a device dropped in, an instrument refused), Live's own .adg presets opened
  3749. // with their chains, and a saved .adg read back. Writes prefix-checks.txt.
  3750. runLiveRackShot190hr (args[args.indexOf ("--liverackshot190hr") + 1].unquoted());
  3751. quit();
  3752. return;
  3753. }
  3754. if (args.contains ("--helixshot190mi"))
  3755. {
  3756. // LYNX --helixshot190mi prefix [bank preset name]: round 190mi off-screen, the Pattern layout's Helix channel
  3757. // window with Helix+'s strip, from a factory preset (default "Growl FM"): the device + strip, LFO 1 (drawn),
  3758. // the Matrix page (macros, Helix+'s rows); --shot-scale 1.5 --shot-suffix @150 for the 150 % pictures.
  3759. const auto i = args.indexOf ("--helixshot190mi");
  3760. runHelixShot190mi (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("Growl FM"));
  3761. quit();
  3762. return;
  3763. }
  3764. if (args.contains ("--helixshot190oc"))
  3765. {
  3766. // LYNX --helixshot190oc prefix: round 190oc off-screen: the Pattern layout's Helix channel window with round 4's
  3767. // row (Grain Swarm, Spectral Ensemble; Frozen Choir and Triple Stack for the side by side with 190mt), the strip's
  3768. // row alone; paint costs in prefix-checks.txt
  3769. runHelixShot190oc (args[args.indexOf ("--helixshot190oc") + 1].unquoted());
  3770. quit();
  3771. return;
  3772. }
  3773. if (args.contains ("--helixshot190mt"))
  3774. {
  3775. // LYNX --helixshot190mt prefix: round 190mt off-screen: the Pattern layout's Helix channel window with round 3's
  3776. // row (Grain Cloud, Frozen Choir, Spectral Glass; Triple Stack for the side by side with 190ml), the Matrix page with
  3777. // the new rows, and the Clip-launch Device View card's Helix+ panel; paint costs in prefix-checks.txt.
  3778. runHelixShot190mt (args[args.indexOf ("--helixshot190mt") + 1].unquoted());
  3779. quit();
  3780. return;
  3781. }
  3782. if (args.contains ("--helixshot190ml"))
  3783. {
  3784. // LYNX --helixshot190ml prefix: round 190ml off-screen: the Pattern layout's Helix channel window with Helix+ 2's
  3785. // rows (Triple Stack, Vowel Sync), the Matrix page's Macros tab, the table editor (Draw, Harmonics) and the
  3786. // Clip-launch Device View card without / with its Helix+ panel; paint costs in prefix-checks.txt.
  3787. runHelixShot190ml (args[args.indexOf ("--helixshot190ml") + 1].unquoted());
  3788. quit();
  3789. return;
  3790. }
  3791. if (args.contains ("--helixshot190ja"))
  3792. {
  3793. // LYNX --helixshot190ja prefix [Wavetable preset .adv]: round 190ja off-screen, the Clip-launch layout's Device
  3794. // View with a Helix track (the preset's values imported as a Live set would bring them, else Helix's defaults):
  3795. // the device and its pages (Matrix, MIDI, MPE, Env 2, LFO 1, Osc 2), then the Pattern layout's channel window.
  3796. const auto i = args.indexOf ("--helixshot190ja");
  3797. runHelixShot190ja (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String());
  3798. quit();
  3799. return;
  3800. }
  3801. if (args.contains ("--liveshot190ce"))
  3802. {
  3803. // LYNX.exe --liveshot190ce prefix: round 190ce off-screen, in the Ableton-style layout: the Device View's cards
  3804. // with their hot-swap and save buttons, a device's menu, hot-swap on (the Browser's bar, the lit button), a
  3805. // swap and its undo, a duplicate, and the Browser's collections (STARRED tab, the Collections menu, a search
  3806. // by a collection's name). Writes prefix-checks.txt.
  3807. runLiveShot190ce (args[args.indexOf ("--liveshot190ce") + 1].unquoted());
  3808. quit();
  3809. return;
  3810. }
  3811. if (args.contains ("--missingsearchshot190eo"))
  3812. {
  3813. // LYNX --missingsearchshot190eo prefix folder...: round 190eo (integration of issue #159's fix) off-screen: the
  3814. // Missing files window's Samples page while a real search of the folders runs (matches streamed in, Stop
  3815. // shown, Apply usable). Writes prefix-searching.png and prefix-checks.txt; the search is let go at the end.
  3816. const auto i = args.indexOf ("--missingsearchshot190eo");
  3817. const auto prefix = args[i + 1].unquoted();
  3818. juce::StringArray folders;
  3819. for (int k = i + 2; k < args.size(); ++k)
  3820. folders.add (args[k].unquoted());
  3821. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3822. std::shared_ptr<juce::Component> panel = lynx::makeMissingFilesPanelSearching (lynx::missingFilesSnapshotInfo(), folders);
  3823. juce::Timer::callAfterDelay (700, [this, panel, prefix] {
  3824. juce::String status;
  3825. bool stopShown = false, applyEnabled = false;
  3826. const auto searching = lynx::missingFilesSearchState (*panel, status, stopShown, applyEnabled);
  3827. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  3828. const auto file = juce::File (prefix + "-searching.png");
  3829. file.deleteFile();
  3830. if (auto out = file.createOutputStream())
  3831. juce::PNGImageFormat().writeImageToStream (image, *out);
  3832. juce::String checks;
  3833. auto check = [&checks] (const char* name, bool ok, const juce::String& detail) {
  3834. checks << name << "=" << (ok ? "OK" : "FAIL") << " " << detail << "\n";
  3835. };
  3836. check ("still_searching_at_the_shot", searching, {});
  3837. check ("status_shows_the_walk", status.contains (lynx::tr ("Searching {0}... {1} files looked at").upToFirstOccurrenceOf ("{0}", false, false)), status);
  3838. check ("stop_shown", stopShown, {});
  3839. check ("apply_usable_during_the_search", applyEnabled, {});
  3840. lynx::stopMissingFilesSearch (*panel);
  3841. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  3842. quit();
  3843. });
  3844. return;
  3845. }
  3846. // --grooveshot190fm <prefix> (round 190fm): a Playlist pattern clip's menu with its Groove items (the chooser, Commit,
  3847. // Extract) and the "Classic swing" folder, and a Groove Pool holding classic swing grooves, offscreen;
  3848. // prefix-checks.txt holds the checks (also the .lynx round trip of a Playlist clip's groove)
  3849. if (args.contains ("--grooveshot190fm"))
  3850. {
  3851. setApplicationReturnValue (runGrooveShot190fm (args[args.indexOf ("--grooveshot190fm") + 1].unquoted()) ? 0 : 1);
  3852. quit();
  3853. return;
  3854. }
  3855. if (args.contains ("--mtshot190fm"))
  3856. {
  3857. // LYNX --mtshot190fm prefix: round 190fm off-screen: the MIDI Tools panel's Generate tab with each generator
  3858. // (prefix-generate-rhythm.png … -euclidean.png), the five side by side as Live's picture shows them
  3859. // (prefix-generate-panels.png; Live's: ableton190o/shots/live-04-generate-panels.png), then each generator
  3860. // written into a one-bar pattern and undone again: prefix-checks.txt.
  3861. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3862. runMtShot190fm (args[args.indexOf ("--mtshot190fm") + 1].unquoted());
  3863. quit();
  3864. return;
  3865. }
  3866. if (args.contains ("--drumshot190ec"))
  3867. {
  3868. // LYNX.exe --drumshot190ec prefix: round 190ec off-screen: a demo Drum Rack's pad view (default and scrolled), its
  3869. // chain list with I-O, sends and return chains, a new empty Drum Rack and the Piano roll's pad names. Writes
  3870. // prefix-checks.txt (hit tests: C1 bottom-left, overview scroll, a pad dragged onto another swaps them).
  3871. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3872. lynx::drumshot::run (args[args.indexOf ("--drumshot190ec") + 1].unquoted());
  3873. quit();
  3874. return;
  3875. }
  3876. if (args.contains ("--linkshot190gl"))
  3877. {
  3878. // LYNX --linkshot190gl prefix (round 190gl): Ableton Link off-screen with a second Link peer in this process —
  3879. // the toolbar in FL's Pattern layout (hidden by default, then shown, off and on) and in the Clip-launch layout
  3880. // ("1 Link", the position display's progress bar, Play waiting), Settings › Ableton Link, the toggle's
  3881. // drop-down and the Options menu. Writes prefix-checks.txt.
  3882. runLinkShot190gl (args[args.indexOf ("--linkshot190gl") + 1].unquoted());
  3883. quit();
  3884. return;
  3885. }
  3886. if (args.contains ("--communityshot190hp"))
  3887. {
  3888. // LYNX --communityshot190hp prefix (round 190hp): global MIDI mappings, Mix snapshots and Split at silence
  3889. // off-screen; writes prefix-checks.txt
  3890. runCommunityShot190hp (args[args.indexOf ("--communityshot190hp") + 1].unquoted());
  3891. quit();
  3892. return;
  3893. }
  3894. if (args.contains ("--mapshot190ef"))
  3895. {
  3896. // LYNX.exe --mapshot190ef prefix: round 190ef's map modes off-screen, in the Clip-launch workflow: MIDI Map Mode
  3897. // (the overlay over the grid, the Session mixer, the Device View and the transport; the Mapping Browser with
  3898. // Min / Max), Key Map Mode, the row menu, the title bar's Draw / Key / MIDI switches, Ctrl+M / Ctrl+K and the
  3899. // Pattern layout keeping Ctrl+M. Writes prefix-checks.txt.
  3900. runMapShot190ef (args[args.indexOf ("--mapshot190ef") + 1].unquoted());
  3901. quit();
  3902. return;
  3903. }
  3904. if (args.contains ("--sceneshot190ef"))
  3905. {
  3906. // LYNX.exe --sceneshot190ef prefix: round 190ef's scene work off-screen, in the Clip-launch workflow: the scene
  3907. // column with its tempo / time signature fields, the scene menu, a scene field's menu, the column title's menu
  3908. // (Rename, colours), a duplicated scene and a captured scene. Writes prefix-checks.txt.
  3909. runSceneShot190ef (args[args.indexOf ("--sceneshot190ef") + 1].unquoted());
  3910. quit();
  3911. return;
  3912. }
  3913. if (args.contains ("--drawshot190ef"))
  3914. {
  3915. // LYNX.exe --drawshot190ef prefix: round 190ef off-screen, in the Clip-launch workflow: Draw Mode in an
  3916. // automation lane, steps at the grid width and an Alt (no grid) freehand stroke drawn through the Playlist's
  3917. // own mouse handlers, and the Options menu with "Draw Mode". Writes prefix-checks.txt.
  3918. runDrawShot190ef (args[args.indexOf ("--drawshot190ef") + 1].unquoted());
  3919. quit();
  3920. return;
  3921. }
  3922. if (args.contains ("--clipenvshot190gi"))
  3923. {
  3924. // LYNX.exe --clipenvshot190gi prefix: round 190gi off-screen: audio clip envelopes on the Playlist (volume and
  3925. // pan lanes, edited through the Playlist's own mouse handlers), the clip menu's LYNX extras (Clip envelope ›,
  3926. // Auto-warp, Quantize audio, run from the menu), warp flags added on the flag strip and moved with Alt + drag,
  3927. // and the Clip-launch Clip View's Envelopes tab (Clip › Gain, Mixer › Track Panning). Writes prefix-checks.txt.
  3928. runClipEnvShot190gi (args[args.indexOf ("--clipenvshot190gi") + 1].unquoted());
  3929. quit();
  3930. return;
  3931. }
  3932. if (args.contains ("--gapsshot190kf"))
  3933. {
  3934. // LYNX.exe --gapsshot190kf prefix [file.wav]: round gaps190kf off-screen: the Clip View's warp time line (Live's
  3935. // loop brace and Start / End markers under the beat-time ruler, the seconds ruler of an unwarped clip) on the
  3936. // probe of gaps190kf/live/cv-clipview.als (voice.wav, warp markers at 30 % / 55 %, Loop 1.3 … 3.3, Start 1.4).
  3937. const auto i = args.indexOf ("--gapsshot190kf");
  3938. runGapsShot190kf (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  3939. quit();
  3940. return;
  3941. }
  3942. if (args.contains ("--livefactsshot190gx"))
  3943. {
  3944. // LYNX.exe --livefactsshot190gx prefix: round 190gx off-screen: the Clip page's Audio panel in Live's 190gu
  3945. // layout (Beats: Preserve label + chooser, the loop-mode icon chooser beside the Transient Envelope box;
  3946. // Tones / Texture: Grain Size [+ Flux]; Complex [Pro]), the Envelopes tab with a Clip Gain staircase on Live's
  3947. // axis, choosers at the bottom left, and an unwarped clip without the Envelopes tab. Writes prefix-checks.txt.
  3948. runLiveFactsShot190gx (args[args.indexOf ("--livefactsshot190gx") + 1].unquoted());
  3949. quit();
  3950. return;
  3951. }
  3952. if (args.contains ("--dvshot190hr"))
  3953. {
  3954. // LYNX.exe --dvshot190hr prefix: round 190hr off-screen, the Clip-launch Clip View: a MIDI clip whose Start
  3955. // marker sits inside its loop, with its own scale and a follow action (Launch panel controls), the docked
  3956. // editor's grid value and menu, Ctrl+1 / Ctrl+3 / Ctrl+U on it, the Quantize Settings panel, and an audio clip
  3957. // transposed past ±12. Writes prefix-checks.txt.
  3958. runDvShot190hr (args[args.indexOf ("--dvshot190hr") + 1].unquoted());
  3959. quit();
  3960. return;
  3961. }
  3962. if (args.contains ("--warpshot190fm"))
  3963. {
  3964. // LYNX.exe --warpshot190fm prefix: round 190fm off-screen: the Clip page's Audio panel of a grid audio clip in
  3965. // Beats (Preserve, Transient Loop Mode, Envelope), Tones and Texture (Grain Size), Complex (none), and the clip
  3966. // made unique by a mode change while another clip shares its channel (O16). Writes prefix-checks.txt.
  3967. runWarpShot190fm (args[args.indexOf ("--warpshot190fm") + 1].unquoted());
  3968. quit();
  3969. return;
  3970. }
  3971. if (args.contains ("--liveshot190dr"))
  3972. {
  3973. // LYNX.exe --liveshot190dr prefix: round 190dr off-screen, in the Clip-launch workflow: the Session mixer
  3974. // under the clip grid (default sections, Track Options, Volume only, hidden, its View menu), the Clip page's
  3975. // Sample panel of an audio clip (Warp on / off, the Set buttons while it plays, the sample's title) and a
  3976. // device dragged from one track's Device View to another track. Writes prefix-checks.txt.
  3977. runLiveShot190dr (args[args.indexOf ("--liveshot190dr") + 1].unquoted());
  3978. quit();
  3979. return;
  3980. }
  3981. if (args.contains ("--modshot190ox"))
  3982. {
  3983. // LYNX.exe --modshot190ox prefix [--shot-scale 1.5 --shot-suffix @150] (round 190ox, modulators stage 2): the
  3984. // Modulators window, rings on knobs, the Modulate with menu; checks in prefix-checks.txt
  3985. runModShot190ox (args[args.indexOf ("--modshot190ox") + 1].unquoted());
  3986. quit();
  3987. return;
  3988. }
  3989. if (args.contains ("--gapshot190og"))
  3990. {
  3991. // LYNX.exe --gapshot190og prefix [--shot-scale 1.5 --shot-suffix @150] (round gap190og, coverage rows still open on
  3992. // 0.1.31): in the Clip-launch layout, the Edit menu's Live block on the Device View (deviceview-0012), the Clip
  3993. // panel's Duplicate (Loop) button (detail-019), the clip menu's Crop Clip and Ctrl+Shift+J (detail-020), the
  3994. // Velocity lane's Randomize footer (detail-047), Key Map Mode on the transport switches (mapping-0028);
  3995. // checks in prefix-checks.txt
  3996. runGapShot190og (args[args.indexOf ("--gapshot190og") + 1].unquoted());
  3997. quit();
  3998. return;
  3999. }
  4000. if (args.contains ("--undoshot190mz"))
  4001. {
  4002. // LYNX.exe --undoshot190mz prefix [--shot-scale 1.5 --shot-suffix @150] (round 190mz, issue #214): the main
  4003. // window's undo keys with three edits, in both "Alternate undo mode" settings, and the Edit menu after each
  4004. // step in the Pattern, Clip-launch and Simple layouts (prefix-menu-*.png); checks in prefix-checks.txt
  4005. runUndoShot190mz (args[args.indexOf ("--undoshot190mz") + 1].unquoted());
  4006. quit();
  4007. return;
  4008. }
  4009. if (args.contains ("--design190igs4shot"))
  4010. {
  4011. // LYNX.exe --design190igs4shot prefix [set.als]: round 190ig slice 4 off-screen, in the Clip-launch layout with the
  4012. // set imported there (Live's colours, CL-6): the Session grid in Live's look idle, then the launch states —
  4013. // playing, a launch waiting (both blink phases), a stop waiting, recording, the status pie at 25 / 50 / 75 % —
  4014. // and the same with Animations off, then round 181a's look (the option); prefix-checks.txt
  4015. const auto i = args.indexOf ("--design190igs4shot");
  4016. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  4017. runDesign190igS4Shot (args[i + 1].unquoted(), project);
  4018. quit();
  4019. return;
  4020. }
  4021. if (args.contains ("--typeaheadtest"))
  4022. {
  4023. // LYNX.exe --typeaheadtest out.txt: issue #64 — a real popup menu (headings, a submenu) driven by key presses
  4024. // through its window's peer, as the OS delivers them; writes what got the highlight and what was picked
  4025. const auto i = args.indexOf ("--typeaheadtest");
  4026. runTypeAheadTest (juce::File (args[i + 1].unquoted()));
  4027. return;
  4028. }
  4029. if (args.contains ("--choosertest"))
  4030. {
  4031. // LYNX --choosertest out.txt file: issue #72 — opens LYNX's file chooser as the UI does (makeFileChooser +
  4032. // launchChooser) and reports which dialog came up and what reached the callback. A built-in dialog is shot
  4033. // (out.txt.png), `file` typed into it and confirmed; a native one (zenity / kdialog) is left to answer.
  4034. const auto i = args.indexOf ("--choosertest");
  4035. runChooserTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  4036. return;
  4037. }
  4038. if (args.contains ("--stabilityshot"))
  4039. {
  4040. // LYNX --stabilityshot <folder> (round 190gg): offscreen PNGs of the crash prompt, the plugin window's crash
  4041. // notice, the Plugin manager's "Separate process" column and the monitor's dropout line (no window opens)
  4042. const auto i = args.indexOf ("--stabilityshot");
  4043. runStabilityShot (args[i + 1].unquoted());
  4044. return;
  4045. }
  4046. if (args.contains ("--repeats190pmshot"))
  4047. {
  4048. // LYNX --repeats190pmshot <folder> (round 190pm, research190oe P19 / P23): Note Repeats and Conditions, Touch mode
  4049. setApplicationReturnValue (runRepeatsShot190pm (args[args.indexOf ("--repeats190pmshot") + 1].unquoted()) ? 0 : 1);
  4050. quit();
  4051. return;
  4052. }
  4053. if (args.contains ("--discord190qushot"))
  4054. {
  4055. // LYNX --discord190qushot <folder> [lanes.flp] (round 190qu, Discord 11-24): keys, Clip View, lanes, Simple, Track-only
  4056. const auto i = args.indexOf ("--discord190qushot");
  4057. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  4058. setApplicationReturnValue (runDiscordShot190qu (args[i + 1].unquoted(), project) ? 0 : 1);
  4059. quit();
  4060. return;
  4061. }
  4062. if (args.contains ("--simpleduck190otshot"))
  4063. {
  4064. // LYNX --simpleduck190otshot <folder> (round 190ot, research190oe P5): "Duck under..." and the Echo send at 100 / 150 %
  4065. setApplicationReturnValue (runSimpleDuckShot190ot (args[args.indexOf ("--simpleduck190otshot") + 1].unquoted()) ? 0 : 1);
  4066. quit();
  4067. return;
  4068. }
  4069. if (args.contains ("--smarttipshot190ok"))
  4070. {
  4071. // LYNX --smarttipshot190ok <folder> [project.flp] (round 190ok, D1): the smart-disable tip at 100 / 150 %
  4072. const auto i = args.indexOf ("--smarttipshot190ok");
  4073. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  4074. setApplicationReturnValue (runSmartTipShot190ok (args[i + 1].unquoted(), project) ? 0 : 1);
  4075. quit();
  4076. return;
  4077. }
  4078. if (args.contains ("--monitorshot190of"))
  4079. {
  4080. // LYNX --monitorshot190of <folder> (round 190of): the Plugin performance monitor with its sample numbers
  4081. // (Longest, Spikes) at 100 % and 150 %, off screen
  4082. const juce::File dir (args[args.indexOf ("--monitorshot190of") + 1].unquoted());
  4083. dir.createDirectory();
  4084. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4085. {
  4086. lynx::AudioEngine offline (false);
  4087. lynx::MainComponent ui (offline, false);
  4088. offline.dispatchPendingMessages();
  4089. for (const auto scale : { 1.0f, 1.5f })
  4090. {
  4091. auto panel = lynx::makePluginMonitorPanel (offline);
  4092. juce::Component frame;
  4093. frame.setSize (panel->getWidth(), panel->getHeight());
  4094. frame.setOpaque (true);
  4095. frame.addAndMakeVisible (*panel);
  4096. savePng (frame.createComponentSnapshot (frame.getLocalBounds(), true, scale),
  4097. dir.getChildFile (scale > 1.0f ? "plugin-monitor@150.png" : "plugin-monitor.png").getFullPathName());
  4098. }
  4099. }
  4100. setApplicationReturnValue (0);
  4101. quit();
  4102. return;
  4103. }
  4104. if (args.contains ("--jsfxshots"))
  4105. {
  4106. // LYNX --jsfxshots <folder> [--shot-scale 1.5 --shot-suffix @150] (round 190pj): the JSFX slider panels of
  4107. // bundled scripts, the Browser's JSFX category and Settings › File with the JSFX folders, off screen
  4108. const auto i = args.indexOf ("--jsfxshots");
  4109. runJsfxShots (args[i + 1].unquoted());
  4110. return;
  4111. }
  4112. if (args.contains ("--snapshot"))
  4113. {
  4114. const auto i = args.indexOf ("--snapshot");
  4115. runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
  4116. return;
  4117. }
  4118. if (args.contains ("--stemsplit"))
  4119. {
  4120. // LYNX.exe --stemsplit input.wav folder ["stems=111100 model=2 ..."]: the stem separation of the clip menu,
  4121. // without the window (round 190jr: the options as the settings file writes them; none = every stem, Standard)
  4122. const auto i = args.indexOf ("--stemsplit");
  4123. lynx::AudioEngine loader (false);
  4124. const auto options = i + 3 < args.size() && args[i + 3].unquoted().containsChar ('=') ? lynx::stemsplit::optionsFromText (args[i + 3].unquoted().toStdString())
  4125. : lynx::stemsplit::Options {};
  4126. const auto started = juce::Time::getMillisecondCounterHiRes();
  4127. const auto error = lynx::extractStemsToFolder (loader, juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), options);
  4128. std::fprintf (stderr, "stemsplit: %.0f ms\n", juce::Time::getMillisecondCounterHiRes() - started);
  4129. juce::File (args[i + 2].unquoted()).getSiblingFile ("stemsplit.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  4130. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  4131. quit();
  4132. return;
  4133. }
  4134. if (args.contains ("--audio2midi"))
  4135. {
  4136. // LYNX.exe --audio2midi input.wav melody|harmony|drums notes.csv: the clip menu's Convert to MIDI, without the
  4137. // window (round a2m189b's measurements)
  4138. // Round 190lj: mode "poly" = the "Convert to MIDI (polyphonic)" dialog's path, settings after the CSV as
  4139. // key=value (poly=0|1 note=0..1 split=0..1 minms=N low=K high=K bends=0|1); audio2midi.txt also gets the
  4140. // seconds spent resampling, in the model and making the notes.
  4141. const auto i = args.indexOf ("--audio2midi");
  4142. const auto mode = args[i + 2] == "drums" ? lynx::a2m::Mode::drums : args[i + 2] == "harmony" ? lynx::a2m::Mode::harmony : lynx::a2m::Mode::melody;
  4143. lynx::AudioEngine loader (false);
  4144. const juce::File csv (args[i + 3].unquoted());
  4145. juce::String error, timing;
  4146. if (args[i + 2] == "poly")
  4147. {
  4148. lynx::a2m::ConvertOptions options;
  4149. for (int k = i + 4; k < args.size() && args[k].containsChar ('='); ++k)
  4150. {
  4151. const auto key = args[k].upToFirstOccurrenceOf ("=", false, false);
  4152. const auto value = args[k].fromFirstOccurrenceOf ("=", false, false);
  4153. if (key == "poly") options.polyphonic = value.getIntValue() != 0;
  4154. else if (key == "note") options.noteSensitivity = value.getFloatValue();
  4155. else if (key == "split") options.splitSensitivity = value.getFloatValue();
  4156. else if (key == "minms") options.minNoteMs = value.getDoubleValue();
  4157. else if (key == "low") options.minKey = value.getIntValue();
  4158. else if (key == "high") options.maxKey = value.getIntValue();
  4159. else if (key == "bends") options.pitchBends = value.getIntValue() != 0;
  4160. }
  4161. error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), options, csv, &timing);
  4162. }
  4163. else
  4164. error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), mode, csv);
  4165. csv.getSiblingFile ("audio2midi.txt").replaceWithText (error.isEmpty() ? "result=OK\n" + (timing.isEmpty() ? juce::String() : "seconds=" + timing + "\n")
  4166. : "result=FAIL " + error + "\n");
  4167. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  4168. quit();
  4169. return;
  4170. }
  4171. if (args.contains ("--stems") || args.contains ("--stemexport"))
  4172. {
  4173. // LYNX.exe --stems project.(flp|als|lynx) base.wav [--separate]: one WAV per insert that has sound (like
  4174. // "Export stems"), in one render of the song (round 190gj; --separate: one render per insert, as before).
  4175. // LYNX.exe --stemexport project base.ext options.txt [--separate]: what the Export window writes with these
  4176. // options (exportopts::toText lines: stems, sections, the full mix, formats...), the same code.
  4177. // Both write <base>.txt: the files with their peaks, the renders, the wall and CPU time.
  4178. const auto full = args.contains ("--stemexport");
  4179. const auto i = args.indexOf (full ? "--stemexport" : "--stems");
  4180. const auto separate = args.contains ("--separate");
  4181. juce::String error, report;
  4182. int written = 0;
  4183. {
  4184. lynx::AudioEngine loader (false);
  4185. const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
  4186. // an .flp or a Live set (.als) opens through the import, as File › Open does (round 182b)
  4187. auto ok = input.hasFileExtension ("flp;als") ? loader.importFlpFile (input, error) : false;
  4188. if (! input.hasFileExtension ("flp;als"))
  4189. if (auto song = lynx::ProjectFile::load (input, error))
  4190. {
  4191. loader.setSong (std::move (*song));
  4192. ok = true;
  4193. }
  4194. const auto& song = loader.getSong();
  4195. lynx::StemPlan plan;
  4196. if (full && ok)
  4197. plan = lynx::planStemExport (song, lynx::exportopts::fromText (juce::File (args[i + 3].unquoted()).loadFileAsString().toStdString()), base);
  4198. else if (ok)
  4199. {
  4200. // every insert a channel goes to, as "<base> - <insert>.wav", 24-bit, 6 s of tail at most
  4201. lynx::ExportSettings settings;
  4202. plan.sets.push_back ({ song, settings.toOptions() });
  4203. for (int t = 1; t < (int) song.mixer.size(); ++t)
  4204. if (std::any_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  4205. plan.items.push_back ({ juce::String (t), base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav"), 0, t,
  4206. lynx::makeBounceSong (song, t), settings.toOptions() });
  4207. }
  4208. const auto wallStart = juce::Time::getMillisecondCounterHiRes();
  4209. const auto cpuStart = std::clock();
  4210. lynx::StemRunStats stats;
  4211. std::vector<juce::String> lines (plan.items.size());
  4212. auto previous = wallStart; // (one render per file: the time since the file before is its render's)
  4213. written = lynx::runStemExport (
  4214. plan, [] (std::function<void()> f) { f(); }, {}, {}, {},
  4215. [&] (std::size_t k, bool done, float peak) {
  4216. const auto now = juce::Time::getMillisecondCounterHiRes();
  4217. if (done)
  4218. lines[k] = plan.items[k].file.getFileName() + " peak=" + juce::String (peak) + " ms=" + juce::String (now - previous, 0) + "\n";
  4219. previous = now;
  4220. },
  4221. separate, full, &stats);
  4222. const auto wallMs = juce::Time::getMillisecondCounterHiRes() - wallStart;
  4223. const auto cpuMs = 1000.0 * (double) (std::clock() - cpuStart) / (double) CLOCKS_PER_SEC;
  4224. for (const auto& line : lines)
  4225. report << line;
  4226. report << "renders=" << (stats.passes + stats.alone) << " shared=" << stats.passes << " inshared=" << stats.inPass
  4227. << " alone=" << stats.alone << "\n";
  4228. for (const auto& why : stats.why)
  4229. report << "alone: " << why << "\n";
  4230. report << "wall_ms=" << juce::String (wallMs, 0) << " cpu_ms=" << juce::String (cpuMs, 0) << " make_ms=" << juce::String (stats.makeMs, 0)
  4231. << " render_ms=" << juce::String (stats.renderMs, 0) << "\n";
  4232. }
  4233. report << "stems=" << written << "\n";
  4234. juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
  4235. setApplicationReturnValue (written > 0 ? 0 : 1);
  4236. quit();
  4237. return;
  4238. }
  4239. // --export-als <in.lynx|.flp|.als> <folder> [--live11] [--reference] [--scan]: "<folder>/<name> Project/<name>.als" (round 175a)
  4240. if (args.contains ("--export-als"))
  4241. {
  4242. const auto i = args.indexOf ("--export-als");
  4243. runAlsExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--live11"), args.contains ("--reference"));
  4244. return;
  4245. }
  4246. // --export-flm <in.lynx|.flp|.als|.flm|...> <out.flm> (round 190og, FLM coverage app-0003): File › "Save a copy as FL
  4247. // Studio Mobile project" without the window; the samples go beside it, the losses and the result to "<out>.txt".
  4248. // --flmexportshot <prefix> <project> [--shot-scale 1.5 --shot-suffix @150]: the window with that project's losses
  4249. if (args.contains ("--export-flm") || args.contains ("--flmexportshot"))
  4250. {
  4251. const auto shot = args.contains ("--flmexportshot");
  4252. const auto i = args.indexOf (shot ? "--flmexportshot" : "--export-flm");
  4253. const juce::File input (args[i + (shot ? 2 : 1)].unquoted());
  4254. juce::String error, report;
  4255. auto ok = false;
  4256. {
  4257. lynx::AudioEngine loader (false);
  4258. if (input.hasFileExtension ("flp;als;flm;songtmpl;band;blx;mod;xm;s3m;it;dawproject"))
  4259. ok = loader.importFlpFile (input, error);
  4260. else if (auto song = lynx::ProjectFile::load (input, error))
  4261. {
  4262. loader.setSong (std::move (*song));
  4263. ok = true;
  4264. }
  4265. if (ok && shot)
  4266. {
  4267. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4268. lynx::FlmExportOptions o;
  4269. o.title = input.getFileNameWithoutExtension().toStdString();
  4270. const auto dry = lynx::exportFlm (loader.getSong(), o);
  4271. auto list = std::make_shared<juce::TextEditor>();
  4272. std::unique_ptr<juce::AlertWindow> w (lynx::buildFlmExportWindow (dry, list));
  4273. saveSnapshot (*w, args[i + 1].unquoted() + "-flmexport.png");
  4274. report << lynx::flmExportLossText (dry) << "\n";
  4275. }
  4276. else if (ok)
  4277. {
  4278. loader.capturePluginStates();
  4279. lynx::FlmExportResult result;
  4280. const juce::File out (args[i + 2].unquoted());
  4281. ok = lynx::writeFlmCopy (loader.getSong(), out, result, error);
  4282. report << "bytes=" << (int) result.bytes.size() << "\nsamples=" << (int) result.samples.size() << "\n";
  4283. for (const auto& l : result.lost)
  4284. report << (l.sound ? "sound: " : "other: ") << juce::String::fromUTF8 (l.text.c_str()).replace ("{0}", juce::String::fromUTF8 (l.detail.c_str())) << "\n";
  4285. }
  4286. }
  4287. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  4288. juce::File (args[i + (shot ? 1 : 2)].unquoted() + (shot ? "-flmexport.txt" : ".txt")).replaceWithText (report);
  4289. setApplicationReturnValue (ok ? 0 : 1);
  4290. quit();
  4291. return;
  4292. }
  4293. // --gamepadshot <prefix> (round 184a, S16): the game controller's hints overlay and the MIDI settings page with
  4294. // the option on, offscreen, plus the poller fed fake pad states ("<prefix>-gamepad.txt")
  4295. if (args.contains ("--gamepadshot"))
  4296. {
  4297. runGamepadShot (args[args.indexOf ("--gamepadshot") + 1].unquoted());
  4298. return;
  4299. }
  4300. // --midioutshot <prefix> [--shot-scale 1.5] (round 190jl): Settings › MIDI with the output devices' Port boxes
  4301. // (the snapshot's sample devices: the volca on port 1 of its own, the drum machine with master sync), offscreen
  4302. if (args.contains ("--midioutshot"))
  4303. {
  4304. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4305. {
  4306. lynx::AudioEngine engine (false);
  4307. auto page = lynx::makeMidiPage (engine, {}, false);
  4308. page->setSize (1000, 1300);
  4309. savePng (lynx::shot::snapshot (*page), args[args.indexOf ("--midioutshot") + 1].unquoted() + "-settings-midi.png");
  4310. }
  4311. setApplicationReturnValue (0);
  4312. quit();
  4313. return;
  4314. }
  4315. // --export-bundle <in.lynx|.flp|.als> <folder> [--zip] [--no-mixdown] [--shot <prefix>] (round 184a, S9): File ›
  4316. // Export › "For other apps..." without the window; the report goes to "<folder>/export-bundle.txt"
  4317. if (args.contains ("--export-bundle"))
  4318. {
  4319. const auto i = args.indexOf ("--export-bundle");
  4320. runBundleExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--zip"), ! args.contains ("--no-mixdown"),
  4321. args.contains ("--shot") ? args[args.indexOf ("--shot") + 1].unquoted() : juce::String());
  4322. return;
  4323. }
  4324. if (args.contains ("--export-flp"))
  4325. {
  4326. const auto i = args.indexOf ("--export-flp");
  4327. runFlExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--substitute"));
  4328. return;
  4329. }
  4330. if (args.contains ("--export"))
  4331. {
  4332. const auto i = args.indexOf ("--export");
  4333. const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
  4334. runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
  4335. return;
  4336. }
  4337. if (args.contains ("--tempomarkershot"))
  4338. {
  4339. // LYNX --tempomarkershot <prefix> <project.lynx> (round 190hq): the Playlist of the project with its tempo
  4340. // markers on the ruler (-playlist.png) and the "Save a copy for an older LYNX" window for each release
  4341. // (-savecopy-<release>.png); no window, nothing saved
  4342. const auto i = args.indexOf ("--tempomarkershot");
  4343. const auto prefix = args[i + 1].unquoted();
  4344. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4345. lynx::AudioEngine shotEngine (false);
  4346. juce::String error;
  4347. auto ok = false;
  4348. if (auto song = lynx::ProjectFile::load (juce::File (args[i + 2].unquoted()), error))
  4349. shotEngine.setSong (std::move (*song)), ok = true;
  4350. if (ok)
  4351. {
  4352. {
  4353. lynx::PlaylistComponent playlist (shotEngine);
  4354. playlist.setBounds (0, 0, 1400, 420);
  4355. playlist.setVisible (true);
  4356. playlist.setViewForSnapshot (70.0, 0, 0);
  4357. shotEngine.dispatchPendingMessages();
  4358. saveSnapshot (playlist, prefix + "-playlist.png");
  4359. }
  4360. auto list = std::make_shared<juce::TextEditor>();
  4361. std::unique_ptr<juce::AlertWindow> w (lynx::MainComponent::buildSaveCopyWindow (lynx::ProjectFile::toJson (shotEngine.getSong()), list));
  4362. const auto releases = lynx::olderlynx::releases();
  4363. for (int k = 0; k < releases.size(); ++k)
  4364. {
  4365. w->getComboBoxComponent ("release")->setSelectedItemIndex (k, juce::sendNotificationSync);
  4366. saveSnapshot (*w, prefix + "-savecopy-" + releases[k] + ".png");
  4367. }
  4368. }
  4369. setApplicationReturnValue (ok ? 0 : 1);
  4370. quit();
  4371. return;
  4372. }
  4373. if (args.contains ("--savecopyfor"))
  4374. {
  4375. // LYNX --savecopyfor <in.lynx> <release> <out.lynx> (round 190hq, B20): File › "Save a copy for an older
  4376. // LYNX..." without the window; what the copy loses goes to <out.lynx>.txt (English), then result=OK
  4377. const auto i = args.indexOf ("--savecopyfor");
  4378. const juce::File input (args[i + 1].unquoted()), output (args[i + 3].unquoted());
  4379. const auto release = args[i + 2].unquoted();
  4380. juce::String report, error;
  4381. auto ok = false;
  4382. if (const auto song = lynx::ProjectFile::load (input, error))
  4383. {
  4384. const auto copy = lynx::olderlynx::forRelease (*song, release);
  4385. for (const auto& l : copy.lost)
  4386. report << (l.sound ? "sound: " : "view: ") << juce::String::fromUTF8 (l.text).replace ("{0}", l.detail) << "\n";
  4387. ok = copy.ok && output.replaceWithText (copy.json, false, false, nullptr);
  4388. if (! copy.ok)
  4389. error = copy.error;
  4390. }
  4391. report << "result=" << (ok ? juce::String ("OK") : "ERROR " + error) << "\n";
  4392. juce::File (output.getFullPathName() + ".txt").replaceWithText (report);
  4393. setApplicationReturnValue (ok ? 0 : 1);
  4394. quit();
  4395. return;
  4396. }
  4397. if (args.contains ("--render"))
  4398. {
  4399. const auto i = args.indexOf ("--render");
  4400. runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
  4401. return;
  4402. }
  4403. // session breadcrumb: a fail-fast (no crash handler runs) still leaves the last steps behind (round 111)
  4404. uncleanLastStep = collectUncleanSessions();
  4405. sessionsFolder().createDirectory();
  4406. lynx::crashguard::beginSession (
  4407. sessionsFolder().getChildFile ("session-" + juce::String (lynx::crashguard::processId()) + ".txt").getFullPathName().toStdString(),
  4408. ("LYNX session\nversion=" + getApplicationVersion() + "\npid=" + juce::String (lynx::crashguard::processId())
  4409. + "\nstart=" + juce::String ((juce::int64) lynx::crashguard::processStartTime())
  4410. + "\nstarted=" + juce::Time::getCurrentTime().toISO8601 (true) + "\n").toStdString());
  4411. startHangWatch();
  4412. // LYNX_PROFILE_MAIN=<file> (round 174f): the message thread sampled every millisecond, 5-second windows
  4413. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  4414. lynx::crashguard::startMainProfiler (profile.toStdString());
  4415. startupTrace.mark ("initialise (normal start)");
  4416. // (round 190hd, Windows) how long before the trace's 0 the process was made: the loader (the exe, its DLLs,
  4417. // relocations) and the static initialisers that ran before this file's
  4418. if (const auto created = lynx::crashguard::processStartTime(); created != 0)
  4419. {
  4420. const auto t0 = (std::uint64_t) std::chrono::duration_cast<std::chrono::microseconds> (startupTrace.t0System.time_since_epoch()).count() * 10u
  4421. + 116444736000000000ull; // (FILETIME: 100 ns since 1601)
  4422. if (t0 > created)
  4423. startupTrace.mark ((" (the process was made " + juce::String ((double) (t0 - created) / 10000.0, 1)
  4424. + " ms before this trace's 0: the loader, the DLLs, the first static initialisers)").toRawUTF8());
  4425. }
  4426. prepareGraphicsDevice();
  4427. if (startupTrace.on)
  4428. lynx::startupMark = startupMarkHook;
  4429. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4430. lynx::themeui::loadSaved(); // the user's theme (Options › Theme, round 162d)
  4431. startupOptions = lynx::StartupOptions::load();
  4432. if (lynx::demo::active()) // (round 190np: --demo records from the first frame: no splash card, no start-up sound)
  4433. startupOptions.splash = startupOptions.sound = false;
  4434. lynx::registerFileTypes();
  4435. startupTrace.mark ("options + file types");
  4436. // Double-clicking a .lynx/.flp opens LYNX with the file as an argument; a path typed in a terminal may be relative
  4437. // (D#92, round 180a: it was ignored, leaving the blank project with no message). A missing file gets "Could not open".
  4438. if (args.size() > 0 && lynx::safety::isFileArgument (args[0].unquoted().toStdString()))
  4439. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[0].unquoted());
  4440. // LYNX --no-plugins project.lynx (round 190ap): File › "Open without third-party plugins..." from the command
  4441. // line, for a project a plugin keeps from opening — no hosted plugin is created, each keeps its settings
  4442. if (const auto i = args.indexOf ("--no-plugins"); i >= 0)
  4443. {
  4444. if (i + 1 < args.size() && lynx::safety::isFileArgument (args[i + 1].unquoted().toStdString()))
  4445. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[i + 1].unquoted());
  4446. startWithoutPlugins = fileToOpen.hasFileExtension ("lynx");
  4447. }
  4448. // LYNX_TEST_MODE=1 LYNX --open-event-test <ms> <file>: the file arrives the way macOS's Finder delivers it (a Linux
  4449. // or Windows run can exercise that path): 0 ms = at once, before the window exists
  4450. if (lynx::platform::testMode() && args[0] == "--open-event-test" && args.size() > 2)
  4451. {
  4452. const auto file = args[2].unquoted().quoted();
  4453. if (args[1].getIntValue() == 0)
  4454. anotherInstanceStarted (file);
  4455. else
  4456. juce::Timer::callAfterDelay (args[1].getIntValue(), [this, file] { anotherInstanceStarted (file); });
  4457. }
  4458. // LYNX --opentime project.(flp|lynx)|- report.txt [idle seconds] (round 165i): the normal start-up (splash, audio
  4459. // device, window) opens the project, waits until it is loaded and LYNX has gone quiet, measures the idle CPU and
  4460. // memory, writes the times and quits normally (a benchmark that killed LYNX left "closed unexpectedly" behind)
  4461. if (args.contains ("--opentime"))
  4462. {
  4463. const auto i = args.indexOf ("--opentime");
  4464. const auto project = args[i + 1].unquoted();
  4465. fileToOpen = project != "-" && juce::File::isAbsolutePath (project) ? juce::File (project) : juce::File();
  4466. openTimeReport = juce::File (args[i + 2].unquoted());
  4467. if (args.size() > i + 3 && ! args[i + 3].startsWith ("--"))
  4468. openTimeIdleSeconds = juce::jlimit (1, 120, args[i + 3].getIntValue());
  4469. }
  4470. // round 190go: the ASIO device of the last session is made and opened from now on, while the splash and the
  4471. // window come up (see below)
  4472. lynx::AudioEngine::prewarmAudioDevice();
  4473. // round 190go: the built-in start-up sound is made while the splash and the window come up (pure maths)
  4474. if (startupOptions.sound && lynx::themeui::current().startupSound.empty())
  4475. startupSampleJob = std::async (std::launch::async, [] { return lynx::makeStartupSample(); });
  4476. // Round 190go (start-up faster than FL Studio): the main window is built first, with the engine ready but no
  4477. // audio device open; the device opens after it. An ASIO device of the last session was made and opened ahead,
  4478. // on a worker, while the window was built (AudioEngine::prewarmAudioDevice; the driver itself only ever runs on
  4479. // JUCE's ASIO thread, as COM wants). Play pressed before the device is open starts with it.
  4480. if (! startupOptions.splash)
  4481. {
  4482. startEngine();
  4483. createMainWindow();
  4484. mainWindow->reveal();
  4485. startupTrace.mark ("window revealed");
  4486. // the device (and the start-up sound) once the window's first frame is on screen
  4487. mainWindow->whenPainted ([this] {
  4488. openAudioDevice();
  4489. openMidiDevices();
  4490. startAfterWindow (lynx::demo::active()); // (round 190np: --demo has no splash; its first run still gets the welcome card)
  4491. });
  4492. return;
  4493. }
  4494. // the splash first; the main window is built behind its card (still: the logo has not started to drop; building
  4495. // it during the drop would stop the animation, both run on the message thread), then the audio device opens
  4496. // (the start-up sound needs it), and the drop starts with its sound. The window shows the moment the logo has
  4497. // landed (round 190go, A4: before, the window was built only after the drop: the drop, then ~0.6 s of build).
  4498. // Round 190hd (Windows): the card draws on a thread of its own, so the main window is built DURING the drop
  4499. // (startOnItsOwnThread below).
  4500. splash = lynx::makeStartupSplash();
  4501. startupTrace.mark ("splash made");
  4502. splash->showOnDesktop();
  4503. startupTrace.mark ("splash on the desktop");
  4504. if (splash->drawsOnItsOwnThread())
  4505. {
  4506. startWithThreadedSplash();
  4507. return;
  4508. }
  4509. // the rest once the card's first frame is on the screen (round 190go: before, a fixed 40 ms), at the latest
  4510. // after 40 ms
  4511. const auto goOn = [this, started = std::make_shared<bool> (false)] {
  4512. if (std::exchange (*started, true) || splash == nullptr) // (once; or quit meanwhile)
  4513. return;
  4514. startEngine();
  4515. if (splash == nullptr) // quit meanwhile
  4516. return;
  4517. createMainWindow();
  4518. if (splash == nullptr || mainWindow == nullptr)
  4519. return;
  4520. if (startupOptions.sound)
  4521. openAudioDevice (false); // (else after the splash: nothing waits for it)
  4522. // one turn of the message loop before the drop: what fell due while the window was built (JUCE's timers,
  4523. // the window's own async work) runs now, on the still card, not in the drop's first frames
  4524. juce::MessageManager::callAsync ([this] { startDrop(); });
  4525. };
  4526. splash->onFirstFrame = goOn;
  4527. juce::Timer::callAfterDelay (40, goOn);
  4528. }
  4529. // Round 190hd (start-up faster than FL Studio, Windows): the card draws on a thread of its own (ui/Splash.cpp), so
  4530. // nothing the message thread does stops the drop. The card shows at once (no Direct2D device is made for it); the
  4531. // engine starts and the audio device opens behind the still card (an ASIO device of the last session was made and
  4532. // opened ahead on its own thread meanwhile), the drop starts with its sound, and the main window is built while
  4533. // the logo drops and shown as soon as it is built, behind the card (the drop and its sound go on above it); the card
  4534. // fades the moment the logo has landed. The card stays for the drop only (the JUCE card's
  4535. // 2.1 s from the process start was there to keep a fast start from flashing; the drop alone is 1.05 s).
  4536. void startWithThreadedSplash()
  4537. {
  4538. splash->onFirstFrame = [this] {
  4539. if (splash != nullptr && startupTrace.on)
  4540. startupTrace.mark ((" splash: first frame on the screen at "
  4541. + juce::String (std::chrono::duration<double, std::milli> (splash->getFirstFrameTime() - startupTrace.t0).count(), 1) + " ms (its own thread)")
  4542. .toRawUTF8());
  4543. };
  4544. juce::MessageManager::callAsync ([this] {
  4545. if (splash == nullptr) // (quit meanwhile)
  4546. return;
  4547. startEngine();
  4548. if (splash == nullptr)
  4549. return;
  4550. if (startupOptions.sound)
  4551. openAudioDevice (false); // (else after the splash: nothing waits for it)
  4552. startDrop();
  4553. // the main window while the logo drops (one more message, so the drop's start is not held by it)
  4554. juce::MessageManager::callAsync ([this] {
  4555. if (splash == nullptr || mainWindow != nullptr || engine == nullptr)
  4556. return;
  4557. createMainWindow();
  4558. // shown as soon as it is built, behind the card: the logo goes on dropping above it and the card fades at
  4559. // the landing as before (LYNX_REVEAL_AT_LANDING=1: the window shows at the landing, as in round 190go)
  4560. if (mainWindow != nullptr && splash != nullptr
  4561. && juce::SystemStats::getEnvironmentVariable ("LYNX_REVEAL_AT_LANDING", {}) != "1")
  4562. {
  4563. mainWindow->reveal();
  4564. windowRevealed = true;
  4565. startupTrace.mark ("window revealed (behind the card, while the logo drops)");
  4566. splash->raise();
  4567. }
  4568. });
  4569. });
  4570. }
  4571. // the logo's drop and the start-up sound together; the window shows the moment the logo has landed
  4572. void startDrop()
  4573. {
  4574. const auto ownThread = splash != nullptr && splash->drawsOnItsOwnThread(); // (the window is built during the drop)
  4575. if (splash == nullptr || (mainWindow == nullptr && ! ownThread) || engine == nullptr)
  4576. return;
  4577. if (startupOptions.sound)
  4578. playStartupSound();
  4579. splash->setStatus (lynx::tr ("Loading the workspace..."));
  4580. splash->startClock();
  4581. // the minimum counts from the process start (the window and the audio device took part of it already); a card
  4582. // on its own thread stays for the drop (round 190hd)
  4583. splashDuration = ownThread ? landingSeconds : lynx::SplashScreen::remainingDuration (startupTrace.seconds());
  4584. splash->setBarDuration (splashDuration);
  4585. splash->whenLanded (splashDuration, [this] {
  4586. if (splash == nullptr || mainWindow == nullptr)
  4587. return;
  4588. if (startupTrace.on)
  4589. startupTrace.mark (("splash: the drop in " + juce::String (splash->getDropFrames()) + " frames, longest gap "
  4590. + juce::String (splash->getLongestDropGapMs(), 1) + " ms"
  4591. + (splash->getLongestDropGapAt() >= 0.0 ? " (at " + juce::String (splash->getLongestDropGapAt(), 3) + " s of its clock; the frame before: "
  4592. + splash->getLongestDropGapDetail() + ")"
  4593. : juce::String()))
  4594. .toRawUTF8());
  4595. if (! std::exchange (windowRevealed, true))
  4596. {
  4597. mainWindow->reveal();
  4598. startupTrace.mark ("window revealed (after the splash)");
  4599. }
  4600. splash->raise();
  4601. const auto deviceOpen = ! engine->isAudioDeviceOpenPending();
  4602. splash->finish ([this, deviceOpen] {
  4603. splash = nullptr;
  4604. // without the start-up sound the device opens now, once the card has faded (the window is up)
  4605. if (! deviceOpen)
  4606. openAudioDevice();
  4607. openMidiDevices();
  4608. if (! deviceOpen)
  4609. startAfterWindow (true);
  4610. });
  4611. if (deviceOpen)
  4612. mainWindow->whenPainted ([this] { startAfterWindow (true); });
  4613. });
  4614. }
  4615. // what follows the window's first frame (the audio device is open): the notice of an unclean end, the start-up
  4616. // project, the probes and the update check; on a first run (with the splash) the setup wizard
  4617. void startAfterWindow (bool offerSetupWizard)
  4618. {
  4619. if (std::exchange (startedAfterWindow, true) || mainWindow == nullptr)
  4620. return;
  4621. // (round 190go) each step after the window is a timed line of the start-up trace
  4622. showUncleanNotice();
  4623. startupTrace.mark ("after the window: unclean-session notice");
  4624. openStartupFile();
  4625. startupTrace.mark ("startup file opened");
  4626. startOpenTimeProbe();
  4627. if (! lynx::demo::active()) // (round 190np: --demo records videos: no update prompt, no support note)
  4628. {
  4629. startUpdateCheck();
  4630. startSupportNote(); // (round 190fq)
  4631. }
  4632. startupTrace.mark ("after the window: probes, update check scheduled");
  4633. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  4634. markSettled(); // (round 190gd)
  4635. // first run: language, audio, plugin folders (FL Studio's included) and a background scan
  4636. if (! offerSetupWizard)
  4637. return;
  4638. // round 190np: a fresh profile gets the welcome card ("Where are you coming from?"); a profile that had LYNX's
  4639. // settings and never finished the old wizard keeps the old wizard; an answered one gets nothing (core/Onboarding.h)
  4640. const auto action = lynx::onboarding::startAction (lynx::setupWizardDone(), lynx::onboardui::profileExistedAtStart(),
  4641. mainWindow->getContent().onboardingStateForCheck().pending);
  4642. using StartAction = lynx::onboarding::StartAction;
  4643. if (action != StartAction::none && lynx::platform::testMode())
  4644. lynx::platform::testModeLog (action == StartAction::welcomeCard ? "setup wizard: welcome card" : "setup wizard");
  4645. else if (action == StartAction::welcomeCard)
  4646. {
  4647. mainWindow->getContent().showWelcomeCard (true);
  4648. startupTrace.mark ("after the window: welcome card shown");
  4649. }
  4650. else if (action == StartAction::setupWizard)
  4651. {
  4652. mainWindow->showSetupWizard();
  4653. startupTrace.mark ("after the window: setup wizard shown");
  4654. }
  4655. // issue #252 (round 190oq; on by default as FL's Welcome window, rollup 0.1.31 step 6): the start page over the start-up project, never over the
  4656. // first run's card, never when a file was given to open
  4657. if (lynx::startpage::showAtStart (lynx::startpage::enabled(), fileToOpen != juce::File(), action != StartAction::none,
  4658. openTimeReport != juce::File() || lynx::platform::testMode()))
  4659. {
  4660. mainWindow->getContent().showStartPage();
  4661. startupTrace.mark ("after the window: start page shown");
  4662. }
  4663. }
  4664. // round 190fq: the start-up support note (ui/SupportLynx.h) counts this start and, from the 10th on, may show its
  4665. // card once at a quiet moment. Only here, on the normal start path (the command-line modes returned earlier); test
  4666. // mode and CI machines neither count nor show it.
  4667. void startSupportNote()
  4668. {
  4669. if (mainWindow == nullptr)
  4670. return;
  4671. const auto env = [] (const char* name) { return juce::SystemStats::getEnvironmentVariable (name, {}).toStdString(); };
  4672. const auto quiet = lynx::supportnote::quietEnvironment (lynx::platform::testMode(), env ("CI"), env ("GITHUB_ACTIONS"), env ("LYNX_NO_SUPPORT_NOTE"));
  4673. if (quiet && lynx::platform::testMode())
  4674. lynx::platform::testModeLog ("support note: not counted (test mode)");
  4675. mainWindow->getContent().startSupportNote (quiet);
  4676. }
  4677. // the start-up trace's last lines: what the first seconds after the window add (lazy work, caches, the first paints)
  4678. static void markSettled()
  4679. {
  4680. if (! startupTrace.on)
  4681. return;
  4682. juce::Timer::callAfterDelay (5000, [] { startupTrace.mark ("5 s after the window"); startupTrace.write(); });
  4683. juce::Timer::callAfterDelay (15000, [] { startupTrace.mark ("15 s after the window"); startupTrace.write(); });
  4684. }
  4685. // Round 190hd (Windows): the Direct3D 11 + Direct2D device (~0.35 s: the graphics driver loads) is made once, on a
  4686. // worker, while the splash card, the engine and the audio device come up, and kept until LYNX closes: a 1 x 1
  4687. // Direct2D image holds JUCE's shared DirectX object (its devices), so the main window finds them made and nothing
  4688. // makes them again (before, every holder going away -- the splash's logo, a temporary one -- could mean a new device
  4689. // at its next use). Other systems: nothing to do.
  4690. void prepareGraphicsDevice()
  4691. {
  4692. #if JUCE_WINDOWS
  4693. if (juce::SystemStats::getEnvironmentVariable ("LYNX_GPU_PREWARM", {}) == "0")
  4694. return;
  4695. graphicsDeviceJob = std::async (std::launch::async, [] {
  4696. const auto from = std::chrono::steady_clock::now();
  4697. juce::Image holder (juce::Image::ARGB, 1, 1, false); // (NativeImageType: Direct2D, the shared device)
  4698. return std::make_pair (holder, std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - from).count());
  4699. });
  4700. #endif
  4701. }
  4702. void markGraphicsDevice()
  4703. {
  4704. if (! graphicsDeviceJob.valid() || ! startupTrace.on || std::exchange (graphicsDeviceMarked, true))
  4705. return;
  4706. const auto ready = graphicsDeviceJob.wait_for (std::chrono::seconds (0)) == std::future_status::ready;
  4707. startupTrace.mark (ready ? (" graphics device made on a worker in " + juce::String (graphicsDeviceJob.get().second, 1) + " ms").toRawUTF8()
  4708. : " graphics device: still being made on its worker");
  4709. }
  4710. void startEngine()
  4711. {
  4712. startupTrace.mark ("before the audio engine");
  4713. lynx::BrowserComponent::allowIndexerProcess = true; // (round 190hd: the normal window only)
  4714. // (round 190go) ready to play, no device open yet: see openAudioDevice
  4715. engine = std::make_unique<lynx::AudioEngine> (true, -1, true, true);
  4716. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  4717. startupTrace.mark ("audio engine (no device yet)");
  4718. crashEngine = engine.get();
  4719. lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
  4720. // a project given on the command line: its slow plugin modules (a Waves shell) start now, on their own
  4721. // thread, while the splash and the main window come up (round 121)
  4722. if (fileToOpen.hasFileExtension ("flp"))
  4723. if (juce::MemoryBlock data; fileToOpen.loadFileAsData (data))
  4724. try
  4725. {
  4726. engine->getPluginHost().startModulesFor (lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  4727. startupTrace.mark ("plugin modules started ahead");
  4728. }
  4729. catch (const flp::Error&)
  4730. {
  4731. }
  4732. }
  4733. // The audio device of the last session, then (withSound) the start-up sound on it (once; message thread)
  4734. void openAudioDevice (bool withSound = true)
  4735. {
  4736. if (engine == nullptr || ! engine->isAudioDeviceOpenPending())
  4737. return;
  4738. engine->openAudioDevice();
  4739. if (const auto prewarmed = lynx::asioPrewarmReport(); prewarmed.isNotEmpty() && startupTrace.on)
  4740. startupTrace.mark ((" " + prewarmed).toRawUTF8());
  4741. startupTrace.mark ("audio device opened");
  4742. addDriverFileDeviceType();
  4743. if (withSound)
  4744. playStartupSound();
  4745. }
  4746. // issue #280 (round 190qr): the LYNX extra "Play a sound when an export finishes" (core/ExportDone.h)
  4747. void bindExportDoneSound()
  4748. {
  4749. lynx::exportdone::playSound = [this] {
  4750. if (engine != nullptr)
  4751. {
  4752. auto sound = lynx::startup::makeDoneSound (48000.0);
  4753. auto sample = std::make_shared<lynx::SampleData>();
  4754. sample->left = std::move (sound.left);
  4755. sample->right = std::move (sound.right);
  4756. sample->sampleRate = sound.sampleRate;
  4757. engine->previewSample (sample);
  4758. }
  4759. };
  4760. }
  4761. void playStartupSound()
  4762. {
  4763. if (startupOptions.sound && ! std::exchange (startupSoundPlayed, true) && engine != nullptr)
  4764. {
  4765. // Options › Theme › Startup sound (issue #12): the user's file, else (or when it can't be read) LYNX's own
  4766. std::shared_ptr<const lynx::SampleData> sound;
  4767. if (const auto& own = lynx::themeui::current().startupSound; ! own.empty() && juce::File (juce::String::fromUTF8 (own.c_str())).existsAsFile())
  4768. sound = engine->getSampleLibrary().load (juce::String::fromUTF8 (own.c_str()));
  4769. if (sound == nullptr && startupSampleJob.valid())
  4770. sound = startupSampleJob.get();
  4771. engine->previewSample (sound != nullptr ? sound : lynx::makeStartupSample());
  4772. }
  4773. startupTrace.mark ("startup sound");
  4774. }
  4775. void openMidiDevices()
  4776. {
  4777. if (engine != nullptr)
  4778. engine->openMidiDevices(); // (its own line in the start-up trace: "engine: MIDI inputs")
  4779. }
  4780. void createMainWindow()
  4781. {
  4782. bindExportDoneSound(); // (round 190qr, #280)
  4783. mainWindow = std::make_unique<MainWindow> ("LYNX SHARE", *engine); // the brand; getApplicationName() stays "LYNX" (an id: instance lock, X11 WM_CLASS, ALSA client)
  4784. lynx::setMainWindowForOwnership (mainWindow.get());
  4785. lynx::crashguard::watchDisplayConnection (onDisplayLost); // (round 190rf, Linux: the display is open now)
  4786. lynx::applyRenderingChoice (*mainWindow); // (GPU rendering off: GDI; round 157a)
  4787. lynx::startRenderingWatch();
  4788. startupTrace.mark ("main window built");
  4789. lynx::remoteui::install ([this] (bool enabled) {
  4790. remoteControl = nullptr;
  4791. if (enabled)
  4792. remoteControl = lynx::RemoteControl::create (*engine, true, [this] {
  4793. const auto title = mainWindow != nullptr ? mainWindow->getName() : juce::String ("Untitled");
  4794. const auto separator = title.indexOf (" - ");
  4795. return separator >= 0 ? title.substring (separator + 3) : title;
  4796. }, [this] {
  4797. const auto file = mainWindow != nullptr ? mainWindow->getContent().getCurrentProjectFile() : juce::File();
  4798. return file == juce::File() ? juce::String() : file.getFullPathName();
  4799. });
  4800. lynx::remoteui::setRuntimeStatus (remoteControl != nullptr && remoteControl->active());
  4801. });
  4802. if (lynx::demo::active()) // round 190np: --demo's view operations (ui.find, ui.click, ui.layout...) on the API
  4803. lynx::RemoteControl::setExtension (lynx::demo::operations(), [this] (const juce::String& op, const juce::var& args) -> juce::var {
  4804. if (mainWindow == nullptr)
  4805. throw std::runtime_error ("No main window");
  4806. return mainWindow->getContent().handleDemoOp (op, args);
  4807. });
  4808. markGraphicsDevice();
  4809. }
  4810. // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
  4811. // Settings › General › "Crash reports" says (round 159), ask whether to send a report, send it unasked, or not
  4812. void showUncleanNotice()
  4813. {
  4814. if (lynx::platform::testMode()) // LYNX_TEST_MODE: no prompt, no report sent (written to test-mode.log)
  4815. {
  4816. if (uncleanLastStep.isNotEmpty())
  4817. lynx::platform::testModeLog ("\"closed unexpectedly\" notice (last step: " + uncleanLastStep + ")");
  4818. return;
  4819. }
  4820. if (uncleanLastStep.isEmpty())
  4821. {
  4822. lynx::crashreporter::retryPending(); // (reports an earlier run could not send: once more)
  4823. return;
  4824. }
  4825. auto message = lynx::tr ("The last session ended without closing normally. Last step: {0}. Backup copies of your project are in "
  4826. "LYNX SHARE's autosave folder; details in crash-history.log.",
  4827. { uncleanLastStep });
  4828. uncleanLastStep.clear();
  4829. const auto cause = uncleanCause();
  4830. // round 157a: a plugin's editor was opening — it crashed (often in the graphics driver, inside the plugin's own
  4831. // OpenGL window): offer to keep that plugin in its own process, where a crash takes only the plugin down
  4832. juce::String separatePlugin;
  4833. if (cause.editorPlugin.isNotEmpty() && ! lynx::pluginSandboxEnabled() && ! lynx::pluginAlwaysSeparate (cause.editorPlugin))
  4834. separatePlugin = cause.editorPlugin;
  4835. // LYNX's own drawing crashed in the graphics driver (Direct2D / Direct3D): draw with the CPU from now on
  4836. else if (cause.gpuDriver && lynx::gpuRenderingEnabled())
  4837. {
  4838. lynx::setGpuRenderingEnabled (false);
  4839. message << "\n\n"
  4840. << lynx::tr ("The crash was in the graphics driver ({0}). LYNX SHARE now draws its windows without the GPU; you can turn GPU "
  4841. "rendering back on in Options > General settings (after a driver update, for example).",
  4842. { cause.driverModule });
  4843. }
  4844. // round 165e: the Visualizer's GPU view was drawing when the session ended (a driver crash, a hang, the machine
  4845. // going down): the Visualizer draws with the 2D renderer from now on (its GPU button turns it back on)
  4846. for (int i = uncleanSteps.size(); --i >= 0;)
  4847. {
  4848. if (uncleanSteps[i].contains (lynx::visualgl::stopNote))
  4849. break;
  4850. if (uncleanSteps[i].contains (lynx::visualgl::startNote))
  4851. {
  4852. if (lynx::visualgl::enabled())
  4853. {
  4854. lynx::visualgl::setEnabled (false);
  4855. message << "\n\n"
  4856. << lynx::tr ("The Visualizer was drawing with the GPU (OpenGL) when it happened. It now draws without the GPU; its GPU "
  4857. "button turns it back on.");
  4858. }
  4859. break;
  4860. }
  4861. }
  4862. const auto session = lynx::crashreporter::parseSession (uncleanSessionText);
  4863. auto* devices = engine != nullptr ? &engine->getDeviceManager() : nullptr;
  4864. const auto action = lynx::crashreport::actionFor (lynx::crashreporter::consent());
  4865. lynx::crashreporter::retryPending();
  4866. if (action == lynx::crashreport::Action::askUser)
  4867. {
  4868. if (separatePlugin.isNotEmpty())
  4869. message << "\n\n"
  4870. << lynx::tr ("It happened while the window of {0} was opening{1}.",
  4871. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() });
  4872. lynx::crashreporter::showStartupDialog (session, message, separatePlugin, [separatePlugin] { lynx::setPluginAlwaysSeparate (separatePlugin, true); },
  4873. devices);
  4874. return;
  4875. }
  4876. if (action == lynx::crashreport::Action::sendSilently)
  4877. {
  4878. const auto input = lynx::crashreporter::makeInput (session, session.kind(), devices);
  4879. lynx::crashreporter::send (lynx::crashreporter::buildJson (input, false), juce::String::fromUTF8 (input.id.c_str()));
  4880. message << "\n\n" << lynx::tr ("A crash report is being sent to help fix it (Options > General settings > Crash reports).");
  4881. }
  4882. if (separatePlugin.isNotEmpty())
  4883. {
  4884. juce::AlertWindow::showOkCancelBox (
  4885. juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"),
  4886. message + "\n\n"
  4887. + lynx::tr ("It happened while the window of {0} was opening{1}. Run {0} in a separate process from now on? If it "
  4888. "crashes again, only the plugin stops and LYNX SHARE keeps running (Plugin wrapper menu: \"Always run in a "
  4889. "separate process\").",
  4890. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() }),
  4891. lynx::tr ("Run separately"), lynx::tr ("No"), nullptr,
  4892. juce::ModalCallbackFunction::create ([separatePlugin] (int result) {
  4893. if (result != 0)
  4894. lynx::setPluginAlwaysSeparate (separatePlugin, true);
  4895. }));
  4896. return;
  4897. }
  4898. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"), message);
  4899. }
  4900. // --opentime: after the start-up file was handed to the window
  4901. void startOpenTimeProbe()
  4902. {
  4903. if (openTimeReport == juce::File())
  4904. return;
  4905. struct Probe final : juce::Timer
  4906. {
  4907. LynxApplication& app;
  4908. juce::File report, project;
  4909. int idleSeconds;
  4910. int phase = 0; // 0 loading, 1 settling, 2 idle measurement
  4911. double revealedS = 0.0, loadedS = -1.0, settledS = -1.0, cpuAtLoaded = 0.0;
  4912. double lastCpu = 0.0, lastT = 0.0, quietSince = -1.0, idleCpu0 = 0.0, idleT0 = 0.0;
  4913. Probe (LynxApplication& a, juce::File r, juce::File p, int idle)
  4914. : app (a), report (std::move (r)), project (std::move (p)), idleSeconds (idle)
  4915. {
  4916. revealedS = startupTrace.seconds();
  4917. startTimer (250);
  4918. }
  4919. bool loaded() const
  4920. {
  4921. if (project == juce::File())
  4922. return true;
  4923. return app.mainWindow != nullptr
  4924. && app.mainWindow->getName().containsIgnoreCase (project.getFileNameWithoutExtension());
  4925. }
  4926. void finish (const juce::String& result)
  4927. {
  4928. stopTimer();
  4929. const auto now = startupTrace.seconds();
  4930. const auto cpu = lynx::processCpuSeconds();
  4931. juce::String text;
  4932. text << "project=" << (project == juce::File() ? juce::String ("-") : project.getFullPathName()) << "\n"
  4933. << "window_s=" << juce::String (revealedS, 3) << "\n"
  4934. << "loaded_s=" << juce::String (loadedS, 3) << "\n"
  4935. << "settled_s=" << juce::String (settledS, 3) << "\n"
  4936. << "cpu_at_loaded_s=" << juce::String (cpuAtLoaded, 3) << "\n"
  4937. << "idle_s=" << juce::String (now - idleT0, 2) << "\n"
  4938. << "idle_cpu_pct=" << juce::String (phase == 2 && now > idleT0 ? 100.0 * (cpu - idleCpu0) / (now - idleT0) : -1.0, 1) << "\n"
  4939. << "working_set_mb=" << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << "\n"
  4940. << "cpu_total_s=" << juce::String (cpu, 3) << "\n"
  4941. << "result=" << result << "\n";
  4942. report.replaceWithText (text);
  4943. app.setApplicationReturnValue (result == "OK" ? 0 : 1);
  4944. app.quit();
  4945. }
  4946. void timerCallback() override
  4947. {
  4948. const auto now = startupTrace.seconds();
  4949. const auto cpu = lynx::processCpuSeconds();
  4950. if (phase == 0)
  4951. {
  4952. if (loaded())
  4953. {
  4954. loadedS = now;
  4955. cpuAtLoaded = cpu;
  4956. phase = 1;
  4957. lastCpu = cpu;
  4958. lastT = now;
  4959. }
  4960. else if (now - revealedS > 240.0)
  4961. finish ("TIMEOUT loading");
  4962. return;
  4963. }
  4964. if (phase == 1)
  4965. {
  4966. // quiet = under 10 % of one core for 1.5 s (the harness's rule), at most 30 s after loading
  4967. const auto use = now > lastT ? 100.0 * (cpu - lastCpu) / (now - lastT) : 0.0;
  4968. lastCpu = cpu;
  4969. lastT = now;
  4970. if (use < 10.0)
  4971. {
  4972. if (quietSince < 0.0)
  4973. quietSince = now - 0.25;
  4974. if (now - quietSince >= 1.5)
  4975. settledS = quietSince;
  4976. }
  4977. else
  4978. quietSince = -1.0;
  4979. if (settledS >= 0.0 || now - loadedS > 30.0)
  4980. {
  4981. phase = 2;
  4982. idleCpu0 = cpu;
  4983. idleT0 = now;
  4984. }
  4985. return;
  4986. }
  4987. if (now - idleT0 >= (double) idleSeconds)
  4988. finish ("OK");
  4989. }
  4990. };
  4991. perf = std::make_unique<Probe> (*this, openTimeReport, fileToOpen, openTimeIdleSeconds);
  4992. }
  4993. // round 166b: the update check of a normal start (never in --opentime and the other command-line modes), a few
  4994. // seconds after the window is up so it never competes with the start-up; and the result of an update just installed
  4995. void startUpdateCheck()
  4996. {
  4997. if (openTimeReport != juce::File())
  4998. return;
  4999. lynx::updater::afterStart();
  5000. juce::Timer::callAfterDelay (3000, [] { lynx::updater::startAutomaticCheck(); });
  5001. }
  5002. void openStartupFile()
  5003. {
  5004. startupFileHandled = true;
  5005. if (fileToOpen != juce::File() && mainWindow != nullptr)
  5006. {
  5007. if (std::exchange (startWithoutPlugins, false)) // --no-plugins (round 190ap)
  5008. mainWindow->getContent().openNextWithoutPlugins (true);
  5009. mainWindow->openFile (fileToOpen);
  5010. mainWindow->getContent().openNextWithoutPlugins (false); // (a file that did not open leaves nothing behind)
  5011. }
  5012. else if (mainWindow != nullptr && openTimeReport == juce::File())
  5013. mainWindow->getContent().openStartupProject(); // issue #123 (FL's Startup project)
  5014. }
  5015. void shutdown() override
  5016. {
  5017. parityShow.reset(); // (LYNX_PARITYSHOT_SHOW's window, before the engine it shows)
  5018. if (relaunched || updateHelper)
  5019. return; // the copy that ran owns the session (its crash notes stay for the next start)
  5020. lynx::crashguard::note ("closing");
  5021. lynx::shutdownPluginSandboxWorker();
  5022. splash = nullptr;
  5023. lynx::shutdownStemExtraction(); // (a separation in flight stops before its window and the engine go)
  5024. lynx::shutdownAudioToMidi(); // (the same for a conversion to MIDI)
  5025. if (mainWindow != nullptr && mainWindow->isVisible())
  5026. mainWindow->saveState();
  5027. lynx::remoteui::shutdown();
  5028. lynx::closeModalWindows(); // (round 190rf: a call-out box or dialog still open goes before the UI and the engine)
  5029. remoteControl = nullptr; // cancels queued control work before its engine and UI go
  5030. mainWindow = nullptr; // the UI goes before the engine
  5031. graphicsDeviceJob = {}; // (round 190hd: the graphics device's holder, after every window)
  5032. lynx::updater::shutdown(); // (a check or download in flight stops)
  5033. crashEngine = nullptr;
  5034. engine = nullptr;
  5035. // separate-process plugins end on threads of their own (issue #159): a moment for them, never the 10 s a dead
  5036. // child's pipe can take
  5037. lynx::finishSandboxTeardowns (2000);
  5038. // CLAP plugins whose instance another thread deleted while this one was busy: deactivated and destroyed now
  5039. lynx::ClapPluginFormat::finishPendingTeardowns();
  5040. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  5041. heartbeat.stopTimer();
  5042. lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
  5043. lynx::crashguard::stopHangWatch();
  5044. lynx::crashguard::stopMainProfiler();
  5045. lynx::crashguard::endSession(); // a clean exit: no breadcrumb left behind
  5046. // everything is saved and closed: a process that loaded third-party plugins ends here, before the DLLs' own
  5047. // teardown runs (some crash in it at exit, round 111)
  5048. if (sandboxChild || lynx::PluginHost::pluginsWereLoaded())
  5049. lynx::crashguard::exitNow (getApplicationReturnValue());
  5050. }
  5051. void systemRequestedQuit() override
  5052. {
  5053. if (mainWindow != nullptr)
  5054. mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
  5055. else
  5056. quit();
  5057. }
  5058. private:
  5059. // round 157a: a frozen UI (Windows' "not responding") writes the message thread's stack to autosave\hang <time>.txt
  5060. // and a session step, so a freeze can be told apart from a crash and located. The timer is the heartbeat.
  5061. struct Heartbeat final : juce::Timer
  5062. {
  5063. void timerCallback() override { lynx::crashguard::heartbeat(); }
  5064. } heartbeat;
  5065. void startHangWatch()
  5066. {
  5067. const auto folder = lynx::platform::settingsFile ("autosave");
  5068. folder.createDirectory();
  5069. // keep the newest hang files only
  5070. auto old = folder.findChildFiles (juce::File::findFiles, false, "hang *.txt");
  5071. lynx::filesort::byTime (old, lynx::filesort::By::modificationTime, true);
  5072. for (int i = 20; i < old.size(); ++i)
  5073. old.getReference (i).deleteFile();
  5074. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString());
  5075. heartbeat.startTimerHz (5);
  5076. }
  5077. bool sandboxChild = false;
  5078. bool relaunched = false; // relaunchFromAsciiPath ran LYNX from its short path: this process only waited
  5079. bool updateHelper = false; // --apply-update (round 166b)
  5080. juce::String uncleanLastStep; // last step of a previous run that ended without closing
  5081. // LYNX_PROFILE_DIR=<folder> LYNX --lv2scantest report.txt (Linux, issue #85): the LV2 scan's promise, with real child
  5082. // processes. A new PluginHost per step, as every start of LYNX has. The LV2 folders of the machine are read too.
  5083. void runLv2ScanTest (const juce::String& reportPath)
  5084. {
  5085. juce::String report;
  5086. auto ok = lynx::platform::profileOverride() != juce::File();
  5087. #if JUCE_LINUX
  5088. const auto folder = lynx::platform::profileOverride().getChildFile ("lv2-test");
  5089. const juce::FileSearchPath paths (folder.getFullPathName());
  5090. const auto check = [&] (const juce::String& name, bool passed) {
  5091. report << name << "=" << (passed ? "ok" : "FAILED") << "\n";
  5092. ok = ok && passed;
  5093. };
  5094. const auto install = [&] (const juce::String& name) {
  5095. const auto bundle = folder.getChildFile (name + ".lv2");
  5096. bundle.createDirectory();
  5097. bundle.getChildFile ("manifest.ttl").replaceWithText ("@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
  5098. "<urn:lynx-test:" + name + "> a lv2:Plugin ; lv2:binary <" + name + ".so> ; rdfs:seeAlso <plugin.ttl> .\n");
  5099. bundle.getChildFile ("plugin.ttl").replaceWithText ("@prefix doap: <http://usefulinc.com/ns/doap#> .\n<urn:lynx-test:" + name + "> doap:name \"" + name + "\" .\n");
  5100. };
  5101. auto date = juce::Time::getCurrentTime();
  5102. const auto touch = [&] { // the next date, whatever the file system's date resolution
  5103. date += juce::RelativeTime::seconds (2.0);
  5104. folder.getChildFile ("a.lv2/plugin.ttl").setLastModificationTime (date);
  5105. };
  5106. const auto listed = [] (lynx::PluginHost& host, const juce::String& name) {
  5107. for (const auto& d : host.getKnownPlugins().getTypes())
  5108. if (d.fileOrIdentifier == "urn:lynx-test:" + name)
  5109. return true;
  5110. return false;
  5111. };
  5112. const auto step = [&] (const juce::String& name, int children, const std::function<void (lynx::PluginHost&)>& prepare = {}) {
  5113. lynx::PluginHost host (true);
  5114. if (prepare)
  5115. prepare (host);
  5116. host.scan (paths, {});
  5117. check (name, host.scanChildrenStarted() == children && listed (host, "a"));
  5118. };
  5119. install ("a");
  5120. step ("first_scan_one_child", 1);
  5121. step ("nothing_changed_no_child", 0);
  5122. touch();
  5123. step ("ttl_updated", 1);
  5124. install ("b");
  5125. step ("bundle_installed", 1);
  5126. step ("forget_file", 1, [] (lynx::PluginHost& host) { host.forgetFile ("urn:lynx-test:a"); });
  5127. step ("forget_all", 1, [] (lynx::PluginHost& host) { host.forgetAll(); });
  5128. lynx::platform::settingsFile ("plugins.xml").deleteFile();
  5129. step ("list_lost", 1);
  5130. step ("nothing_changed_again", 0);
  5131. // cancelled while the child works: stopped at once, and nothing is taken for done
  5132. touch();
  5133. setenv ("LYNX_TEST_CRASH", "lv2-batch-hang", 1);
  5134. {
  5135. lynx::PluginHost host (true);
  5136. const auto started = juce::Time::getMillisecondCounter();
  5137. host.scan (paths, [] (float, const juce::String&) { return false; });
  5138. check ("cancel_stops_the_child", host.scanChildrenStarted() == 1 && juce::Time::getMillisecondCounter() - started < 20000);
  5139. }
  5140. unsetenv ("LYNX_TEST_CRASH");
  5141. step ("described_after_cancel", 1);
  5142. // the child dies: plugin by plugin takes over (stopped after two of them: a machine may have hundreds)
  5143. touch();
  5144. setenv ("LYNX_TEST_CRASH", "lv2-batch", 1);
  5145. {
  5146. lynx::PluginHost host (true);
  5147. host.scan (paths, [&host] (float, const juce::String&) { return host.scanChildrenStarted() < 3; });
  5148. check ("crash_falls_back_plugin_by_plugin", host.scanChildrenStarted() == 3);
  5149. auto blamed = false;
  5150. for (const auto& file : host.getKnownPlugins().getBlacklistedFiles())
  5151. blamed = blamed || file.startsWith ("lv2-folders:");
  5152. check ("crash_blacklists_nothing", ! blamed);
  5153. }
  5154. unsetenv ("LYNX_TEST_CRASH");
  5155. step ("described_after_crash", 1);
  5156. // round 190fw: past the first limit, a child that still works is waited for (FL Studio's own VST plugin boots
  5157. // the FL engine), one that sits still is killed as before, and a busy one only up to the cap. Limits are
  5158. // shortened for the test: 2 s first limit, 2 s without work, 8 s cap (real: 30 s, 30 s, 5 min).
  5159. setenv ("LYNX_TEST_SCAN_MS", "2000,2000,8000", 1);
  5160. const auto timed = [&] (const char* fault, const std::function<bool (lynx::PluginHost&)>& progress) {
  5161. touch();
  5162. setenv ("LYNX_TEST_CRASH", fault, 1);
  5163. lynx::PluginHost host (true);
  5164. const auto started = juce::Time::getMillisecondCounter();
  5165. host.scan (paths, [&] (float, const juce::String&) { return ! progress || progress (host); });
  5166. unsetenv ("LYNX_TEST_CRASH");
  5167. const auto took = (int) (juce::Time::getMillisecondCounter() - started);
  5168. report << " " << fault << ": " << took << " ms, children " << host.scanChildrenStarted() << "\n";
  5169. return std::make_pair (took, host.scanChildrenStarted());
  5170. };
  5171. // (after a failed batch, one plugin-by-plugin child and no more: it describes quickly)
  5172. const auto stopAfterBatch = [] (lynx::PluginHost& host) { return host.scanChildrenStarted() < 2; };
  5173. {
  5174. const auto [took, children] = timed ("lv2-batch-busy:5000", {});
  5175. check ("busy_child_is_waited_for", children == 1 && took >= 4500);
  5176. }
  5177. {
  5178. const auto [took, children] = timed ("lv2-batch-hang", stopAfterBatch);
  5179. check ("idle_child_ends_near_the_first_limit", children == 2 && took >= 1900 && took < 9000);
  5180. }
  5181. {
  5182. const auto [took, children] = timed ("lv2-batch-busy:60000", stopAfterBatch);
  5183. check ("busy_child_ends_at_the_cap", children == 2 && took >= 7500 && took < 20000);
  5184. }
  5185. unsetenv ("LYNX_TEST_SCAN_MS");
  5186. step ("described_after_slow_children", 1);
  5187. #endif
  5188. juce::File (reportPath).replaceWithText (report + "result=" + (ok ? "OK" : "FAILED") + "\n");
  5189. setApplicationReturnValue (ok ? 0 : 1);
  5190. quit();
  5191. }
  5192. // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
  5193. // Exit code 0 = audio came out, 1 = silence.
  5194. // --selftest (round 190ci): two more copies of LYNX end by a fault on purpose (--faulttest), one on a normal stack
  5195. // (the top-level filter) and one on a stack Windows cannot walk (the first-chance hook); each must leave
  5196. // "crash <time>.txt" with the access violation in the folder it is given.
  5197. // Round 190dt (Linux / macOS): a plain fault, and LYNX's own fault inside a guarded plugin call (in its code, and in
  5198. // the C library called from its code), must each leave the crash file with the signal: the plugin guard passes
  5199. // LYNX's own faults on to the crash handler instead of swallowing them ("swallowed.txt" = it did).
  5200. // Round 190gj (P9): the inserts' stems from one render are the files each stem's own render writes, byte for byte
  5201. // (a short song with a bus, a send return, delay compensation, a channel on the Master, an automated insert and a
  5202. // side-chained insert), streamed (24-bit WAV with the full mix) and buffered (normalised float).
  5203. static juce::String stemsSinglePassSelfTest()
  5204. {
  5205. auto s = lynx::Song::makeDefault();
  5206. s.mixer = lynx::Song::defaultMixer (7);
  5207. for (std::size_t c = 0; c < s.channels.size(); ++c)
  5208. s.channels[c].mixerTrack = (int) c + 1;
  5209. auto onMaster = s.channels[2];
  5210. onMaster.mixerTrack = 0;
  5211. onMaster.pan = -0.4f;
  5212. s.channels.push_back (onMaster);
  5213. for (int step : { 1, 5, 9, 13 })
  5214. s.patterns[0].toggleStep ((int) s.channels.size() - 1, step);
  5215. for (int step : { 4, 12 })
  5216. s.patterns[0].toggleStep (3, step); // the snare
  5217. for (int k = 0; k < 4; ++k) // the synth under the kick (its compressor listens to it)
  5218. s.patterns[0].notes.push_back ({ (std::int64_t) k * lynx::ppq, lynx::ppq - 60, 4, 57 + 3 * k, 0.9f });
  5219. s.patterns[0].sortNotes();
  5220. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  5221. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::compressor));
  5222. s.mixer[2].toMaster = false;
  5223. s.mixer[2].sends = { lynx::MixerSend { 6, 1.0f } };
  5224. s.mixer[3].sends = { lynx::MixerSend { 7, 0.5f } };
  5225. s.mixer[3].latencyMs = 3.0f;
  5226. s.mixer[4].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  5227. s.mixer[4].latencyMs = 5.0f;
  5228. s.mixer[4].sends = { lynx::MixerSend { 6, 0.7f } };
  5229. s.mixer[4].masterLevel = 0.8f;
  5230. auto keyed = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  5231. keyed.params[0] = 0.5f; // (−30 dB: the kick's hits pull the synth down)
  5232. keyed.sidechain = 1;
  5233. s.mixer[5].effects.push_back (keyed);
  5234. s.mixer[6].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::distortion));
  5235. s.mixer[7].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  5236. lynx::Automation a;
  5237. a.target = { lynx::AutomationTargetKind::mixerPan, 3 };
  5238. a.points = { { 0, 0.2f, 0.0f }, { 8 * lynx::ppq, 0.9f, 0.0f } };
  5239. s.automations.push_back (a);
  5240. s.playlist.clear();
  5241. for (int bar = 0; bar < 2; ++bar)
  5242. s.playlist.push_back ({ 0, 0, bar * 4 * lynx::ppq, 4 * lynx::ppq, 0 });
  5243. lynx::Clip automationClip;
  5244. automationClip.kind = lynx::ClipKind::automation;
  5245. automationClip.automation = 0;
  5246. automationClip.length = 8 * lynx::ppq;
  5247. automationClip.track = 1;
  5248. s.playlist.push_back (automationClip);
  5249. s.mode = lynx::PlayMode::song;
  5250. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-stems190gj-" + juce::String (juce::Time::currentTimeMillis()));
  5251. juce::String problems;
  5252. auto run = [&] (lynx::exportopts::Options o, const juce::String& name) {
  5253. o.stems = lynx::exportopts::Stems::mixerTracks;
  5254. o.maxTailSeconds = 3.0;
  5255. const auto alone = dir.getChildFile ("alone"), shared = dir.getChildFile ("shared");
  5256. alone.createDirectory();
  5257. shared.createDirectory();
  5258. const auto ext = juce::String (lynx::exportopts::extension (o.format));
  5259. const auto planAlone = lynx::planStemExport (s, o, alone.getChildFile (name + ext));
  5260. const auto planShared = lynx::planStemExport (s, o, shared.getChildFile (name + ext));
  5261. auto now = [] (std::function<void()> f) { f(); };
  5262. lynx::StemRunStats stats;
  5263. const auto a = lynx::runStemExport (planAlone, now, {}, {}, {}, {}, true);
  5264. const auto b = lynx::runStemExport (planShared, now, {}, {}, {}, {}, false, true, &stats);
  5265. if (a != (int) planAlone.items.size() || b != a)
  5266. problems << name << ": " << a << " / " << b << " files; ";
  5267. // (every insert from the one render, insert 5 with its side-chain too: it stays ducked as in the mix)
  5268. if (stats.passes != 1 || stats.inPass < 6)
  5269. problems << name << ": renders " << stats.passes << " shared, " << stats.inPass << " in it, " << stats.alone << " alone; ";
  5270. for (std::size_t k = 0; k < planShared.items.size() && k < planAlone.items.size(); ++k)
  5271. {
  5272. juce::MemoryBlock x, y;
  5273. planAlone.items[k].file.loadFileAsData (x);
  5274. planShared.items[k].file.loadFileAsData (y);
  5275. if (x.getSize() == 0 || x != y)
  5276. problems << name << ": " << planShared.items[k].file.getFileName() << " differs; ";
  5277. }
  5278. };
  5279. lynx::exportopts::Options streamed;
  5280. streamed.wavBits = 24;
  5281. streamed.stemsIncludeMaster = true;
  5282. run (streamed, "streamed");
  5283. lynx::exportopts::Options buffered;
  5284. buffered.wavBits = 32;
  5285. buffered.normalize = true;
  5286. run (buffered, "buffered");
  5287. dir.deleteRecursively();
  5288. return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems;
  5289. }
  5290. static juce::String faultReportSelfTest()
  5291. {
  5292. #if (JUCE_WINDOWS && (defined (_M_X64) || defined (__x86_64__))) \
  5293. || ((JUCE_LINUX || JUCE_MAC) && (defined (__x86_64__) || defined (__aarch64__)))
  5294. const auto exe = juce::File::getSpecialLocation (juce::File::currentExecutableFile);
  5295. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  5296. .getChildFile ("lynx-faulttest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  5297. juce::StringArray problems;
  5298. // (rollup step 12: + hang = the crash handler's watchdog ends a handler that never returns, within its time limit
  5299. // (3 s here); heap = the C library's heap-corruption abort leaves the allocation-free crash file and no recovered
  5300. // project, at once (before the watchdog: the old handler waited for ever on the allocator's lock); Linux / macOS)
  5301. #if JUCE_WINDOWS
  5302. const char* const kinds[] = { "plain", "unwalkable", "hang" };
  5303. #else
  5304. const char* const kinds[] = { "plain", "guarded", "guarded-libc", "thread", "thread-libc", "hang", "heap" };
  5305. #endif
  5306. for (const auto* kind : kinds)
  5307. {
  5308. const auto folder = root.getChildFile (kind);
  5309. folder.createDirectory();
  5310. const auto watchdogTest = juce::String (kind) == "hang" || juce::String (kind) == "heap";
  5311. #if JUCE_WINDOWS
  5312. _putenv_s ("LYNX_CRASH_WATCHDOG_S", watchdogTest ? "3" : "");
  5313. #else
  5314. if (watchdogTest)
  5315. setenv ("LYNX_CRASH_WATCHDOG_S", "3", 1);
  5316. else
  5317. unsetenv ("LYNX_CRASH_WATCHDOG_S");
  5318. #endif
  5319. juce::ChildProcess child;
  5320. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  5321. const auto started = child.start (juce::StringArray { exe.getFullPathName(), "--faulttest", kind, folder.getFullPathName() }, 0);
  5322. const auto ended = started && child.waitForProcessToFinish (60000);
  5323. const auto seconds = (juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0;
  5324. if (! ended)
  5325. {
  5326. child.kill();
  5327. problems.add (juce::String (kind) + ": " + (started ? "did not end" : "did not start"));
  5328. continue;
  5329. }
  5330. juce::String text;
  5331. for (const auto& file : folder.findChildFiles (juce::File::findFiles, false, "crash *.txt"))
  5332. text = file.loadFileAsString();
  5333. if (watchdogTest)
  5334. {
  5335. const auto recovered = folder.findChildFiles (juce::File::findFiles, false, "recovered *").size();
  5336. if (juce::String (kind) == "hang" && (seconds < 2.5 || seconds > 30.0 || text.isEmpty()))
  5337. problems.add ("hang: ended after " + juce::String (seconds, 1) + " s (the watchdog: 3 s)" + (text.isEmpty() ? ", no crash file" : ""));
  5338. if (juce::String (kind) == "heap" && (seconds > 20.0 || ! text.contains ("heap-corruption abort") || recovered != 0))
  5339. problems.add ("heap: " + juce::String (seconds, 1) + " s, " + (text.isEmpty() ? juce::String ("no crash file") : text.upToFirstOccurrenceOf ("\n", false, false))
  5340. + ", " + juce::String (recovered) + " recovered project(s)");
  5341. continue;
  5342. }
  5343. #if JUCE_WINDOWS
  5344. const auto found = text.contains ("0xc0000005");
  5345. #else
  5346. const auto found = text.contains ("segmentation fault") || text.contains ("bus error");
  5347. #endif
  5348. if (folder.getChildFile ("swallowed.txt").existsAsFile())
  5349. problems.add (juce::String (kind) + ": LYNX's own fault was caught as a plugin's ("
  5350. + folder.getChildFile ("swallowed.txt").loadFileAsString() + ")");
  5351. else if (! found)
  5352. problems.add (juce::String (kind) + ": " + (text.isEmpty() ? "no crash file" : "a crash file without the fault")
  5353. + " (exit code 0x" + juce::String::toHexString ((juce::int64) child.getExitCode()) + ")");
  5354. }
  5355. root.deleteRecursively();
  5356. #if JUCE_WINDOWS
  5357. _putenv_s ("LYNX_CRASH_WATCHDOG_S", "");
  5358. #else
  5359. unsetenv ("LYNX_CRASH_WATCHDOG_S");
  5360. #endif
  5361. return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems.joinIntoString ("; ");
  5362. #else
  5363. return "SKIPPED (Windows x64, Linux / macOS x86-64 / ARM64 only)";
  5364. #endif
  5365. }
  5366. void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
  5367. {
  5368. lynx::AudioEngine offline (false);
  5369. const auto peak = offline.renderOffline (2.0, 48000.0);
  5370. const auto audioOk = peak > 0.01f && peak < 10.0f;
  5371. // round 190qk (core/ExtrasDefaults.h, the owner's policy 11-23): first, before any item switches an option — every
  5372. // LYNX extra starts at the default the list names (the visual four on, FL's own two on, the rest off); a 0.1.31
  5373. // ui-options.txt keeps what the user changed and takes the new defaults for the rest; a file with the user-set
  5374. // list keeps a choice that differs from the default; the page's two buttons' values
  5375. juce::String extras190qkResult = "OK";
  5376. {
  5377. lynx::SettingsHooks hooks;
  5378. hooks.getGeneral = [] { return lynx::GeneralOptions {}; };
  5379. for (const auto& item : lynx::extras::items)
  5380. {
  5381. const auto now = item.id == "general.stretchedClipsLoop" ? lynx::stretchedClipsLoop()
  5382. : lynx::lynxExtraOn (offline, hooks, item.id);
  5383. if (now != lynx::extras::defaultOn (item.id))
  5384. extras190qkResult = "ERROR default of " + juce::String (std::string (item.id));
  5385. }
  5386. const auto kept = lynx::extras::userSet();
  5387. std::vector<std::string> old { "wheelZones=1", "shadeFadedAudio=0", "hoverValues=0", "escClosesWindows=0", "liveScaleControl=1" };
  5388. lynx::extras::followDefaults (old);
  5389. const std::vector<std::string> expected { "wheelZones=1", "shadeFadedAudio=0", "hoverValues=0", "escClosesWindows=0", "liveScaleControl=1" };
  5390. if (old != expected || lynx::extras::userSet() != std::set<std::string> { "controlBar.liveScale", "general.escCloses", "playlist.wheelZones" })
  5391. extras190qkResult = "ERROR 0.1.31 file";
  5392. std::vector<std::string> mine { "trackInserts=0", "prChordHighlight=0", "extrasUserSet=playlist.trackInserts" };
  5393. lynx::extras::followDefaults (mine);
  5394. if (mine[0] != "trackInserts=0" || mine[1] != "prChordHighlight=1")
  5395. extras190qkResult = "ERROR user-set list";
  5396. if (lynx::extras::noteUserChoices ("\nshadeFadedAudio=0\ntrackInserts=0\nwheelZones=1") != "\nextrasUserSet=playlist.trackInserts,playlist.wheelZones")
  5397. extras190qkResult = "ERROR noting the choices";
  5398. if (! lynx::extras::flExactOn ("general.escCloses") || lynx::extras::flExactOn ("playlist.shadeFadedAudio") || lynx::extras::flExactOn ("general.stretchedClipsLoop"))
  5399. extras190qkResult = "ERROR FL-exact values";
  5400. lynx::extras::userSet() = kept;
  5401. }
  5402. // project format round trip, with accents in the name
  5403. auto original = lynx::Song::makeDefault();
  5404. original.channels[0].name = "Bumbo ação";
  5405. original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
  5406. original.mode = lynx::PlayMode::song;
  5407. original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  5408. original.mixer[3].effects[0].params[1] = 0.25f;
  5409. lynx::Automation automation;
  5410. automation.name = "Pan";
  5411. automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
  5412. automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
  5413. original.automations.push_back (automation);
  5414. lynx::Clip automationClip;
  5415. automationClip.kind = lynx::ClipKind::automation;
  5416. automationClip.automation = 0;
  5417. automationClip.track = 4;
  5418. automationClip.length = 3840;
  5419. original.playlist.push_back (automationClip);
  5420. original.loopStart = 960;
  5421. original.loopEnd = 7680;
  5422. original.playlistTracks.resize (3);
  5423. original.playlistTracks[2].colour = 0xFF2A6FDB; // a track colour (round 90)
  5424. { // the clip grid (round 181a)
  5425. lynx::launcher::setClip (original, 1, 2, { 0, 0, 0, 1920, 0 });
  5426. auto& slot = *lynx::launcher::settingsAt (*original.clipGrid, 1, 2);
  5427. slot.name = "Clip ação";
  5428. slot.mode = lynx::LaunchMode::toggle;
  5429. slot.quant = lynx::LaunchQuant::eighthTriplet;
  5430. slot.legato = true;
  5431. slot.loop = false;
  5432. original.clipGrid->scenes[0].name = "Intro";
  5433. original.clipGrid->globalQuant = lynx::LaunchQuant::bars2;
  5434. }
  5435. std::uint32_t savedGroove = 0;
  5436. { // round 190bv: the groove pool, a groove on the slot's clip, and that clip copied and the copy moved
  5437. lynx::Groove g;
  5438. g.name = "Balanço";
  5439. g.base = lynx::GrooveBase::eighth;
  5440. g.quantize = 0.25f;
  5441. g.timing = 0.8f;
  5442. g.random = 0.1f;
  5443. g.velocity = -0.5f;
  5444. g.length = 1920;
  5445. g.points = { { 0, 1.0f }, { 560, 0.5f } };
  5446. savedGroove = lynx::groove::add (original.grooves, g);
  5447. original.grooves.amount = 1.2f;
  5448. lynx::groove::setClipGroove (original, 1, 2, savedGroove);
  5449. lynx::session::moveClip (original, 1, 2, 0, 1, true);
  5450. lynx::session::moveClip (original, 0, 1, 2, 0, false);
  5451. original.playlist[0].groove = savedGroove; // round 190fm: a Playlist pattern clip's groove
  5452. }
  5453. original.playlistTracks[2].grouped = true; // track groups and rack filter groups (round 104)
  5454. original.playlistTracks[1].collapsed = true;
  5455. original.channelGroups = { "Drums", "Keys" };
  5456. original.channels[1].group = 1;
  5457. original.channels[1].cutOthersOnly = original.channels[1].cutAtNoteEnd = true; // FL Studio Mobile's cut rule (round 190fe)
  5458. juce::String error;
  5459. if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
  5460. lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
  5461. const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
  5462. // round 190bw: FL's curve modes of automation points come back from a project, tension whole; a bent point
  5463. // without a mode (a project saved before the modes: [tick, value, tension]) keeps LYNX's older law
  5464. const auto curveModesOk = [&original] {
  5465. auto song = original;
  5466. auto& a = song.automations[0];
  5467. a.points = { { 0, 0.25f, 0.5f, (std::uint8_t) lynx::flcurve::stairs },
  5468. { 960, 1.0f, -0.123456f, (std::uint8_t) lynx::flcurve::smooth },
  5469. { 1920, 0.5f, 0.0f, (std::uint8_t) lynx::flcurve::hold },
  5470. { 2400, 0.75f, 0.7f, lynx::AutomationPoint::legacyCurve },
  5471. { 2880, 0.3f, 0.0f, 0 },
  5472. { 3840, 0.6f, 0.0f, 0 } };
  5473. a.lfo.on = true;
  5474. a.lfo.amp = { { 0, 1.0f, -0.25f, (std::uint8_t) lynx::flcurve::pulse }, { 960, 0.5f, 0.0f, 0 } };
  5475. juce::String e;
  5476. const auto text = lynx::ProjectFile::toJson (song);
  5477. const auto back = lynx::ProjectFile::fromJson (text, e);
  5478. return back && back->automations.size() == 1 && back->automations[0].points == a.points && back->automations[0].lfo.amp == a.lfo.amp
  5479. && back->automations[0].valueAt (700.0) == a.valueAt (700.0) && back->automations[0].valueAt (2600.0) == a.valueAt (2600.0);
  5480. }();
  5481. const auto projectOk = curveModesOk && reloaded && reloaded->channels.size() == original.channels.size()
  5482. && reloaded->channels[0].name == original.channels[0].name
  5483. && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
  5484. && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
  5485. && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
  5486. && reloaded->clipGrid.has_value() && reloaded->clipGrid->globalQuant == lynx::LaunchQuant::bars2
  5487. && reloaded->clipGrid->scenes.size() == 3 && reloaded->clipGrid->scenes[0].name == "Intro"
  5488. && lynx::launcher::clipAt (*reloaded->clipGrid, 1, 2) != nullptr
  5489. && [&reloaded] {
  5490. auto grid = *reloaded->clipGrid;
  5491. const auto* slot = lynx::launcher::settingsAt (grid, 1, 2);
  5492. return slot != nullptr && slot->name == "Clip ação" && slot->mode == lynx::LaunchMode::toggle
  5493. && slot->quant == lynx::LaunchQuant::eighthTriplet && slot->legato && ! slot->loop;
  5494. }()
  5495. && [&reloaded, &original, savedGroove] { // round 190bv
  5496. auto grid = *reloaded->clipGrid;
  5497. const auto* kept = lynx::launcher::settingsAt (grid, 1, 2);
  5498. const auto* moved = lynx::launcher::settingsAt (grid, 2, 0);
  5499. const auto* clip = lynx::launcher::clipAt (grid, 2, 0);
  5500. return reloaded->grooves == original.grooves && reloaded->grooves.grooves.size() == 1
  5501. && reloaded->grooves.amount == 1.2f && reloaded->grooves.grooves[0].name == "Balanço"
  5502. && reloaded->grooves.grooves[0].points.size() == 2 && savedGroove != 0
  5503. && kept != nullptr && kept->groove == savedGroove
  5504. && lynx::launcher::clipAt (grid, 0, 1) == nullptr
  5505. && clip != nullptr && clip->pattern == 0 && clip->length == 1920
  5506. && moved != nullptr && moved->groove == savedGroove && moved->name == "Clip ação"
  5507. && moved->mode == lynx::LaunchMode::toggle && moved->legato && ! moved->loop
  5508. && reloaded->playlist[0].groove == savedGroove && reloaded->playlist[1].groove == 0; // (190fm)
  5509. }()
  5510. && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
  5511. && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
  5512. && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
  5513. && reloaded->automations[0].points[1].tick == 3840
  5514. && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
  5515. && reloaded->playlistTracks.size() == 3 && reloaded->playlistTracks[2].colour == 0xFF2A6FDB
  5516. && reloaded->playlistTracks[1].colour == 0
  5517. && reloaded->playlistTracks[2].grouped && reloaded->playlistTracks[1].collapsed && ! reloaded->playlistTracks[1].grouped
  5518. && reloaded->channelGroups == original.channelGroups && reloaded->channels[1].group == 1 && reloaded->channels[0].group == -1
  5519. && reloaded->channels[1].cutOthersOnly && reloaded->channels[1].cutAtNoteEnd && ! reloaded->channels[0].cutOthersOnly
  5520. && ! reloaded->channels[0].cutAtNoteEnd
  5521. && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
  5522. && reloaded->mixer[3].effects.size() == 1
  5523. && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
  5524. && reloaded->mixer[3].effects[0].params[1] == 0.25f;
  5525. // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
  5526. auto rich = lynx::Song::makeDefault();
  5527. auto& synth = rich.channels[4].synth;
  5528. synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
  5529. synth.filterType = 2;
  5530. synth.mono = true;
  5531. synth.portaBeats = 0.125f;
  5532. synth.am = true;
  5533. synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
  5534. synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
  5535. auto& sampler = rich.channels[0].sampler;
  5536. sampler.cutoff = 1200.0f;
  5537. sampler.resonance = 0.3f;
  5538. sampler.filterType = 1;
  5539. sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
  5540. sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
  5541. rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
  5542. rich.mixer[2].eq.hz[1] = 2200.0f;
  5543. auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  5544. peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
  5545. peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
  5546. rich.mixer[2].effects.push_back (peqSlot);
  5547. auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5548. utilitySlot.params[1] = 0.2f;
  5549. rich.mixer[2].effects.push_back (utilitySlot);
  5550. auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
  5551. for (int i = 0; i < 300; ++i)
  5552. vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
  5553. vocodexSlot.sidechain = 1;
  5554. vocodexSlot.sidechain2 = 2;
  5555. rich.mixer[3].effects.push_back (vocodexSlot);
  5556. rich.addMarker ({ 3840, "Refrão", 0, 4 });
  5557. rich.addMarker ({ 7680, {}, 7, 8 });
  5558. const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
  5559. auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
  5560. for (std::size_t i = 0; i < a.size(); ++i)
  5561. if (std::abs (a[i] - b[i]) > 1.0e-3f)
  5562. return false;
  5563. return true;
  5564. };
  5565. // round 190bu: a one-knob effect, the chain's Blend and its preset name travel in the project; a project without
  5566. // them reads as before (no goal, Blend 100 %) and writes none of the new keys
  5567. bool fx190buOk = false;
  5568. {
  5569. auto song = lynx::Song::makeDefault();
  5570. const auto plainJson = lynx::ProjectFile::toJson (song);
  5571. const auto* preset = lynx::chains::find ("Whisper Air");
  5572. if (preset != nullptr && song.mixer.size() > 2)
  5573. {
  5574. lynx::chains::apply (song, 1, *preset);
  5575. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::room, 0.62f));
  5576. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::bass, 0.3f));
  5577. song.mixer[2].chainBlend = 0.4f;
  5578. const auto json = lynx::ProjectFile::toJson (song);
  5579. const auto back = lynx::ProjectFile::fromJson (json, error);
  5580. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  5581. auto same = back && back->mixer.size() == song.mixer.size();
  5582. for (std::size_t t = 1; same && t <= 2; ++t)
  5583. {
  5584. const auto& a = song.mixer[t];
  5585. const auto& b = back->mixer[t];
  5586. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  5587. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  5588. same = a.effects[i].kind == b.effects[i].kind && a.effects[i].goal == b.effects[i].goal
  5589. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f && a.effects[i].row == b.effects[i].row
  5590. && lynx::goals::active (b.effects[i]) == lynx::goals::active (a.effects[i]);
  5591. }
  5592. fx190buOk = same && lynx::chains::unchanged (*back, 1) && back->mixer[2].chainPreset.empty()
  5593. && ! plainJson.contains ("\"goal\"") && ! plainJson.contains ("chainBlend") && ! plainJson.contains ("chainPreset")
  5594. && json.contains ("\"goalAmount\"") && plainBack && plainBack->mixer[1].chainBlend == 1.0f
  5595. && lynx::ProjectFile::toJson (*back) == json;
  5596. // a user's chain preset file: the slots, Blend and name come back; the strip's level is not part of it
  5597. song.mixer[2].volume = 0.31f;
  5598. const auto file = lynx::ProjectFile::mixerTrackStateToJson (lynx::chains::stateOf (song.mixer[2], "Mine"));
  5599. const auto state = lynx::ProjectFile::mixerTrackStateFromJson (file, error);
  5600. fx190buOk = fx190buOk && state && state->effects.size() == 2 && state->effects[0].goal == lynx::goals::room
  5601. && lynx::goals::active (state->effects[1]) && std::abs (state->chainBlend - 0.4f) < 1.0e-6f && state->chainPreset == "Mine"
  5602. && state->volume == lynx::MixerTrack().volume;
  5603. }
  5604. }
  5605. const auto richOk = fx190buOk && richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
  5606. && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
  5607. && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
  5608. && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
  5609. && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
  5610. && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
  5611. && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
  5612. && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
  5613. && richBack->markers() == rich.markers();
  5614. // issue #96's per-plugin option: saved only when on; old projects (no field) read as off
  5615. bool hostKeysOk = false;
  5616. {
  5617. auto song = lynx::Song::makeDefault();
  5618. lynx::ChannelDef plugin;
  5619. plugin.instrument = lynx::InstrumentKind::plugin;
  5620. plugin.plugin.id = "x";
  5621. song.channels.push_back (plugin);
  5622. const auto channel = song.channels.size() - 1;
  5623. const auto off = lynx::ProjectFile::toJson (song);
  5624. song.channels[channel].plugin.allowHostKeys = true;
  5625. song.channels[channel].plugin.hostKeysFirst = true;
  5626. song.channels[channel].plugin.pinned = true; // (round 190ao: Pin on top)
  5627. song.channels[channel].plugin.velocityMode = lynx::prefs::pluginVelocityFixed; // (round 190ao: the plugin's own velocity)
  5628. song.channels[channel].plugin.fixedVelocity = 64;
  5629. const auto on = lynx::ProjectFile::toJson (song);
  5630. const auto offBack = lynx::ProjectFile::fromJson (off, error);
  5631. const auto onBack = lynx::ProjectFile::fromJson (on, error);
  5632. hostKeysOk = ! off.contains ("allowHostKeys") && on.contains ("allowHostKeys") && offBack && onBack
  5633. && ! offBack->channels[channel].plugin.allowHostKeys && onBack->channels[channel].plugin.allowHostKeys
  5634. && ! off.contains ("hostKeysFirst") && ! offBack->channels[channel].plugin.hostKeysFirst && onBack->channels[channel].plugin.hostKeysFirst
  5635. && ! off.contains ("pinnedOnTop") && ! offBack->channels[channel].plugin.pinned && onBack->channels[channel].plugin.pinned
  5636. && ! off.contains ("velocityMode") && ! off.contains ("fixedVelocity") && offBack->channels[channel].plugin.velocityMode == 0
  5637. && offBack->channels[channel].plugin.fixedVelocity == lynx::prefs::defaultFixedVelocity
  5638. && onBack->channels[channel].plugin.velocityMode == lynx::prefs::pluginVelocityFixed && onBack->channels[channel].plugin.fixedVelocity == 64;
  5639. }
  5640. // round 190ad: a new project has FL's plugin levels and keeps them through a save; a project saved before
  5641. // (no "pluginLevels") reads as LYNX's own law, and stays so when it opens
  5642. bool pluginLevelsOk = false;
  5643. {
  5644. const auto fresh = lynx::makeNewProject();
  5645. const auto saved = lynx::ProjectFile::toJson (fresh);
  5646. const auto back = lynx::ProjectFile::fromJson (saved, error);
  5647. auto old = lynx::Song::makeDefault(); // (what every earlier version made)
  5648. const auto oldSaved = lynx::ProjectFile::toJson (old);
  5649. const auto oldBack = lynx::ProjectFile::fromJson (oldSaved, error);
  5650. const auto stripped = lynx::ProjectFile::fromJson (saved.replace ("\"pluginLevels\"", "\"pluginLevelsGone\""), error);
  5651. pluginLevelsOk = fresh.flPluginLevels && saved.contains ("\"pluginLevels\"") && back && back->flPluginLevels
  5652. && ! old.flPluginLevels && ! oldSaved.contains ("pluginLevels") && oldBack && ! oldBack->flPluginLevels
  5653. && stripped && ! stripped->flPluginLevels;
  5654. }
  5655. // hardware output targets (REA round 156): saved only when set; old projects (no field) keep the defaults
  5656. bool hwOutOk = false;
  5657. {
  5658. auto song = lynx::Song::makeDefault();
  5659. const auto plain = lynx::ProjectFile::toJson (song);
  5660. song.mixer[0].outputChannel = lynx::outputNone;
  5661. song.mixer[1].outputChannel = 2;
  5662. song.mixer[1].outputMode = lynx::OutputMode::monoRight;
  5663. song.mixer[2].outputChannel = 6;
  5664. song.mixer[3].outputChannel = 4;
  5665. song.mixer[3].outputMode = lynx::OutputMode::monoSum;
  5666. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5667. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  5668. hwOutOk = back && back->mixer[0].outputChannel == lynx::outputNone && back->mixer[1].outputChannel == 2
  5669. && back->mixer[1].outputMode == lynx::OutputMode::monoRight && back->mixer[2].outputChannel == 6
  5670. && back->mixer[2].outputMode == lynx::OutputMode::stereo && back->mixer[3].outputMode == lynx::OutputMode::monoSum
  5671. && back->mixer[4].outputChannel == lynx::outputDefault && ! plain.contains ("\"output\"") && plainBack
  5672. && plainBack->mixer[0].outputChannel == lynx::outputDefault && plainBack->mixer[1].outputChannel == lynx::outputDefault;
  5673. }
  5674. // round 168j: FL's icons (channel / mixer track / playlist track), PDC Automatic / Compensate automations, Time
  5675. // settings, scale highlighting and data folder — saved only when set, old projects load with FL's defaults
  5676. bool flp168jOk = false;
  5677. {
  5678. auto song = lynx::Song::makeDefault();
  5679. const auto plain = lynx::ProjectFile::toJson (song);
  5680. song.channels[0].icon = 75;
  5681. song.mixer[2].icon = 71;
  5682. song.playlistTracks.resize (3);
  5683. song.playlistTracks[2].icon = 30;
  5684. song.autoPdc = false;
  5685. song.compensateAutomations = false;
  5686. song.timeSignatureMode = true;
  5687. song.scaleHighlight = { 10, 5 };
  5688. song.dataFolder = "D:\\Projects\\data";
  5689. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5690. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  5691. flp168jOk = back && back->channels[0].icon == 75 && back->mixer[2].icon == 71 && back->playlistTracks.size() >= 3
  5692. && back->playlistTracks[2].icon == 30 && ! back->autoPdc && ! back->compensateAutomations && back->timeSignatureMode
  5693. && back->scaleHighlight == song.scaleHighlight && back->dataFolder == song.dataFolder && plainBack && plainBack->autoPdc
  5694. && plainBack->compensateAutomations && ! plainBack->timeSignatureMode && plainBack->scaleHighlight == lynx::Song::ScaleHighlight {}
  5695. && plainBack->dataFolder.empty() && plainBack->channels[0].icon == 0 && ! plain.contains ("\"icon\"")
  5696. && ! plain.contains ("autoPdc") && ! plain.contains ("scaleHighlight");
  5697. }
  5698. // round 180d: clip fades take FL's S curve; a project saved before that keeps its straight fades, also after another
  5699. // save, and a clip made in it takes the S curve. FL's fade tensions and stretch mode and PITCH survive a save.
  5700. // issue #122: playlist tracks linked to inserts (audio) and channels (instrument) survive save, load and save
  5701. // again byte for byte (they were read before the mixer and fell back to Unassigned)
  5702. bool trackModes122Ok = false;
  5703. {
  5704. auto song = lynx::Song::makeDefault();
  5705. song.playlistTracks.resize (6);
  5706. song.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  5707. song.playlistTracks[1].mixerTrack = 3;
  5708. song.playlistTracks[4].mode = lynx::PlaylistTrackMode::audio;
  5709. song.playlistTracks[4].mixerTrack = (int) song.mixer.size() - 1;
  5710. song.playlistTracks[5].mode = lynx::PlaylistTrackMode::instrument;
  5711. song.playlistTracks[5].channel = 1;
  5712. song.playlistTracks[5].mixerTrack = 2;
  5713. const auto json = lynx::ProjectFile::toJson (song, false);
  5714. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  5715. const auto again = loaded ? lynx::ProjectFile::toJson (*loaded, false) : juce::String();
  5716. trackModes122Ok = loaded && json.contains ("playlistTrackModes") && again == json && loaded->playlistTracks.size() >= 6
  5717. && loaded->playlistTracks[1].mode == lynx::PlaylistTrackMode::audio && loaded->playlistTracks[1].mixerTrack == 3
  5718. && loaded->playlistTracks[4].mode == lynx::PlaylistTrackMode::audio
  5719. && loaded->playlistTracks[4].mixerTrack == (int) song.mixer.size() - 1
  5720. && loaded->playlistTracks[5].mode == lynx::PlaylistTrackMode::instrument && loaded->playlistTracks[5].channel == 1;
  5721. }
  5722. bool clipFades180dOk = false;
  5723. {
  5724. auto song = lynx::Song::makeDefault();
  5725. lynx::Clip faded;
  5726. faded.kind = lynx::ClipKind::audio;
  5727. faded.channel = 0;
  5728. faded.length = lynx::ppq * 8;
  5729. faded.fadeIn = lynx::ppq;
  5730. faded.fadeOutTension = -812.933f;
  5731. faded.fadeOut = lynx::ppq * 2;
  5732. lynx::Clip plainClip = faded;
  5733. plainClip.fadeIn = plainClip.fadeOut = 0;
  5734. plainClip.fadeOutTension = 0.0f;
  5735. plainClip.start = lynx::ppq * 16;
  5736. song.playlist = { faded, plainClip };
  5737. song.channels[0].sampler.flStretchMode = 5;
  5738. song.channels[0].sampler.flStretchPitch = 247;
  5739. const auto json = lynx::ProjectFile::toJson (song);
  5740. const auto current = lynx::ProjectFile::fromJson (json, error);
  5741. const auto oldJson = json.replace ("\"clipFadesPerClip\"", "\"clipFadesOther\"");
  5742. auto old = lynx::ProjectFile::fromJson (oldJson, error);
  5743. auto resaved = old;
  5744. if (resaved)
  5745. {
  5746. auto added = faded;
  5747. added.start = lynx::ppq * 32;
  5748. added.linearFades = 0;
  5749. resaved->playlist.push_back (added);
  5750. resaved = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*resaved), error);
  5751. }
  5752. clipFades180dOk = current && old && resaved && json.contains ("clipFadesPerClip") && ! oldJson.contains ("clipFadesPerClip")
  5753. && current->playlist.size() == 2 && ! current->playlist[0].linearFades
  5754. && current->playlist[0].fadeOutTension == -812.933f && ! current->playlist[1].linearFades
  5755. && current->channels[0].sampler.flStretchMode == 5 && current->channels[0].sampler.flStretchPitch == 247
  5756. && old->playlist.size() == 2 && old->playlist[0].linearFades && ! old->playlist[1].linearFades
  5757. && resaved->playlist.size() == 3 && resaved->playlist[0].linearFades && ! resaved->playlist[1].linearFades
  5758. && ! resaved->playlist[2].linearFades && resaved->playlist[0].fadeOutTension == -812.933f;
  5759. }
  5760. // FL's legacy Pattern Blocks (round 170f): the option and every arrangement's blocks are saved; a project without
  5761. // them has neither in its file and loads with the option off
  5762. bool blocksOk = false;
  5763. {
  5764. auto song = lynx::Song::makeDefault();
  5765. const auto plain = lynx::ProjectFile::toJson (song);
  5766. song.patternBlocksOn = true;
  5767. lynx::patternblocks::place (song, 0, 0);
  5768. lynx::patternblocks::place (song, 0, 4 * 4 * lynx::ppq);
  5769. lynx::patternblocks::setMuted (song, 1, true); // (round 190ht, issue #127: a muted block keeps its mute)
  5770. song.addArrangement ("Second");
  5771. lynx::patternblocks::place (song, 0, 2 * 4 * lynx::ppq);
  5772. song.selectArrangement (0);
  5773. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5774. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  5775. blocksOk = back && back->patternBlocksOn && back->blocks == song.blocks && song.blocks.size() == 2 && back->blocks[1].muted
  5776. && back->arrangements.size() == 2 && back->arrangements[1].blocks == song.arrangements[1].blocks
  5777. && song.arrangements[1].blocks.size() == 1 && back->songLength() == song.songLength() && plainBack
  5778. && ! plainBack->patternBlocksOn && plainBack->blocks.empty() && ! plain.contains ("blocks")
  5779. && ! plain.contains ("patternBlocks");
  5780. }
  5781. // FL's pattern clip takeover (issue #158): saved when on; a project saved before it (no key) loads with it off and
  5782. // keeps playing every overlapping clip of a pattern in full; new projects have it on
  5783. bool takeoverOk = false;
  5784. {
  5785. auto song = lynx::Song::makeDefault();
  5786. const auto plain = lynx::ProjectFile::toJson (song);
  5787. song.patternClipTakeover = true;
  5788. const auto json = lynx::ProjectFile::toJson (song);
  5789. const auto back = lynx::ProjectFile::fromJson (json, error);
  5790. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  5791. takeoverOk = back && back->patternClipTakeover && json.contains ("patternClipTakeover") && plainBack
  5792. && ! plainBack->patternClipTakeover && ! plain.contains ("patternClipTakeover")
  5793. && lynx::makeNewProject().patternClipTakeover;
  5794. }
  5795. // comping (round 177c): a comp's equal-power crossfades (Clip::fadeCurve) and the crossfade length are saved; a
  5796. // project without them has neither in its file
  5797. bool compOk = false;
  5798. {
  5799. auto song = lynx::Song::makeDefault();
  5800. const auto plain = lynx::ProjectFile::toJson (song);
  5801. lynx::ChannelDef take;
  5802. take.instrument = lynx::InstrumentKind::audioClip;
  5803. take.samplePath = "take.wav";
  5804. song.channels.push_back (take);
  5805. lynx::Clip a;
  5806. a.kind = lynx::ClipKind::audio;
  5807. a.channel = (int) song.channels.size() - 1;
  5808. a.length = lynx::ppq;
  5809. a.fadeOut = 20;
  5810. a.fadeCurve = 2;
  5811. auto b = a;
  5812. b.start = lynx::ppq - 20;
  5813. b.fadeOut = 0;
  5814. b.fadeIn = 20;
  5815. b.fadeCurve = 1;
  5816. // round 180d's FL fade fields (indices 17..20) and the comp curve (index 21) on one clip, all kept
  5817. auto c = a;
  5818. c.start = 4 * lynx::ppq;
  5819. c.fadeIn = 30;
  5820. c.fadeInTension = -0.75f;
  5821. c.fadeOutTension = 0.5f;
  5822. c.linearFades = 2;
  5823. c.flFadeFlags = 0x1234u;
  5824. c.fadeCurve = 3;
  5825. song.playlist = { a, b, c };
  5826. song.compCrossfadeMs = 12.5f;
  5827. song.playlistTracks.resize (2);
  5828. song.playlistTracks[0].compTrack = true;
  5829. song.playlistTracks[1].grouped = true;
  5830. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5831. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  5832. const auto* both = back && back->playlist.size() == 3 ? &back->playlist[2] : nullptr;
  5833. compOk = back && back->playlist.size() == 3 && back->playlist[0].fadeCurve == 2 && back->playlist[1].fadeCurve == 1
  5834. && both != nullptr && both->fadeCurve == 3 && both->fadeInTension == -0.75f && both->fadeOutTension == 0.5f
  5835. && both->linearFades == 2 && both->flFadeFlags == 0x1234u && both->fadeIn == 30
  5836. && back->playlist[1].fadeIn == 20 && back->compCrossfadeMs == 12.5f && back->playlistTracks[0].compTrack && ! back->playlistTracks[1].compTrack && plainBack
  5837. && plainBack->compCrossfadeMs == lynx::Song::defaultCompCrossfadeMs && ! plain.contains ("compCrossfadeMs") && ! plain.contains ("playlistCompTracks");
  5838. }
  5839. // Misc › Mono / Porta / Slide on every generator (round 168l): kept in the file; a project saved before (an
  5840. // imported engine's flags in its synth settings) gets them back, a Max polyphony of 1 is not Mono
  5841. bool polyOk = false;
  5842. {
  5843. auto song = lynx::Song::makeDefault();
  5844. lynx::ChannelDef osc;
  5845. osc.instrument = lynx::InstrumentKind::threeosc;
  5846. osc.misc.mono = osc.misc.porta = true;
  5847. osc.misc.portaBeats = 0.25f;
  5848. song.channels.push_back (osc);
  5849. auto old = osc;
  5850. old.misc = {};
  5851. old.synth.mono = old.synth.porta = true;
  5852. old.synth.portaBeats = 0.5f;
  5853. song.channels.push_back (old);
  5854. old.maxPolyphony = 1;
  5855. song.channels.push_back (old);
  5856. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5857. const auto n = song.channels.size();
  5858. polyOk = back && back->channels.size() == n && back->channels[n - 3].misc.mono && back->channels[n - 3].misc.porta
  5859. && std::abs (back->channels[n - 3].misc.portaBeats - 0.25f) < 1e-6f && back->channels[n - 2].misc.mono
  5860. && back->channels[n - 2].misc.porta && std::abs (back->channels[n - 2].misc.portaBeats - 0.5f) < 1e-6f
  5861. && ! back->channels[n - 1].misc.mono && back->channels[n - 1].maxPolyphony == 1
  5862. && ! back->channels[4].misc.mono; // (the LYNX Synth keeps its own flags)
  5863. }
  5864. // FL's track latency (REA round 165f-mixer): manual ms, bypass mode and master compensation saved only when set
  5865. bool latencyOk = false;
  5866. {
  5867. auto song = lynx::Song::makeDefault();
  5868. const auto plain = lynx::ProjectFile::toJson (song);
  5869. song.mixer[1].latencyMs = -20.0f;
  5870. song.mixer[2].latencyMs = 12.5f;
  5871. song.mixer[2].latencyBypass = lynx::LatencyBypass::always;
  5872. song.mixer[3].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  5873. song.mixer[3].compensateMasterLatency = false;
  5874. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5875. latencyOk = back && back->mixer[1].latencyMs == -20.0f && back->mixer[2].latencyMs == 12.5f
  5876. && back->mixer[2].latencyBypass == lynx::LatencyBypass::always
  5877. && back->mixer[3].latencyBypass == lynx::LatencyBypass::whenRecordingOrStopped && ! back->mixer[3].compensateMasterLatency
  5878. && back->mixer[4].latencyMs == 0.0f && back->mixer[4].compensateMasterLatency
  5879. && ! plain.contains ("latencyMs") && ! plain.contains ("latencyBypass") && ! plain.contains ("compensateMaster");
  5880. }
  5881. // LYNX's pre-fader sends (round 190aq): saved only when one is used, in a list of its own ("preSends") that a
  5882. // version from before ignores (its sends then play post-fader, as FL's)
  5883. bool preSendOk = false;
  5884. {
  5885. auto song = lynx::Song::makeDefault();
  5886. song.setRoute (1, 3, true, 0.5f);
  5887. song.setRoute (1, 4, true);
  5888. song.setRoute (2, 3, true);
  5889. const auto plain = lynx::ProjectFile::toJson (song);
  5890. song.setSendPre (1, 3, true);
  5891. const auto json = lynx::ProjectFile::toJson (song);
  5892. const auto back = lynx::ProjectFile::fromJson (json, error);
  5893. preSendOk = back && back->sendPre (1, 3) && ! back->sendPre (1, 4) && ! back->sendPre (2, 3)
  5894. && std::abs (back->routeLevel (1, 3) - 0.5f) < 1.0e-4f && back->mixer[1].sends == song.mixer[1].sends
  5895. && ! plain.contains ("preSends") && json.contains ("preSends")
  5896. && json.replace ("\"preSends\"", "\"preSendsOld\"") != json;
  5897. // the same file without the list (what an older version reads): the sends are there, post-fader
  5898. if (const auto old = lynx::ProjectFile::fromJson (json.replace ("\"preSends\"", "\"unknownToOldVersions\""), error))
  5899. preSendOk = preSendOk && old->routes (1, 3) && ! old->sendPre (1, 3) && old->mixer[1].sends.size() == 2;
  5900. else
  5901. preSendOk = false;
  5902. }
  5903. // LYNX's "Low latency while recording" (round 190aq): a latency-adding effect on a monitored insert's path is
  5904. // bypassed in the engine only — PDC drops, the slot is marked, the song and the saved project stay as they are —
  5905. // and it is back when the option goes off
  5906. bool lowLatencyOk = false;
  5907. {
  5908. lynx::AudioEngine live (false);
  5909. live.editSong ([] (lynx::Song& s) {
  5910. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter)); // 1.5 ms look-ahead
  5911. s.mixer[1].inputChannel = 0;
  5912. s.mixer[1].monitor = lynx::InputMonitor::on;
  5913. });
  5914. const auto before = live.getLatencySamples();
  5915. const auto saved = lynx::ProjectFile::toJson (live.getSong());
  5916. const auto idle = live.lowLatencyBypassedCount() == 0; // the option is off: nothing is bypassed
  5917. auto o = live.getRecordOptions();
  5918. o.lowLatencyRecording = true;
  5919. live.setRecordOptions (o);
  5920. const auto during = live.getLatencySamples();
  5921. const auto marked = live.isSlotLowLatencyBypassed (1, 0) && live.lowLatencyBypassedLatency (1, 0) > 0 && live.lowLatencyBypassedCount() >= 1;
  5922. const auto untouched = live.getSong().mixer[1].effects[0].enabled && lynx::ProjectFile::toJson (live.getSong()) == saved;
  5923. // monitoring leaves "On" (nothing armed): the effect returns
  5924. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::whenArmed; });
  5925. const auto released = live.getLatencySamples() == before && ! live.isSlotLowLatencyBypassed (1, 0);
  5926. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::on; });
  5927. const auto again = live.getLatencySamples() == during && live.isSlotLowLatencyBypassed (1, 0);
  5928. o.lowLatencyRecording = false;
  5929. live.setRecordOptions (o);
  5930. lowLatencyOk = before > 0 && idle && during < before && marked && untouched && released && again
  5931. && live.getLatencySamples() == before && live.lowLatencyBypassedCount() == 0;
  5932. }
  5933. // The Browser's "Preview in time" (round 190aq): a loop whose name gives its tempo is stretched to the project's
  5934. // and starts on the beat; a one-shot plays as it always did; off, nothing changes
  5935. bool previewInTimeOk = false;
  5936. double previewPrepareMs = 0.0;
  5937. {
  5938. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-preview");
  5939. dir.deleteRecursively();
  5940. dir.createDirectory();
  5941. auto writeWav = [&dir] (const juce::String& name, int frames, bool loop) {
  5942. const auto wav = dir.getChildFile (name);
  5943. juce::WavAudioFormat format;
  5944. juce::AudioBuffer<float> audio (1, frames);
  5945. for (int i = 0; i < frames; ++i) // a click on every beat of 120 BPM over a tone, or a decaying hit
  5946. audio.setSample (0, i, loop ? (i % 24000 < 400 ? 0.8f : 0.0f) + 0.1f * std::sin (0.02f * (float) i)
  5947. : 0.6f * std::exp (-(float) i / 2000.0f) * std::sin (0.05f * (float) i));
  5948. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  5949. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  5950. {
  5951. out.release();
  5952. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  5953. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  5954. }
  5955. return wav;
  5956. };
  5957. const auto loop = writeWav ("selftest loop 120 bpm.wav", 96000, true); // 4 beats at 120 BPM
  5958. const auto hit = writeWav ("selftest hit.wav", 14400, false); // 0.3 s
  5959. lynx::AudioEngine player (false);
  5960. const auto projectBpm = player.getTransport().bpm.load();
  5961. // off (FL's preview): nothing is prepared, the file plays as it is
  5962. player.previewFile (loop);
  5963. const auto offOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  5964. player.setPreviewInTime (true);
  5965. player.previewFile (hit); // a one-shot: as it always played, at once
  5966. const auto hitOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  5967. player.previewFile (loop);
  5968. const auto queued = player.getPreviewTiming().pending || std::abs (projectBpm - 120.0) < 0.2;
  5969. player.finishPreviewJobs();
  5970. const auto timing = player.getPreviewTiming();
  5971. previewPrepareMs = player.getLastPreviewPrepareMs();
  5972. const auto wanted = lynx::previewtempo::stretchRatio (120.0, projectBpm);
  5973. const auto stretchedOk = timing.inTime && ! timing.pending && timing.source == lynx::previewtempo::Source::name
  5974. && std::abs (timing.fileBpm - 120.0) < 1.0e-9 && std::abs (timing.ratio - wanted) < 1.0e-12
  5975. && std::abs ((double) timing.frames - 96000.0 * wanted) < 96000.0 * 0.01;
  5976. // the second click on the same file has its stretch ready
  5977. player.previewFile (loop);
  5978. const auto cachedOk = ! player.getPreviewTiming().pending && player.getPreviewTiming().inTime && player.getPreviewTiming().frames == timing.frames;
  5979. player.previewFile ({});
  5980. const auto stoppedOk = ! player.getPreviewTiming().inTime && player.getPreviewInTimeProgress() < 0.0;
  5981. // the start: on the next heard beat while the transport plays (sample exact), at once when it is stopped
  5982. auto firstSample = [] (bool playing, double startTick, int latency) {
  5983. lynx::Transport transport;
  5984. transport.sampleRate.store (48000.0);
  5985. transport.bpm.store (120.0); // 0.04 ticks per sample
  5986. transport.playing.store (playing);
  5987. transport.positionTicks.store (startTick);
  5988. lynx::PreviewPlayer p;
  5989. p.prepareToPlay (48000.0, 512);
  5990. p.setTransport (&transport);
  5991. p.setSyncLatency (latency);
  5992. auto dc = std::make_shared<lynx::SampleData>();
  5993. dc->sampleRate = 48000.0;
  5994. dc->left.assign (48000, 0.5f);
  5995. p.playBrowser (dc, 1.0f, true);
  5996. juce::AudioBuffer<float> block (2, 512);
  5997. juce::MidiBuffer midi;
  5998. for (int done = 0; done < 48000; done += 512)
  5999. {
  6000. p.processBlock (block, midi);
  6001. for (int i = 0; i < 512; ++i)
  6002. if (block.getSample (0, i) != 0.0f)
  6003. return done + i;
  6004. if (playing)
  6005. transport.positionTicks.store (transport.positionTicks.load() + 512 * transport.ticksPerSample());
  6006. }
  6007. return -1;
  6008. };
  6009. const auto beatOk = firstSample (true, 480.0, 0) == 12000 // half a beat to go: 480 ticks / 0.04
  6010. && firstSample (true, 480.0, 100) == 12100 // the song is heard 100 samples late (PDC)
  6011. && firstSample (true, 960.0, 0) == 0 // on a beat: now
  6012. && firstSample (false, 480.0, 0) == 0; // stopped: a free start
  6013. previewInTimeOk = loop.existsAsFile() && hit.existsAsFile() && offOk && hitOk && queued && stretchedOk && cachedOk && stoppedOk && beatOk;
  6014. dir.deleteRecursively();
  6015. }
  6016. // LYNX substitutes (round 98): a missing plugin's slot plays a built-in equivalent and the project keeps the
  6017. // original reference byte for byte (.flp record and LYNX plugin state)
  6018. bool substituteOk = false;
  6019. {
  6020. auto song = lynx::Song::makeDefault();
  6021. lynx::ForeignPlugin vv; // an .flp VST3 record (ValhallaVintageVerb's class ID), opaque state
  6022. vv.format = lynx::ForeignPlugin::Format::vst3;
  6023. const std::uint8_t cid[] = { 0x76, 0x54, 0x53, 0x56, 0x65, 0x65, 0x76, 0x33, 0x61, 0x6c, 0x68, 0x61, 0x6c, 0x6c, 0x61, 0x76 };
  6024. std::copy (std::begin (cid), std::end (cid), vv.classId.begin());
  6025. vv.hasClassId = true;
  6026. vv.name = "ValhallaVintageVerb";
  6027. vv.path = "C:\\x\\ValhallaVintageVerb.vst3";
  6028. for (int i = 0; i < 777; ++i)
  6029. vv.state.push_back ((std::uint8_t) (i * 13 + 1));
  6030. lynx::EffectSlot fromFlp;
  6031. fromFlp.kind = lynx::EffectKind::plugin;
  6032. fromFlp.plugin.foreign = vv;
  6033. lynx::EffectSlot fromLynx; // a LYNX reference whose plugin isn't installed here
  6034. fromLynx.kind = lynx::EffectKind::plugin;
  6035. fromLynx.plugin.id = "VST3-FabFilter Pro-Q 3-1a2b3c4d-5e6f7a8b";
  6036. fromLynx.plugin.name = "FabFilter Pro-Q 3";
  6037. fromLynx.plugin.state = "AAECAwQFBgcICQ==";
  6038. const auto flpRef = fromFlp.plugin, lynxRef = fromLynx.plugin;
  6039. song.mixer[1].effects = { fromFlp, fromLynx };
  6040. const auto substitutesOn = lynx::pluginSubstitutesEnabled();
  6041. const auto changed = offline.getPluginHost().applySubstitutes (song);
  6042. auto& fx = song.mixer[1].effects;
  6043. // only the LYNX reference is substituted here (an .flp record is the import's job); do the .flp one directly
  6044. const auto flpSubstituted = lynx::substituteEffectSlot (fx[0], lynx::pluginIdentity (vv));
  6045. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  6046. substituteOk = flpSubstituted && fx[0].kind == lynx::EffectKind::epochVerb
  6047. && (! substitutesOn || (changed == 1 && fx[1].kind == lynx::EffectKind::facetEq && fx[1].substituteFor == lynxRef))
  6048. && back && back->mixer[1].effects.size() == 2 && back->mixer[1].effects[0].kind == lynx::EffectKind::epochVerb
  6049. && back->mixer[1].effects[0].substituteFor == flpRef && back->mixer[1].effects[0].substituteFor.foreign.state == vv.state
  6050. && back->mixer[1].effects[1].kind == fx[1].kind && back->mixer[1].effects[1].substituteFor == fx[1].substituteFor;
  6051. }
  6052. // undo/redo
  6053. offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
  6054. offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  6055. offline.undo();
  6056. const auto afterUndo = offline.getSong().bpm;
  6057. offline.redo();
  6058. const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
  6059. && offline.isModified();
  6060. // Remote-owned steps still behave as ordinary native history when no RemoteControl instance is enabled.
  6061. // Only API undo/redo refuse device drift; remote reads, staging and publication never hold the audio-device callback lock.
  6062. const auto remoteHistoryResult = []() -> juce::String {
  6063. int checks = 0;
  6064. const auto require = [&] (bool condition, const char* message) {
  6065. ++checks;
  6066. if (! condition) throw std::runtime_error (message);
  6067. };
  6068. try
  6069. {
  6070. for (const auto session : { false, true })
  6071. {
  6072. lynx::AudioEngine history (false);
  6073. lynx::Song initial;
  6074. initial.channels.resize (1);
  6075. initial.channels[0].instrument = lynx::InstrumentKind::synth;
  6076. initial.mixer = lynx::Song::defaultMixer (1);
  6077. initial.bpm = 120.0;
  6078. history.setSong (std::move (initial));
  6079. history.setSessionHistory (session);
  6080. const auto editTempo = [&] (double bpm) {
  6081. require (history.editSongRemoteTransaction ([&] (lynx::Song& s) { s.bpm = bpm; }), "remote tempo edit was not committed");
  6082. };
  6083. const auto refused = [&] (const std::function<void()>& operation) {
  6084. const auto position = history.getHistoryPosition();
  6085. const auto before = lynx::ProjectFile::toJsonExact (history.getSong());
  6086. bool changed = false;
  6087. try { operation(); }
  6088. catch (const lynx::RemoteError& e) { changed = e.code == "changed" && ! e.uncertain; }
  6089. require (changed, "API history did not refuse untracked device changes");
  6090. require (history.getHistoryPosition() == position && lynx::ProjectFile::toJsonExact (history.getSong()) == before,
  6091. "refused API history changed the project or history position");
  6092. };
  6093. const auto withoutDeviceLock = [&] (const std::function<void()>& operation) {
  6094. juce::WaitableEvent locked, release;
  6095. bool timedOut = false;
  6096. std::thread callback ([&] {
  6097. const juce::ScopedLock lock (history.getDeviceManager().getAudioCallbackLock());
  6098. locked.signal();
  6099. timedOut = ! release.wait (3000);
  6100. });
  6101. const auto acquired = locked.wait (3000);
  6102. std::exception_ptr failure;
  6103. try { if (acquired) operation(); }
  6104. catch (...) { failure = std::current_exception(); }
  6105. release.signal();
  6106. callback.join();
  6107. // Check before rethrowing: an expected rejection must not conceal waiting for this lock.
  6108. require (acquired && ! timedOut, "remote read, edit or history publication waited for the audio-device callback lock");
  6109. if (failure) std::rethrow_exception (failure);
  6110. };
  6111. const auto baseline = lynx::ProjectFile::toJsonExact (history.getSong());
  6112. const auto baselineStamp = history.getSongStamp();
  6113. const auto baselinePosition = history.getHistoryPosition();
  6114. const auto unchanged = [&] {
  6115. return history.getSongStamp() == baselineStamp && history.getHistoryPosition() == baselinePosition
  6116. && lynx::ProjectFile::toJsonExact (history.getSong()) == baseline;
  6117. };
  6118. withoutDeviceLock ([&] {
  6119. require (lynx::ProjectFile::toJsonExact (history.snapshotForRemoteControl()) == baseline,
  6120. "remote snapshot changed the project");
  6121. require (history.remoteDeviceStateHash().isNotEmpty(), "remote snapshot did not hash device state");
  6122. });
  6123. require (unchanged(), "remote reads changed the project, revision or history");
  6124. bool staged = false;
  6125. withoutDeviceLock ([&] {
  6126. require (! history.editSongRemoteTransaction ([&] (lynx::Song&) { staged = true; }),
  6127. "remote no-op committed a history step");
  6128. });
  6129. require (staged && unchanged(), "remote no-op did not stage cleanly without changing history");
  6130. bool rejected = false;
  6131. try {
  6132. withoutDeviceLock ([&] {
  6133. history.editSongRemoteTransaction ([] (lynx::Song& next) {
  6134. next.bpm = 999.0;
  6135. throw lynx::RemoteError ("invalid", "selftest stage rejection");
  6136. });
  6137. });
  6138. }
  6139. catch (const lynx::RemoteError& e) { rejected = e.code == "invalid" && ! e.uncertain; }
  6140. require (rejected && unchanged(), "rejected staging changed the project, revision or history");
  6141. for (const auto cancelAfterStage : { false, true })
  6142. {
  6143. int calls = 0;
  6144. staged = false;
  6145. bool cancelledEdit = false;
  6146. try {
  6147. withoutDeviceLock ([&] {
  6148. history.editSongRemoteTransaction ([&] (lynx::Song& next) { staged = true; next.bpm = 999.0; },
  6149. [&] { return ++calls >= (cancelAfterStage ? 2 : 1); });
  6150. });
  6151. }
  6152. catch (const lynx::RemoteError& e) { cancelledEdit = e.code == "failed" && ! e.uncertain; }
  6153. require (cancelledEdit && staged == cancelAfterStage && unchanged(),
  6154. "cancelled edit changed the project, revision or history");
  6155. }
  6156. withoutDeviceLock ([&] { editTempo (130.0); });
  6157. require (history.getSong().bpm == 130.0 && history.getHistoryPosition() == baselinePosition + 1
  6158. && history.getSongStamp() > baselineStamp, "remote commit did not publish one history step");
  6159. history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.23f; }, false);
  6160. refused ([&] { history.undoRemoteControl(); });
  6161. withoutDeviceLock ([&] { history.undo(); });
  6162. require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0 && history.getRemoteHistoryError().isEmpty(),
  6163. "native undo refused device drift while remote control was disabled");
  6164. history.editSong ([] (lynx::Song& s) { s.channels[0].name = "Untracked change"; }, false);
  6165. refused ([&] { history.redoRemoteControl(); });
  6166. withoutDeviceLock ([&] { history.redo(); });
  6167. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
  6168. "native redo refused device drift while remote control was disabled");
  6169. withoutDeviceLock ([&] { editTempo (140.0); });
  6170. history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.42f; }, false);
  6171. withoutDeviceLock ([&] { history.jumpToHistory (0); });
  6172. require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0, "native history jump stopped at a remote step");
  6173. withoutDeviceLock ([&] { history.jumpToHistory (2); });
  6174. require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "native redo jump stopped at a remote step");
  6175. withoutDeviceLock ([&] { history.undoRemoteControl(); });
  6176. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0, "API undo failed with an unchanged device fence");
  6177. withoutDeviceLock ([&] { history.redoRemoteControl(); });
  6178. require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "API redo failed with an unchanged device fence");
  6179. int cancelledChecks = 0;
  6180. bool cancelled = false;
  6181. try { history.undoRemoteControl ([&] { return ++cancelledChecks >= 2; }); }
  6182. catch (const lynx::RemoteError& e) { cancelled = e.code == "failed" && ! e.uncertain; }
  6183. require (cancelled && history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0,
  6184. "cancelled API history moved a step");
  6185. withoutDeviceLock ([&] { history.undo(); });
  6186. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
  6187. "API cancellation leaked into native history");
  6188. }
  6189. return "OK (" + juce::String (checks) + " checks)";
  6190. }
  6191. catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
  6192. }();
  6193. // Hosted state access and processing share a per-instance lock, including fixed blocks and deferred resets.
  6194. const auto hostedStateLockResult = []() -> juce::String {
  6195. struct Probe final : juce::AudioPluginInstance
  6196. {
  6197. struct Parameter final : juce::HostedAudioProcessorParameter
  6198. {
  6199. explicit Parameter (Probe& p) : owner (p) {}
  6200. float getValue() const override { owner.access (owner.parameterReads); return value.load(); }
  6201. void setValue (float v) override { owner.access (owner.parameterWrites); value.store (v); }
  6202. float getDefaultValue() const override { return 0.0f; }
  6203. juce::String getName (int) const override { return "Value"; }
  6204. juce::String getLabel() const override { return {}; }
  6205. juce::String getParameterID() const override { return "value"; }
  6206. float getValueForText (const juce::String& text) const override { return text.getFloatValue(); }
  6207. Probe& owner;
  6208. std::atomic<float> value { 0.0f };
  6209. };
  6210. Probe() : AudioPluginInstance (BusesProperties().withInput ("Input", juce::AudioChannelSet::stereo(), true)
  6211. .withOutput ("Output", juce::AudioChannelSet::stereo(), true))
  6212. {
  6213. addHostedParameter (std::make_unique<Parameter> (*this));
  6214. }
  6215. const juce::String getName() const override { return "State lock probe"; }
  6216. void fillInPluginDescription (juce::PluginDescription& d) const override { d.name = getName(); }
  6217. void prepareToPlay (double, int) override {}
  6218. void releaseResources() override {}
  6219. void processBlock (juce::AudioBuffer<float>& audio, juce::MidiBuffer&) override { access (blocks); audio.clear(); }
  6220. void reset() override { access (resets, std::this_thread::get_id() == ui); } // (on the UI thread: the export reset)
  6221. double getTailLengthSeconds() const override { return 0.0; }
  6222. bool acceptsMidi() const override { return true; }
  6223. bool producesMidi() const override { return false; }
  6224. bool hasEditor() const override { return false; }
  6225. juce::AudioProcessorEditor* createEditor() override { return nullptr; }
  6226. int getNumPrograms() override { return 1; }
  6227. int getCurrentProgram() override { return 0; }
  6228. void setCurrentProgram (int) override {}
  6229. const juce::String getProgramName (int) override { return {}; }
  6230. void changeProgramName (int, const juce::String&) override {}
  6231. void getStateInformation (juce::MemoryBlock& state) override { access (captures); state.replaceAll ("state", 5); }
  6232. void setStateInformation (const void*, int) override { access (restores, true); }
  6233. // Round 190ha: only a restore and the export reset are exclusive with the audio side. A capture and the
  6234. // UI's parameter changes run beside processing, as on JUCE's own hosts (UI-thread calls never overlap
  6235. // each other here: they run in turn).
  6236. void access (std::atomic<int>& calls, bool exclusive = false)
  6237. {
  6238. ++calls;
  6239. if (exclusive)
  6240. {
  6241. ++exclusiveActive;
  6242. if (active.fetch_add (1) != 0) overlap = true;
  6243. }
  6244. else
  6245. {
  6246. ++active;
  6247. if (exclusiveActive.load() != 0) overlap = true;
  6248. }
  6249. juce::Thread::sleep (1); // widen the concurrent vendor-call window without using real plugins
  6250. --active;
  6251. if (exclusive) --exclusiveActive;
  6252. }
  6253. const std::thread::id ui = std::this_thread::get_id();
  6254. std::atomic<int> active { 0 }, exclusiveActive { 0 }, blocks { 0 }, resets { 0 }, captures { 0 }, restores { 0 };
  6255. std::atomic<int> parameterReads { 0 }, parameterWrites { 0 };
  6256. std::atomic<bool> overlap { false };
  6257. };
  6258. int checks = 0;
  6259. const auto require = [&] (bool condition, const char* message) {
  6260. ++checks;
  6261. if (! condition) throw std::runtime_error (message);
  6262. };
  6263. const auto exercise = [&] (auto& adapter, Probe& probe, const auto& render, const auto& reset) {
  6264. const auto saved = adapter.captureState();
  6265. require (saved.has_value(), "mock hosted state could not be captured");
  6266. juce::WaitableEvent start (true);
  6267. std::thread audio ([&] {
  6268. start.wait();
  6269. for (int i = 0; i < 32; ++i)
  6270. {
  6271. adapter.setParameter (0, i % 2 == 0 ? 0.25f : 0.75f);
  6272. (void) adapter.parameterValue (0);
  6273. reset();
  6274. render();
  6275. }
  6276. });
  6277. const juce::ScopeGuard joinAudio { [&] { if (audio.joinable()) audio.join(); } };
  6278. start.signal();
  6279. bool stateOk = true;
  6280. for (int i = 0; i < 32; ++i)
  6281. {
  6282. stateOk = adapter.captureState().has_value() && stateOk;
  6283. stateOk = adapter.restoreState (*saved) && stateOk;
  6284. adapter.setParameterFromUi (0, i % 2 == 0 ? 0.1f : 0.9f);
  6285. if (i % 8 == 0) adapter.resetForExport();
  6286. }
  6287. audio.join();
  6288. // Contended audio callbacks may all have bypassed while state was held.
  6289. // Exercise a successful callback after release before checking coverage.
  6290. adapter.setParameter (0, 0.5f);
  6291. (void) adapter.parameterValue (0);
  6292. reset();
  6293. render();
  6294. require (stateOk && probe.blocks > 0 && probe.resets > 0 && probe.captures > 0 && probe.restores > 0,
  6295. "mock did not exercise processing, resets and hosted state access");
  6296. require (probe.parameterReads > 0 && probe.parameterWrites > 0,
  6297. "mock did not exercise concurrent hosted parameter access");
  6298. require (! probe.overlap, "hosted processing/reset/parameters overlapped a state restore or the export reset");
  6299. require (! adapter.hasCrashed(), "mock hosted adapter crashed");
  6300. };
  6301. try
  6302. {
  6303. for (const auto fixed : { 0, 64 })
  6304. {
  6305. std::array<float, 128> left {}, right {};
  6306. auto instrument = std::make_unique<Probe>();
  6307. auto* instrumentProbe = instrument.get();
  6308. lynx::PluginInstrument voice (std::move (instrument), 128, fixed);
  6309. exercise (voice, *instrumentProbe, [&] { voice.render (left.data(), right.data(), 128, 1.0f, 1.0f); }, [&] { voice.panic(); });
  6310. auto effect = std::make_unique<Probe>();
  6311. auto* effectProbe = effect.get();
  6312. lynx::PluginEffect fx (std::move (effect), 128, fixed);
  6313. exercise (fx, *effectProbe, [&] { fx.process (left.data(), right.data(), 128, {}, 120.0); }, [&] { fx.transportReset(); });
  6314. }
  6315. return "OK (" + juce::String (checks) + " checks)";
  6316. }
  6317. catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
  6318. }();
  6319. const auto hostedStateContentionResult = lynx::pluginStateContentionSelfTest();
  6320. const auto modulators190oxResult = lynx::modulators190oxSelfTest(); // round 190ox: modulators stage 2
  6321. const auto generatorSmartResult = lynx::generatorSmartDisableSelfTest(); // (round 190ok, D2)
  6322. // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
  6323. // (Blend on: this checks that the take joins the pattern's notes; a new install starts with Blend off)
  6324. const auto notesBefore = offline.getSong().patterns[0].notes.size();
  6325. {
  6326. auto o = offline.getRecordOptions();
  6327. o.mode = lynx::RecordMode::overdub;
  6328. offline.setRecordOptions (o);
  6329. }
  6330. offline.setRecording (true);
  6331. offline.play();
  6332. offline.getTransport().positionTicks.store (960.0);
  6333. offline.sendLiveNote (2, 72, 0.9f, true, true);
  6334. offline.getTransport().positionTicks.store (1920.0);
  6335. offline.sendLiveNote (2, 72, 0.0f, false, true);
  6336. offline.setRecording (false);
  6337. offline.stop();
  6338. const auto& recorded = offline.getSong().patterns[0].notes;
  6339. const auto recordOk = recorded.size() == notesBefore + 1
  6340. && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
  6341. return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
  6342. });
  6343. offline.undo();
  6344. const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
  6345. // FL's Tools › Cancel recording (round 187a): the pass's notes go, an edit made before it stays, recording turns
  6346. // off and playback goes on; nothing to redo
  6347. bool cancelRecordOk = false;
  6348. {
  6349. offline.editSong ([] (lynx::Song& s) { s.bpm = 123.0; });
  6350. const auto notesThen = offline.getSong().patterns[0].notes.size();
  6351. offline.setRecording (true);
  6352. offline.play();
  6353. offline.getTransport().positionTicks.store (960.0);
  6354. offline.sendLiveNote (2, 74, 0.9f, true, true);
  6355. offline.getTransport().positionTicks.store (1920.0);
  6356. offline.sendLiveNote (2, 74, 0.0f, false, true);
  6357. offline.sendLiveNote (2, 76, 0.9f, true, true); // (still held when the pass is cancelled)
  6358. const auto cancelled = offline.cancelRecording();
  6359. cancelRecordOk = cancelled && ! offline.isRecording() && offline.getTransport().playing.load()
  6360. && offline.getSong().patterns[0].notes.size() == notesThen && offline.getSong().bpm == 123.0 && ! offline.canRedo()
  6361. && ! offline.cancelRecording(); // (not recording: nothing to cancel)
  6362. offline.sendLiveNote (2, 76, 0.0f, false, false);
  6363. offline.stop();
  6364. }
  6365. // MIDI: exporting the pattern and importing it back gives the same notes
  6366. bool midiOk = false;
  6367. {
  6368. auto source = lynx::Song::makeDefault();
  6369. source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
  6370. source.patterns[0].sortNotes();
  6371. const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
  6372. juce::String midiError;
  6373. const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
  6374. const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
  6375. midiFile.deleteFile();
  6376. if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
  6377. && std::abs (song->bpm - source.bpm) < 0.01)
  6378. {
  6379. midiOk = true;
  6380. const auto& a = source.patterns[0].notes;
  6381. const auto& b = song->patterns[0].notes;
  6382. for (std::size_t i = 0; i < a.size(); ++i)
  6383. midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
  6384. }
  6385. }
  6386. // project package (REA round 118): a project with a sample exported as .zip, extracted and opened again,
  6387. // finds its sample inside the extracted folder
  6388. bool packageOk = false;
  6389. {
  6390. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-package");
  6391. dir.deleteRecursively();
  6392. dir.getChildFile ("src").createDirectory();
  6393. const auto wav = dir.getChildFile ("src/hit.wav");
  6394. {
  6395. juce::WavAudioFormat format;
  6396. juce::AudioBuffer<float> hit (1, 480);
  6397. for (int i = 0; i < 480; ++i)
  6398. hit.setSample (0, i, 0.5f * std::sin (0.1f * (float) i));
  6399. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  6400. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  6401. {
  6402. out.release();
  6403. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  6404. writer->writeFromAudioSampleBuffer (hit, 0, 480);
  6405. }
  6406. }
  6407. auto source = lynx::Song::makeDefault();
  6408. lynx::ChannelDef c;
  6409. c.name = "Hit";
  6410. c.instrument = lynx::InstrumentKind::sampler;
  6411. c.samplePath = wav.getFullPathName().toStdString();
  6412. source.channels.push_back (c);
  6413. lynx::ProjectPackage::Result packed;
  6414. juce::String packageError;
  6415. const auto zip = dir.getChildFile ("Beat.zip");
  6416. if (wav.existsAsFile() && lynx::ProjectPackage::exportZip (source, "Beat", zip, packed, packageError) && packed.files == 1)
  6417. {
  6418. const auto project = lynx::ProjectPackage::extractZip (zip, dir.getChildFile ("out"), packageError);
  6419. const auto song = project.existsAsFile() ? lynx::ProjectFile::load (project, packageError) : std::nullopt;
  6420. if (song && ! song->channels.empty())
  6421. {
  6422. const juce::File back (juce::String::fromUTF8 (song->channels.back().samplePath.c_str()));
  6423. packageOk = back.existsAsFile() && back.isAChildOf (project.getParentDirectory()) && back.getSize() == wav.getSize();
  6424. }
  6425. }
  6426. dir.deleteRecursively();
  6427. }
  6428. // D#92, round 180a: a non-ASCII folder and a dotted name save and load back; an unwritable place says so, and a
  6429. // relative path resolves as the start-up argument does
  6430. bool projectSaveOk = false;
  6431. {
  6432. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-save180a");
  6433. dir.deleteRecursively();
  6434. const auto folder = dir.getChildFile (juce::String::fromUTF8 ("M\xc3\xbasica nova"));
  6435. folder.createDirectory();
  6436. const auto named = lynx::ProjectFile::withProjectExtension (folder.getChildFile (juce::String::fromUTF8 ("Can\xc3\xa7\xc3\xa3o.v2")));
  6437. auto song = lynx::Song::makeDefault();
  6438. lynx::Note note;
  6439. note.length = 240;
  6440. note.key = 64;
  6441. song.patterns[0].notes.push_back (note);
  6442. juce::String error, blockedError;
  6443. const auto again = lynx::ProjectFile::save (song, named, error) ? lynx::ProjectFile::load (named, error) : std::nullopt;
  6444. const auto blocker = dir.getChildFile ("a file");
  6445. blocker.replaceWithText ("x");
  6446. const auto cwd = juce::File::getCurrentWorkingDirectory();
  6447. folder.setAsCurrentWorkingDirectory();
  6448. const auto relative = juce::File::getCurrentWorkingDirectory().getChildFile (named.getFileName());
  6449. cwd.setAsCurrentWorkingDirectory();
  6450. projectSaveOk = named.getFileName().endsWith (".v2.lynx") && again && again->patterns[0].notes.size() == song.patterns[0].notes.size()
  6451. && relative == named && ! lynx::ProjectFile::save (song, blocker.getChildFile ("x.lynx"), blockedError)
  6452. && blockedError.isNotEmpty() && lynx::ProjectFile::withProjectExtension (named) == named;
  6453. dir.deleteRecursively();
  6454. }
  6455. // Online Sessions (round 168a): a project sent as a .lynxpack (one sample used twice is stored once, the uids
  6456. // survive), a stand-in rendered through an ExportJob, the guest's part sent back and merged by the host
  6457. juce::String sessionResult = "ERROR";
  6458. {
  6459. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-session");
  6460. dir.deleteRecursively();
  6461. dir.getChildFile ("src").createDirectory();
  6462. const auto wav = dir.getChildFile ("src/hit.wav");
  6463. {
  6464. juce::WavAudioFormat format;
  6465. juce::AudioBuffer<float> hit (1, 4800);
  6466. for (int i = 0; i < 4800; ++i)
  6467. hit.setSample (0, i, 0.5f * std::sin (0.05f * (float) i) * (1.0f - (float) i / 4800.0f));
  6468. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  6469. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  6470. {
  6471. out.release();
  6472. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  6473. writer->writeFromAudioSampleBuffer (hit, 0, 4800);
  6474. }
  6475. }
  6476. auto host = lynx::Song::makeDefault();
  6477. host.mode = lynx::PlayMode::song;
  6478. const auto copyOfWav = dir.getChildFile ("src/hit copy.wav"); // the same bytes under another name: stored once
  6479. wav.copyFileTo (copyOfWav);
  6480. for (const auto& [name, file] : { std::pair<const char*, juce::File> { "Hit", wav }, { "Hit 2", copyOfWav } })
  6481. {
  6482. lynx::ChannelDef c;
  6483. c.name = name;
  6484. c.instrument = lynx::InstrumentKind::sampler;
  6485. c.samplePath = file.getFullPathName().toStdString();
  6486. host.channels.push_back (c);
  6487. }
  6488. const auto hitChannel = (int) host.channels.size() - 2;
  6489. lynx::Note hitNote;
  6490. hitNote.channel = hitChannel;
  6491. hitNote.length = 480;
  6492. host.patterns[0].notes.push_back (hitNote);
  6493. host.playlist.push_back ({ 0, 0, 0, host.patterns[0].effectiveLength (host.meter()), 0 });
  6494. lynx::uids::normalize (host);
  6495. const auto* guest = lynx::parts::invite (host, "Host", "Ana", 0xFF3D9BE9, false);
  6496. juce::String e;
  6497. std::vector<lynx::sessionpack::Rendered> rendered;
  6498. // (a sampler stands in for a plugin channel here: render() renders whatever it is given)
  6499. const std::vector<lynx::sessionpack::RenderItem> items { { false, hitChannel, false, "Hit", "Test" } };
  6500. const auto renderedOk = guest != nullptr && lynx::sessionpack::render (host, items, 44100.0, dir.getChildFile ("stems"), "Host", rendered, {}, e)
  6501. && rendered.size() == 1 && rendered[0].standIns.size() == 2
  6502. && juce::File (juce::String::fromUTF8 (rendered[0].standIns[0].path.c_str())).getSize() > 1000;
  6503. if (renderedOk)
  6504. lynx::sessionpack::apply (host, rendered);
  6505. lynx::sessionpack::Manifest m;
  6506. m.projectName = "Selftest";
  6507. m.from = *host.session.find (lynx::session::hostTag);
  6508. m.to = *host.session.find (2);
  6509. lynx::sessionpack::WriteResult written;
  6510. const auto pack = dir.getChildFile (juce::String ("Selftest") + lynx::sessionpack::extension);
  6511. const auto packOk = renderedOk && lynx::sessionpack::write (lynx::parts::guestCopy (host, 2), m, offline.getPluginHost(), pack, written, e)
  6512. && written.media == 3 && written.duplicates == 1; // the sample once (used twice), the stand-in pair
  6513. auto opened = packOk ? lynx::sessionpack::open (pack, dir.getChildFile ("received"), e) : std::nullopt;
  6514. bool openOk = false, mergeOk = false;
  6515. if (opened && opened->corrupt.isEmpty())
  6516. {
  6517. const auto& g = opened->song;
  6518. const juce::File sample (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].samplePath.c_str()));
  6519. openOk = g.session.me == 2 && g.projectId == host.projectId && g.channels[(std::size_t) hitChannel].uid == host.channels[(std::size_t) hitChannel].uid
  6520. && sample.existsAsFile() && sample.isAChildOf (opened->folder) && g.channels[(std::size_t) hitChannel].standIns.size() == 2
  6521. && juce::File (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].standIns[1].path.c_str())).existsAsFile();
  6522. // the guest adds a channel and a pattern of his own, sends his part back
  6523. auto copy = g;
  6524. lynx::ChannelDef mine;
  6525. mine.name = "Ana's hit";
  6526. mine.instrument = lynx::InstrumentKind::sampler;
  6527. mine.samplePath = sample.getFullPathName().toStdString();
  6528. copy.channels.push_back (mine);
  6529. lynx::Pattern p;
  6530. p.name = "Ana";
  6531. lynx::Note note;
  6532. note.channel = (int) copy.channels.size() - 1;
  6533. note.length = 240;
  6534. note.key = 64;
  6535. p.notes.push_back (note);
  6536. copy.patterns.push_back (p);
  6537. lynx::uids::normalize (copy);
  6538. // its uids survive a save and a load
  6539. const auto saved = dir.getChildFile ("guest.lynx");
  6540. auto reloaded = lynx::ProjectFile::save (copy, saved, e) ? lynx::ProjectFile::load (saved, e) : std::nullopt;
  6541. lynx::sessionpack::Manifest back;
  6542. back.part = true;
  6543. back.from = *copy.session.self();
  6544. const auto partFile = dir.getChildFile (juce::String ("Ana part") + lynx::sessionpack::extension);
  6545. lynx::sessionpack::WriteResult partWritten;
  6546. auto part = reloaded && reloaded->channels.back().uid == copy.channels.back().uid && lynx::uids::tagOf (reloaded->channels.back().uid) == 2
  6547. ? lynx::sessionpack::write (lynx::parts::extract (*reloaded, 2), back, offline.getPluginHost(), partFile, partWritten, e)
  6548. : false;
  6549. auto partOpened = part ? lynx::sessionpack::open (partFile, dir.getChildFile ("parts"), e) : std::nullopt;
  6550. if (partOpened && partOpened->manifest.part && lynx::sessionpack::adoptMedia (partOpened->song, dir.getChildFile ("Session media/Ana"), e))
  6551. {
  6552. const auto report = lynx::parts::merge (host, partOpened->song, 2);
  6553. const auto& added = host.channels.back();
  6554. mergeOk = report.ok && report.channels >= 1 && added.name == "Ana's hit" && lynx::uids::tagOf (added.uid) == 2
  6555. && juce::File (juce::String::fromUTF8 (added.samplePath.c_str())).isAChildOf (dir.getChildFile ("Session media/Ana"))
  6556. && host.channels[(std::size_t) hitChannel].name == "Hit";
  6557. }
  6558. }
  6559. // a crafted package whose project points at a file elsewhere on this computer: opening it must not
  6560. // reach that file, or merging would copy it into the project and the next package would send it on
  6561. if (mergeOk)
  6562. {
  6563. const auto secret = dir.getChildFile ("secret.wav");
  6564. wav.copyFileTo (secret);
  6565. auto evil = lynx::Song::makeDefault();
  6566. lynx::ChannelDef c;
  6567. c.instrument = lynx::InstrumentKind::sampler;
  6568. c.samplePath = secret.getFullPathName().toStdString();
  6569. evil.channels.push_back (c);
  6570. lynx::ChannelDef keys; // (FL Keys' zones are read by the engine but are not in the media list)
  6571. keys.instrument = lynx::InstrumentKind::flkeys;
  6572. keys.zones.push_back ({});
  6573. keys.zones.back().path = c.samplePath;
  6574. evil.channels.push_back (keys);
  6575. lynx::ChannelDef patch; // (a Patcher's nodes are not in the media list either)
  6576. patch.instrument = lynx::InstrumentKind::patcher;
  6577. patch.patcher.nodes.resize (2);
  6578. patch.patcher.nodes[0].generator = true;
  6579. patch.patcher.nodes[0].channel = c;
  6580. patch.patcher.nodes[1].effect.samplePath = c.samplePath;
  6581. evil.channels.push_back (patch);
  6582. evil.mixer[1].recordTo = dir.getChildFile ("overwritten.wav").getFullPathName().toStdString();
  6583. const auto evilProject = dir.getChildFile ("evil.lynx");
  6584. lynx::sessionpack::Manifest em;
  6585. em.part = true;
  6586. juce::ZipFile::Builder b;
  6587. const auto json = lynx::sessionpack::manifestToJson (em);
  6588. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  6589. const auto evilPack = dir.getChildFile (juce::String ("Evil") + lynx::sessionpack::extension);
  6590. bool zipped = false;
  6591. if (lynx::ProjectFile::save (evil, evilProject, e))
  6592. {
  6593. b.addFile (evilProject, 0, "project.lynx");
  6594. juce::FileOutputStream out (evilPack);
  6595. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  6596. }
  6597. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil"), e) : std::nullopt;
  6598. const auto media = dir.getChildFile ("Session media/Evil");
  6599. mergeOk = evilOpened && lynx::sessionpack::adoptMedia (evilOpened->song, media, e)
  6600. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  6601. return juce::File (juce::String::fromUTF8 (ch.samplePath.c_str())) == secret
  6602. || std::any_of (ch.zones.begin(), ch.zones.end(), [&] (const lynx::SampleZone& z) { return juce::File (juce::String::fromUTF8 (z.path.c_str())) == secret; });
  6603. })
  6604. && evilOpened->song.channels.back().patcher.nodes.size() == 2
  6605. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[0].channel.samplePath.c_str())) != secret
  6606. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[1].effect.samplePath.c_str())) != secret
  6607. && evilOpened->song.mixer[1].recordTo.empty()
  6608. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  6609. if (! mergeOk && e.isEmpty())
  6610. e = "a received package reached a file outside it";
  6611. }
  6612. // ... nor through its own folder: "..", Windows' dotted names (". ." climbs like ".." there), and a manifest
  6613. // media entry outside the package (it must not even be read: "/dev/zero" would never end)
  6614. if (mergeOk)
  6615. {
  6616. const auto secret = dir.getChildFile ("secret.wav");
  6617. const auto folder = dir.getChildFile ("evil2").getChildFile ("Evil2"); // (where open() will unpack it)
  6618. const auto climb = folder.getFullPathName() + "/media/../../../secret.wav";
  6619. const auto dotted = folder.getFullPathName() + "/. ./.. ./secret.wav";
  6620. auto evil = lynx::Song::makeDefault();
  6621. for (const auto& path : { climb, dotted })
  6622. {
  6623. lynx::ChannelDef c;
  6624. c.instrument = lynx::InstrumentKind::sampler;
  6625. c.samplePath = path.toStdString();
  6626. evil.channels.push_back (c);
  6627. }
  6628. juce::MemoryBlock secretBytes;
  6629. secret.loadFileAsData (secretBytes);
  6630. lynx::sessionpack::Manifest em;
  6631. em.part = true;
  6632. em.media.push_back ({ "sha256-" + juce::String (lynx::sha256Hex ((const std::uint8_t*) secretBytes.getData(), secretBytes.getSize())),
  6633. "secret.wav", (juce::int64) secretBytes.getSize(), "../../secret.wav" });
  6634. const auto evilProject = dir.getChildFile ("evil2.lynx");
  6635. juce::ZipFile::Builder b;
  6636. const auto json = lynx::sessionpack::manifestToJson (em);
  6637. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  6638. const auto evilPack = dir.getChildFile (juce::String ("Evil2") + lynx::sessionpack::extension);
  6639. bool zipped = false;
  6640. if (lynx::ProjectFile::save (evil, evilProject, e))
  6641. {
  6642. b.addFile (evilProject, 0, "project.lynx");
  6643. juce::FileOutputStream out (evilPack);
  6644. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  6645. }
  6646. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil2"), e) : std::nullopt;
  6647. const auto media = dir.getChildFile ("Session media/Evil2");
  6648. mergeOk = evilOpened && evilOpened->folder == folder && evilOpened->corrupt.contains ("secret.wav")
  6649. && lynx::sessionpack::adoptMedia (evilOpened->song, media, e) && evilOpened->song.channels.size() >= 2
  6650. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  6651. const auto p = juce::String::fromUTF8 (ch.samplePath.c_str());
  6652. return p == climb || p == dotted || (juce::File::isAbsolutePath (p) && juce::File (p) == secret);
  6653. })
  6654. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  6655. if (! mergeOk && e.isEmpty())
  6656. e = "a received package climbed out of its folder";
  6657. }
  6658. if (! packOk && e.isEmpty())
  6659. e = "media " + juce::String (written.media) + ", duplicates " + juce::String (written.duplicates) + ", missing "
  6660. + written.missing.joinIntoString (";");
  6661. sessionResult = mergeOk ? juce::String ("OK")
  6662. : "ERROR (" + juce::String (renderedOk ? packOk ? openOk ? "merge" : "open" : "pack" : "render") + (e.isEmpty() ? "" : ": " + e) + ")";
  6663. dir.deleteRecursively();
  6664. }
  6665. // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
  6666. juce::String wavpack = "NO_FL";
  6667. {
  6668. const auto roots = lynx::findFlStudioRoots();
  6669. const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
  6670. const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
  6671. if (! found.isEmpty())
  6672. {
  6673. lynx::SampleLibrary library;
  6674. const auto sample = library.load (found.getFirst().getFullPathName());
  6675. float peakWv = 0.0f;
  6676. if (sample != nullptr)
  6677. for (std::size_t i = 0; i < sample->frames(); ++i)
  6678. peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
  6679. wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
  6680. }
  6681. }
  6682. // every built-in effect's editor and engine with extreme settings (round 111): a crash or NaN output fails here
  6683. const auto effectsOk = runEffectFuzz (4, {}); // (no mouse drags: nothing may open on screen)
  6684. // FL's Patcher (round 141): a mixer slot and a generator channel with their graphs survive save / load, and the
  6685. // generator one plays through the rack
  6686. bool patcherOk = false;
  6687. {
  6688. auto song = lynx::Song::makeDefault();
  6689. song.mixer.resize (4);
  6690. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  6691. lynx::PatchNode reverb, gain;
  6692. reverb.effect = lynx::makeEffectSlot (lynx::EffectKind::utility); // (exact defaults: params are saved to 4 decimals)
  6693. reverb.label = "Room";
  6694. reverb.x = 120.5f;
  6695. reverb.y = 40.0f;
  6696. gain.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  6697. gain.effect.enabled = false;
  6698. slot.patcher.nodes = { reverb, gain };
  6699. lynx::PatchWire a, b, c, control;
  6700. a.to = 0;
  6701. b.from = 0, b.to = 1, b.gain = 0.5f;
  6702. c.from = 1;
  6703. control.kind = lynx::PatchWire::Kind::control, control.from = 0, control.to = 1, control.toPort = 0, control.curve = { 0.0f, 0.25f, 1.0f };
  6704. slot.patcher.wires = { a, b, c, control };
  6705. slot.patcher.outputTracks = { 3 };
  6706. song.mixer[1].effects = { slot };
  6707. lynx::ChannelDef ch;
  6708. ch.name = "Patched";
  6709. ch.instrument = lynx::InstrumentKind::patcher;
  6710. lynx::PatchNode synth;
  6711. synth.generator = true;
  6712. synth.channel.instrument = lynx::InstrumentKind::synth;
  6713. synth.channel.name = "Synth";
  6714. ch.patcher.nodes = { synth };
  6715. lynx::PatchWire notes, out;
  6716. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  6717. out.from = 0;
  6718. ch.patcher.wires = { notes, out };
  6719. // round 162: the I/O nodes' MIDI pins and a MIDI Out node between them
  6720. lynx::PatchNode midiOutNode;
  6721. midiOutNode.generator = true;
  6722. midiOutNode.channel.instrument = lynx::InstrumentKind::midiOut;
  6723. lynx::midictl::writeMidiOut (midiOutNode.channel.pluginState, { 4, 0, 0, -1, -1 });
  6724. ch.patcher.nodes.push_back (midiOutNode);
  6725. lynx::PatchWire portIn, portOut;
  6726. portIn.kind = portOut.kind = lynx::PatchWire::Kind::midi;
  6727. portIn.fromPort = lynx::patchMidiPortPin (7), portIn.to = 1;
  6728. portOut.from = 1, portOut.to = lynx::patchToHost, portOut.toPort = 9;
  6729. ch.patcher.wires.push_back (portIn);
  6730. ch.patcher.wires.push_back (portOut);
  6731. ch.patcher.fromMidiPorts = { 2, 7 };
  6732. ch.patcher.toMidiPorts = { 9, 11 };
  6733. ch.patcher.fromNotesHidden = true;
  6734. song.channels.push_back (ch);
  6735. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  6736. patcherOk = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1
  6737. && back->mixer[1].effects[0].kind == lynx::EffectKind::patcher && back->mixer[1].effects[0].patcher == slot.patcher
  6738. && back->channels.back().instrument == lynx::InstrumentKind::patcher && back->channels.back().patcher.nodes.size() == 2
  6739. && back->channels.back().patcher.fromMidiPorts == ch.patcher.fromMidiPorts
  6740. && back->channels.back().patcher.toMidiPorts == ch.patcher.toMidiPorts && back->channels.back().patcher.fromNotesHidden
  6741. && back->channels.back().patcher.nodes[1].channel.pluginState == midiOutNode.channel.pluginState
  6742. && back->channels.back().patcher.nodes[0].generator
  6743. && back->channels.back().patcher.nodes[0].channel.instrument == lynx::InstrumentKind::synth
  6744. && back->channels.back().patcher.wires == ch.patcher.wires;
  6745. }
  6746. // Round 183c, Racks: (1) a plain Patcher's stored JSON loads and saves back byte for byte and never holds a
  6747. // "rack" key (FL's Patcher is untouched); (2) an Audio Effect Rack slot and an Instrument Rack channel survive save /
  6748. // load with their chains, zones, macros, mappings, variations and compiled cables
  6749. juce::String rackResult = "OK";
  6750. {
  6751. lynx::MixerTrack plain;
  6752. plain.name = "Plain Patcher";
  6753. auto fx = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  6754. lynx::PatchNode a, b;
  6755. a.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  6756. a.label = "A";
  6757. a.x = 120.5f;
  6758. b.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  6759. b.effect.enabled = false;
  6760. fx.patcher.nodes = { a, b };
  6761. lynx::PatchWire w1, w2, w3, wc;
  6762. w1.to = 0;
  6763. w2.from = 0, w2.to = 1, w2.gain = 0.5f;
  6764. w3.from = 1;
  6765. wc.kind = lynx::PatchWire::Kind::control, wc.from = 0, wc.to = 1, wc.toPort = 0, wc.curve = { 0.0f, 0.25f, 1.0f };
  6766. fx.patcher.wires = { w1, w2, w3, wc };
  6767. lynx::SurfaceControl knob;
  6768. knob.name = "Drive";
  6769. knob.value = 0.25f;
  6770. fx.patcher.surface = { knob };
  6771. lynx::PatchParam pp;
  6772. pp.node = 0, pp.param = 1, pp.name = "Balance";
  6773. fx.patcher.published = { pp };
  6774. plain.effects = { fx };
  6775. const auto first = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (plain), true);
  6776. const auto again = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (first))), true);
  6777. if (first != again || first.contains ("\"rack\"") || first.contains ("rackMixer"))
  6778. rackResult = "ERROR plain Patcher changed";
  6779. auto song = lynx::Song::makeDefault();
  6780. song.mixer.resize (3);
  6781. auto rackSlot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  6782. auto& doc = rackSlot.patcher;
  6783. lynx::PatchNode u;
  6784. u.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  6785. const auto n0 = lynx::rack::addDevice (doc, 0, u);
  6786. lynx::rack::addChain (doc, "Wet");
  6787. lynx::rack::addDevice (doc, 1, u);
  6788. doc.rack[0].chains[1].select = { 10, 90, 30, 70 };
  6789. lynx::rack::setChainPan (doc, 1, -0.5f);
  6790. lynx::RackMapping m;
  6791. m.node = n0, m.param = 0, m.min = 0.2f, m.max = 0.9f;
  6792. lynx::rack::map (doc, 0, m);
  6793. lynx::RackMapping v;
  6794. v.target = lynx::RackMapping::Target::chainVolume, v.chain = 1, v.min = 0.0f, v.max = lynx::rack::unityVolume;
  6795. lynx::rack::map (doc, 1, v);
  6796. lynx::rack::setMacro (doc, 0, 64.0f);
  6797. lynx::rack::storeVariation (doc);
  6798. lynx::rack::setMacro (doc, 0, 100.0f);
  6799. lynx::rack::storeVariation (doc);
  6800. doc.rack[0].morphOn = true, doc.rack[0].morphA = 0, doc.rack[0].morphB = 1;
  6801. lynx::rack::setMorph (doc, 0.5f);
  6802. lynx::rack::compile (doc);
  6803. song.mixer[1].effects = { rackSlot };
  6804. lynx::ChannelDef inst;
  6805. inst.name = "Instrument Rack";
  6806. inst.instrument = lynx::InstrumentKind::patcher;
  6807. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  6808. lynx::PatchNode synth;
  6809. synth.generator = true;
  6810. synth.channel.instrument = lynx::InstrumentKind::synth;
  6811. synth.channel.name = "Synth";
  6812. lynx::rack::addDevice (inst.patcher, 0, synth);
  6813. inst.patcher.rack[0].chains[0].velocity = { 1, 127, 64, 127 };
  6814. lynx::rack::compile (inst.patcher);
  6815. song.channels.push_back (inst);
  6816. const auto json = lynx::ProjectFile::toJson (song);
  6817. const auto back = lynx::ProjectFile::fromJson (json, error);
  6818. // (the devices' parameters are stored to 4 decimals: the documents are compared as stored, the rack exactly)
  6819. const auto loaded = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1;
  6820. const auto& got = loaded ? back->mixer[1].effects[0].patcher : doc;
  6821. if (! loaded)
  6822. rackResult = "ERROR rack slot not loaded";
  6823. else if (got.rack != doc.rack)
  6824. rackResult = "ERROR rack model";
  6825. else if (got.wires != doc.wires)
  6826. rackResult = "ERROR rack cables";
  6827. else if (got.nodes.size() != doc.nodes.size())
  6828. rackResult = "ERROR rack devices";
  6829. else if (back->channels.back().patcher.rack != inst.patcher.rack || back->channels.back().patcher.wires != inst.patcher.wires
  6830. || back->channels.back().patcher.zones != inst.patcher.zones || back->channels.back().patcher.nodes.size() != inst.patcher.nodes.size())
  6831. rackResult = "ERROR instrument rack";
  6832. // the slot's insert as stored, once more: the same text (the stored form is stable)
  6833. else if (const auto once = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (back->mixer[1]), true);
  6834. once != juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (once))), true))
  6835. rackResult = "ERROR rack stored form not stable";
  6836. }
  6837. // Round 190ec, Drum Rack: pads (Receive / Play / Choke / Audio To / sends), return chains and the views survive save /
  6838. // load with their compiled zones and cables
  6839. if (rackResult == "OK")
  6840. {
  6841. lynx::Song song;
  6842. song.mixer.resize (2);
  6843. lynx::ChannelDef ch;
  6844. ch.name = "Drums";
  6845. ch.instrument = lynx::InstrumentKind::patcher;
  6846. ch.patcher = lynx::rack::makeDrumRack();
  6847. lynx::PatchNode synth;
  6848. synth.generator = true;
  6849. synth.channel.instrument = lynx::InstrumentKind::synth;
  6850. const auto kick = lynx::rack::addPad (ch.patcher, 36, "Kick", synth);
  6851. const auto hat = lynx::rack::addPad (ch.patcher, 42, "Hat", synth);
  6852. lynx::rack::addPad (ch.patcher, -1, "Every note");
  6853. lynx::rack::addReturn (ch.patcher, "A Verb");
  6854. lynx::rack::setPlay (ch.patcher, kick, 64);
  6855. lynx::rack::setChoke (ch.patcher, hat, 2);
  6856. lynx::rack::setSend (ch.patcher, hat, 0, 0.25f, false);
  6857. lynx::rack::setAudioTo (ch.patcher, kick, 0);
  6858. lynx::rack::rackOf (ch.patcher)->showIO = true;
  6859. lynx::rack::rackOf (ch.patcher)->padScroll = 17;
  6860. song.channels.push_back (ch);
  6861. juce::String error;
  6862. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  6863. const auto& got = back && ! back->channels.empty() ? back->channels.back().patcher : lynx::PatcherDoc {};
  6864. if (! back || ! lynx::rack::isDrumRack (got))
  6865. rackResult = "ERROR drum rack not loaded";
  6866. else if (got.rack != ch.patcher.rack)
  6867. rackResult = "ERROR drum rack model";
  6868. else if (got.zones != ch.patcher.zones || got.wires != ch.patcher.wires)
  6869. rackResult = "ERROR drum rack cables";
  6870. }
  6871. // FL engines in a native project (round 142, issue #5): every engine this PC can make survives save / load and
  6872. // the instruments play through the rack
  6873. juce::String nativesResult = "OK";
  6874. int nativesMade = 0, nativesSilent = 0;
  6875. {
  6876. auto song = lynx::Song::makeDefault();
  6877. song.channels.clear();
  6878. song.patterns[0].notes.clear();
  6879. song.mixer.resize (3);
  6880. const auto& fl = lynx::flStudioAccess();
  6881. for (const auto& e : lynx::natives::instrumentEngines())
  6882. if (lynx::natives::available (e, fl))
  6883. if (auto c = lynx::natives::makeChannel (e.kind, fl))
  6884. {
  6885. c->mixerTrack = 1;
  6886. song.channels.push_back (*c);
  6887. }
  6888. for (const auto& e : lynx::natives::effectEngines())
  6889. if (auto fx = lynx::natives::makeSlot (e.kind, fl))
  6890. song.mixer[2].effects.push_back (*fx);
  6891. nativesMade = (int) (song.channels.size() + song.mixer[2].effects.size());
  6892. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  6893. auto same = back && back->channels.size() == song.channels.size() && back->mixer.size() >= 3
  6894. && back->mixer[2].effects.size() == song.mixer[2].effects.size();
  6895. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  6896. {
  6897. const auto& a = song.channels[i];
  6898. const auto& b = back->channels[i];
  6899. same = a.instrument == b.instrument && a.pluginState == b.pluginState && a.samplePath == b.samplePath && a.zones.size() == b.zones.size()
  6900. && a.modelParams.size() == b.modelParams.size();
  6901. if (! same)
  6902. nativesResult = "ERROR channel " + juce::String::fromUTF8 (a.name.c_str());
  6903. }
  6904. for (std::size_t i = 0; same && i < song.mixer[2].effects.size(); ++i)
  6905. {
  6906. const auto& a = song.mixer[2].effects[i];
  6907. const auto& b = back->mixer[2].effects[i];
  6908. same = a.kind == b.kind && a.state == b.state;
  6909. for (std::size_t p = 0; same && p < a.params.size(); ++p)
  6910. same = std::abs (a.params[p] - b.params[p]) < 1.0e-3f;
  6911. if (! same)
  6912. nativesResult = juce::String ("ERROR effect ") + lynx::effectInfo (a.kind).name;
  6913. }
  6914. if (! back)
  6915. nativesResult = "ERROR " + error;
  6916. // each instrument plays a note alone. The Granulizer and Wave Traveller play the channel's sample, and a new
  6917. // one has none (a PC without FL Studio, macOS / Linux: FL's presets are not there either), so they get a
  6918. // generated one: a second of a 220 Hz tone (round 167m, PR #19: Wave Traveller was "SILENT 1" on macOS)
  6919. const auto toneWav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-natives.wav");
  6920. {
  6921. juce::WavAudioFormat format;
  6922. juce::AudioBuffer<float> tone (1, 48000);
  6923. for (int i = 0; i < 48000; ++i)
  6924. tone.setSample (0, i, 0.5f * std::sin (juce::MathConstants<float>::twoPi * 220.0f * (float) i / 48000.0f));
  6925. toneWav.deleteFile();
  6926. std::unique_ptr<juce::OutputStream> out (toneWav.createOutputStream().release());
  6927. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  6928. {
  6929. out.release();
  6930. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  6931. writer->writeFromAudioSampleBuffer (tone, 0, 48000);
  6932. }
  6933. }
  6934. juce::StringArray silentNames;
  6935. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  6936. {
  6937. auto one = song;
  6938. one.channels = { song.channels[i] };
  6939. one.channels[0].mixerTrack = 1;
  6940. const auto kind = song.channels[i].instrument;
  6941. // A new Fruity Slicer has no sample and no slices, and FL's is silent then too (round 180c), so it is
  6942. // not one of the engines that must sound here (Linux / macOS CI: "SILENT 1 [Fruity Slicer]", 0.1.25)
  6943. if (kind == lynx::InstrumentKind::fruityslicer && one.channels[0].samplePath.empty())
  6944. continue;
  6945. if (kind == lynx::InstrumentKind::slicex && one.channels[0].samplePath.empty()) // (the same: no sample on its decks yet)
  6946. continue;
  6947. if (kind == lynx::InstrumentKind::directwave && one.channels[0].zones.empty()) // (FL's new DirectWave: no zones yet, round 190hz)
  6948. continue;
  6949. if ((kind == lynx::InstrumentKind::granulizer || kind == lynx::InstrumentKind::wavetraveller) && one.channels[0].samplePath.empty())
  6950. one.channels[0].samplePath = toneWav.getFullPathName().toStdString();
  6951. one.mixer[2].effects.clear();
  6952. // Drumaxx plays pad 1's key: FL's default kit has a pad at 48, LYNX's own bank kits (a PC without FL,
  6953. // macOS / Linux; round 168p) start at 36 (round 169d: "SILENT 1 [Drumaxx]" on the Linux / macOS CI)
  6954. auto key = 60;
  6955. if (kind == lynx::InstrumentKind::drumaxx)
  6956. {
  6957. const auto padKey = lynx::drumaxxParam (one.channels[0].pluginState, 4);
  6958. key = std::isfinite (padKey) && padKey >= 0.0f && padKey <= 127.0f ? (int) padKey : 48;
  6959. }
  6960. // FPC plays its pads' keys; a kit without a sample (FL's "Empty" kit: no FL Studio on this PC) is silent
  6961. // in FL too (round 190q)
  6962. if (kind == lynx::InstrumentKind::fpc)
  6963. {
  6964. const auto pads = lynx::fpcChannelPads (one.channels[0]);
  6965. if (pads.empty())
  6966. continue;
  6967. key = pads.front().key;
  6968. }
  6969. one.patterns[0].notes = { { 0, 1920, 0, key, 0.8f } };
  6970. lynx::AudioEngine player (false);
  6971. player.setSong (std::move (one));
  6972. player.dispatchPendingMessages();
  6973. if (! (player.renderOffline (1.0, 48000.0) > 1.0e-4f))
  6974. {
  6975. ++nativesSilent;
  6976. silentNames.add (juce::String::fromUTF8 (song.channels[i].name.c_str()));
  6977. }
  6978. }
  6979. toneWav.deleteFile();
  6980. if (nativesSilent > 0 && nativesResult == "OK")
  6981. nativesResult = "SILENT " + juce::String (nativesSilent) + " [" + silentNames.joinIntoString (", ") + "]";
  6982. }
  6983. const auto nativesOk = nativesResult == "OK";
  6984. // The metronome as FL 2026 plays it (round 165z-a2): FL's five sounds from its install, the downbeat at
  6985. // 0.9404 × the Tick two semitones up, into the Master ("---") by default; insert 2 as its track plays it through
  6986. // insert 2 (muted: silent); never in an export
  6987. juce::String metronomeResult = "OK";
  6988. int metronomeFlSounds = 0;
  6989. float metronomeMaster = 0.0f;
  6990. {
  6991. const auto& flData = lynx::flStudioAccess().roots.data;
  6992. const auto sounds = lynx::Metronome::loadSounds (flData.empty() ? juce::File() : lynx::platform::localFile (flData));
  6993. for (const auto& s : sounds)
  6994. metronomeFlSounds += s.fromFl ? 1 : 0;
  6995. auto renderClick = [] (int track, bool muteInsert, bool include) {
  6996. auto song = lynx::Song::makeDefault();
  6997. song.channels.clear();
  6998. song.playlist.clear();
  6999. for (auto& p : song.patterns)
  7000. p.notes.clear();
  7001. song.mixer[0].effects.clear(); // (the default Master limiter)
  7002. song.mixer[2].muted = muteInsert;
  7003. lynx::AudioEngine player (false);
  7004. player.setSong (std::move (song));
  7005. player.dispatchPendingMessages();
  7006. auto& t = player.getTransport();
  7007. t.metronome = true;
  7008. t.metronomeSound = 1; // Tick
  7009. t.metronomeTrack = track;
  7010. lynx::AudioEngine::RenderOptions o;
  7011. o.seconds = 0.25;
  7012. o.sampleRate = 44100.0;
  7013. o.pluginWarmUp = false;
  7014. o.includeMetronome = include;
  7015. return player.renderOffline (o);
  7016. };
  7017. metronomeMaster = renderClick (0, false, true);
  7018. const auto insert = renderClick (2, false, true);
  7019. const auto muted = renderClick (2, true, true);
  7020. const auto exported = renderClick (0, false, false);
  7021. // FL's Tick peaks at 1.0: its downbeat at most 0.9404 (the interpolation may land between peaks)
  7022. const auto expectHigh = metronomeFlSounds == lynx::metronome::soundCount ? lynx::metronome::downbeatGain + 1.0e-3f : 1.0f;
  7023. if (! (metronomeMaster > 0.5f && metronomeMaster < expectHigh))
  7024. metronomeResult = "ERROR master " + juce::String (metronomeMaster, 4);
  7025. else if (std::abs (insert - metronomeMaster) > 2.0e-3f)
  7026. metronomeResult = "ERROR insert " + juce::String (insert, 4);
  7027. else if (muted > 1.0e-4f)
  7028. metronomeResult = "ERROR muted insert " + juce::String (muted, 4);
  7029. else if (exported > 1.0e-4f)
  7030. metronomeResult = "ERROR in export " + juce::String (exported, 4);
  7031. }
  7032. const auto metronomeOk = metronomeResult == "OK";
  7033. // Settings › Audio "Driver settings…" with a fake driver panel (issue #13's crash, the panel's buffer kept)
  7034. const auto driverPanel = lynx::AudioEngine::driverPanelSelfTest();
  7035. // issue #134 (round 190c): the output device, its rate and its buffer changed under a playing project, on
  7036. // stand-in devices (a short run; --devicechangetest plays every instrument and effect)
  7037. const auto deviceChange = lynx::AudioEngine::deviceChangeSelfTest (10, false);
  7038. // round 190gh: export parity (B7) and MIDI device hot-plug (B8)
  7039. const auto exportParity = lynx::AudioEngine::exportParitySelfTest();
  7040. // round 190jb: exports with the live plugin instances (Surge XT when it is installed here; otherwise only noted)
  7041. juce::StringArray livePlugins;
  7042. #if JUCE_WINDOWS
  7043. livePlugins.add ("C:\\Program Files\\Common Files\\VST3\\Surge Synth Team\\Surge XT.vst3");
  7044. #elif JUCE_MAC
  7045. livePlugins.add ("/Library/Audio/Plug-Ins/VST3/Surge XT.vst3");
  7046. #else
  7047. livePlugins.add (juce::File::getSpecialLocation (juce::File::userHomeDirectory).getChildFile (".vst3/Surge XT.vst3").getFullPathName());
  7048. #endif
  7049. const auto exportLive = lynx::AudioEngine::exportLiveSelfTest ({}, livePlugins);
  7050. const auto midiHotplug = lynx::AudioEngine::midiHotplugSelfTest();
  7051. const auto midiOutPorts = lynx::AudioEngine::midiOutPortSelfTest(); // round 190jl
  7052. // Online Sessions P2 (round 169b): live sessions without a network (the JSON round trip of every entity, replicas
  7053. // through it, the invite code's keys)
  7054. const auto liveResult = lynx::livetest::selfTest (&rich);
  7055. // issue #67: every built-in effect's parameters, named and hidden (the Parametric EQ's FL law, processing, band
  7056. // mask...), at odd values, through a project save and reload: the same floats back
  7057. juce::String effectParamsResult = "OK";
  7058. {
  7059. auto song = lynx::Song::makeDefault();
  7060. song.mixer.resize (1);
  7061. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  7062. {
  7063. const auto kind = (lynx::EffectKind) k;
  7064. if (kind == lynx::EffectKind::plugin || kind == lynx::EffectKind::parallel)
  7065. continue;
  7066. auto fx = lynx::makeEffectSlot (kind);
  7067. for (std::size_t i = 0; i < fx.params.size(); ++i)
  7068. {
  7069. auto v = (float) ((double) ((i * 7919 + (std::size_t) k * 104729) % 65521) / 65521.0);
  7070. fx.params[i] = v == fx.params[i] ? 1.0f - v : v;
  7071. }
  7072. if (kind == lynx::EffectKind::fruitySend) // ("Send to" is written over the insert span)
  7073. fx.params[3] = 0.0f;
  7074. song.mixer.emplace_back();
  7075. song.mixer.back().name = "Insert " + std::to_string (song.mixer.size() - 1);
  7076. song.mixer.back().effects.push_back (fx);
  7077. }
  7078. // round 171b's Patcher round trip (coordinator): the Frequency Splitter, Fruity Delay 3 and Peak Controller
  7079. // nodes came back different (their FL defaults, e.g. the LFO speed 32750 / 65336, lost to 4 decimals)
  7080. {
  7081. auto patch = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  7082. for (const auto kind : { lynx::EffectKind::frequencySplitter, lynx::EffectKind::fruityDelay3, lynx::EffectKind::peakController,
  7083. lynx::EffectKind::reverb, lynx::EffectKind::hardwareInsert })
  7084. {
  7085. lynx::PatchNode node;
  7086. node.effect = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  7087. if (kind == lynx::EffectKind::peakController)
  7088. node.effect.params[7] = 32750.0f / 65336.0f;
  7089. node.x = 200.0f, node.y = 60.0f * (float) patch.patcher.nodes.size();
  7090. patch.patcher.nodes.push_back (node);
  7091. }
  7092. song.mixer.emplace_back();
  7093. song.mixer.back().name = "Patcher";
  7094. song.mixer.back().effects.push_back (patch);
  7095. }
  7096. juce::String why;
  7097. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  7098. if (back && back->mixer.size() == song.mixer.size())
  7099. {
  7100. const auto& a = song.mixer.back().effects[0].patcher.nodes;
  7101. const auto& b = back->mixer.back().effects[0].patcher.nodes;
  7102. for (std::size_t n = 0; n < a.size(); ++n)
  7103. if (n >= b.size() || ! (a[n].effect == b[n].effect))
  7104. effectParamsResult = juce::String ("ERROR Patcher node ") + lynx::effectInfo (a[n].effect.kind).name;
  7105. }
  7106. if (! back || back->mixer.size() != song.mixer.size())
  7107. effectParamsResult = "ERROR load " + why;
  7108. else
  7109. for (std::size_t t = 1; t + 1 < song.mixer.size() && effectParamsResult == "OK"; ++t)
  7110. if (back->mixer[t].effects.size() != 1 || back->mixer[t].effects[0].params != song.mixer[t].effects[0].params)
  7111. {
  7112. effectParamsResult = juce::String ("ERROR ") + lynx::effectInfo (song.mixer[t].effects[0].kind).name;
  7113. break;
  7114. }
  7115. }
  7116. // round 170j: the Themed plugin style (its resolution with and without art; every art draws)
  7117. const auto artResult = lynx::skin::artSelfTest();
  7118. // round 177b: a plugin's sidechain bus gets the slot's sidechain (one-click sidechain)
  7119. const auto sidechainResult = lynx::pluginSidechainSelfTest();
  7120. // round 190pj (issue #241): JSFX scripts in slots, their state, PDC, MIDI, file policy, the copy for older releases
  7121. // (rollup 0.1.31 step 7: the message thread's floating-point environment before and after it, reported and put back:
  7122. // the Linux arm64 self-test's float round trips, renders and paint tiles after this item differed from x86's: EEL2's
  7123. // code left FPCR at round-toward-minus-infinity; ysfx_lynx_fp_guard in third_party/ysfx/sources/ysfx.cpp now puts the
  7124. // caller's environment back, and this check counts in result=)
  7125. std::fenv_t fpBeforeJsfx {};
  7126. std::fegetenv (&fpBeforeJsfx);
  7127. const auto fpModeNow = [] {
  7128. #if defined (__aarch64__) && ! defined (_MSC_VER)
  7129. juce::uint64 fpcr = 0; // (an instruction, not GCC's __builtin_aarch64_get_fpcr: Apple clang has no such builtin)
  7130. asm volatile ("mrs %0, fpcr" : "=r" (fpcr));
  7131. return fpcr;
  7132. #else
  7133. return (juce::uint64) std::fegetround();
  7134. #endif
  7135. };
  7136. const auto fpModeBeforeJsfx = fpModeNow();
  7137. const auto jsfxResult = lynx::jsfx::selfTest ({});
  7138. const auto fpModeAfterJsfx = fpModeNow();
  7139. std::fesetenv (&fpBeforeJsfx);
  7140. const auto jsfxFpResult = fpModeAfterJsfx == fpModeBeforeJsfx ? juce::String ("OK")
  7141. : "CHANGED 0x" + juce::String::toHexString ((juce::int64) fpModeBeforeJsfx) + " -> 0x"
  7142. + juce::String::toHexString ((juce::int64) fpModeAfterJsfx) + " (put back)";
  7143. // round 190qi: the slot menu's Recent section, a plugin hidden from the lists, one row per plugin's formats, a MIDI
  7144. // file's preview schedule (src/Picker190qiShot.inc)
  7145. const auto picker190qiResult = picker190qiSelfTest (juce::File::getSpecialLocation (juce::File::tempDirectory));
  7146. // round 190ap: the Versions panel's list of files, and its labels on disk beside them
  7147. const auto versionsResult = lynx::versionsSelfTest();
  7148. // round 190ap: a project opened with its plugins off creates none of them and saves their settings unchanged
  7149. const auto pluginsOffResult = lynx::pluginsOffSelfTest();
  7150. const auto missingFilesResult = lynx::missingFilesSelfTest(); // issue #165
  7151. // round 190cj: a dancer's own native window stays where the stage put it (it drifted off the screen: JUCE
  7152. // moved a transparent child window by the main window's client offset on every repaint)
  7153. juce::String danceWindowDetail;
  7154. const auto danceWindowResult = lynx::danceWindowSelfTest (&danceWindowDetail);
  7155. // issue #161: a click in a panel (a native child window that takes no focus on a click) of an inactive main
  7156. // window activates it (back from another app, Space played nothing until the Browser was clicked)
  7157. const auto clickActivationResult = lynx::nativechild::clickActivationSelfTest();
  7158. // round 190jy (queue item 44): the holes the native panels get under a docked editor drawn by the main window
  7159. const auto editorHolesResult = lynx::nativechild::editorHolesSelfTest();
  7160. // round 177b: automation lanes come back from a project (track, automation, height, folded)
  7161. juce::String lanesResult = "OK";
  7162. {
  7163. auto song = lynx::Song::makeDefault();
  7164. const auto lane = lynx::autolanes::addLane (song, 3, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Vol", 0.4f);
  7165. song.playlistTracks[3].lanes[0].height = 72;
  7166. song.playlistTracks[3].lanesFolded = true;
  7167. // (the same round's clip LFO and modulators ride along)
  7168. auto& lfo = song.automations[(std::size_t) lane].lfo;
  7169. lfo.on = true;
  7170. lfo.level = -40;
  7171. lfo.speed = 30000;
  7172. lfo.flags = 1 | 4;
  7173. lfo.phase = 123456789u;
  7174. lfo.amp = { { 0, 0.5f, 0.0f }, { 960, 1.0f, 0.0f } };
  7175. lynx::Modulator mod;
  7176. mod.name = "LFO 1";
  7177. mod.shape = lynx::ModShape::square;
  7178. mod.sync = false;
  7179. mod.hz = 2.5;
  7180. mod.routes = { { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  7181. song.modulators.push_back (mod);
  7182. juce::String why;
  7183. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  7184. if (! back || back->playlistTracks.size() < 4 || ! (back->playlistTracks[3].lanes == song.playlistTracks[3].lanes)
  7185. || ! back->playlistTracks[3].lanesFolded || back->automations.size() != song.automations.size()
  7186. || ! (back->automations[(std::size_t) lane].points == song.automations[(std::size_t) lane].points)
  7187. || ! (back->automations[(std::size_t) lane].lfo == lfo) || ! (back->modulators == song.modulators))
  7188. lanesResult = "ERROR " + why;
  7189. }
  7190. // round 190cg: the loop switch, folded tracks and the tempo lane's range come back from a project; a project
  7191. // without them loads as before (loop on, nothing folded, the whole range)
  7192. juce::String arrange190cgResult = "OK";
  7193. {
  7194. auto song = lynx::Song::makeDefault();
  7195. juce::String why;
  7196. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  7197. song.loopStart = 960;
  7198. song.loopEnd = 4800;
  7199. song.loopOff = true;
  7200. song.tempoViewLow = 80.0;
  7201. song.tempoViewHigh = 160.0;
  7202. song.playlistTracks.resize (std::max<std::size_t> (song.playlistTracks.size(), 6));
  7203. song.playlistTracks[2].folded = song.playlistTracks[5].folded = true;
  7204. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  7205. if (! plain || plain->loopOff || plain->tempoViewLow != 0.0 || plain->tempoViewHigh != 0.0
  7206. || std::any_of (plain->playlistTracks.begin(), plain->playlistTracks.end(), [] (const lynx::PlaylistTrack& t) { return t.folded; }))
  7207. arrange190cgResult = "ERROR defaults " + why;
  7208. else if (! back || ! back->loopOff || back->loopStart != 960 || back->loopEnd != 4800 || back->loopPlays() || back->tempoViewLow != 80.0
  7209. || back->tempoViewHigh != 160.0 || back->playlistTracks.size() < 6 || ! back->playlistTracks[2].folded
  7210. || ! back->playlistTracks[5].folded || back->playlistTracks[3].folded)
  7211. arrange190cgResult = "ERROR round trip " + why;
  7212. }
  7213. // round 190gz (issue #170): "Link Playlist tracks to mixer tracks" comes back from a project with its links; a
  7214. // project without it loads with it off (FL's tracks)
  7215. juce::String trackauto190gzResult = "OK";
  7216. {
  7217. auto song = lynx::Song::makeDefault();
  7218. juce::String why;
  7219. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  7220. lynx::Clip clip;
  7221. clip.kind = lynx::ClipKind::pattern;
  7222. clip.pattern = 0; // (the default pattern: Kick, Clap and Hat; a second one plays Kick alone)
  7223. song.playlist.push_back (clip);
  7224. auto& kick = song.patterns.emplace_back();
  7225. kick.name = "Kick";
  7226. kick.toggleStep (0, 0);
  7227. clip.pattern = (int) song.patterns.size() - 1;
  7228. clip.track = 1;
  7229. song.playlist.push_back (clip);
  7230. lynx::autolink::setOn (song, true);
  7231. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  7232. if (! plain || plain->linkTracksToMixer)
  7233. trackauto190gzResult = "ERROR defaults " + why;
  7234. // (round 190ib: Track 1 holds Kick, Clap and Hat, so they all go through insert 1 and Track 1 is its audio
  7235. // track; Track 2 only repeats Kick and stays unassigned)
  7236. // (a .lynx keeps the tracks up to the last one that differs from a plain track: Track 2 may not be written)
  7237. else if (! back || ! back->linkTracksToMixer || back->playlistTracks.empty() || back->playlistTracks[0].mode != lynx::PlaylistTrackMode::audio
  7238. || back->playlistTracks[0].mixerTrack != 1
  7239. || (back->playlistTracks.size() > 1 && back->playlistTracks[1].mode != lynx::PlaylistTrackMode::unassigned)
  7240. || back->channels[1].mixerTrack != 1 || back->channels[2].mixerTrack != 1)
  7241. {
  7242. trackauto190gzResult = "ERROR round trip " + why;
  7243. if (back && ! back->playlistTracks.empty() && back->channels.size() >= 3)
  7244. trackauto190gzResult << " tracks " << (int) back->playlistTracks.size() << " mode " << (int) back->playlistTracks[0].mode << " insert "
  7245. << back->playlistTracks[0].mixerTrack << " routes " << back->channels[0].mixerTrack << " "
  7246. << back->channels[1].mixerTrack << " " << back->channels[2].mixerTrack;
  7247. }
  7248. }
  7249. // round 190fm: the MIDI Tools generators' settings come back from a project; a project without them loads with
  7250. // Live's defaults (and saves none)
  7251. juce::String midigen190fmResult = "OK";
  7252. {
  7253. auto song = lynx::Song::makeDefault();
  7254. juce::String why;
  7255. const auto plainJson = lynx::ProjectFile::toJson (song);
  7256. const auto plain = lynx::ProjectFile::fromJson (plainJson, why);
  7257. song.midiGenerate.tool = lynx::midigen::Settings::stacks;
  7258. song.midiGenerate.rhythmOptions.pattern = 3;
  7259. song.midiGenerate.seedOptions.voices = 2;
  7260. song.midiGenerate.shapeOptions.levels[4] = 0.25f;
  7261. song.midiGenerate.shapeOptions.preset = lynx::midigen::ShapeOptions::custom;
  7262. song.midiGenerate.stacksOptions.sequence.push_back ({ 4, 3, 67, 1, 1, 0.5f, 2.0f });
  7263. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  7264. if (! plain || ! plain->midiGenerate.isDefault() || plainJson.contains ("midiGenerate"))
  7265. midigen190fmResult = "ERROR defaults " + why;
  7266. else if (! back || ! (back->midiGenerate == song.midiGenerate))
  7267. midigen190fmResult = "ERROR round trip " + why;
  7268. }
  7269. // round 190gi: audio clip envelopes come back from a project (an entry two clips share stays shared, an unused one
  7270. // is not written, the lane shown, FL's curve modes); a project without them writes neither "clipEnvelopes" nor a
  7271. // clip field 25 (older projects save byte-identical)
  7272. juce::String clipenv190giResult = "OK";
  7273. {
  7274. auto song = lynx::Song::makeDefault();
  7275. lynx::ChannelDef channel;
  7276. channel.instrument = lynx::InstrumentKind::audioClip;
  7277. channel.samplePath = "clipenv190gi.wav";
  7278. song.channels.push_back (channel);
  7279. lynx::Clip clip;
  7280. clip.kind = lynx::ClipKind::audio;
  7281. clip.channel = (int) song.channels.size() - 1;
  7282. clip.length = lynx::ppq * 4;
  7283. song.playlist.push_back (clip);
  7284. juce::String why;
  7285. const auto plainJson = lynx::ProjectFile::toJson (song);
  7286. lynx::ClipEnvelope e;
  7287. e.volume = { { 0, 1.0f, 0.0f, 0 }, { lynx::ppq * 4, 0.25f, 0.3f, 1 } };
  7288. e.pan = { { 0, 0.5f, 0.0f, 0 }, { lynx::ppq * 2, 0.0f, 0.0f, 0 } };
  7289. e.shown = lynx::clipenv::panLane;
  7290. song.clipEnvelopes.emplace_back(); // (no clip uses it: not written)
  7291. song.clipEnvelopes.push_back (e);
  7292. song.playlist.back().envelope = 1;
  7293. auto twin = song.playlist.back();
  7294. twin.start = lynx::ppq * 8;
  7295. song.playlist.push_back (twin);
  7296. const auto json = lynx::ProjectFile::toJson (song);
  7297. const auto back = lynx::ProjectFile::fromJson (json, why);
  7298. if (plainJson.contains ("clipEnvelopes") || ! json.contains ("clipEnvelopes"))
  7299. clipenv190giResult = "ERROR written " + why;
  7300. else if (! back || back->clipEnvelopes.size() != 1 || ! (back->clipEnvelopes[0] == e))
  7301. clipenv190giResult = "ERROR table " + why;
  7302. else
  7303. {
  7304. int withEnvelope = 0;
  7305. for (const auto& c : back->playlist)
  7306. withEnvelope += c.kind == lynx::ClipKind::audio && c.envelope == 0 ? 1 : 0;
  7307. if (withEnvelope != 2)
  7308. clipenv190giResult = "ERROR clips " + why;
  7309. }
  7310. }
  7311. // round 190gx: Beats' law in the .lynx — a new project's channels are Measured; a project saved before the law
  7312. // (no "beatsLaw190gx" mark, or a nine-number warpModes list) loads Classic; a Classic channel stays Classic
  7313. juce::String beatslaw190gxResult = "OK";
  7314. {
  7315. auto song = lynx::Song::makeDefault();
  7316. lynx::ChannelDef channel;
  7317. channel.instrument = lynx::InstrumentKind::audioClip;
  7318. channel.samplePath = "beatslaw190gx.wav";
  7319. channel.sampler.keepPitch = true;
  7320. channel.sampler.stretchMethod = lynx::StretchMethod::beats;
  7321. song.channels.push_back (channel);
  7322. const auto index = song.channels.size() - 1;
  7323. juce::String why;
  7324. const auto json = lynx::ProjectFile::toJson (song);
  7325. const auto lawOf = [&] (const juce::String& text) {
  7326. const auto back = lynx::ProjectFile::fromJson (text, why);
  7327. return back && back->channels.size() > index ? (int) back->channels[index].sampler.warpModes.beatsLaw : -1;
  7328. };
  7329. auto oldVar = juce::JSON::parse (json); // (the mark removed: a project saved before 190gx)
  7330. if (auto* o = oldVar.getDynamicObject())
  7331. o->removeProperty ("beatsLaw190gx");
  7332. const auto old = juce::JSON::toString (oldVar);
  7333. auto classic = song;
  7334. classic.channels[index].sampler.warpModes.beatsLaw = lynx::WarpModeSettings::beatsLawClassic;
  7335. auto nine = song;
  7336. nine.channels[index].sampler.warpModes.beatsLoop = 0; // (a 190fm project with a changed setting: nine numbers)
  7337. // (the list with its tenth number, the law, removed: what a 190fm build wrote)
  7338. auto nineVar = juce::JSON::parse (lynx::ProjectFile::toJson (nine));
  7339. bool trimmed = false;
  7340. if (auto* channels = nineVar.getProperty ("channels", {}).getArray(); channels != nullptr && (int) index < channels->size())
  7341. if (auto* modes = (*channels)[(int) index].getProperty ("samplerSettings", {}).getProperty ("warpModes", {}).getArray(); modes != nullptr && modes->size() == 11)
  7342. {
  7343. modes->removeLast (2); // (round 190ik's eleventh number too)
  7344. trimmed = true;
  7345. }
  7346. const auto nineJson = juce::JSON::toString (nineVar);
  7347. if (! json.contains ("beatsLaw190gx") || old.contains ("beatsLaw190gx"))
  7348. beatslaw190gxResult = "ERROR mark";
  7349. else if (lawOf (json) != lynx::WarpModeSettings::beatsLawPitchAware) // (round 190ik: the new default)
  7350. beatslaw190gxResult = "ERROR new " + why;
  7351. else if (lawOf (old) != lynx::WarpModeSettings::beatsLawClassic)
  7352. beatslaw190gxResult = "ERROR old " + why;
  7353. else if (lawOf (lynx::ProjectFile::toJson (classic)) != lynx::WarpModeSettings::beatsLawClassic)
  7354. beatslaw190gxResult = "ERROR classic kept " + why;
  7355. else if (! trimmed || lawOf (nineJson) != lynx::WarpModeSettings::beatsLawClassic)
  7356. beatslaw190gxResult = "ERROR nine-number list";
  7357. }
  7358. // round 190ik: the pitch-aware Beats law and the Texture / Complex Pro engines in the .lynx — a new project's channels
  7359. // use them; a project saved before 190ik (no "warpLaw190ik" mark, or a ten-number warpModes list) keeps Beats Measured
  7360. // and the Classic engines; a channel kept on an older law stays on it when saved again
  7361. juce::String warplaw190ikResult = "OK";
  7362. {
  7363. auto song = lynx::Song::makeDefault();
  7364. lynx::ChannelDef channel;
  7365. channel.instrument = lynx::InstrumentKind::audioClip;
  7366. channel.samplePath = "warplaw190ik.wav";
  7367. channel.sampler.keepPitch = true;
  7368. channel.sampler.stretchMethod = lynx::StretchMethod::texture;
  7369. song.channels.push_back (channel);
  7370. const auto index = song.channels.size() - 1;
  7371. juce::String why;
  7372. const auto lawsOf = [&] (const juce::String& text) {
  7373. const auto back = lynx::ProjectFile::fromJson (text, why);
  7374. if (! back || back->channels.size() <= index)
  7375. return std::pair<int, int> { -1, -1 };
  7376. const auto& w = back->channels[index].sampler.warpModes;
  7377. return std::pair<int, int> { (int) w.beatsLaw, (int) w.warpLaw };
  7378. };
  7379. const auto json = lynx::ProjectFile::toJson (song);
  7380. auto oldVar = juce::JSON::parse (json); // (the mark removed: a project saved by 0.1.28 / 0.1.29)
  7381. if (auto* o = oldVar.getDynamicObject())
  7382. o->removeProperty ("warpLaw190ik");
  7383. const auto old = juce::JSON::toString (oldVar);
  7384. auto kept = song; // a channel left on the older laws
  7385. kept.channels[index].sampler.warpModes.beatsLaw = lynx::WarpModeSettings::beatsLawMeasured;
  7386. kept.channels[index].sampler.warpModes.warpLaw = lynx::WarpModeSettings::warpLawClassic;
  7387. auto ten = song; // a changed setting saved by 0.1.28: a ten-number list
  7388. ten.channels[index].sampler.warpModes.textureFlux = 60.0f;
  7389. auto tenVar = juce::JSON::parse (lynx::ProjectFile::toJson (ten));
  7390. bool trimmed = false;
  7391. if (auto* channels = tenVar.getProperty ("channels", {}).getArray(); channels != nullptr && (int) index < channels->size())
  7392. if (auto* modes = (*channels)[(int) index].getProperty ("samplerSettings", {}).getProperty ("warpModes", {}).getArray(); modes != nullptr && modes->size() == 11)
  7393. {
  7394. modes->removeLast();
  7395. modes->set (9, 1); // (0.1.28 wrote Measured)
  7396. trimmed = true;
  7397. }
  7398. const auto tenJson = juce::JSON::toString (tenVar);
  7399. const std::pair<int, int> newest { lynx::WarpModeSettings::beatsLawPitchAware, lynx::WarpModeSettings::warpLawMeasured };
  7400. const std::pair<int, int> older { lynx::WarpModeSettings::beatsLawMeasured, lynx::WarpModeSettings::warpLawClassic };
  7401. if (! json.contains ("warpLaw190ik") || old.contains ("warpLaw190ik"))
  7402. warplaw190ikResult = "ERROR mark";
  7403. else if (lawsOf (json) != newest)
  7404. warplaw190ikResult = "ERROR new " + why;
  7405. else if (lawsOf (old) != older)
  7406. warplaw190ikResult = "ERROR old " + why;
  7407. else if (lawsOf (lynx::ProjectFile::toJson (kept)) != older)
  7408. warplaw190ikResult = "ERROR older laws kept " + why;
  7409. else if (! trimmed || lawsOf (tenJson) != std::pair<int, int> { lynx::WarpModeSettings::beatsLawMeasured, lynx::WarpModeSettings::warpLawClassic })
  7410. warplaw190ikResult = "ERROR ten-number list";
  7411. }
  7412. // round 190he (issue #152): a channel window's Scaling is saved with the channel; the default (125 %) writes
  7413. // nothing, so older projects and untouched channels read as before
  7414. juce::String editorScale190heResult = "OK";
  7415. {
  7416. auto song = lynx::Song::makeDefault();
  7417. song.channels[0].editorScale = 100;
  7418. song.channels[1].editorScale = 0;
  7419. juce::String why;
  7420. const auto json = lynx::ProjectFile::toJson (song);
  7421. const auto back = lynx::ProjectFile::fromJson (json, why);
  7422. auto outOfRange = juce::JSON::parse (json);
  7423. if (auto* chans = outOfRange.getProperty ("channels", {}).getArray(); chans != nullptr && ! chans->isEmpty())
  7424. if (auto* o = (*chans)[0].getDynamicObject())
  7425. o->setProperty ("editorScale", 9000);
  7426. const auto clamped = lynx::ProjectFile::fromJson (juce::JSON::toString (outOfRange), why);
  7427. if (! back || back->channels[0].editorScale != 100 || back->channels[1].editorScale != 0)
  7428. editorScale190heResult = "ERROR round trip " + why;
  7429. else if (json.indexOf ("editorScale") != json.lastIndexOf ("editorScale"))
  7430. editorScale190heResult = "ERROR written for a default channel";
  7431. else if (! clamped || clamped->channels[0].editorScale != lynx::editorscale::maxPercent)
  7432. editorScale190heResult = "ERROR not clamped";
  7433. }
  7434. // round 190he (coordinator's gate): a project saved before 190he (no "sfModBase190he") keeps the old 0.5 centre of
  7435. // a Modulation route on a Soundfont knob; a new song, saved and opened again, centres on the knob
  7436. juce::String sfModBase190heResult = "OK";
  7437. {
  7438. auto song = lynx::Song::makeDefault();
  7439. juce::String why;
  7440. const auto json = lynx::ProjectFile::toJson (song);
  7441. auto oldVar = juce::JSON::parse (json);
  7442. if (auto* o = oldVar.getDynamicObject())
  7443. o->removeProperty ("sfModBase190he");
  7444. const auto back = lynx::ProjectFile::fromJson (json, why);
  7445. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (oldVar), why);
  7446. auto resaved = old ? lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*old), why) : std::optional<lynx::Song> {};
  7447. if (! json.contains ("sfModBase190he") || ! back || ! back->soundfontModBaseReal)
  7448. sfModBase190heResult = "ERROR new song " + why;
  7449. else if (! old || old->soundfontModBaseReal)
  7450. sfModBase190heResult = "ERROR old project " + why;
  7451. else if (! resaved || resaved->soundfontModBaseReal)
  7452. sfModBase190heResult = "ERROR old project saved again";
  7453. }
  7454. // round 190hq: tempo markers (B11) and the fader / route PDC switch (B13) in the .lynx, and the copy for an older
  7455. // LYNX (B20): an effect 0.1.27 does not know keeps its slot (as a switched-off Utility) and loses its automation,
  7456. // the later slots and their automation stay; the copy for 0.1.28 turns the markers into a plain tempo clip
  7457. juce::String community190hqResult = "OK";
  7458. {
  7459. auto song = lynx::Song::makeDefault();
  7460. song.mode = lynx::PlayMode::song;
  7461. lynx::tempomarkers::add (song, 4 * lynx::ppq, 90.0);
  7462. lynx::tempomarkers::add (song, 8 * lynx::ppq, 140.0, true);
  7463. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::anvilBus));
  7464. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  7465. for (const auto slot : { 0, 1 })
  7466. {
  7467. lynx::Automation a;
  7468. a.name = slot == 0 ? "Anvil" : "Delay";
  7469. a.target = { lynx::AutomationTargetKind::effectParam, 1, slot, 1 };
  7470. a.points = { { 0, 0.2f }, { 1920, 0.8f } };
  7471. song.automations.push_back (a);
  7472. }
  7473. juce::String why;
  7474. const auto json = lynx::ProjectFile::toJson (song);
  7475. const auto back = lynx::ProjectFile::fromJson (json, why);
  7476. auto unmarked = juce::JSON::parse (json);
  7477. if (auto* o = unmarked.getDynamicObject())
  7478. o->removeProperty ("mixerLevelPdc190hq");
  7479. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (unmarked), why);
  7480. const auto marks = back ? lynx::tempomarkers::list (*back) : std::vector<lynx::tempomarkers::Mark> {};
  7481. const auto for127 = lynx::olderlynx::forRelease (song, "0.1.27");
  7482. const auto for128 = lynx::olderlynx::forRelease (song, "0.1.28");
  7483. const auto copy127 = for127.ok ? lynx::ProjectFile::fromJson (for127.json, why) : std::optional<lynx::Song> {};
  7484. const auto copy128 = for128.ok ? lynx::ProjectFile::fromJson (for128.json, why) : std::optional<lynx::Song> {};
  7485. const auto anvilLost = std::any_of (for127.lost.begin(), for127.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  7486. return juce::String (l.text).startsWith ("Anvil Bus");
  7487. });
  7488. auto targetOf = [] (const std::optional<lynx::Song>& s, const char* name) {
  7489. if (s)
  7490. for (const auto& a : s->automations)
  7491. if (a.name == name)
  7492. return a.target;
  7493. return lynx::AutomationTarget {};
  7494. };
  7495. if (! back || ! back->compensateMixerLevels || ! old || old->compensateMixerLevels)
  7496. community190hqResult = "ERROR mixer level PDC mark " + why;
  7497. else if (marks.size() != 2 || marks[0].tick != 4 * lynx::ppq || std::abs (marks[1].bpm - 140.0) > 0.01 || ! marks[1].glide || marks[0].glide
  7498. || std::abs (back->tempoAt (5.0 * lynx::ppq) - 102.5) > 0.5) // (90 at bar 2, ramping into the gliding 140 at bar 3)
  7499. community190hqResult = "ERROR tempo markers round trip";
  7500. else if (! copy127 || for127.json.contains ("anvilBus") || copy127->mixer[1].effects.size() != 2
  7501. || copy127->mixer[1].effects[0].kind != lynx::EffectKind::utility || copy127->mixer[1].effects[0].enabled
  7502. || copy127->mixer[1].effects[1].kind != lynx::EffectKind::delay || ! anvilLost)
  7503. community190hqResult = "ERROR copy for 0.1.27: slots " + why;
  7504. else if (targetOf (copy127, "Anvil").kind != lynx::AutomationTargetKind::none
  7505. || ! (targetOf (copy127, "Delay") == lynx::AutomationTarget { lynx::AutomationTargetKind::effectParam, 1, 1, 1 }))
  7506. community190hqResult = "ERROR copy for 0.1.27: automation";
  7507. else if (! juce::JSON::parse (for127.json)["savedBy"].toString().equalsIgnoreCase ("0.1.27") || for127.json.contains ("tempoMarkers")
  7508. || for127.json.contains ("mixerLevelPdc190hq") || for127.json.contains ("beatsLaw190gx"))
  7509. community190hqResult = "ERROR copy for 0.1.27: fields";
  7510. else if (! copy128 || for128.json.contains ("tempoMarkers") || ! for128.json.contains ("anvilBus") || lynx::tempomarkers::automationIndex (*copy128) >= 0
  7511. || std::abs (copy128->tempoAt (5.0 * lynx::ppq) - 102.5) > 0.5 || std::abs (copy128->tempoAt (12.0 * lynx::ppq) - 140.0) > 0.01)
  7512. community190hqResult = "ERROR copy for 0.1.28";
  7513. else if (lynx::olderlynx::forRelease (song, "0.1.9").ok)
  7514. community190hqResult = "ERROR unknown release accepted";
  7515. }
  7516. // rollup 0.1.30 (round 190il): the copy for 0.1.28 knows what the other 0.1.30 rounds save: a Tetra channel becomes
  7517. // an empty Sampler, MPE note curves, muted Pattern Blocks, clips transposed past ±12, clip slots' Start markers and
  7518. // scales, Voice Shift's revision 1, Ridge's Pink EQ, Hush's Allround timing (round 190iy), automation colours and mix snapshots are reported and taken
  7519. // out; a DirectWave state's 36-byte sample format record is completed (0.1.28 skipped it, and the loop with it)
  7520. juce::String rollup030Result = "OK";
  7521. {
  7522. auto song = lynx::Song::makeDefault();
  7523. lynx::ChannelDef tetra;
  7524. tetra.name = "FM";
  7525. tetra.instrument = lynx::InstrumentKind::tetra;
  7526. tetra.modelParams = { 0.5f, 0.25f };
  7527. song.channels.push_back (tetra);
  7528. lynx::ChannelDef wave;
  7529. wave.name = "Piano";
  7530. wave.instrument = lynx::InstrumentKind::directwave;
  7531. {
  7532. auto doc = lynx::dw::freshDoc();
  7533. lynx::dw::Node zone;
  7534. zone.id = 3;
  7535. zone.container = true;
  7536. lynx::dw::Node format;
  7537. format.id = 0x1F7;
  7538. format.body.assign (36, 0);
  7539. format.body[20] = 2; // loop mode
  7540. format.body[24] = 44; // loop A
  7541. format.body[28] = 200; // loop B
  7542. zone.kids.push_back (format);
  7543. for (auto& n : doc.top)
  7544. if (n.id == 1 && n.container)
  7545. {
  7546. n.kids.push_back (zone);
  7547. break;
  7548. }
  7549. wave.pluginState = lynx::dw::writeDoc (doc);
  7550. }
  7551. song.channels.push_back (wave);
  7552. lynx::Note curved;
  7553. curved.key = 60;
  7554. curved.length = lynx::ppq;
  7555. lynx::NoteCurves curves;
  7556. curves.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { 96.0f, 200.0f } };
  7557. curved.curves = curves;
  7558. song.patterns[0].notes.push_back (curved);
  7559. song.patternBlocksOn = true;
  7560. lynx::patternblocks::place (song, 0, 0);
  7561. lynx::patternblocks::place (song, 0, 4 * lynx::ppq);
  7562. lynx::patternblocks::setMuted (song, 1, true);
  7563. lynx::Clip up;
  7564. up.track = 1;
  7565. up.length = 4 * lynx::ppq;
  7566. up.pitch = 24.0f;
  7567. song.playlist.push_back (up);
  7568. lynx::Clip slotClip;
  7569. slotClip.length = 4 * lynx::ppq;
  7570. if (const auto id = lynx::launcher::setClip (song, 0, 0, slotClip); id >= 0)
  7571. {
  7572. song.clipGrid->slots[(std::size_t) id].startMarker = lynx::ppq;
  7573. song.clipGrid->slots[(std::size_t) id].ownScale = true;
  7574. }
  7575. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::voiceShift)); // (a new one: revision 1)
  7576. auto ridgeSlot = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  7577. ridgeSlot.params[(std::size_t) lynx::mixsuite::ridge::k4Pink] = 1.0f;
  7578. song.mixer[2].effects.push_back (ridgeSlot);
  7579. auto hushSlot = lynx::makeEffectSlot (lynx::EffectKind::hushDeEsser); // (a new one: the measured timing, round 190iq)
  7580. hushSlot.params[(std::size_t) lynx::mixsuite::hush::allround] = 1.0f;
  7581. song.mixer[3].effects.push_back (hushSlot);
  7582. lynx::Automation coloured;
  7583. coloured.name = "Cutoff";
  7584. coloured.colour = 0xFFC03030u;
  7585. coloured.points = { { 0, 0.2f }, { 1920, 0.8f } };
  7586. song.automations.push_back (coloured);
  7587. lynx::mixsnap::take (song);
  7588. // rollup step 3 (round 190jk): Helix (190ja), the effects' hidden revisions (190is / 190it), a warped Texture
  7589. // channel with its offline transposition and tempo automation (190ik), a deactivated clip slot (190im)
  7590. lynx::ChannelDef helix;
  7591. helix.name = "WT";
  7592. helix.instrument = lynx::InstrumentKind::helix;
  7593. helix.modelParams = { 0.5f };
  7594. song.channels.push_back (helix);
  7595. lynx::ChannelDef loop;
  7596. loop.name = "Loop";
  7597. loop.instrument = lynx::InstrumentKind::sampler;
  7598. loop.sampler.stretchBeats = 8.0f;
  7599. loop.sampler.keepPitch = true;
  7600. loop.sampler.stretchMethod = lynx::StretchMethod::texture;
  7601. loop.sampler.stretchPitch = 5.0f;
  7602. song.channels.push_back (loop);
  7603. lynx::Automation tempoClip;
  7604. tempoClip.name = "Tempo";
  7605. tempoClip.target.kind = lynx::AutomationTargetKind::tempo;
  7606. tempoClip.points = { { 0, 0.4f }, { 1920, 0.6f } };
  7607. song.automations.push_back (tempoClip);
  7608. if (song.clipGrid)
  7609. for (auto& slot : song.clipGrid->slots)
  7610. slot.active = false;
  7611. auto echoSlot = lynx::makeEffectSlot (lynx::EffectKind::echoform); // (new: voicings revision 1)
  7612. echoSlot.params[(std::size_t) lynx::echosuite::echoform::voicing] = 1.0f;
  7613. song.mixer[4].effects.push_back (echoSlot);
  7614. auto haloSlot = lynx::makeEffectSlot (lynx::EffectKind::halo); // (new: revision 1 of the Measured law)
  7615. haloSlot.params[(std::size_t) lynx::verbs::halo::engineLaw] = 1.0f;
  7616. song.mixer[5].effects.push_back (haloSlot);
  7617. song.mixer[6].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::latticeMod));
  7618. auto luxeSlot = lynx::makeEffectSlot (lynx::EffectKind::luxeVerb);
  7619. luxeSlot.params[(std::size_t) lynx::luxeVerbSpaceDucking] = 0.5f;
  7620. song.mixer[7].effects.push_back (luxeSlot);
  7621. // rollup step 4 (round 190jt): Facet's automatic threshold (190jh), a MIDI Out channel (190jl), a hosted VST3's
  7622. // automated parameter (190jg), a nested Playlist folder (190jf), the Limiter's CURVE view (190jd)
  7623. auto facetSlot = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  7624. facetSlot.params[(std::size_t) lynx::facet::autoThresholdParam0 + 2] = 1.0f;
  7625. song.mixer[8].effects.push_back (facetSlot);
  7626. auto limiterSlot = lynx::makeEffectSlot (lynx::EffectKind::fruityLimiter);
  7627. limiterSlot.displayView = 1;
  7628. song.mixer[9].effects.push_back (limiterSlot);
  7629. lynx::ChannelDef midiOut;
  7630. midiOut.name = "Hardware";
  7631. midiOut.instrument = lynx::InstrumentKind::midiOut;
  7632. song.channels.push_back (midiOut);
  7633. lynx::ChannelDef hosted;
  7634. hosted.name = "Hosted";
  7635. hosted.instrument = lynx::InstrumentKind::plugin;
  7636. hosted.plugin.id = "VST3-Test Synth-1a2b3c4d-5e6f7a8b";
  7637. hosted.plugin.name = "Test Synth";
  7638. song.channels.push_back (hosted);
  7639. lynx::Automation pluginKnob;
  7640. pluginKnob.name = "Test Synth - Cutoff";
  7641. pluginKnob.target.kind = lynx::AutomationTargetKind::channelParam;
  7642. pluginKnob.target.index = (int) song.channels.size() - 1;
  7643. pluginKnob.target.param = 3;
  7644. pluginKnob.points = { { 0, 0.1f }, { 1920, 0.9f } };
  7645. song.automations.push_back (pluginKnob);
  7646. if (song.playlistTracks.size() < 4)
  7647. song.playlistTracks.resize (4);
  7648. song.playlistTracks[1].grouped = true;
  7649. song.playlistTracks[2].grouped = true;
  7650. song.playlistTracks[2].nest = 1;
  7651. // rollup step 5 (round 190kh): Hush's Single Vocal revision (190js), a slide note on an FL native generator (190jv)
  7652. song.mixer[10].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::hushDeEsser)); // (new: Single Vocal, revision 1)
  7653. lynx::ChannelDef slider;
  7654. slider.name = "Slides";
  7655. slider.instrument = lynx::InstrumentKind::sampler;
  7656. song.channels.push_back (slider);
  7657. if (song.patterns.empty())
  7658. song.patterns.emplace_back();
  7659. {
  7660. lynx::Note slide;
  7661. slide.start = 0;
  7662. slide.length = lynx::ppq;
  7663. slide.channel = (int) song.channels.size() - 1;
  7664. slide.key = 64;
  7665. slide.slide = true;
  7666. song.patterns[0].notes.push_back (slide);
  7667. }
  7668. // rollup step 6 (round 190km): Live's Crossfade Assign and a return track (190kc), the Simple Controls tab's own
  7669. // mapping (190ke), a Newtone slot whose state is version 3 (natives190kj: + the key and the notes' velocity)
  7670. song.mixer[11].crossfade = lynx::CrossfadeAssign::a;
  7671. song.crossfader = -0.5f;
  7672. song.mixer[12].liveReturn = true;
  7673. song.mixer[12].returnPre = true;
  7674. song.mixer[13].smartControls = "custom";
  7675. {
  7676. auto newtoneSlot = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  7677. lynx::newtonefx::Track nt;
  7678. nt.frames = 48000;
  7679. nt.key = 9;
  7680. lynx::newtonefx::Note n;
  7681. n.origEnd = n.curEnd = 24000;
  7682. n.origPitch = 69.0;
  7683. n.velocity = 0.8;
  7684. n.validEnd = 20000;
  7685. nt.pitches = { n };
  7686. nt.notes = 1;
  7687. newtoneSlot.state = lynx::newtonefx::writeNative (nt);
  7688. song.mixer[14].effects.push_back (newtoneSlot);
  7689. }
  7690. // rollup step 7 (round 190lc): a Peak Controller on a LYNX shape (190kl), Crest's console law (190kt), a locked
  7691. // insert beside a solo (190kn), an imported take lane (qafix190kq), a plugin that records no notes from its
  7692. // window (190ks)
  7693. {
  7694. auto peakSlot = lynx::makeEffectSlot (lynx::EffectKind::peakController);
  7695. peakSlot.params[(std::size_t) lynx::peakshapes::extraShapeParam] = (float) lynx::peakshapes::expFall / lynx::peakshapes::idScale;
  7696. song.mixer[15].effects.push_back (peakSlot);
  7697. auto crestSlot = lynx::makeEffectSlot (lynx::EffectKind::crestCompressor);
  7698. crestSlot.params[(std::size_t) lynx::dyn::crest::busLaw] = 1.0f;
  7699. song.mixer[16].effects.push_back (crestSlot);
  7700. // rollup step 8: a new Crest (round 190kw's revision 1), a Crest on round 190ky's FET law, a Ridge Strip with
  7701. // round 190lb's 4K G filters, an Echoform on round 190kw's Timeless 3 line law in a locked slot (round
  7702. // 190ld), and a Playlist track's solo lock (round 190ld)
  7703. song.mixer[16].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::crestCompressor));
  7704. auto fetSlot = lynx::makeEffectSlot (lynx::EffectKind::crestCompressor);
  7705. fetSlot.params[(std::size_t) lynx::dyn::crest::revision] = 0.0f;
  7706. fetSlot.params[(std::size_t) lynx::dyn::crest::fetLaw] = lynx::dyn::crest::fetLawValue (0);
  7707. song.mixer[16].effects.push_back (fetSlot);
  7708. auto k4gSlot = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  7709. k4gSlot.params[(std::size_t) lynx::mixsuite::ridge::k4gLaw] = 1.0f;
  7710. song.mixer[16].effects.push_back (k4gSlot);
  7711. auto lineSlot = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  7712. lineSlot.params[(std::size_t) lynx::echosuite::echoform::lineLaw] = 1.0f;
  7713. lineSlot.lockState = true;
  7714. song.mixer[16].effects.push_back (lineSlot);
  7715. // (round 190mo: track 4 is the fifth; the song had four tracks here, so this wrote one byte past the
  7716. // vector's end: the heap corruption of the Linux self-test, "corrupted size vs. prev_size" later on)
  7717. if (song.playlistTracks.size() < 5)
  7718. song.playlistTracks.resize (5);
  7719. song.playlistTracks[4].soloLock = true;
  7720. song.mixer[1].lockState = true; // (the default mixer has inserts 1…16)
  7721. song.mixer[2].solo = true;
  7722. song.playlistTracks[3].takeLane = true;
  7723. for (auto& c : song.channels)
  7724. if (c.name == "Hosted")
  7725. c.plugin.recordOwnNotes = false;
  7726. }
  7727. // rollup step 9 (round 190lu): a new Ember (round 190kw / 190lg's Saturn laws), a Prism on round 190lg's Pro-MB
  7728. // law, round 190lf's L2 law on the Limiter, cell law on Glow Leveler, direct sound on Reeverb 2, zero law on Quell
  7729. // and H-Delay loop law on Echoform, round 190ln's all-pass dispersion on Facet, and a note on an audio clip
  7730. // channel (round 190lq: FL's law in a marked project)
  7731. {
  7732. auto& m16 = song.mixer[16].effects;
  7733. m16.push_back (lynx::makeEffectSlot (lynx::EffectKind::ember)); // [5]
  7734. auto prism = lynx::makeEffectSlot (lynx::EffectKind::prismMultiband);
  7735. prism.params[(std::size_t) lynx::dyn::prism::revision] = 1.0f;
  7736. m16.push_back (prism); // [6]
  7737. auto l2 = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  7738. l2.params[(std::size_t) lynx::limiterlaw::lawParam] = lynx::limiterlaw::l2LawValue;
  7739. m16.push_back (l2); // [7]
  7740. auto glow = lynx::makeEffectSlot (lynx::EffectKind::glowLeveler);
  7741. glow.params[(std::size_t) lynx::mixsuite::glow::cellLaw] = 1.0f;
  7742. m16.push_back (glow); // [8]
  7743. auto verb = lynx::makeEffectSlot (lynx::EffectKind::reeverb2);
  7744. verb.params[(std::size_t) lynx::reeverb2DirectLaw] = 1.0f;
  7745. m16.push_back (verb); // [9]
  7746. auto quell = lynx::makeEffectSlot (lynx::EffectKind::quellDenoiser);
  7747. quell.params[(std::size_t) lynx::voicetools::quell::zeroLaw] = 1.0f;
  7748. m16.push_back (quell); // [10]
  7749. auto disperser = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  7750. disperser.params[(std::size_t) lynx::facet::dispersionCountParam] = 0.25f;
  7751. m16.push_back (disperser); // [11]
  7752. auto hybrid = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  7753. hybrid.params[(std::size_t) lynx::echosuite::echoform::hybridLaw] = 1.0f;
  7754. m16.push_back (hybrid); // [12]
  7755. lynx::ChannelDef clipChannel;
  7756. clipChannel.name = "Clip";
  7757. clipChannel.instrument = lynx::InstrumentKind::audioClip;
  7758. song.channels.push_back (clipChannel);
  7759. lynx::Note hit;
  7760. hit.length = lynx::ppq / 4;
  7761. hit.channel = (int) song.channels.size() - 1;
  7762. hit.key = 67;
  7763. song.patterns[0].notes.push_back (hit);
  7764. }
  7765. // rollup step 10 (round 190me): a new Apex Limiter and Sentry Gate (round 190lp's revision 1), a LuxeVerb on its
  7766. // Space engine (revision 1, round 190kw / 190lz), an Echoform on round 190ly's ValhallaDelay law, a new Spiral Echo
  7767. // on the Measured law (round 190ly's rate law) and a scene follow action (round 190lr)
  7768. {
  7769. auto& m16 = song.mixer[16].effects; // (after step 9's [5] … [12]: the song has inserts 0 … 16)
  7770. m16.push_back (lynx::makeEffectSlot (lynx::EffectKind::apexLimiter)); // [13]
  7771. m16.push_back (lynx::makeEffectSlot (lynx::EffectKind::sentryGate)); // [14]
  7772. auto luxe = lynx::makeEffectSlot (lynx::EffectKind::luxeVerb);
  7773. luxe.params[(std::size_t) lynx::luxeVerbSpaceFirst] = 1.0f;
  7774. m16.push_back (luxe); // [15]
  7775. auto valhalla = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  7776. valhalla.params[(std::size_t) lynx::echosuite::echoform::valhallaLaw] = 1.0f;
  7777. m16.push_back (valhalla); // [16]
  7778. auto spiral = lynx::makeEffectSlot (lynx::EffectKind::spiralEcho);
  7779. spiral.params[(std::size_t) lynx::echosuite::spiral::law] = 1.0f;
  7780. m16.push_back (spiral); // [17]
  7781. if (! song.clipGrid)
  7782. song.clipGrid.emplace();
  7783. if (song.clipGrid->scenes.empty())
  7784. song.clipGrid->scenes.emplace_back();
  7785. song.clipGrid->scenes[0].follow.enabled = true;
  7786. }
  7787. // rollup step 11 (round 190mn): a new Horizon (round 190mb / 190mj's revision and FutureVerb law), a Nebula on the
  7788. // Supermassive tone, an Orbit on the SpaceModulator laws (190mb / 190mj), round 190mg's Waves laws (Prism C4,
  7789. // Compressor Renaissance, Quell NS1, Gemini splice, LYNX Tune Waves Tune, Facet PuigTec) and a note repeat (190ma)
  7790. {
  7791. auto& m16 = song.mixer[16].effects; // (after step 10's [13] … [17])
  7792. m16.push_back (lynx::makeEffectSlot (lynx::EffectKind::horizon)); // [18]
  7793. auto nebula = lynx::makeEffectSlot (lynx::EffectKind::nebula);
  7794. nebula.params[(std::size_t) lynx::verbs::nebula::toneLaw] = 1.0f;
  7795. m16.push_back (nebula); // [19]
  7796. auto orbit = lynx::makeEffectSlot (lynx::EffectKind::orbit);
  7797. orbit.params[(std::size_t) lynx::echosuite::orbit::smLaw] = 1.0f;
  7798. orbit.params[(std::size_t) lynx::echosuite::orbit::voiceLaw] = 1.0f;
  7799. m16.push_back (orbit); // [20]
  7800. auto c4 = lynx::makeEffectSlot (lynx::EffectKind::prismMultiband);
  7801. c4.params[(std::size_t) lynx::dyn::prism::c4Law] = lynx::dyn::prism::c4LawValue (false);
  7802. m16.push_back (c4); // [21]
  7803. auto ren = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  7804. ren.params[(std::size_t) lynx::compressorRenLaw] = 1.0f;
  7805. m16.push_back (ren); // [22]
  7806. auto ns1 = lynx::makeEffectSlot (lynx::EffectKind::quellDenoiser);
  7807. ns1.params[(std::size_t) lynx::voicetools::quell::ns1Law] = 1.0f;
  7808. m16.push_back (ns1); // [23]
  7809. auto splice = lynx::makeEffectSlot (lynx::EffectKind::geminiDoubler);
  7810. splice.params[(std::size_t) lynx::voicetools::gemini::spliceLaw] = 1.0f;
  7811. m16.push_back (splice); // [24]
  7812. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  7813. tune.params[(std::size_t) lynx::lynxtune::wavesLaw] = 1.0f;
  7814. m16.push_back (tune); // [25]
  7815. auto puig = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  7816. puig.params[(std::size_t) lynx::facet::puigLawParam] = lynx::facet::puigLawValue (2);
  7817. m16.push_back (puig); // [26]
  7818. lynx::Note repeated;
  7819. repeated.length = lynx::ppq;
  7820. repeated.channel = 0;
  7821. repeated.key = 60;
  7822. repeated.repeat = 9;
  7823. song.patterns[0].notes.push_back (repeated);
  7824. }
  7825. // rollup step 12 (round 190mu): round 190mm's Waves laws (Facet's Waves design law, Compressor's Vox / API-2500 /
  7826. // RChannel EQ, Prism's C6 floating bands, Hush's Renaissance law, Low Lifter's bass law, Aether's Vitamin law,
  7827. // Ridge's omni law), round 190mk's Multiband display SPEED and a zipped channel
  7828. {
  7829. auto& m16 = song.mixer[16].effects; // (after step 11's [18] … [26])
  7830. auto req = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  7831. req.params[(std::size_t) lynx::facet::wavesLawParam] = 1.0f;
  7832. req.params[(std::size_t) lynx::facet::wavesBandParam0] = lynx::facet::waveCodeValue (lynx::facet::WaveCode::reqBell);
  7833. m16.push_back (req); // [27]
  7834. auto vox = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  7835. vox.params[8] = 1.0f;
  7836. vox.params[(std::size_t) lynx::compressorVoxLaw] = 1.0f;
  7837. m16.push_back (vox); // [28]
  7838. auto api = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  7839. api.params[(std::size_t) lynx::compressorApiLaw] = 1.0f;
  7840. m16.push_back (api); // [29]
  7841. auto rchannel = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  7842. rchannel.params[(std::size_t) lynx::compressorRenLaw] = 1.0f;
  7843. rchannel.params[(std::size_t) lynx::compressorChannelLaw] = 1.0f;
  7844. m16.push_back (rchannel); // [30]
  7845. auto c6 = lynx::makeEffectSlot (lynx::EffectKind::prismMultiband);
  7846. c6.params[(std::size_t) lynx::dyn::prism::c4Law] = lynx::dyn::prism::c4LawValue (false);
  7847. c6.params[(std::size_t) lynx::dyn::prism::c6Param (1, lynx::dyn::prism::c6On)] = 1.0f;
  7848. m16.push_back (c6); // [31]
  7849. auto rdeesser = lynx::makeEffectSlot (lynx::EffectKind::hushDeEsser);
  7850. rdeesser.params[(std::size_t) lynx::mixsuite::hush::essLaw] = 1.0f;
  7851. m16.push_back (rdeesser); // [32]
  7852. auto maxx = lynx::makeEffectSlot (lynx::EffectKind::flLowLifter);
  7853. maxx.params[(std::size_t) lynx::lowlifter::bassLaw] = 1.0f;
  7854. m16.push_back (maxx); // [33]
  7855. auto vitamin = lynx::makeEffectSlot (lynx::EffectKind::aether);
  7856. vitamin.params[(std::size_t) lynx::mixsuite::aether::vitLaw] = 1.0f;
  7857. m16.push_back (vitamin); // [34]
  7858. auto scheps = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  7859. scheps.params[(std::size_t) lynx::mixsuite::ridge::omniLaw] = 1.0f;
  7860. m16.push_back (scheps); // [35]
  7861. auto multiband = lynx::makeEffectSlot (lynx::EffectKind::fruityMultiband);
  7862. multiband.displayView = 100;
  7863. m16.push_back (multiband); // [36]
  7864. song.channels[0].zipped = true;
  7865. }
  7866. // rollup step 13 (round 190na): round 190mt's Waves laws (Facet's API-560 law, Compressor's RVox type and gate,
  7867. // Ridge's G-Channel EQ law) and round 190mv's FL Current mixer track (round 190mr's window layout: below)
  7868. int currentAt = -1;
  7869. {
  7870. auto& m16 = song.mixer[16].effects; // (after step 12's [27] … [36])
  7871. auto api560 = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  7872. api560.params[(std::size_t) lynx::facet::api560LawParam] = 1.0f;
  7873. api560.params[(std::size_t) lynx::facet::api560GainParam0 + 3] = lynx::facet::api560GainValue (6.0);
  7874. m16.push_back (api560); // [37]
  7875. auto rch = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  7876. rch.params[(std::size_t) lynx::compressorRenLaw] = 1.0f;
  7877. rch.params[(std::size_t) lynx::compressorRVoxType] = 1.0f;
  7878. rch.params[(std::size_t) lynx::compressorRchGate] = 1.0f;
  7879. m16.push_back (rch); // [38]
  7880. auto sslG = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  7881. sslG.params[(std::size_t) lynx::mixsuite::ridge::gEqLaw] = 1.0f;
  7882. sslG.params[(std::size_t) lynx::mixsuite::ridge::gHfKHz] = 0.5f;
  7883. m16.push_back (sslG); // [39]
  7884. currentAt = lynx::mixerops::addCurrentTrack (song);
  7885. if (currentAt >= 0)
  7886. song.mixer[(std::size_t) currentAt].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::facetEq));
  7887. }
  7888. // rollup step 14 (round 190nf): round 190nb's Kilohearts law on Effector, round 190mx's launched pattern clip that
  7889. // plays its pattern's events (the grid's slot clip above plays pattern 1)
  7890. {
  7891. auto khs = lynx::makeEffectSlot (lynx::EffectKind::effector);
  7892. khs.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::resonator);
  7893. khs.params[(std::size_t) lynx::khsdsp::valueParam] = 0.5f;
  7894. song.mixer[16].effects.push_back (khs); // [40]
  7895. lynx::PatternEvents knob;
  7896. knob.target.kind = lynx::AutomationTargetKind::channelVolume;
  7897. knob.target.index = 0;
  7898. knob.events = { { 0, 0.2f }, { lynx::ppq, 0.8f } };
  7899. song.patterns[0].events.push_back (knob);
  7900. }
  7901. // round 190qf (PR #260): a copy for 0.1.30 / 0.1.28 keeps 10 effect slots per insert (those releases hold 10) and
  7902. // leaves the rest out. The effects [10] … [40] this test lays on insert 16 move to inserts of their own, 10 each
  7903. // (added at the end), so every law above still reaches the copy; m16[k] below finds effect k where it went.
  7904. std::vector<int> spread16;
  7905. for (std::size_t from = 10; from < song.mixer[16].effects.size(); from += 10)
  7906. {
  7907. auto& added = song.mixer.emplace_back();
  7908. added.name = "Insert " + std::to_string (song.mixer.size() - 1);
  7909. const auto end = std::min (from + 10, song.mixer[16].effects.size());
  7910. added.effects.assign (song.mixer[16].effects.begin() + (std::ptrdiff_t) from, song.mixer[16].effects.begin() + (std::ptrdiff_t) end);
  7911. for (auto& fx : added.effects)
  7912. fx.row = -1;
  7913. spread16.push_back ((int) song.mixer.size() - 1);
  7914. }
  7915. if (song.mixer[16].effects.size() > 10)
  7916. song.mixer[16].effects.resize (10);
  7917. struct Spread16
  7918. {
  7919. const juce::var& root;
  7920. const std::vector<int>& inserts;
  7921. juce::var operator[] (int k) const
  7922. {
  7923. if (k < 10)
  7924. return root["mixer"][16]["effects"][k];
  7925. const auto chunk = (std::size_t) (k / 10 - 1);
  7926. return chunk < inserts.size() ? root["mixer"][inserts[chunk]]["effects"][k % 10] : juce::var();
  7927. }
  7928. };
  7929. const auto copy = lynx::olderlynx::forRelease (song, "0.1.28");
  7930. juce::String why;
  7931. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  7932. const auto said = [&copy] (const char* start) {
  7933. return std::any_of (copy.lost.begin(), copy.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  7934. };
  7935. const auto parsed = juce::JSON::parse (copy.json);
  7936. const auto* channels = parsed["channels"].getArray();
  7937. bool fmEmpty = false, notesCut = true, waveDone = false, wtEmpty = false, loopKnob = false;
  7938. if (channels != nullptr)
  7939. for (const auto& c : *channels)
  7940. {
  7941. if (c["name"].toString() == "FM")
  7942. fmEmpty = c["instrument"].toString() == "sampler" && ! c.hasProperty ("modelParams");
  7943. if (c["name"].toString() == "WT")
  7944. wtEmpty = c["instrument"].toString() == "sampler" && ! c.hasProperty ("modelParams");
  7945. if (c["name"].toString() == "Loop")
  7946. loopKnob = std::abs ((double) c["samplerSettings"]["pitch"] - 5.0) < 1.0e-6 && ! c["samplerSettings"].hasProperty ("stretchPitch")
  7947. && (! c["samplerSettings"]["warpModes"].isArray() || c["samplerSettings"]["warpModes"].size() <= 10);
  7948. if (c["name"].toString() == "Piano")
  7949. {
  7950. juce::MemoryOutputStream bytes;
  7951. if (juce::Base64::convertFromBase64 (bytes, c["pluginState"].toString()))
  7952. {
  7953. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  7954. if (const auto st = lynx::dw::parseState (std::vector<std::uint8_t> (b, b + bytes.getDataSize())))
  7955. for (const auto& prog : st->programs)
  7956. for (const auto& z : prog.zones)
  7957. waveDone = waveDone || (z.loopMode == 2 && z.loopA == 44 && z.loopB == 200 && z.bits == 32);
  7958. if (const auto doc = lynx::dw::readDoc (std::vector<std::uint8_t> (b, b + bytes.getDataSize())))
  7959. for (const auto& n : doc->top)
  7960. for (const auto& z : n.kids)
  7961. for (const auto& r : z.kids)
  7962. if (r.id == 0x1F7)
  7963. waveDone = waveDone && r.body.size() == 40;
  7964. }
  7965. }
  7966. }
  7967. if (const auto* patterns = parsed["patterns"].getArray())
  7968. for (const auto& pt : *patterns)
  7969. if (const auto* notes = pt["notes"].getArray())
  7970. for (const auto& n : *notes)
  7971. notesCut = notesCut && n.size() <= 19;
  7972. if (! copy.ok || ! back)
  7973. rollup030Result = "ERROR copy " + why;
  7974. else if (! fmEmpty || ! said ("Tetra is not in this release"))
  7975. rollup030Result = "ERROR Tetra channel";
  7976. else if (! waveDone)
  7977. rollup030Result = "ERROR DirectWave short record";
  7978. else if (! notesCut || ! said ("{0} note(s) lose their MPE curves"))
  7979. rollup030Result = "ERROR note curves";
  7980. else if (back->blocks.size() != 1 || back->blocks[0].start != 0 || ! said ("{0} muted Pattern Block(s)"))
  7981. rollup030Result = "ERROR muted blocks";
  7982. else if (std::none_of (back->playlist.begin(), back->playlist.end(), [] (const lynx::Clip& c) { return c.pitch == 12.0f; })
  7983. || ! said ("{0} clip(s) transposed"))
  7984. rollup030Result = "ERROR clip pitch";
  7985. else if (copy.json.contains ("startMarker") || copy.json.contains ("clipScale") || ! said ("{0} clip slot(s) launch") || ! said ("Clip scales"))
  7986. rollup030Result = "ERROR clip slots";
  7987. else if (! said ("Voice Shift's Measured law") || ! said ("Ridge Strip's 4K Pink EQ") || ! said ("Hush De-esser's Allround mode")
  7988. || parsed["mixer"][1]["effects"][0]["params"].size() > lynx::voiceshift::revision
  7989. || parsed["mixer"][3]["effects"][0]["params"].size() > lynx::mixsuite::hush::timing)
  7990. rollup030Result = "ERROR effects";
  7991. else if (copy.json.contains ("mixSnapshots") || ! said ("Mix snapshots") || ! said ("Automation clip colours")
  7992. || std::any_of (back->automations.begin(), back->automations.end(), [] (const lynx::Automation& a) { return a.colour != 0; }))
  7993. rollup030Result = "ERROR view items";
  7994. else if (! wtEmpty || ! said ("Helix is not in this release"))
  7995. rollup030Result = "ERROR Helix channel";
  7996. else if (! said ("Echoform's echo voicings") || ! said ("Epoch Verb, Atrium, Foil Plate and Halo") || ! said ("Lattice Mod plays")
  7997. || ! said ("LuxeVerb's Space ducking")
  7998. || parsed["mixer"][4]["effects"][0]["params"].size() > lynx::echosuite::echoform::revision
  7999. || parsed["mixer"][5]["effects"][0]["params"].size() > lynx::verbs::halo::revision
  8000. || parsed["mixer"][6]["effects"][0]["params"].size() > lynx::echosuite::lattice::revision
  8001. || parsed["mixer"][7]["effects"][0]["params"].size() > lynx::luxeVerbSpaceDucking)
  8002. rollup030Result = "ERROR step-3 effects";
  8003. else if (! loopKnob || ! said ("Texture and Complex Pro play") || ! said ("Complex Pro and Texture transpositions") || ! said ("Warped samples do not follow"))
  8004. rollup030Result = juce::String ("ERROR warp engines ") + (loopKnob ? "" : "knob ") + (said ("Texture and Complex Pro play") ? "" : "engines ")
  8005. + (said ("Complex Pro and Texture transpositions") ? "" : "transpose ") + (said ("Warped samples do not follow") ? "" : "tempo");
  8006. else if (copy.json.contains ("\"inactive\"") || ! said ("{0} deactivated clip slot(s)"))
  8007. rollup030Result = "ERROR deactivated slots";
  8008. else if (! said ("Facet EQ's automatic dynamic thresholds") || parsed["mixer"][8]["effects"][0]["params"].size() > lynx::facet::autoThresholdParam0)
  8009. rollup030Result = "ERROR Facet automatic threshold";
  8010. else if (! said ("MIDI Out channels and plugins' MIDI output") || ! said ("Automation of hosted CLAP and VST3 plugins"))
  8011. rollup030Result = juce::String ("ERROR engine notes ") + (said ("MIDI Out channels") ? "" : "midi-out ") + (said ("Automation of hosted") ? "" : "timed");
  8012. else if (copy.json.contains ("playlistTrackNest") || copy.json.contains ("displayView") || ! said ("{0} track(s) in nested Playlist folders")
  8013. || ! said ("Fruity Limiter's CURVE view"))
  8014. rollup030Result = "ERROR step-4 view items";
  8015. else if (! said ("Hush De-esser's Single Vocal mode") || ! said ("Slide notes on FL's native generators"))
  8016. rollup030Result = juce::String ("ERROR step-5 engine notes ") + (said ("Hush De-esser's Single Vocal") ? "" : "hush ") + (said ("Slide notes") ? "" : "slides");
  8017. else if (! said ("The crossfader (Live's Crossfade Assign)") || ! said ("Live return tracks show") || ! said ("The Simple Controls tab's")
  8018. || copy.json.contains ("\"crossfade") || copy.json.contains ("liveReturn") || copy.json.contains ("returnPre")
  8019. || copy.json.contains ("smartControls") || copy.json.contains ("engineRev"))
  8020. rollup030Result = "ERROR step-6 mixer items";
  8021. else if (const auto nts = [&parsed] {
  8022. juce::MemoryOutputStream bytes;
  8023. std::vector<std::uint8_t> st;
  8024. if (juce::Base64::convertFromBase64 (bytes, parsed["mixer"][14]["effects"][0]["state"].toString()))
  8025. st.assign (static_cast<const std::uint8_t*> (bytes.getData()), static_cast<const std::uint8_t*> (bytes.getData()) + bytes.getDataSize());
  8026. return st;
  8027. }();
  8028. ! said ("Newtone's detected key") || lynx::newtonefx::nativeVersionOf (nts) != 2 || ! lynx::newtonefx::parseNative (nts)
  8029. || lynx::newtonefx::parseNative (nts)->pitches.size() != 1 || lynx::newtonefx::parseNative (nts)->pitches[0].curEnd != 24000)
  8030. rollup030Result = "ERROR step-6 Newtone state";
  8031. else if (! said ("The Peak Controller's LYNX LFO shapes") || ! said ("Crest Compressor's console law") || ! said ("Mixer lock states")
  8032. || ! said ("{0} imported take lane(s)")
  8033. || parsed["mixer"][15]["effects"][0]["params"].size() > lynx::peakshapes::extraShapeParam
  8034. || parsed["mixer"][16]["effects"][0]["params"].size() > lynx::dyn::crest::busLaw
  8035. || copy.json.contains ("lockState") || copy.json.contains ("playlistTakeLanes") || copy.json.contains ("recordOwnNotes"))
  8036. rollup030Result = "ERROR step-7 items";
  8037. else if (const Spread16 m16 { parsed, spread16 };
  8038. ! said ("Crest Compressor's styles play their earlier laws") || ! said ("Crest Compressor's FET law")
  8039. || ! said ("Ridge Strip's measured SSL 4K G / 4K E filters") || ! said ("Echoform's Timeless 3 line law")
  8040. || ! said ("Lock states of effect slots and Playlist tracks") || copy.json.contains ("playlistTrackSoloLocks")
  8041. || m16[1]["params"].size() > lynx::dyn::crest::busLaw || m16[2]["params"].size() > lynx::dyn::crest::busLaw
  8042. || m16[3]["params"].size() > lynx::mixsuite::ridge::k4Pink || m16[4]["params"].size() > lynx::echosuite::echoform::revision)
  8043. rollup030Result = "ERROR step-8 items";
  8044. else if (const Spread16 m16 { parsed, spread16 };
  8045. ! said ("Ember's Saturn styles") || ! said ("Prism Multiband's Pro-MB band law") || ! said ("The Limiter's L2 law")
  8046. || ! said ("Glow Leveler's cell law") || ! said ("Reeverb 2's measured direct sound") || ! said ("Quell's zero law")
  8047. || ! said ("Facet EQ's all-pass dispersion") || ! said ("Echoform's H-Delay loop law")
  8048. || ! said ("Notes on audio clip channels play cut") || copy.json.contains ("clipNotes190lq") || copy.json.contains ("clipNoteLegacy")
  8049. || m16[5]["params"].size() > lynx::mixsuite::ember::revision || m16[6]["params"].size() > lynx::dyn::prism::revision
  8050. || m16[7]["params"].size() > lynx::limiterlaw::lawParam || m16[8]["params"].size() > lynx::mixsuite::glow::cellLaw
  8051. || m16[9]["params"].size() > lynx::reeverb2DirectLaw || m16[10]["params"].size() > lynx::voicetools::quell::zeroLaw
  8052. || m16[11]["params"].size() > lynx::facet::autoThresholdParam0 || m16[12]["params"].size() > lynx::echosuite::echoform::revision)
  8053. rollup030Result = "ERROR step-9 items";
  8054. else if (const Spread16 m16 { parsed, spread16 };
  8055. ! said ("Apex Limiter's styles") || ! said ("Sentry Gate plays its earlier") || ! said ("LuxeVerb's Space engine plays")
  8056. || ! said ("Echoform's ValhallaDelay loop law") || ! said ("Spiral Echo's Measured loop") || ! said ("{0} scene follow action")
  8057. || m16[13]["params"].size() > lynx::apex::pRevision || m16[14]["params"].size() > (int) lynx::dyn::sentry::revision
  8058. || m16[15]["params"].size() > lynx::luxeVerbSpaceDucking || m16[16]["params"].size() > lynx::echosuite::echoform::revision
  8059. || m16[17]["params"].size() > (int) lynx::echosuite::spiral::rateLaw || parsed["clipGrid"]["scenes"][0].hasProperty ("follow"))
  8060. rollup030Result = "ERROR step-10 items";
  8061. else if (const Spread16 m16 { parsed, spread16 };
  8062. ! said ("Horizon plays its earlier") || ! said ("Nebula's classic modes") || ! said ("Orbit plays its own voices")
  8063. || ! said ("Prism Multiband's C4 law") || ! said ("Compressor's Renaissance law") || ! said ("Quell's NS1 law")
  8064. || ! said ("Gemini Doubler's splice law") || ! said ("LYNX Tune's Waves Tune") || ! said ("Facet EQ's PuigTec law")
  8065. || ! said ("{0} note(s) play once instead of repeating")
  8066. || m16[18]["params"].size() > lynx::verbs::horizon::revision || m16[19]["params"].size() > lynx::verbs::nebula::toneLaw
  8067. || m16[20]["params"].size() > (int) lynx::echosuite::orbit::smLaw || m16[21]["params"].size() > (int) lynx::dyn::prism::revision
  8068. || m16[22]["params"].size() > lynx::compressorRenLaw || m16[23]["params"].size() > (int) lynx::voicetools::quell::zeroLaw
  8069. || m16[24]["params"].size() > (int) lynx::voicetools::gemini::spliceLaw || m16[25]["params"].size() > (int) lynx::lynxtune::wavesLaw
  8070. || m16[26]["params"].size() > lynx::facet::autoThresholdParam0)
  8071. rollup030Result = "ERROR step-11 items";
  8072. else if (const Spread16 m16 { parsed, spread16 };
  8073. ! said ("Facet EQ's Waves design law") || ! said ("Compressor's Vox law") || ! said ("Compressor's bus law")
  8074. || ! said ("Compressor's channel EQ") || ! said ("Prism Multiband's floating bands") || ! said ("Hush De-esser's Renaissance law")
  8075. || ! said ("Low Lifter's bass law") || ! said ("Aether's Vitamin law") || ! said ("Ridge Strip's omni law")
  8076. || ! said ("Fruity Multiband Compressor's display SPEED") || ! said ("{0} zipped channel(s)")
  8077. || m16[27]["params"].size() > lynx::facet::autoThresholdParam0 || m16[28]["params"].size() > lynx::compressorRenLaw
  8078. || m16[29]["params"].size() > lynx::compressorRenLaw || m16[30]["params"].size() > lynx::compressorRenLaw
  8079. || m16[31]["params"].size() > (int) lynx::dyn::prism::revision || m16[32]["params"].size() > (int) lynx::mixsuite::hush::timing
  8080. || m16[33]["params"].size() > (int) lynx::lowlifter::bassLaw || m16[34]["params"].size() > (int) lynx::mixsuite::aether::vitLaw
  8081. || m16[35]["params"].size() > (int) lynx::mixsuite::ridge::k4Pink || m16[36].hasProperty ("displayView")
  8082. || copy.json.contains ("\"zipped\""))
  8083. rollup030Result = "ERROR step-12 items";
  8084. else if (const Spread16 m16 { parsed, spread16 };
  8085. ! said ("Facet EQ's API-560 law") || ! said ("Compressor's RVox type") || ! said ("Compressor's gate")
  8086. || ! said ("Ridge Strip's G-Channel EQ law") || ! said ("The Current mixer track shows as an ordinary insert")
  8087. || m16[37]["params"].size() > lynx::facet::autoThresholdParam0 || m16[38]["params"].size() > lynx::compressorRenLaw
  8088. || m16[39]["params"].size() > (int) lynx::mixsuite::ridge::k4Pink || currentAt < 0
  8089. || parsed["mixer"][currentAt].hasProperty ("current") || parsed["mixer"][currentAt]["effects"].size() != 1)
  8090. rollup030Result = "ERROR step-13 items";
  8091. else if (const auto laid = lynx::olderlynx::forRelease (lynx::ProjectFile::withWindowLayout (lynx::ProjectFile::toJson (lynx::Song::makeDefault()),
  8092. { 0, "rollup step 13" }), "0.1.28");
  8093. ! laid.ok || laid.json.contains ("windowLayout")
  8094. || std::none_of (laid.lost.begin(), laid.lost.end(), [] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith ("The window layout saved"); }))
  8095. rollup030Result = "ERROR step-13 window layout";
  8096. else if (const Spread16 m16 { parsed, spread16 };
  8097. ! said ("Effector's Kilohearts laws") || ! said ("Launched pattern clips play without their pattern's events")
  8098. || m16[40]["params"].size() > lynx::khsdsp::lawParam || parsed["patterns"][0]["events"].size() != 1)
  8099. rollup030Result = juce::String ("ERROR step-14 items (") + (said ("Effector's Kilohearts laws") ? "" : "no Kilohearts line, ")
  8100. + (said ("Launched pattern clips play without their pattern's events") ? "" : "no launched-clip line, ")
  8101. + "Effector params " + juce::String (m16[40]["params"].size()) + ", events " + juce::String (parsed["patterns"][0]["events"].size()) + ")";
  8102. else if (const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.28");
  8103. ! plain.ok || std::any_of (plain.lost.begin(), plain.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  8104. const auto t = juce::String (l.text);
  8105. return t.startsWith ("Tetra") || t.contains ("MPE") || t.contains ("Pattern Block") || t.contains ("Voice Shift")
  8106. || t.contains ("Ridge") || t.contains ("Hush") || t.startsWith ("Automation clip colours") || t.startsWith ("Mix snapshots")
  8107. || t.startsWith ("Helix") || t.contains ("Echoform") || t.contains ("Halo") || t.contains ("Lattice") || t.contains ("LuxeVerb")
  8108. || t.contains ("Texture") || t.contains ("Beats'") || t.startsWith ("Warped") || t.contains ("deactivated")
  8109. || t.contains ("Facet") || t.contains ("MIDI Out") || t.contains ("hosted CLAP") || t.contains ("nested Playlist")
  8110. || t.contains ("CURVE") || t.startsWith ("Slide notes") || t.contains ("crossfader") || t.contains ("return tracks")
  8111. || t.contains ("Controls tab") || t.startsWith ("Harmor") || t.startsWith ("Newtone")
  8112. || t.contains ("Peak Controller") || t.contains ("console law") || t.startsWith ("Mixer lock") || t.contains ("take lane")
  8113. || t.contains ("Crest") || t.startsWith ("Lock states") || t.startsWith ("Ember") || t.startsWith ("Prism")
  8114. || t.contains ("L2 law") || t.startsWith ("Glow") || t.startsWith ("Reeverb 2") || t.startsWith ("Quell")
  8115. || t.contains ("audio clip channels") || t.startsWith ("Apex") || t.startsWith ("Sentry") || t.startsWith ("Spiral")
  8116. || t.contains ("scene follow") || t.startsWith ("Horizon") || t.startsWith ("Nebula") || t.startsWith ("Orbit")
  8117. || t.startsWith ("Compressor's") || t.startsWith ("Gemini") || t.startsWith ("LYNX Tune") || t.contains ("Repeat")
  8118. || t.startsWith ("Low Lifter") || t.startsWith ("Aether") || t.startsWith ("Ridge Strip's omni") || t.startsWith ("Hush De-esser's Renaissance")
  8119. || t.startsWith ("Fruity Multiband") || t.contains ("zipped") || t.contains ("Current mixer track") || t.contains ("window layout")
  8120. || t.startsWith ("Effector's Kilohearts") || t.startsWith ("Launched pattern clips");
  8121. }))
  8122. rollup030Result = "ERROR a plain project reports a loss it does not have";
  8123. }
  8124. // rollup 0.1.31 step 1 (round 190no): File › "Save a copy for an older LYNX" for 0.1.30 drops or converts what the
  8125. // 0.1.31 rounds save (190ni LYNX Model, 190nh Kilohearts part-2 laws, 190ne track clips, 190nc Solo / Cue); round
  8126. // 190nb's laws (0.1.30 has them) stay; the copy for 0.1.28 runs this step first; a plain project loses nothing
  8127. juce::String rollup031Result = "OK";
  8128. {
  8129. auto song = lynx::Song::makeDefault();
  8130. lynx::ChannelDef model;
  8131. model.name = "Bars";
  8132. model.instrument = lynx::InstrumentKind::lynxModel;
  8133. model.modelParams = { 0.0f, 0.5f, 0.3f };
  8134. song.channels.push_back (model);
  8135. auto comb = lynx::makeEffectSlot (lynx::EffectKind::effector);
  8136. comb.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::comb);
  8137. comb.params[(std::size_t) lynx::khsdsp::valueParam] = 0.4f;
  8138. auto resonator = lynx::makeEffectSlot (lynx::EffectKind::effector);
  8139. resonator.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::resonator);
  8140. resonator.params[(std::size_t) lynx::khsdsp::valueParam] = 0.5f;
  8141. song.mixer[3].effects.push_back (comb); // [0]
  8142. song.mixer[3].effects.push_back (resonator); // [1]
  8143. song.patterns[0].trackClip = true;
  8144. if (song.playlistTracks.empty())
  8145. song.playlistTracks.resize (1);
  8146. song.playlistTracks[0].ownClips = true;
  8147. lynx::launcher::ensureGrid (song);
  8148. song.clipGrid->cue.cueMode = true;
  8149. song.clipGrid->cue.out = 2;
  8150. song.mixer[2].cue = true;
  8151. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  8152. const auto older = lynx::olderlynx::forRelease (song, "0.1.28");
  8153. juce::String why;
  8154. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  8155. const auto count = [] (const lynx::olderlynx::Copy& c, const char* start) {
  8156. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  8157. };
  8158. const auto parsed = juce::JSON::parse (copy.json);
  8159. const auto& fx = parsed["mixer"][3]["effects"];
  8160. juce::String bars;
  8161. if (const auto* channels = parsed["channels"].getArray())
  8162. for (const auto& c : *channels)
  8163. if (c["name"].toString() == "Bars")
  8164. bars = c["instrument"].toString() + (c.hasProperty ("modelParams") ? "+params" : "");
  8165. const char* lines[] = { "LYNX Model is not in this release", "Effector's newer Kilohearts laws", "{0} track clip(s) show as ordinary patterns",
  8166. "Live's Solo/Cue settings" };
  8167. if (! copy.ok || ! back)
  8168. rollup031Result = "ERROR copy " + copy.error + why;
  8169. else if (! parsed["savedBy"].toString().equalsIgnoreCase ("0.1.30") || lynx::olderlynx::releases()[1] != "0.1.30") // (rollup 0.1.32: 0.1.31 is [0])
  8170. rollup031Result = "ERROR release list / stamp";
  8171. else if (bars != "sampler")
  8172. rollup031Result = "ERROR LYNX Model channel: " + bars;
  8173. else if (fx[0]["params"].size() > lynx::khsdsp::lawParam || fx[1]["params"].size() <= lynx::khsdsp::lawParam
  8174. || lynx::khsdsp::lawOf ((float) (double) fx[1]["params"][lynx::khsdsp::lawParam]) != lynx::khsdsp::Law::resonator)
  8175. rollup031Result = "ERROR Kilohearts laws (comb params " + juce::String (fx[0]["params"].size()) + ")";
  8176. else if (copy.json.contains ("\"trackClip\"") || copy.json.contains ("playlistOwnClips") || parsed["clipGrid"].hasProperty ("cue")
  8177. || parsed["mixer"][2].hasProperty ("cue"))
  8178. rollup031Result = "ERROR 0.1.31 keys left in the copy";
  8179. else if (std::any_of (std::begin (lines), std::end (lines), [&] (const char* l) { return count (copy, l) != 1 || count (older, l) != 1; }))
  8180. rollup031Result = "ERROR loss lines (each once, in both copies)";
  8181. else if (! older.ok || older.json.contains ("lynxmodel") || juce::JSON::parse (older.json)["mixer"][3]["effects"][1]["params"].size() > lynx::khsdsp::lawParam
  8182. || count (older, "Effector's Kilohearts laws") != 1)
  8183. rollup031Result = "ERROR copy for 0.1.28 after the 0.1.30 step";
  8184. else if (const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30"); ! plain.ok || ! plain.lost.empty())
  8185. rollup031Result = "ERROR a plain project loses something in the copy for 0.1.30";
  8186. }
  8187. // rollup 0.1.31 step 2 (round 190nv): what the step's rounds save needs nothing in the copies for 0.1.30 / 0.1.28 —
  8188. // 190ns's Created date (#231, ProjectInfo.created: 0.1.30 reads it), its linked audio track ⇄ insert names and
  8189. // colours (#235: the same mixerTrack / name / colour fields; only the syncing is new), 190nq's "(target deleted)"
  8190. // automation names (#226: text) — and 190np's onboarding, 190nq's ruler / fade switches and 190nr's installed-files
  8191. // list live in the profile, never in a project. Checked: the copy keeps them, reports no loss and has every key of
  8192. // the project (the copy keeps every key the project has, none dropped or renamed)
  8193. juce::String rollup031s2Result = "OK";
  8194. {
  8195. auto song = lynx::Song::makeDefault();
  8196. song.info.created = 1763600000.0;
  8197. if (song.mixer.size() < 3)
  8198. song.mixer.resize (3);
  8199. song.playlistTracks.resize (std::max<std::size_t> (2, song.playlistTracks.size()));
  8200. auto& vox = song.playlistTracks[1];
  8201. vox.mode = lynx::PlaylistTrackMode::audio;
  8202. vox.mixerTrack = 2;
  8203. vox.name = song.mixer[2].name = "Vox";
  8204. vox.colour = song.mixer[2].colour = 0xff8040c0;
  8205. song.patterns[0].name = lynx::mixerops::targetDeletedName ("BEAT BUS - Send level");
  8206. const auto keysOf = [] (const juce::var& v) {
  8207. std::set<juce::String> keys;
  8208. std::function<void (const juce::var&, const juce::String&)> walk = [&] (const juce::var& x, const juce::String& path) {
  8209. if (auto* o = x.getDynamicObject())
  8210. for (const auto& p : o->getProperties())
  8211. {
  8212. if (path.isEmpty() && (p.name.toString() == "savedBy" || p.name.toString() == "copiedFrom")) // (the copy's stamp)
  8213. continue;
  8214. keys.insert (path + "/" + p.name.toString());
  8215. walk (p.value, path + "/" + p.name.toString());
  8216. }
  8217. else if (auto* a = x.getArray())
  8218. for (const auto& e : *a)
  8219. walk (e, path + "[]");
  8220. };
  8221. walk (v, {});
  8222. return keys;
  8223. };
  8224. const auto original = juce::JSON::parse (lynx::ProjectFile::toJson (song));
  8225. for (const auto* release : { "0.1.30", "0.1.28" })
  8226. {
  8227. const auto copy = lynx::olderlynx::forRelease (song, release);
  8228. juce::String why;
  8229. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  8230. if (! copy.ok || ! back)
  8231. rollup031s2Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  8232. else if (back->info.created != song.info.created)
  8233. rollup031s2Result = juce::String ("ERROR Created date in the copy for ") + release;
  8234. else if (back->playlistTracks.size() < 2 || back->playlistTracks[1].mixerTrack != 2 || back->playlistTracks[1].colour != vox.colour
  8235. || back->playlistTracks[1].name != "Vox" || back->mixer[2].colour != vox.colour || back->mixer[2].name != "Vox")
  8236. rollup031s2Result = juce::String ("ERROR linked track / insert in the copy for ") + release;
  8237. else if (back->patterns[0].name != song.patterns[0].name)
  8238. rollup031s2Result = juce::String ("ERROR automation name in the copy for ") + release;
  8239. else if (! copy.lost.empty())
  8240. rollup031s2Result = juce::String ("ERROR loss lines in the copy for ") + release + ": " + juce::String (copy.lost.front().text);
  8241. else if (const auto kept = keysOf (juce::JSON::parse (copy.json)), all = keysOf (original); juce::String (release) == "0.1.30" && kept != all)
  8242. {
  8243. juce::StringArray diff;
  8244. for (const auto& k : all)
  8245. if (kept.count (k) == 0)
  8246. diff.add ("-" + k);
  8247. for (const auto& k : kept)
  8248. if (all.count (k) == 0)
  8249. diff.add ("+" + k);
  8250. rollup031s2Result = "ERROR keys differ in the copy for 0.1.30: " + diff.joinIntoString (" ").substring (0, 300);
  8251. }
  8252. if (rollup031s2Result != "OK")
  8253. break;
  8254. }
  8255. }
  8256. // rollup 0.1.31 step 3 (round 190ny): the copies for 0.1.30 / 0.1.28 drop what this step's rounds save and nothing
  8257. // else — 190nu's key markers' keys ("markerKeys" beside each pattern's marker list; the markers and their names
  8258. // stay) and 190nw's tracker view settings (root "tracker"; the notes are the patterns' own) — each with its one
  8259. // line, in both copies; 190nx (offline switch, --demo) and 190nt (site) save nothing in a project
  8260. juce::String rollup031s3Result = "OK";
  8261. {
  8262. using namespace lynx::keyregions;
  8263. auto song = lynx::Song::makeDefault();
  8264. auto& p = song.patterns[(std::size_t) song.currentPattern];
  8265. p.markers.push_back ({ 2 * lynx::ppq, "Verse", 0, 4 });
  8266. addKeyMarker (p, 0, { State::key, { 9, flScaleNamed ("Minor Harmonic") } });
  8267. addKeyMarker (p, 4 * lynx::ppq, { State::key, { 2, flScaleNamed ("Other Dorian") } });
  8268. for (int c = 0; c < 2; ++c)
  8269. song.channels.emplace_back().name = "S3-" + std::to_string (c);
  8270. lynx::uids::normalize (song);
  8271. song.tracker.rowsPerBeat = 6;
  8272. song.tracker.showPan = true;
  8273. song.tracker.groups.push_back ({ "Pair", { song.channels[song.channels.size() - 2].uid, song.channels.back().uid } });
  8274. const auto keysOf = [] (const juce::var& v) {
  8275. std::set<juce::String> keys;
  8276. std::function<void (const juce::var&, const juce::String&)> walk = [&] (const juce::var& x, const juce::String& path) {
  8277. if (auto* o = x.getDynamicObject())
  8278. for (const auto& prop : o->getProperties())
  8279. {
  8280. if (path.isEmpty() && (prop.name.toString() == "savedBy" || prop.name.toString() == "copiedFrom")) // (the copy's stamp)
  8281. continue;
  8282. keys.insert (path + "/" + prop.name.toString());
  8283. walk (prop.value, path + "/" + prop.name.toString());
  8284. }
  8285. else if (auto* a = x.getArray())
  8286. for (const auto& e : *a)
  8287. walk (e, path + "[]");
  8288. };
  8289. walk (v, {});
  8290. return keys;
  8291. };
  8292. const auto json = lynx::ProjectFile::toJson (song);
  8293. auto expected = keysOf (juce::JSON::parse (json));
  8294. for (auto it = expected.begin(); it != expected.end();)
  8295. it = it->startsWith ("/tracker") || it->contains ("/markerKeys") ? expected.erase (it) : std::next (it);
  8296. const char* lines[] = { "key marker(s) in the Piano roll", "The tracker's view settings" };
  8297. for (const auto* release : { "0.1.30", "0.1.28" })
  8298. {
  8299. const auto copy = lynx::olderlynx::forRelease (song, release);
  8300. juce::String why;
  8301. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  8302. const auto count = [&copy] (const char* l) {
  8303. return (int) std::count_if (copy.lost.begin(), copy.lost.end(), [l] (const lynx::olderlynx::Loss& x) { return juce::String (x.text).contains (l); });
  8304. };
  8305. if (! copy.ok || ! back)
  8306. rollup031s3Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  8307. else if (copy.json.contains ("markerKeys") || copy.json.contains ("\"tracker\""))
  8308. rollup031s3Result = juce::String ("ERROR 0.1.31 keys left in the copy for ") + release;
  8309. else if (std::any_of (std::begin (lines), std::end (lines), [&] (const char* l) { return count (l) != 1; }))
  8310. rollup031s3Result = juce::String ("ERROR loss lines in the copy for ") + release + " (" + juce::String ((int) copy.lost.size()) + ")";
  8311. else if (const auto& bp = back->patterns[(std::size_t) back->currentPattern];
  8312. bp.markers.size() != p.markers.size() || bp.notes != p.notes
  8313. || std::any_of (bp.markers.begin(), bp.markers.end(), [] (const lynx::Marker& m) { return keyOf (m).has_value(); }))
  8314. rollup031s3Result = juce::String ("ERROR markers / notes in the copy for ") + release;
  8315. else if (juce::String (release) == "0.1.30" && (copy.lost.size() != 2 || keysOf (juce::JSON::parse (copy.json)) != expected))
  8316. rollup031s3Result = "ERROR the copy for 0.1.30 drops more than the two (" + juce::String ((int) copy.lost.size()) + " lines)";
  8317. if (rollup031s3Result != "OK")
  8318. break;
  8319. }
  8320. }
  8321. // round chord2_190nu (discussion #105): the Piano roll's key markers come back from a project (their keys beside the
  8322. // marker list, so older releases keep the markers), the copy for 0.1.30 / 0.1.28 drops the keys with a line, and
  8323. // a MIDI file carries them as key signatures (with the exact scale in a "Key: ..." marker meta event)
  8324. juce::String keys190nuResult = "OK";
  8325. {
  8326. using namespace lynx::keyregions;
  8327. auto song = lynx::Song::makeDefault();
  8328. auto& p = song.patterns[(std::size_t) song.currentPattern];
  8329. const auto bar = 4 * lynx::ppq;
  8330. const lynx::projectkey::Key dorian { 2, flScaleNamed ("Other Dorian") }, harmonic { 0, flScaleNamed ("Minor Harmonic") };
  8331. p.markers.push_back ({ bar / 2, "Verse", 0, 4 });
  8332. addKeyMarker (p, 0, { State::key, dorian });
  8333. addKeyMarker (p, bar, { State::key, harmonic });
  8334. addKeyMarker (p, 2 * bar, { State::none, {} });
  8335. lynx::Note n;
  8336. n.key = 62;
  8337. n.length = lynx::ppq;
  8338. p.notes.push_back (n);
  8339. p.lengthTicks = 3 * bar; // (a MIDI file gets the key changes within the pattern's length)
  8340. juce::String why;
  8341. const auto json = lynx::ProjectFile::toJson (song);
  8342. const auto back = lynx::ProjectFile::fromJson (json, why);
  8343. bool oldShape = true; // (every marker array as 0.1.30 reads it: 4 or 5 items)
  8344. const auto parsedJson = juce::JSON::parse (json); // (kept: operator[] refers into it)
  8345. if (auto* patterns = parsedJson["patterns"].getArray())
  8346. for (const auto& pv : *patterns)
  8347. if (auto* ms = pv["markers"].getArray())
  8348. for (const auto& m : *ms)
  8349. oldShape = oldShape && m.isArray() && (m.size() == 4 || m.size() == 5);
  8350. const auto for130 = lynx::olderlynx::forRelease (song, "0.1.30");
  8351. const auto for128 = lynx::olderlynx::forRelease (song, "0.1.28");
  8352. const auto copy130 = for130.ok ? lynx::ProjectFile::fromJson (for130.json, why) : std::optional<lynx::Song> {};
  8353. const auto said = std::any_of (for130.lost.begin(), for130.lost.end(), [] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains ("key marker(s)"); });
  8354. const auto file = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-keys190nu.mid");
  8355. juce::String midiError;
  8356. const auto saved = lynx::MidiFileIo::savePattern (song, song.currentPattern, file, midiError);
  8357. const auto parsed = saved ? lynx::MidiFileIo::parseFile (file, midiError) : std::nullopt;
  8358. const auto loaded = saved ? lynx::MidiFileIo::loadSong (file, midiError) : std::nullopt;
  8359. file.deleteFile();
  8360. const auto& bp = back ? back->patterns[(std::size_t) back->currentPattern] : p;
  8361. if (! back || bp.markers != p.markers)
  8362. keys190nuResult = "ERROR project round trip " + why;
  8363. else if (! oldShape)
  8364. keys190nuResult = "ERROR marker arrays an older release skips";
  8365. else if (! copy130 || for130.json.contains ("markerKeys") || ! said || ! for128.ok || for128.json.contains ("markerKeys"))
  8366. keys190nuResult = "ERROR copy for 0.1.30 / 0.1.28";
  8367. else if (const auto& cp = copy130->patterns[(std::size_t) copy130->currentPattern];
  8368. cp.markers.size() != 4 || cp.markers[0].name != "D Other Dorian" || cp.markers[0].action != lynx::Marker::keyScale || keyOf (cp.markers[0]))
  8369. keys190nuResult = "ERROR the copy's markers";
  8370. else if (! parsed || parsed->keys.size() != 2 || parsed->keys[0].tick != 0 || parsed->keys[0].flScale != dorian.flScale || parsed->keys[0].root != 2
  8371. || parsed->keys[1].tick != bar || parsed->keys[1].flScale != harmonic.flScale)
  8372. keys190nuResult = "ERROR MIDI key signatures " + midiError;
  8373. else if (! loaded || ! (lynx::projectkey::get (*loaded) == dorian) || ! (stateAt (loaded->patterns[0], bar).value == harmonic))
  8374. keys190nuResult = "ERROR MIDI file opened as a project " + midiError;
  8375. }
  8376. // round 190oc: the copy for 0.1.30 cuts Helix round 4's block (revision 4 back to 3; a loss line only when a unison
  8377. // or reverse grains play) and the Kilohearts Nonlinear Filter law (code 49, its own loss line); the copy for 0.1.28
  8378. // still turns Helix into an empty Sampler after it; a Helix channel of revision 4 at the block's defaults loses nothing
  8379. juce::String helix4khs190ocResult = "OK";
  8380. {
  8381. auto song = lynx::Song::makeDefault();
  8382. if (song.mixer.size() < 3)
  8383. song.mixer.resize (3);
  8384. lynx::ChannelDef plain, swarm;
  8385. plain.name = "Plain", swarm.name = "Swarm";
  8386. plain.instrument = swarm.instrument = lynx::InstrumentKind::helix;
  8387. const auto d = lynx::helixDefaults();
  8388. plain.modelParams = swarm.modelParams = d;
  8389. swarm.modelParams[(std::size_t) (lynx::wt::ext4Base + lynx::wt::ext4::grainUnison)] = 5.0f;
  8390. swarm.modelParams[(std::size_t) (lynx::wt::ext4Base + lynx::wt::ext4::grainReverse)] = 0.4f;
  8391. song.channels.push_back (plain);
  8392. song.channels.push_back (swarm);
  8393. auto nlf = lynx::makeEffectSlot (lynx::EffectKind::effector);
  8394. nlf.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::nonlinearFilter);
  8395. nlf.params[(std::size_t) lynx::khsdsp::valueParam + 2] = 0.5f;
  8396. song.mixer[2].effects.push_back (nlf);
  8397. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  8398. const auto older = lynx::olderlynx::forRelease (song, "0.1.28");
  8399. const auto count = [] (const lynx::olderlynx::Copy& c, const char* start) {
  8400. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  8401. };
  8402. const auto parsed = juce::JSON::parse (copy.json);
  8403. int helixCut = 0, revisions3 = 0;
  8404. juce::String lossDetail;
  8405. for (const auto& l : copy.lost)
  8406. if (juce::String (l.text).startsWith ("Helix's unison"))
  8407. lossDetail = l.detail;
  8408. if (const auto* channels = parsed["channels"].getArray())
  8409. for (const auto& c : *channels)
  8410. if (c["instrument"].toString() == "helix")
  8411. {
  8412. auto values = juce::StringArray::fromTokens (c["modelParams"].toString(), " ", "");
  8413. values.removeEmptyStrings();
  8414. helixCut += values.size() == lynx::wt::ext4Base ? 1 : 0;
  8415. revisions3 += values.size() > lynx::wt::extBase && values[lynx::wt::extBase].getFloatValue() == 3.0f ? 1 : 0;
  8416. }
  8417. if (! copy.ok || ! older.ok)
  8418. helix4khs190ocResult = "ERROR copy " + copy.error + older.error;
  8419. else if (helixCut != 2 || revisions3 != 2)
  8420. helix4khs190ocResult = "ERROR Helix block in the copy (cut " + juce::String (helixCut) + ", revision 3 " + juce::String (revisions3) + ")";
  8421. else if (count (copy, "Helix's unison") != 1 || ! lossDetail.contains ("Swarm") || lossDetail.contains ("Plain"))
  8422. helix4khs190ocResult = "ERROR Helix loss line: " + lossDetail;
  8423. else if (parsed["mixer"][2]["effects"][0]["params"].size() > lynx::khsdsp::lawParam || count (copy, "Effector's Kilohearts Nonlinear Filter") != 1
  8424. || count (copy, "Effector's newer Kilohearts laws") != 0)
  8425. helix4khs190ocResult = "ERROR Nonlinear Filter law in the copy";
  8426. else if (older.json.contains ("\"helix\"") || count (older, "Helix is not in this release") != 1)
  8427. helix4khs190ocResult = "ERROR copy for 0.1.28 after the 0.1.30 step";
  8428. }
  8429. // rollup 0.1.31 step 4 (round 190oi): the copies for 0.1.30 / 0.1.28 of a project with everything step 4 brought:
  8430. // 190oc's Helix round-4 block and Effector law 49 (each one line), 190od's slide of the note properties (#236: the
  8431. // key goes; one line counting only slide notes that move something), 190od's #239 colours and icons by name and a
  8432. // #238 "no colour" channel (ordinary project data: kept as they are), 190nz's clipboard (no project data), 190oa's
  8433. // main (monitor) volume and Gross Beat's scratch offset (merge 4; its window places are not in a copy: the copy is
  8434. // the song's JSON without the window layout). The 0.1.30 copy keeps every key but "slideNoteProps" and "mainVolume";
  8435. // a project whose slide notes move nothing, or saved before #236, gets no slide line
  8436. juce::String rollup031s4Result = "OK";
  8437. {
  8438. auto song = lynx::Song::makeDefault();
  8439. if (song.mixer.size() < 3)
  8440. song.mixer.resize (3);
  8441. song.slideNoteProps = true;
  8442. lynx::ChannelDef bass, lead, swarm, plain;
  8443. bass.name = "Bass 808", lead.name = "Lead", swarm.name = "Swarm", plain.name = "No colour";
  8444. swarm.instrument = lynx::InstrumentKind::helix;
  8445. swarm.modelParams = lynx::helixDefaults();
  8446. swarm.modelParams[(std::size_t) (lynx::wt::ext4Base + lynx::wt::ext4::specUnison)] = 4.0f;
  8447. for (auto* c : { &bass, &lead, &swarm, &plain })
  8448. song.channels.push_back (*c);
  8449. const int bassIndex = (int) song.channels.size() - 4, leadIndex = bassIndex + 1;
  8450. auto nlf = lynx::makeEffectSlot (lynx::EffectKind::effector);
  8451. nlf.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::nonlinearFilter);
  8452. song.mixer[2].effects.push_back (nlf);
  8453. // merge 4 (190oa): the toolbar's main (monitor) volume off 0 dB and Gross Beat's scratch offset set (DF-21, DP-8)
  8454. song.mainVolume = 0.5f;
  8455. auto gross = lynx::makeEffectSlot (lynx::EffectKind::grossBeat);
  8456. gross.params[8] = 0.25f;
  8457. song.mixer[2].effects.push_back (gross);
  8458. lynx::autolook::Rules rules;
  8459. rules.on = true;
  8460. rules.list.push_back ({ "bass", lynx::autolook::Match::contains, 0xFF2266AAu, 7, lynx::autolook::everything });
  8461. const auto coloured = lynx::autolook::applyAll (song, rules);
  8462. auto& p = song.patterns[(std::size_t) song.currentPattern];
  8463. const auto note = [] (int channel, juce::int64 start, int key, float velocity, float pan, bool slide) {
  8464. lynx::Note n;
  8465. n.channel = channel, n.start = start, n.length = lynx::ppq, n.key = key, n.velocity = velocity, n.pan = pan, n.slide = slide;
  8466. return n;
  8467. };
  8468. p.notes.push_back (note (bassIndex, 0, 36, 0.78f, 0.0f, false));
  8469. p.notes.push_back (note (bassIndex, lynx::ppq / 2, 43, 0.3f, 0.0f, true)); // moves the velocity
  8470. p.notes.push_back (note (bassIndex, lynx::ppq, 41, 0.78f, -0.5f, true)); // moves the pan
  8471. p.notes.push_back (note (leadIndex, 0, 60, 0.78f, 0.0f, false));
  8472. p.notes.push_back (note (leadIndex, lynx::ppq / 2, 64, 0.78f, 0.0f, true)); // pitch only: sounds the same in 0.1.30
  8473. p.sortNotes(); // (the order a project reads back in)
  8474. lynx::uids::normalize (song);
  8475. const auto keysOf = [] (const juce::var& v) {
  8476. std::set<juce::String> keys;
  8477. std::function<void (const juce::var&, const juce::String&)> walk = [&] (const juce::var& x, const juce::String& path) {
  8478. if (auto* o = x.getDynamicObject())
  8479. for (const auto& prop : o->getProperties())
  8480. {
  8481. if (path.isEmpty() && (prop.name.toString() == "savedBy" || prop.name.toString() == "copiedFrom"))
  8482. continue;
  8483. keys.insert (path + "/" + prop.name.toString());
  8484. walk (prop.value, path + "/" + prop.name.toString());
  8485. }
  8486. else if (auto* a = x.getArray())
  8487. for (const auto& e : *a)
  8488. walk (e, path + "[]");
  8489. };
  8490. walk (v, {});
  8491. return keys;
  8492. };
  8493. auto expected = keysOf (juce::JSON::parse (lynx::ProjectFile::toJson (song)));
  8494. const auto hadKey = expected.erase ("/slideNoteProps") == 1 && expected.erase ("/mainVolume") == 1;
  8495. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* start) {
  8496. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  8497. };
  8498. const char* slideLine = "{0} slide note(s) move only the pitch";
  8499. if (coloured != 1 || ! hadKey)
  8500. rollup031s4Result = "ERROR set-up (coloured " + juce::String (coloured) + ")";
  8501. for (const auto* release : { "0.1.30", "0.1.28" })
  8502. {
  8503. if (rollup031s4Result != "OK")
  8504. break;
  8505. const auto copy = lynx::olderlynx::forRelease (song, release);
  8506. juce::String why;
  8507. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  8508. juce::String slideDetail;
  8509. for (const auto& l : copy.lost)
  8510. if (juce::String (l.text).startsWith (slideLine))
  8511. slideDetail = l.detail;
  8512. const auto is130 = juce::String (release) == "0.1.30";
  8513. if (! copy.ok || ! back)
  8514. rollup031s4Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  8515. else if (copy.json.contains ("slideNoteProps") || back->slideNoteProps)
  8516. rollup031s4Result = juce::String ("ERROR slideNoteProps left in the copy for ") + release;
  8517. else if (countOf (copy, slideLine) != 1 || slideDetail != "2")
  8518. rollup031s4Result = juce::String ("ERROR the slide line in the copy for ") + release + " (" + slideDetail + ")";
  8519. else if (countOf (copy, "Effector's Kilohearts Nonlinear Filter") != 1 || (is130 && countOf (copy, "Helix's unison") != 1)
  8520. || (! is130 && countOf (copy, "Helix is not in this release") != 1))
  8521. rollup031s4Result = juce::String ("ERROR 190oc's lines in the copy for ") + release;
  8522. else if (countOf (copy, "The main (monitor) volume") != 1 || countOf (copy, "Gross Beat's scratch offset") != 1
  8523. || copy.json.contains ("mainVolume") || juce::JSON::parse (copy.json)["mixer"][2]["effects"][1]["params"].size() != 8)
  8524. rollup031s4Result = juce::String ("ERROR 190oa's main volume / Gross Beat offset in the copy for ") + release;
  8525. else if (back->patterns[(std::size_t) back->currentPattern].notes != p.notes)
  8526. rollup031s4Result = juce::String ("ERROR the notes in the copy for ") + release;
  8527. else if (back->channels[(std::size_t) bassIndex].colour != 0xFF2266AAu || back->channels[(std::size_t) bassIndex].icon != 7
  8528. || back->channels[(std::size_t) bassIndex + 3].colour != 0 || back->channels[(std::size_t) leadIndex].colour != song.channels[(std::size_t) leadIndex].colour)
  8529. rollup031s4Result = juce::String ("ERROR #239 / #238 colours in the copy for ") + release;
  8530. else if (is130 && (copy.lost.size() != 5 || keysOf (juce::JSON::parse (copy.json)) != expected))
  8531. rollup031s4Result = "ERROR the copy for 0.1.30 drops more than step 4's five (" + juce::String ((int) copy.lost.size()) + " lines)";
  8532. }
  8533. // slide notes that move nothing, and a project saved before #236 (key off): no slide line
  8534. if (rollup031s4Result == "OK")
  8535. {
  8536. auto still = song;
  8537. auto& sp = still.patterns[(std::size_t) still.currentPattern];
  8538. sp.notes.erase (std::remove_if (sp.notes.begin(), sp.notes.end(), [bassIndex] (const lynx::Note& n) { return n.slide && n.channel == bassIndex; }), sp.notes.end());
  8539. auto before = song;
  8540. before.slideNoteProps = false;
  8541. const auto a = lynx::olderlynx::forRelease (still, "0.1.30"), b = lynx::olderlynx::forRelease (before, "0.1.30");
  8542. if (! a.ok || ! b.ok || countOf (a, slideLine) != 0 || countOf (b, slideLine) != 0)
  8543. rollup031s4Result = "ERROR a slide line where nothing moves";
  8544. }
  8545. }
  8546. // rollup 0.1.31 step 5 (round 190or): Save a copy for 0.1.30 / 0.1.28 with everything step 5 saves. 190ol's sections
  8547. // (plain markers at their starts, one view line); 190ol's Simple time signature changes (ordinary signature markers
  8548. // 0.1.30 has: kept, n/1 and 7/8 included); 190oh's wrapper GUI flags on a channel's plugin and an insert's plugin (keys
  8549. // dropped, one view line naming both); gap190og's transport mappings (the Overdub key mapping dropped with a line,
  8550. // the Play one kept); 190ob's tracker volume automation (a channel Volume multiplier clip: kept point for point);
  8551. // 190on's stacked lanes and palette are profile settings and 190og's .flm export keeps no settings (the song is the
  8552. // same after an export). The 0.1.30 copy keeps every key but the three dropped ones and has exactly three lines
  8553. const auto autolinks190ovResult = runAutoLinks190ovCheck(); // round 190ov (src/AutoLinks190ovCheck.inc)
  8554. juce::String rollup031s5Result = "OK";
  8555. {
  8556. auto song = lynx::Song::makeDefault();
  8557. if (song.mixer.size() < 3)
  8558. song.mixer.resize (3);
  8559. // 190ol: two sections; Simple signature changes at the start (5/1, BandLab's n/1: the song's meter) and on bar 9 (7/8:
  8560. // a signature marker)
  8561. lynx::sections::add (song, "Intro");
  8562. lynx::sections::add (song, "Verse");
  8563. lynx::signatureedit::set (song, 0, 5, 1);
  8564. lynx::signatureedit::set (song, song.barAt (0).tick + 8 * 5 * lynx::ppq * 4, 7, 8);
  8565. std::vector<lynx::Marker> signatures;
  8566. for (const auto& m : song.markers())
  8567. if (m.isSignature())
  8568. signatures.push_back (m);
  8569. // 190oh: a plugin channel with DPI aware off, an insert plugin with Scale editor dimensions on
  8570. lynx::ChannelDef synth;
  8571. synth.name = "Old Synth";
  8572. synth.instrument = lynx::InstrumentKind::plugin;
  8573. synth.plugin.id = "VST3:old-synth";
  8574. synth.plugin.name = "Old Synth";
  8575. synth.plugin.dpiAware = false;
  8576. synth.smartDisable = true; // (merge 6, 190ok D2: dropped without a line)
  8577. song.channels.push_back (synth);
  8578. const auto synthIndex = (int) song.channels.size() - 1;
  8579. lynx::EffectSlot fx;
  8580. fx.kind = lynx::EffectKind::plugin;
  8581. fx.plugin.id = "VST3:tiny-eq";
  8582. fx.plugin.name = "Tiny EQ";
  8583. fx.plugin.scaleEditorDimensions = true;
  8584. song.mixer[2].effects.push_back (fx);
  8585. auto ember = lynx::makeEffectSlot (lynx::EffectKind::ember); // (merge 6, 190ok D3: engine revision 2 -> 1 in the copies)
  8586. song.mixer[2].effects.push_back (ember);
  8587. // gap190og: a key mapped to Arrangement Overdub (newer) and one to Play (0.1.30 has it)
  8588. lynx::RemoteMapping overdub, play;
  8589. overdub.source = play.source = lynx::RemoteMapping::Source::key;
  8590. overdub.key = 'O', overdub.action = lynx::RemoteAction::overdub;
  8591. play.key = 'P', play.action = lynx::RemoteAction::play;
  8592. song.remoteMappings = { overdub, play };
  8593. // 190ob: the tracker import's volume automation (the channel's Levels "Volume multiplier", 5000 = 100 %)
  8594. lynx::Automation volume;
  8595. volume.name = "Old Synth volume (ch 1)";
  8596. volume.target.kind = lynx::AutomationTargetKind::channelAdjust;
  8597. volume.target.index = synthIndex;
  8598. volume.target.param = lynx::leveladjust::volume;
  8599. volume.points = { { 0, 0.5f }, { lynx::ppq, 0.25f }, { 2 * lynx::ppq, 0.4f } };
  8600. song.automations.push_back (volume);
  8601. lynx::uids::normalize (song);
  8602. const auto json = lynx::ProjectFile::toJson (song);
  8603. const auto keysOf = [] (const juce::var& v) {
  8604. std::set<juce::String> keys;
  8605. std::function<void (const juce::var&, const juce::String&)> walk = [&] (const juce::var& x, const juce::String& path) {
  8606. if (auto* o = x.getDynamicObject())
  8607. for (const auto& prop : o->getProperties())
  8608. {
  8609. if (path.isEmpty() && (prop.name.toString() == "savedBy" || prop.name.toString() == "copiedFrom"))
  8610. continue;
  8611. keys.insert (path + "/" + prop.name.toString());
  8612. walk (prop.value, path + "/" + prop.name.toString());
  8613. }
  8614. else if (auto* a = x.getArray())
  8615. for (const auto& e : *a)
  8616. walk (e, path + "[]");
  8617. };
  8618. walk (v, {});
  8619. return keys;
  8620. };
  8621. auto expected = keysOf (juce::JSON::parse (json));
  8622. const auto hadKeys = expected.erase ("/arrangements[]/sections") == 1 && expected.erase ("/channels[]/plugin/dpiAware") == 1
  8623. && expected.erase ("/mixer[]/effects[]/plugin/scaleEditorDimensions") == 1 && expected.erase ("/channels[]/smartDisable") == 1;
  8624. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* start) {
  8625. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  8626. };
  8627. const auto detailOf = [] (const lynx::olderlynx::Copy& c, const char* start) {
  8628. for (const auto& l : c.lost)
  8629. if (juce::String (l.text).startsWith (start))
  8630. return juce::String (l.detail);
  8631. return juce::String();
  8632. };
  8633. if (! hadKeys || song.sections().size() != 2 || song.beatsPerBar != 5 || song.beatUnit != 1 || signatures.size() != 1 || signatures[0].numerator != 7)
  8634. rollup031s5Result = "ERROR set-up (" + juce::String ((int) signatures.size()) + " signature changes)";
  8635. // (190og: the .flm export reads the song and keeps nothing in it)
  8636. if (rollup031s5Result == "OK")
  8637. {
  8638. const auto flm = lynx::exportFlm (song);
  8639. if (flm.bytes.empty() || lynx::ProjectFile::toJson (song) != json)
  8640. rollup031s5Result = "ERROR the .flm export (" + juce::String ((int) flm.bytes.size()) + " bytes)";
  8641. }
  8642. for (const auto* release : { "0.1.30", "0.1.28" })
  8643. {
  8644. if (rollup031s5Result != "OK")
  8645. break;
  8646. const auto copy = lynx::olderlynx::forRelease (song, release);
  8647. juce::String why;
  8648. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  8649. const auto is130 = juce::String (release) == "0.1.30";
  8650. std::vector<lynx::Marker> backSignatures;
  8651. int sectionMarkers = 0;
  8652. if (back)
  8653. {
  8654. for (const auto& m : back->markers())
  8655. {
  8656. if (m.isSignature())
  8657. backSignatures.push_back (m);
  8658. else if (m.name == "Intro" || m.name == "Verse")
  8659. ++sectionMarkers;
  8660. }
  8661. }
  8662. const auto bars = song.barsBetween (0, 400 * lynx::ppq);
  8663. const auto backBars = back ? back->barsBetween (0, 400 * lynx::ppq) : std::vector<lynx::Bar> {};
  8664. const auto backFx = back && back->mixer.size() > 2 && back->mixer[2].effects.size() >= 2 ? back->mixer[2].effects[back->mixer[2].effects.size() - 2].plugin : lynx::PluginRef {};
  8665. const auto backEmberRev = back && back->mixer.size() > 2 && ! back->mixer[2].effects.empty() ? back->mixer[2].effects.back().engineRev : -1;
  8666. if (! copy.ok || ! back)
  8667. rollup031s5Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  8668. else if (copy.json.contains ("\"sections\"") || ! back->sections().empty() || sectionMarkers != 2
  8669. || countOf (copy, "{0} song section(s) of the Sections lane") != 1)
  8670. rollup031s5Result = juce::String ("ERROR 190ol's sections in the copy for ") + release;
  8671. else if (backSignatures.size() != signatures.size()
  8672. || ! std::equal (signatures.begin(), signatures.end(), backSignatures.begin(), [] (const lynx::Marker& a, const lynx::Marker& b) {
  8673. return a.tick == b.tick && a.numerator == b.numerator && a.denominator == b.denominator;
  8674. })
  8675. || back->beatsPerBar != song.beatsPerBar || back->beatUnit != song.beatUnit
  8676. || ! std::equal (bars.begin(), bars.end(), backBars.begin(), backBars.end(), [] (const lynx::Bar& a, const lynx::Bar& b) {
  8677. return a.tick == b.tick && a.length == b.length && a.number == b.number;
  8678. }))
  8679. rollup031s5Result = juce::String ("ERROR 190ol's time signature changes in the copy for ") + release;
  8680. else if (copy.json.contains ("dpiAware") || copy.json.contains ("scaleEditorDimensions") || ! back->channels[(std::size_t) synthIndex].plugin.dpiAware
  8681. || backFx.scaleEditorDimensions || backFx.name != "Tiny EQ"
  8682. || countOf (copy, "FL's wrapper GUI settings") != 1 || ! detailOf (copy, "FL's wrapper GUI settings").contains ("Old Synth")
  8683. || ! detailOf (copy, "FL's wrapper GUI settings").contains ("Tiny EQ"))
  8684. rollup031s5Result = juce::String ("ERROR 190oh's wrapper GUI settings in the copy for ") + release + " (" + detailOf (copy, "FL's wrapper GUI settings") + ")";
  8685. else if (back->remoteMappings.size() != 1 || back->remoteMappings[0].action != lynx::RemoteAction::play
  8686. || countOf (copy, "{0} key / MIDI mapping(s) of Overdub") != 1 || detailOf (copy, "{0} key / MIDI mapping(s) of Overdub") != "1")
  8687. rollup031s5Result = juce::String ("ERROR gap190og's transport mappings in the copy for ") + release;
  8688. else if (copy.json.contains ("smartDisable") || back->channels[(std::size_t) synthIndex].smartDisable || song.mixer[2].effects.back().engineRev < 2 // (round 190qz: 3 is current)
  8689. || backEmberRev != (is130 ? 1 : 0))
  8690. rollup031s5Result = juce::String ("ERROR 190ok's smart disable / engine revision in the copy for ") + release + " (rev " + juce::String (backEmberRev) + ")";
  8691. else if (back->automations != song.automations)
  8692. rollup031s5Result = juce::String ("ERROR 190ob's volume automation in the copy for ") + release;
  8693. else if (is130 && (copy.lost.size() != 3 || keysOf (juce::JSON::parse (copy.json)) != expected))
  8694. rollup031s5Result = "ERROR the copy for 0.1.30 drops more than step 5's three (" + juce::String ((int) copy.lost.size()) + " lines)";
  8695. }
  8696. // a project without any of them: no step-5 line (the default song)
  8697. if (rollup031s5Result == "OK")
  8698. {
  8699. const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30");
  8700. if (! plain.ok || ! plain.lost.empty())
  8701. rollup031s5Result = "ERROR lines for a project with none of step 5's data (" + juce::String ((int) plain.lost.size()) + ")";
  8702. }
  8703. }
  8704. // round 190pi: "Save a copy for 0.1.30" of FL's slide law (Song::slideNoteProps): a slide note over a chord (FL moves
  8705. // every held note by one interval) and a Slide arpeggio (its voice at the first held note's velocity) each get one
  8706. // sound line; a project with neither gets none of them; the copy reads back
  8707. juce::String slides190piResult = "OK";
  8708. {
  8709. auto song = lynx::Song::makeDefault();
  8710. song.slideNoteProps = true;
  8711. if (song.patterns.empty())
  8712. song.patterns.emplace_back();
  8713. if (song.channels.empty())
  8714. song.channels.emplace_back();
  8715. song.patterns[0].notes.clear();
  8716. const auto count = [] (const lynx::olderlynx::Copy& copy, const char* start) {
  8717. return (int) std::count_if (copy.lost.begin(), copy.lost.end(), [start] (const lynx::olderlynx::Loss& l) {
  8718. return juce::String (l.text).startsWith (start) && l.sound;
  8719. });
  8720. };
  8721. const auto plain = lynx::olderlynx::forRelease (song, "0.1.30");
  8722. lynx::Note a, b, slide;
  8723. a.start = 0, a.length = 4 * lynx::ppq, a.key = 60, a.channel = 0;
  8724. b = a, b.key = 67;
  8725. slide = a, slide.start = lynx::ppq, slide.length = lynx::ppq / 2, slide.slide = true;
  8726. song.patterns[0].notes = { a, b, slide };
  8727. song.channels[0].arp.direction = 1;
  8728. song.channels[0].arp.slide = true;
  8729. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  8730. juce::String why;
  8731. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  8732. if (! plain.ok || count (plain, "{0} slide note(s) over chords") != 0 || count (plain, "{0} channel(s) with a Slide arpeggio") != 0)
  8733. slides190piResult = "ERROR lines for a project without chord slides or Slide arpeggios";
  8734. else if (! copy.ok || count (copy, "{0} slide note(s) over chords") != 1 || count (copy, "{0} channel(s) with a Slide arpeggio") != 1)
  8735. slides190piResult = "ERROR the copy's lines " + copy.error;
  8736. else if (! back || back->slideNoteProps || copy.json.contains ("slideNoteProps"))
  8737. slides190piResult = "ERROR the copy read back " + why;
  8738. }
  8739. // round 190qo (issues #270, #271): LYNX's typing chord layouts follow FL's own four chord files; "Save a copy for 0.1.31"
  8740. // of a SoundFont channel with slide notes (engine revision 5: slide velocity and pan) gets one sound line and
  8741. // revision 3, a project without slide notes none
  8742. juce::String issues190qoResult = "OK";
  8743. {
  8744. const auto rule = lynx::keys::typingpiano::chordRuleCheck();
  8745. auto song = lynx::Song::makeDefault();
  8746. if (song.patterns.empty())
  8747. song.patterns.emplace_back();
  8748. lynx::ChannelDef sf;
  8749. sf.instrument = lynx::InstrumentKind::soundfont;
  8750. sf.name = "SF 190qo";
  8751. song.channels.push_back (sf);
  8752. const auto ch = (int) song.channels.size() - 1;
  8753. lynx::Note a, slide;
  8754. a.start = 0, a.length = 4 * lynx::ppq, a.key = 60, a.channel = ch;
  8755. slide = a, slide.start = lynx::ppq, slide.length = lynx::ppq, slide.slide = true, slide.velocity = 0.1f;
  8756. song.patterns[0].notes = { a };
  8757. const auto lines = [] (const lynx::olderlynx::Copy& copy) {
  8758. return (int) std::count_if (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  8759. return juce::String (l.text).startsWith ("Slide notes move only the pitch on these channels") && l.sound;
  8760. });
  8761. };
  8762. const auto plain = lynx::olderlynx::forRelease (song, "0.1.31");
  8763. song.patterns[0].notes.push_back (slide);
  8764. const auto copy = lynx::olderlynx::forRelease (song, "0.1.31");
  8765. juce::String why;
  8766. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  8767. if (rule != "OK")
  8768. issues190qoResult = "ERROR typing chord rule " + juce::String (rule);
  8769. else if (! plain.ok || lines (plain) != 0)
  8770. issues190qoResult = "ERROR a line for a project without SoundFont slides";
  8771. else if (! copy.ok || lines (copy) != 1)
  8772. issues190qoResult = "ERROR the copy's line " + copy.error;
  8773. else if (! back || back->channels.back().engineRev > 3)
  8774. issues190qoResult = "ERROR the copy read back " + why;
  8775. }
  8776. // round 190pr: "Save a copy for 0.1.30" of the export's marker actions (Song::exportMarkers: one sound line when an
  8777. // arrangement has a skip or Start marker, none otherwise; the key goes), of Harmor's automation and of Sytrus'
  8778. // note Mod X / Y (engine revision 3: written at 2, one line each naming the clip / channel); the .lynx keys read back
  8779. juce::String flparity190prResult = "OK";
  8780. {
  8781. auto song = lynx::Song::makeDefault();
  8782. song.exportMarkers = true;
  8783. const auto has = [] (const lynx::olderlynx::Copy& copy, const char* start) {
  8784. return std::any_of (copy.lost.begin(), copy.lost.end(), [start] (const lynx::olderlynx::Loss& l) {
  8785. return juce::String (l.text).startsWith (start) && l.sound;
  8786. });
  8787. };
  8788. const char* markerLine = "The export plays the song straight through in this release";
  8789. const char* harmorLine = "Automation of Harmor's filter frequencies";
  8790. const auto plain = lynx::olderlynx::forRelease (song, "0.1.30");
  8791. lynx::Marker skip;
  8792. skip.tick = 4 * lynx::ppq, skip.action = lynx::Marker::markerSkip, skip.name = "Skip";
  8793. song.addMarker (skip);
  8794. lynx::ChannelDef harmorChannel;
  8795. harmorChannel.name = "Harmor 190pr";
  8796. harmorChannel.instrument = lynx::InstrumentKind::harmor;
  8797. song.channels.push_back (harmorChannel);
  8798. lynx::ChannelDef sytrusChannel;
  8799. sytrusChannel.name = "Sytrus 190pr";
  8800. sytrusChannel.instrument = lynx::InstrumentKind::sytrus;
  8801. song.channels.push_back (sytrusChannel);
  8802. if (song.patterns.empty())
  8803. song.patterns.emplace_back();
  8804. lynx::Note click;
  8805. click.channel = (int) song.channels.size() - 1, click.key = 60, click.length = lynx::ppq, click.modY = 190.0f / 256.0f;
  8806. song.patterns[0].notes.push_back (click);
  8807. const char* sytrusLine = "Sytrus plays every note at the default Mod X / Y";
  8808. lynx::Automation clip;
  8809. clip.name = "Cutoff 190pr";
  8810. clip.target = { lynx::AutomationTargetKind::channelParam, (int) song.channels.size() - 2, 0, 52 };
  8811. song.automations.push_back (clip);
  8812. const auto json = lynx::ProjectFile::toJson (song);
  8813. juce::String why;
  8814. const auto back = lynx::ProjectFile::fromJson (json, why);
  8815. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  8816. juce::String why2;
  8817. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why2) : std::optional<lynx::Song> {};
  8818. const auto n = song.channels.size();
  8819. if (! plain.ok || has (plain, markerLine) || has (plain, harmorLine) || has (plain, sytrusLine))
  8820. flparity190prResult = "ERROR lines for a project without markers, Harmor automation or Sytrus Mod X / Y";
  8821. else if (! json.contains ("exportMarkers") || ! back || ! back->exportMarkers || back->channels.size() != n
  8822. || back->channels[n - 2].engineRev < 3 || back->channels[n - 1].engineRev < 3) // (round 190py: 4 is current)
  8823. flparity190prResult = "ERROR the .lynx keys " + why;
  8824. else if (! copy.ok || ! has (copy, markerLine) || ! has (copy, harmorLine) || ! has (copy, sytrusLine))
  8825. flparity190prResult = "ERROR the copy's lines " + copy.error;
  8826. else if (! old || old->exportMarkers || copy.json.contains ("exportMarkers") || old->channels.size() != n
  8827. || old->channels[n - 2].engineRev != 2 || old->channels[n - 1].engineRev != 2)
  8828. flparity190prResult = "ERROR the copy read back " + why2;
  8829. }
  8830. // round 190oz: FL's held step notes (Note::held) in .lynx ("heldNotes", only when a pattern has one), back from it,
  8831. // and the copy for 0.1.30 (the marks dropped with one sound line, the notes kept one step long)
  8832. juce::String heldSteps190ozResult = "OK";
  8833. {
  8834. auto song = lynx::Song::makeDefault();
  8835. const auto plainJson = lynx::ProjectFile::toJson (song);
  8836. if (song.patterns.empty())
  8837. song.patterns.emplace_back();
  8838. auto& notes = song.patterns[0].notes;
  8839. notes.clear();
  8840. lynx::Note held, plain;
  8841. held.start = 0, held.channel = 0, held.held = true;
  8842. plain.start = lynx::ticksPerStep * 4, plain.channel = 0;
  8843. notes = { held, plain };
  8844. const auto json = lynx::ProjectFile::toJson (song);
  8845. juce::String why;
  8846. const auto back = lynx::ProjectFile::fromJson (json, why);
  8847. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  8848. const auto lines = (int) std::count_if (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  8849. return juce::String (l.text).startsWith ("{0} FL step note(s) on generators") && l.detail == "1" && l.sound;
  8850. });
  8851. juce::String why2;
  8852. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why2) : std::optional<lynx::Song> {};
  8853. if (plainJson.contains ("heldNotes") || ! json.contains ("heldNotes"))
  8854. heldSteps190ozResult = "ERROR the .lynx key";
  8855. else if (! back || back->patterns.empty() || back->patterns[0].notes.size() != 2 || ! back->patterns[0].notes[0].held
  8856. || back->patterns[0].notes[1].held || back->patterns[0].notes[0].start != 0)
  8857. heldSteps190ozResult = "ERROR the .lynx round trip " + why;
  8858. else if (! copy.ok || copy.json.contains ("heldNotes") || lines != 1 || ! old || old->patterns.empty()
  8859. || old->patterns[0].notes.size() != 2 || old->patterns[0].notes[0].held)
  8860. heldSteps190ozResult = "ERROR the copy for 0.1.30 (" + juce::String (lines) + " lines) " + copy.error + why2;
  8861. }
  8862. // rollup 0.1.31 step 6: "Save a copy for 0.1.30 / 0.1.28" over every round of the step. One project with: 190om's SimSynth
  8863. // (engine revision 2, the velocity law), two patterns' event lanes on one control and a note with a pitch curve in a
  8864. // Playlist clip (decisions 4 / 5: lines only); 190op's hidden track and deactivated insert; 190oq's ARA plugin on an
  8865. // insert (#243); 190ot's "Duck under..."; 190ov's clip linked to two controls with a scale; 190ow's step on an
  8866. // automation row, a re-ranged clip and a muted clip; 190ox's Steps modulator. Each line once in each copy, none of the
  8867. // new keys left in the 0.1.30 copy, both copies read back; the default song gets none of these lines
  8868. juce::String rollup031s6Result = "OK";
  8869. {
  8870. namespace st = lynx::simpletracks;
  8871. auto song = lynx::Song::makeDefault();
  8872. st::Request q;
  8873. q.kind = st::Kind::audio;
  8874. q.name = "Kick";
  8875. const auto kick = st::addTrack (song, q).insert;
  8876. q.name = "Pad";
  8877. const auto pad = st::addTrack (song, q).insert;
  8878. const auto duckSet = st::setDuck (song, pad, kick, 0.6f) == st::DuckResult::set;
  8879. lynx::ChannelDef sim;
  8880. sim.name = "Sim Lead";
  8881. sim.instrument = lynx::InstrumentKind::simsynth; // (engineRev 2: a new channel)
  8882. song.channels.push_back (sim);
  8883. const auto simIndex = (int) song.channels.size() - 1;
  8884. while (song.patterns.size() < 2)
  8885. song.patterns.push_back (song.patterns.front());
  8886. song.patterns[0].name = "Lanes A";
  8887. song.patterns[1].name = "Lanes B";
  8888. lynx::AutomationTarget simVolume;
  8889. simVolume.kind = lynx::AutomationTargetKind::channelVolume;
  8890. simVolume.index = simIndex;
  8891. for (int p = 0; p < 2; ++p)
  8892. {
  8893. lynx::PatternEvents lane;
  8894. lane.target = simVolume;
  8895. lane.events = { { 0, 0.3f + 0.2f * (float) p } };
  8896. song.patterns[(std::size_t) p].events.push_back (lane);
  8897. lynx::Clip clip;
  8898. clip.pattern = p;
  8899. clip.track = 0;
  8900. clip.start = (std::int64_t) p * 4 * lynx::ppq;
  8901. clip.length = 4 * lynx::ppq;
  8902. song.playlist.push_back (clip);
  8903. }
  8904. {
  8905. lynx::Note bent;
  8906. bent.channel = simIndex;
  8907. bent.length = lynx::ppq;
  8908. lynx::NoteCurves curves;
  8909. curves.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { (float) lynx::ppq, 200.0f } };
  8910. bent.curves = curves;
  8911. song.patterns[0].notes.push_back (bent);
  8912. }
  8913. if (song.playlistTracks.size() < 4)
  8914. song.playlistTracks.resize (4);
  8915. song.playlistTracks[3].hidden = true;
  8916. song.mixer[(std::size_t) kick].deactivated = true;
  8917. lynx::EffectSlot ara;
  8918. ara.kind = lynx::EffectKind::plugin;
  8919. ara.plugin.id = "VST3:ara-editor";
  8920. ara.plugin.name = "ARA Editor";
  8921. ara.ara = true;
  8922. song.mixer[(std::size_t) pad].effects.push_back (ara);
  8923. // 190ov: a clip linked to two controls, the first with a scale; 190ow: a step on its row, a re-ranged clip, a muted one
  8924. lynx::Automation linked;
  8925. linked.name = "Linked";
  8926. linked.target = simVolume;
  8927. lynx::Automation::Link first, second;
  8928. first.target = simVolume;
  8929. first.scale = { 0.0f, 0.4f, 1.0f };
  8930. second.target.kind = lynx::AutomationTargetKind::channelPan;
  8931. second.target.index = simIndex;
  8932. linked.links = { first, second };
  8933. linked.points = { { 0, 0.2f }, { lynx::ppq, 0.8f } };
  8934. song.automations.push_back (linked);
  8935. const auto linkedIndex = (int) song.automations.size() - 1;
  8936. lynx::Clip autoClip;
  8937. autoClip.kind = lynx::ClipKind::automation;
  8938. autoClip.automation = linkedIndex;
  8939. autoClip.track = 2;
  8940. autoClip.length = 4 * lynx::ppq;
  8941. song.playlist.push_back (autoClip);
  8942. lynx::Automation ranged = linked;
  8943. ranged.name = "Ranged";
  8944. ranged.links.clear();
  8945. ranged.target.kind = lynx::AutomationTargetKind::mixerVolume;
  8946. ranged.target.index = pad;
  8947. ranged.rangeMin = 0.25f;
  8948. ranged.rangeMax = 0.75f;
  8949. song.automations.push_back (ranged);
  8950. lynx::Automation muted = ranged;
  8951. muted.name = "Muted";
  8952. muted.rangeMin = 0.0f;
  8953. muted.rangeMax = 1.0f;
  8954. muted.target.kind = lynx::AutomationTargetKind::mixerPan;
  8955. muted.muted = true;
  8956. song.automations.push_back (muted);
  8957. lynx::Note step;
  8958. step.channel = (int) song.automations.size() - 2; // ("Ranged": a step on its rack row)
  8959. step.length = 0;
  8960. song.patterns[1].autoNotes.push_back (step);
  8961. auto steps = lynx::Modulator::make (lynx::ModKind::steps);
  8962. steps.name = "Steps 1";
  8963. lynx::ModRoute route;
  8964. route.target.kind = lynx::AutomationTargetKind::mixerPan;
  8965. route.target.index = pad;
  8966. steps.routes.push_back (route);
  8967. song.modulators.push_back (steps);
  8968. lynx::uids::normalize (song);
  8969. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* start) {
  8970. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  8971. };
  8972. const char* const lines[] = { "SimSynth plays every note at full level", "Controls that several patterns' event lanes drive",
  8973. "In Song mode these patterns' notes play without", "{0} hidden Playlist track(s) show again",
  8974. "Deactivated channels and inserts load their plugins again", "ARA plugins on mixer inserts play as ordinary",
  8975. "{0} \"Duck under...\" effect(s)", "Automation clips linked to several controls move them 1:1",
  8976. "{0} step(s) or note(s) on automation clip rows start no clip", "An automation clip's LFO keeps",
  8977. "Muted automation clips lose their target", "These modulators are not in this release" };
  8978. const auto hasLane = [&simVolume] (const lynx::Pattern& p) {
  8979. return std::any_of (p.events.begin(), p.events.end(), [&simVolume] (const lynx::PatternEvents& l) { return l.target == simVolume && ! l.events.empty(); });
  8980. };
  8981. if (! duckSet || kick <= 0 || pad <= 0 || song.channels[(std::size_t) simIndex].engineRev < 2) // (≥ 2: round 190pr's 3 too)
  8982. rollup031s6Result = "ERROR set-up";
  8983. for (const auto* release : { "0.1.30", "0.1.28" })
  8984. {
  8985. if (rollup031s6Result != "OK")
  8986. break;
  8987. const auto is130 = juce::String (release) == "0.1.30";
  8988. const auto copy = lynx::olderlynx::forRelease (song, release);
  8989. juce::String why;
  8990. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  8991. if (! copy.ok || ! back)
  8992. {
  8993. rollup031s6Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  8994. break;
  8995. }
  8996. for (const auto* line : lines)
  8997. {
  8998. // (no LFO on the re-ranged clip: that line must not show)
  8999. const auto want = juce::String (line).startsWith ("An automation clip's LFO") ? 0 : 1;
  9000. if (countOf (copy, line) != want)
  9001. {
  9002. rollup031s6Result = juce::String ("ERROR the copy for ") + release + ": \"" + line + "\" " + juce::String (countOf (copy, line)) + " times";
  9003. break;
  9004. }
  9005. }
  9006. if (rollup031s6Result != "OK")
  9007. break;
  9008. const auto json = copy.json;
  9009. if (json.contains ("playlistTracksHidden") || json.contains ("\"deactivated\"") || json.contains ("\"ara\": true") || json.contains ("autoNotes")
  9010. || json.contains ("modulators190ox"))
  9011. rollup031s6Result = juce::String ("ERROR a new key is left in the copy for ") + release;
  9012. else if (is130 && back->channels[(std::size_t) simIndex].engineRev != 1)
  9013. rollup031s6Result = "ERROR SimSynth's revision in the copy for 0.1.30 (" + juce::String (back->channels[(std::size_t) simIndex].engineRev) + ")";
  9014. else if (! back->mixer[(std::size_t) kick].muted || back->mixer[(std::size_t) kick].deactivated || (back->playlistTracks.size() > 3 && back->playlistTracks[3].hidden))
  9015. rollup031s6Result = juce::String ("ERROR 190op's units in the copy for ") + release;
  9016. else if (is130 && (back->patterns.size() < 2 || ! hasLane (back->patterns[0]) || ! hasLane (back->patterns[1])
  9017. || std::none_of (back->patterns[0].notes.begin(), back->patterns[0].notes.end(), [] (const lynx::Note& n) { return n.curves.has(); })))
  9018. rollup031s6Result = "ERROR the copy for 0.1.30 lost 190om's lanes or curves (lines only)";
  9019. else if (back->automations.size() < 3 || (is130 && back->automations[(std::size_t) linkedIndex].links.size() != 2)
  9020. || (! back->automations[(std::size_t) linkedIndex].links.empty() && ! back->automations[(std::size_t) linkedIndex].links[0].scale.empty()) || back->automations.back().target.kind != lynx::AutomationTargetKind::none
  9021. || back->automations[back->automations.size() - 2].reranged())
  9022. rollup031s6Result = juce::String ("ERROR 190ov / 190ow's clips in the copy for ") + release;
  9023. else if (is130 && (back->modulators.size() != song.modulators.size() - 1))
  9024. rollup031s6Result = "ERROR 190ox's Steps modulator in the copy for 0.1.30 (" + juce::String ((int) back->modulators.size()) + ")";
  9025. }
  9026. // the default song: none of these lines
  9027. if (rollup031s6Result == "OK")
  9028. {
  9029. const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30");
  9030. if (! plain.ok || ! plain.lost.empty())
  9031. rollup031s6Result = "ERROR lines for a project with none of step 6's data (" + juce::String ((int) plain.lost.size()) + ")";
  9032. }
  9033. }
  9034. // rollup 0.1.31 step 7: Save a copy for 0.1.30 / 0.1.28 of everything step 7 brought. One project with 190pf's Chord
  9035. // lane (2 chords, a following channel), 190pe's track versions (2 on a track), 190pa's write mode (Latch) and range,
  9036. // 190pj's JSFX insert, 190pi's Ogun (engine revision 2) and an automation clip of Sytrus' Mod X; each copy: every line
  9037. // once (the Ogun line only for a patch with link velocity: none here without FL's files), the chords as markers,
  9038. // none of the new keys left, Ogun at revision 1 (0.1.30), both copies read back; the default song gets none of them.
  9039. // (Note repeats / conditions, research190oe P19: not built, nothing to convert; the header gear's choice is window
  9040. // state, never in a copy.)
  9041. juce::String rollup031s7Result = "OK";
  9042. {
  9043. auto song = lynx::Song::makeDefault();
  9044. if (song.playlistTracks.size() < 3)
  9045. song.playlistTracks.resize (3);
  9046. lynx::SongChord am, g7;
  9047. am.start = 0, am.length = 4 * lynx::ppq, am.root = 9, am.quality = 1;
  9048. g7.start = 4 * lynx::ppq, g7.length = 4 * lynx::ppq, g7.root = 7, g7.quality = 0, g7.extensions = { 10 }, g7.bass = 11;
  9049. song.chords() = { am, g7 };
  9050. lynx::ChannelDef follower;
  9051. follower.name = "Follower";
  9052. follower.followChords = 1;
  9053. song.channels.push_back (follower);
  9054. lynx::ChannelDef ogun;
  9055. ogun.name = "Ogun Pad";
  9056. ogun.instrument = lynx::InstrumentKind::ogun; // (engineRev 2: a new channel)
  9057. song.channels.push_back (ogun);
  9058. const auto ogunIndex = (int) song.channels.size() - 1;
  9059. lynx::ChannelDef sytrus;
  9060. sytrus.name = "Sytrus Lead";
  9061. sytrus.instrument = lynx::InstrumentKind::sytrus;
  9062. song.channels.push_back (sytrus);
  9063. lynx::Automation modX;
  9064. modX.name = "Sytrus Mod X";
  9065. modX.target.kind = lynx::AutomationTargetKind::channelParam;
  9066. modX.target.index = (int) song.channels.size() - 1;
  9067. modX.target.param = 18;
  9068. modX.points = { { 0, 0.2f }, { lynx::ppq, 0.8f } };
  9069. song.automations.push_back (modX);
  9070. song.automationWriteMode = 2; // (Latch)
  9071. song.trackRange.from = 0, song.trackRange.to = 2 * lynx::ppq, song.trackRange.tracks = { 0, 1 };
  9072. lynx::EffectSlot jsfx;
  9073. jsfx.kind = lynx::EffectKind::plugin;
  9074. jsfx.plugin.id = "JSFX-chokehold/soft_clipper";
  9075. jsfx.plugin.name = "soft_clipper";
  9076. if (song.mixer.size() < 3)
  9077. song.mixer.resize (3);
  9078. song.mixer[2].effects.push_back (jsfx);
  9079. lynx::Clip clip;
  9080. clip.pattern = 0;
  9081. clip.track = 1;
  9082. clip.length = 4 * lynx::ppq;
  9083. song.playlist.push_back (clip);
  9084. const auto versioned = lynx::trackversions::add (song, 1, lynx::trackversions::Start::empty, "Take B", "Take A") >= 0;
  9085. lynx::uids::normalize (song);
  9086. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* start) {
  9087. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  9088. };
  9089. const char* const lines[] = { "{0} chord(s) of the Chord lane become plain Playlist markers", "{0} channel(s) followed the Chord lane",
  9090. "{0} track version(s) that are not active are left out", "The automation write mode ({0}) goes back",
  9091. "The range selected on some Playlist tracks is left out", "JSFX scripts are not in this release",
  9092. "Automation of Sytrus' main knobs" };
  9093. if (! versioned || song.channels[(std::size_t) ogunIndex].engineRev < 2) // (≥ 2: round 190pr's 3 too)
  9094. rollup031s7Result = "ERROR set-up";
  9095. for (const auto* release : { "0.1.30", "0.1.28" })
  9096. {
  9097. if (rollup031s7Result != "OK")
  9098. break;
  9099. const auto is130 = juce::String (release) == "0.1.30";
  9100. const auto copy = lynx::olderlynx::forRelease (song, release);
  9101. juce::String why;
  9102. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  9103. if (! copy.ok || ! back)
  9104. {
  9105. rollup031s7Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  9106. break;
  9107. }
  9108. for (const auto* line : lines)
  9109. if (countOf (copy, line) != 1)
  9110. {
  9111. rollup031s7Result = juce::String ("ERROR the copy for ") + release + ": \"" + line + "\" " + juce::String (countOf (copy, line)) + " times";
  9112. break;
  9113. }
  9114. if (rollup031s7Result != "OK")
  9115. break;
  9116. const auto& json = copy.json;
  9117. const auto markerNamed = [&back] (const char* name) {
  9118. return std::any_of (back->markers().begin(), back->markers().end(), [name] (const lynx::Marker& m) { return m.name == name; });
  9119. };
  9120. if (countOf (copy, "Ogun and Autogun play every note") != 0)
  9121. rollup031s7Result = juce::String ("ERROR an Ogun line without a link-velocity patch in the copy for ") + release;
  9122. else if (json.contains ("\"chords\"") || json.contains ("followChords") || json.contains ("playlistTrackVersions")
  9123. || json.contains ("automationWriteMode") || json.contains ("trackRange") || json.contains ("JSFX-"))
  9124. rollup031s7Result = juce::String ("ERROR a new key is left in the copy for ") + release;
  9125. else if (! markerNamed ("Am") || ! markerNamed ("G7/B"))
  9126. rollup031s7Result = juce::String ("ERROR the chords are not markers in the copy for ") + release;
  9127. else if (is130 && back->channels[(std::size_t) ogunIndex].engineRev != 1)
  9128. rollup031s7Result = "ERROR Ogun's revision in the copy for 0.1.30 (" + juce::String (back->channels[(std::size_t) ogunIndex].engineRev) + ")";
  9129. else if ((back->playlistTracks.size() > 1 && ! back->playlistTracks[1].versions.empty()) // (an empty default row may not be written)
  9130. || std::any_of (back->playlist.begin(), back->playlist.end(), [] (const lynx::Clip& c) { return c.track == 1; }))
  9131. rollup031s7Result = juce::String ("ERROR track 2 is not its active (empty) version in the copy for ") + release + " (rows "
  9132. + juce::String ((int) back->playlistTracks.size()) + ", clips on it "
  9133. + juce::String ((int) std::count_if (back->playlist.begin(), back->playlist.end(), [] (const lynx::Clip& c) { return c.track == 1; })) + ")";
  9134. else if (back->automations.empty() || back->automations[0].points.size() != 2)
  9135. rollup031s7Result = juce::String ("ERROR the Sytrus clip's data in the copy for ") + release;
  9136. }
  9137. if (rollup031s7Result == "OK")
  9138. {
  9139. const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30");
  9140. if (! plain.ok || ! plain.lost.empty())
  9141. rollup031s7Result = "ERROR lines for a project with none of step 7's data (" + juce::String ((int) plain.lost.size()) + ")";
  9142. }
  9143. }
  9144. // rollup 0.1.31 step 8: Save a copy for 0.1.30 / 0.1.28 of engine revision 3 (round 190pr, ChannelDef::engineRev: FL
  9145. // imports and new channels) and of the export's marker switch (Song::exportMarkers). One project with a channel of
  9146. // every kind a revision gates (SimSynth, Ogun, Autogun: 2; Harmor, Sytrus: 3) and a plain Synth, all new (3), a
  9147. // Harmor filter clip, a Sytrus note off the default Mod Y, a Start marker after bar 1 and a skip marker. Each copy:
  9148. // 190pr's three lines once, no exportMarkers key, the markers kept as markers; 0.1.30: SimSynth / Ogun / Autogun at 1,
  9149. // Harmor / Sytrus / the Synth at 2; 0.1.28: no revision at all (0). Revisions stay ordered: a project saved before
  9150. // (every channel at 2, the switch off) reads back as it was saved and gets none of 190pr's lines.
  9151. juce::String rollup031s8Result = "OK";
  9152. {
  9153. auto song = lynx::Song::makeDefault();
  9154. song.exportMarkers = true;
  9155. lynx::Marker start, skip;
  9156. start.tick = 4 * lynx::ppq, start.action = lynx::Marker::start, start.name = "Start 190s8";
  9157. skip.tick = 8 * lynx::ppq, skip.action = lynx::Marker::markerSkip, skip.name = "Skip 190s8";
  9158. song.addMarker (start);
  9159. song.addMarker (skip);
  9160. const lynx::InstrumentKind kinds[] = { lynx::InstrumentKind::simsynth, lynx::InstrumentKind::ogun, lynx::InstrumentKind::autogun,
  9161. lynx::InstrumentKind::harmor, lynx::InstrumentKind::sytrus, lynx::InstrumentKind::synth };
  9162. const int want130[] = { 1, 1, 1, 2, 2, 2 };
  9163. const auto first = (int) song.channels.size();
  9164. for (const auto kind : kinds)
  9165. {
  9166. lynx::ChannelDef c;
  9167. c.name = "Rev3 " + std::to_string ((int) song.channels.size() - first + 1);
  9168. c.instrument = kind;
  9169. song.channels.push_back (c);
  9170. }
  9171. const auto harmorIndex = first + 3, sytrusIndex = first + 4;
  9172. if (song.patterns.empty())
  9173. song.patterns.emplace_back();
  9174. lynx::Note click;
  9175. click.channel = sytrusIndex, click.key = 60, click.length = lynx::ppq, click.modY = 0.8f;
  9176. song.patterns[0].notes.push_back (click);
  9177. lynx::Automation cutoff;
  9178. cutoff.name = "Harmor cutoff s8";
  9179. cutoff.target = { lynx::AutomationTargetKind::channelParam, harmorIndex, 0, 52 };
  9180. cutoff.points = { { 0, 0.2f }, { lynx::ppq, 0.8f } };
  9181. song.automations.push_back (cutoff);
  9182. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* begin) {
  9183. return (int) std::count_if (c.lost.begin(), c.lost.end(), [begin] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (begin); });
  9184. };
  9185. const char* const lines[] = { "The export plays the song straight through in this release", "Automation of Harmor's filter frequencies",
  9186. "Sytrus plays every note at the default Mod X / Y" };
  9187. const auto markersKept = [] (const lynx::Song& s) {
  9188. const auto& m = s.markers();
  9189. return std::any_of (m.begin(), m.end(), [] (const lynx::Marker& x) { return x.name == "Start 190s8"; })
  9190. && std::any_of (m.begin(), m.end(), [] (const lynx::Marker& x) { return x.name == "Skip 190s8"; });
  9191. };
  9192. juce::String why;
  9193. const auto json = lynx::ProjectFile::toJson (song);
  9194. const auto back = lynx::ProjectFile::fromJson (json, why);
  9195. const auto n = (int) song.channels.size();
  9196. if (std::any_of (song.channels.begin() + first, song.channels.end(), [] (const lynx::ChannelDef& c) { return c.engineRev < 3; }))
  9197. rollup031s8Result = "ERROR set-up: a new channel is not at revision 3 or later"; // (round 190py: 4 is current)
  9198. else if (! back || ! back->exportMarkers || (int) back->channels.size() != n
  9199. || std::any_of (back->channels.begin() + first, back->channels.end(), [] (const lynx::ChannelDef& c) { return c.engineRev < 3; }))
  9200. rollup031s8Result = "ERROR the .lynx did not keep revision 3 / the export's markers " + why;
  9201. for (const auto* release : { "0.1.30", "0.1.28" })
  9202. {
  9203. if (rollup031s8Result != "OK")
  9204. break;
  9205. const auto is130 = juce::String (release) == "0.1.30";
  9206. const auto copy = lynx::olderlynx::forRelease (song, release);
  9207. juce::String why2;
  9208. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why2) : std::optional<lynx::Song> {};
  9209. if (! copy.ok || ! old || (int) old->channels.size() != n)
  9210. {
  9211. rollup031s8Result = juce::String ("ERROR copy ") + release + " " + copy.error + why2;
  9212. break;
  9213. }
  9214. for (const auto* line : lines)
  9215. if (countOf (copy, line) != 1)
  9216. {
  9217. rollup031s8Result = juce::String ("ERROR the copy for ") + release + ": \"" + line + "\" " + juce::String (countOf (copy, line)) + " times";
  9218. break;
  9219. }
  9220. if (rollup031s8Result != "OK")
  9221. break;
  9222. if (copy.json.contains ("exportMarkers") || old->exportMarkers)
  9223. rollup031s8Result = juce::String ("ERROR the export's marker switch is left in the copy for ") + release;
  9224. else if (! markersKept (*old))
  9225. rollup031s8Result = juce::String ("ERROR the Start / skip markers are gone from the copy for ") + release;
  9226. else if (! is130 && copy.json.contains ("engineRev"))
  9227. rollup031s8Result = "ERROR a revision is left in the copy for 0.1.28";
  9228. else
  9229. for (int k = 0; k < (int) std::size (kinds); ++k)
  9230. if (const auto rev = old->channels[(std::size_t) (first + k)].engineRev; rev != (is130 ? want130[k] : 0))
  9231. {
  9232. rollup031s8Result = juce::String ("ERROR the copy for ") + release + ": channel " + juce::String (first + k + 1)
  9233. + " at revision " + juce::String (rev) + " (want " + juce::String (is130 ? want130[k] : 0) + ")";
  9234. break;
  9235. }
  9236. }
  9237. if (rollup031s8Result == "OK")
  9238. {
  9239. auto before = song; // (a project saved before round 190pr: revision 2 at most, the switch off)
  9240. before.exportMarkers = false;
  9241. for (auto& c : before.channels)
  9242. c.engineRev = std::min (c.engineRev, 2);
  9243. juce::String why3;
  9244. const auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (before), why3);
  9245. const auto copy = lynx::olderlynx::forRelease (before, "0.1.30");
  9246. if (! again || again->exportMarkers
  9247. || std::any_of (again->channels.begin() + first, again->channels.end(), [] (const lynx::ChannelDef& c) { return c.engineRev != 2; }))
  9248. rollup031s8Result = "ERROR a project saved before 190pr does not read back as saved " + why3;
  9249. else if (! copy.ok || std::any_of (std::begin (lines), std::end (lines), [&] (const char* l) { return countOf (copy, l) != 0; }))
  9250. rollup031s8Result = "ERROR 190pr's lines for a project saved before it";
  9251. else if (const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30"); ! plain.ok || ! plain.lost.empty())
  9252. rollup031s8Result = "ERROR lines for the default song (" + juce::String ((int) plain.lost.size()) + ")";
  9253. }
  9254. }
  9255. // rollup 0.1.32 step 1 (round 190qn): Save a copy for 0.1.31 (the new first step, toRelease0131) and the chain under it.
  9256. // One project with every 0.1.32 format addition: 12 effects on an insert with 14 rows and an automation of slot 12 (PR
  9257. // #260), a note with 4 ratchets and one with a Condition (190pm), a 3x Osc at revision 4 with an automation of one of
  9258. // its FL parameters and a channel PITCH clip (190py), Effector at the Kilohearts Flanger (50) and Ensemble (52) laws
  9259. // (190py-khs). The copy for 0.1.31: 10 effects and no slotRows, the ratchets as 4 notes and no note past [20], every
  9260. // channel at revision 3 or lower, Effector's [12 …] cut, each line once, stamped 0.1.31; the copies for 0.1.30 and
  9261. // 0.1.28 run it first: each line once there too, revisions 2 / none. The default song: no line. Round 190px's caches are
  9262. // not in projects: a stretched copy of a stereo file with identical channels is written with header channels -2 (one
  9263. // channel; 0.1.31 accepts only 1 / 2 and stretches again) and reads back as both channels; a streamed one (over 30 s)
  9264. // keeps .L.pcm + .R.same and no .R.pcm (0.1.31 wants both .pcm files, so it decodes again).
  9265. juce::String rollup032Result = "OK";
  9266. {
  9267. auto song = lynx::Song::makeDefault();
  9268. if (song.mixer.size() < 3)
  9269. song.mixer = lynx::Song::defaultMixer (4);
  9270. auto& bus = song.mixer[1];
  9271. bus.name = "Bus 190qn";
  9272. bus.effects.clear();
  9273. for (int i = 0; i < 12; ++i)
  9274. {
  9275. auto fx = lynx::makeEffectSlot (i == 0 ? lynx::EffectKind::effector : i == 1 ? lynx::EffectKind::effector : lynx::EffectKind::utility);
  9276. fx.row = i;
  9277. if (i < 2)
  9278. fx.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (i == 0 ? lynx::khsdsp::Law::flanger : lynx::khsdsp::Law::ensemble2);
  9279. bus.effects.push_back (fx);
  9280. }
  9281. bus.slotRows = 14;
  9282. lynx::Automation slotGain;
  9283. slotGain.name = "Slot 12 gain 190qn";
  9284. slotGain.target = { lynx::AutomationTargetKind::effectParam, 1, 11, 0 };
  9285. slotGain.points = { { 0, 0.25f }, { lynx::ppq, 0.75f } };
  9286. song.automations.push_back (slotGain);
  9287. const auto first = (int) song.channels.size();
  9288. lynx::ChannelDef osc;
  9289. osc.name = "3x Osc 190qn";
  9290. osc.instrument = lynx::InstrumentKind::threeosc;
  9291. song.channels.push_back (osc);
  9292. int oscParam = -1;
  9293. for (int k = 0; k < 120 && oscParam < 0; ++k)
  9294. if (lynx::threeosc::isFlTarget (k))
  9295. oscParam = k;
  9296. lynx::Automation oscClip, pitchClip;
  9297. oscClip.name = "3x Osc param 190qn";
  9298. oscClip.target = { lynx::AutomationTargetKind::channelParam, first, 0, oscParam };
  9299. oscClip.points = { { 0, 0.2f }, { lynx::ppq, 0.8f } };
  9300. pitchClip.name = "Pitch 190qn";
  9301. pitchClip.target = { lynx::AutomationTargetKind::channelParam, 0, 0, lynx::channelPitchParam };
  9302. pitchClip.points = { { 0, 0.5f }, { lynx::ppq, 0.75f } };
  9303. song.automations.push_back (oscClip);
  9304. song.automations.push_back (pitchClip);
  9305. // rollup 0.1.32 step 2: round 190qo's engine revision 5 (issue #271): a SoundFont channel with a slide note and a
  9306. // quiet note, a BooBass channel with a quiet note
  9307. const auto fontChannel = (int) song.channels.size();
  9308. lynx::ChannelDef font, boo;
  9309. font.name = "SoundFont 190qv";
  9310. font.instrument = lynx::InstrumentKind::soundfont;
  9311. boo.name = "BooBass 190qv";
  9312. boo.instrument = lynx::InstrumentKind::boobass;
  9313. song.channels.push_back (font);
  9314. song.channels.push_back (boo);
  9315. // round 190qz: an Envelope Controller (channel revision 6) and a Peak Controller (slot revision 3) with links; an
  9316. // Effector at round 190qz-khs's law 55 (kHs Delay) on insert 2
  9317. lynx::ChannelDef envelope;
  9318. envelope.name = "Envelope 190qz";
  9319. envelope.instrument = lynx::InstrumentKind::controller;
  9320. envelope.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  9321. song.channels.push_back (envelope);
  9322. {
  9323. auto& bus2 = song.mixer[2];
  9324. bus2.effects.clear();
  9325. auto peakCtl = lynx::makeEffectSlot (lynx::EffectKind::peakController);
  9326. auto delay55 = lynx::makeEffectSlot (lynx::EffectKind::effector);
  9327. delay55.row = 1;
  9328. delay55.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::delay);
  9329. bus2.effects = { peakCtl, delay55 };
  9330. lynx::Automation envLink, peakLink;
  9331. envLink.name = "Envelope link 190qz";
  9332. envLink.target = { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
  9333. envLink.source.channel = fontChannel + 2;
  9334. peakLink.name = "Peak link 190qz";
  9335. peakLink.target = { lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 };
  9336. peakLink.source.track = 2;
  9337. peakLink.source.slot = 0;
  9338. song.automations.push_back (envLink);
  9339. song.automations.push_back (peakLink);
  9340. }
  9341. if (song.patterns.empty())
  9342. song.patterns.emplace_back();
  9343. auto& notes = song.patterns[0].notes;
  9344. notes.clear();
  9345. lynx::Note ratchet, conditioned;
  9346. ratchet.channel = 0, ratchet.key = 60, ratchet.start = 0, ratchet.length = lynx::ppq, ratchet.ratchets = 4;
  9347. conditioned.channel = 0, conditioned.key = 64, conditioned.start = 2 * lynx::ppq, conditioned.length = lynx::ppq;
  9348. conditioned.cycle = 4, conditioned.cycleMask = 2; // 2:4
  9349. notes.push_back (ratchet);
  9350. notes.push_back (conditioned);
  9351. lynx::Note fontNote, fontSlide, booNote;
  9352. fontNote.channel = fontChannel, fontNote.key = 48, fontNote.start = 0, fontNote.length = 2 * lynx::ppq, fontNote.velocity = 0.3f;
  9353. fontSlide.channel = fontChannel, fontSlide.key = 55, fontSlide.start = lynx::ppq, fontSlide.length = lynx::ppq / 2, fontSlide.slide = true;
  9354. booNote.channel = fontChannel + 1, booNote.key = 36, booNote.start = 0, booNote.length = lynx::ppq, booNote.velocity = 0.4f;
  9355. notes.push_back (fontNote);
  9356. notes.push_back (fontSlide);
  9357. notes.push_back (booNote);
  9358. const char* const lines[] = { "This release holds 10 effect slots", "{0} note(s) with ratchets become their strikes",
  9359. "{0} note(s) with a Condition", "Automation of a channel's Pitch knob does nothing",
  9360. "Automation of 3x Osc's parameters does nothing", "Effector's newer Kilohearts laws (the Comb Filter",
  9361. "Effector's Kilohearts Flanger and Dual Delay laws",
  9362. "Slide notes move only the pitch on these channels", // (round 190qo, revision 5)
  9363. "SoundFont channels play low velocities much quieter", "BooBass plays every note at full level",
  9364. "Peak and Envelope Controller links set their targets from the start", // (round 190qz)
  9365. "Effector's newer Kilohearts laws (the kHs Ring Mod's oversampled path" }; // (round 190qz-khs)
  9366. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* begin) {
  9367. return (int) std::count_if (c.lost.begin(), c.lost.end(), [begin] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (begin); });
  9368. };
  9369. const auto rels = lynx::olderlynx::releases();
  9370. if (oscParam < 0)
  9371. rollup032Result = "ERROR set-up: no 3x Osc FL target";
  9372. else if (song.channels[(std::size_t) first].engineRev != 6 || song.channels[(std::size_t) fontChannel].engineRev != 6) // (round 190qo: 5, issue #271's slide velocity; round 190qz: 6)
  9373. rollup032Result = "ERROR set-up: a new channel is not at revision 6";
  9374. else if (rels.size() != 4 || rels[0] != "0.1.31" || rels[1] != "0.1.30" || rels[2] != "0.1.28" || rels[3] != "0.1.27")
  9375. rollup032Result = "ERROR the release list: " + rels.joinIntoString (" ");
  9376. for (const auto* release : { "0.1.31", "0.1.30", "0.1.28" })
  9377. {
  9378. if (rollup032Result != "OK")
  9379. break;
  9380. const auto rel = juce::String (release);
  9381. const auto copy = lynx::olderlynx::forRelease (song, rel);
  9382. const auto root = juce::JSON::parse (copy.json);
  9383. juce::String why;
  9384. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  9385. if (! copy.ok || ! old)
  9386. {
  9387. rollup032Result = "ERROR copy " + rel + " " + copy.error + why;
  9388. break;
  9389. }
  9390. for (const auto* l : lines)
  9391. if (countOf (copy, l) != 1)
  9392. {
  9393. rollup032Result = "ERROR the copy for " + rel + ": \"" + l + "\" " + juce::String (countOf (copy, l)) + " times";
  9394. break;
  9395. }
  9396. if (rollup032Result != "OK")
  9397. break;
  9398. const auto& fx = root["mixer"][1]["effects"];
  9399. int longest = 0, struck = 0;
  9400. if (const auto* ns = root["patterns"][0]["notes"].getArray())
  9401. for (const auto& n : *ns)
  9402. {
  9403. longest = std::max (longest, n.size());
  9404. struck += (int) n[3] == 60 ? 1 : 0;
  9405. }
  9406. bool detached = false;
  9407. if (const auto* autos = root["automations"].getArray())
  9408. for (const auto& a : *autos)
  9409. if (a["name"].toString() == "Slot 12 gain 190qn")
  9410. detached = a["target"][0].toString() == "none";
  9411. const auto maxRev = rel == "0.1.31" ? 3 : rel == "0.1.30" ? 2 : 0;
  9412. const auto revOk = std::all_of (old->channels.begin(), old->channels.end(), [maxRev] (const lynx::ChannelDef& c) { return c.engineRev <= maxRev; })
  9413. && (rel != "0.1.28" || ! copy.json.contains ("engineRev"))
  9414. && (rel != "0.1.31" || (old->channels[(std::size_t) first].engineRev == 3 && old->channels[(std::size_t) fontChannel].engineRev == 3));
  9415. if (! root["savedBy"].toString().equalsIgnoreCase (rel))
  9416. rollup032Result = "ERROR the copy for " + rel + " is stamped " + root["savedBy"].toString();
  9417. else if (fx.size() != 10 || copy.json.contains ("slotRows") || ! detached)
  9418. rollup032Result = "ERROR the copy for " + rel + ": slots (" + juce::String (fx.size()) + " effects)";
  9419. else if (longest > 21 || struck != 4)
  9420. rollup032Result = "ERROR the copy for " + rel + ": notes (longest " + juce::String (longest) + ", strikes " + juce::String (struck) + ")";
  9421. else if (fx[0]["params"].size() > lynx::khsdsp::lawParam || fx[1]["params"].size() > lynx::khsdsp::lawParam)
  9422. rollup032Result = "ERROR the copy for " + rel + ": Effector's [12] is left";
  9423. else if (! revOk)
  9424. rollup032Result = "ERROR the copy for " + rel + ": engine revisions";
  9425. else if ((int) root["mixer"][2]["effects"][0]["engineRev"] > 2 || root["mixer"][2]["effects"][1]["params"].size() > lynx::khsdsp::lawParam)
  9426. rollup032Result = "ERROR the copy for " + rel + ": round 190qz's Peak Controller revision / Effector law 55";
  9427. }
  9428. if (rollup032Result == "OK")
  9429. if (const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.31"); ! plain.ok || ! plain.lost.empty())
  9430. rollup032Result = "ERROR lines for the default song (" + juce::String ((int) plain.lost.size()) + ")";
  9431. // round 190px's caches (not in projects; what 0.1.31 does with them)
  9432. if (rollup032Result == "OK")
  9433. {
  9434. const auto dir = lynx::SampleLibrary::cacheFolder().getParentDirectory().getChildFile ("selftest-190qn");
  9435. dir.deleteRecursively();
  9436. dir.createDirectory();
  9437. const auto writeSame = [&dir] (const juce::String& name, int frames) {
  9438. const auto wav = dir.getChildFile (name);
  9439. juce::WavAudioFormat format;
  9440. juce::AudioBuffer<float> audio (2, frames);
  9441. for (int i = 0; i < frames; ++i)
  9442. {
  9443. const auto v = 0.4f * std::sin (0.031f * (float) i) + 0.2f * std::sin (0.0071f * (float) i);
  9444. audio.setSample (0, i, v);
  9445. audio.setSample (1, i, v);
  9446. }
  9447. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  9448. if (auto* w = format.createWriterFor (out.get(), 44100.0, 2, 16, {}, 0))
  9449. {
  9450. out.release();
  9451. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  9452. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  9453. }
  9454. return wav;
  9455. };
  9456. const auto cache = lynx::SampleLibrary::cacheFolder();
  9457. const auto newest = [&cache] (const juce::String& pattern, juce::Time since) {
  9458. juce::File found;
  9459. for (const auto& f : cache.findChildFiles (juce::File::findFiles, false, pattern))
  9460. if (f.getLastModificationTime() >= since && (found == juce::File() || f.getLastModificationTime() > found.getLastModificationTime()))
  9461. found = f;
  9462. return found;
  9463. };
  9464. const auto since = juce::Time::getCurrentTime() - juce::RelativeTime::seconds (2.0);
  9465. lynx::SampleLibrary library;
  9466. const auto shortWav = writeSame ("same 190qn.wav", 44100);
  9467. // (a ratio within resampleTolerance: the copy is resampled channel by channel, so identical channels stay identical,
  9468. // as Thief's near-tempo stems; the spectral stretchers' stereo output need not be bit-identical across channels)
  9469. const auto stretched = library.loadStretched (shortWav.getFullPathName(), 1.0005);
  9470. // (the copy is written by the cache's writer thread: the new .str file whose frames are this copy's)
  9471. juce::File str;
  9472. juce::MemoryBlock bytes;
  9473. std::int32_t channels = 0;
  9474. std::int64_t frames = 0;
  9475. for (int tries = 0; tries < 600 && str == juce::File() && stretched != nullptr; ++tries) // (rollup 0.1.32 step 2: up to 30 s — the writer thread queues behind the self-test's other cache writes; 10 s ran out once under load)
  9476. {
  9477. juce::Thread::sleep (50);
  9478. for (const auto& f : cache.findChildFiles (juce::File::findFiles, false, "*.str"))
  9479. {
  9480. juce::MemoryBlock b;
  9481. std::int64_t n = 0;
  9482. if (f.getLastModificationTime() < since || ! f.loadFileAsData (b) || b.getSize() < 32)
  9483. continue;
  9484. std::memcpy (&n, static_cast<const char*> (b.getData()) + 16, 8);
  9485. if (n != (std::int64_t) stretched->frames() || (juce::int64) b.getSize() < 32 + n * (juce::int64) sizeof (float))
  9486. continue;
  9487. str = f, bytes = b, frames = n;
  9488. std::memcpy (&channels, static_cast<const char*> (b.getData()) + 24, 4);
  9489. break;
  9490. }
  9491. }
  9492. // 0.1.31's acceptance (SampleLibrary.cpp readStretched at v0.1.31-alpha): channels 1 or 2 and the size they make
  9493. const auto acceptedBy0131 = frames > 0 && (channels == 1 || channels == 2)
  9494. && (juce::int64) bytes.getSize() == 32 + frames * channels * (juce::int64) sizeof (float);
  9495. if (stretched == nullptr || ! stretched->isStereo() || str == juce::File())
  9496. rollup032Result = juce::String ("ERROR stretch cache: nothing written (")
  9497. + (stretched == nullptr ? "no copy" : ! stretched->isStereo() ? "the copy is mono" : "no new .str in 30 s") + ")";
  9498. else if (channels != -2 || frames != (std::int64_t) stretched->frames() || (juce::int64) bytes.getSize() != 32 + frames * (juce::int64) sizeof (float)
  9499. || std::memcmp (static_cast<const char*> (bytes.getData()) + 32, stretched->leftData(), (std::size_t) frames * sizeof (float)) != 0
  9500. || std::memcmp (stretched->leftData(), stretched->rightData(), (std::size_t) frames * sizeof (float)) != 0)
  9501. rollup032Result = "ERROR stretch cache: header channels " + juce::String (channels) + ", frames " + juce::String ((juce::int64) frames);
  9502. else if (acceptedBy0131)
  9503. rollup032Result = "ERROR stretch cache: 0.1.31 would read the one-channel file";
  9504. if (rollup032Result == "OK")
  9505. {
  9506. const auto longWav = writeSame ("same long 190qn.wav", 44100 * 31);
  9507. const auto streamed = library.load (longWav.getFullPathName());
  9508. const auto same = newest ("*.R.same", since);
  9509. const auto key = same.getFileName().upToFirstOccurrenceOf (".R.same", false, false);
  9510. if (streamed == nullptr || ! streamed->isMapped() || ! streamed->isStereo() || streamed->rightData() != streamed->leftData())
  9511. rollup032Result = "ERROR stream cache: not mapped as one channel";
  9512. else if (same == juce::File() || ! cache.getChildFile (key + ".L.pcm").existsAsFile() || cache.getChildFile (key + ".R.pcm").existsAsFile())
  9513. rollup032Result = "ERROR stream cache files (" + same.getFileName() + ")";
  9514. }
  9515. dir.deleteRecursively();
  9516. }
  9517. }
  9518. // rollup 0.1.31 step 7 (PRs #248 / #256 by FKHR26): the docked channel window's header shows by default; its gear hides
  9519. // it, a window of the same channel opened again hides it too (the choice kept per window), the project's window
  9520. // places carry it ([key, "headerHidden"]) and give it back, an older project's places (0.1.30's shape) none; the gear
  9521. // shows it again
  9522. juce::String headerGearResult = "OK";
  9523. {
  9524. lynx::AudioEngine e (false);
  9525. lynx::windowplaces::fromVar ({});
  9526. const auto shownIn = [] (juce::Component* w) { return w == nullptr ? std::optional<bool> {} : lynx::channelWindowHeaderShown (*w); };
  9527. auto first = lynx::makeChannelWindowForShot (e, 0, 0);
  9528. if (shownIn (first.get()) != std::optional<bool> (true))
  9529. headerGearResult = "ERROR not shown by default";
  9530. else if (! lynx::pressChannelHeaderGear (*first) || shownIn (first.get()) != std::optional<bool> (false))
  9531. headerGearResult = "ERROR the gear did not hide it";
  9532. first.reset();
  9533. if (headerGearResult == "OK")
  9534. {
  9535. auto again = lynx::makeChannelWindowForShot (e, 0, 0);
  9536. const auto saved = lynx::windowplaces::toVar();
  9537. const auto savedText = juce::JSON::toString (saved, true);
  9538. if (shownIn (again.get()) != std::optional<bool> (false))
  9539. headerGearResult = "ERROR the choice was not kept for the window";
  9540. else if (! savedText.contains ("headerHidden"))
  9541. headerGearResult = "ERROR the places do not carry it: " + savedText;
  9542. else
  9543. {
  9544. again.reset();
  9545. lynx::windowplaces::fromVar (juce::JSON::parse (juce::String ("[[\"ch:1\", 10, 10, 300, 200, false]]")));
  9546. auto older = lynx::makeChannelWindowForShot (e, 0, 0);
  9547. if (shownIn (older.get()) != std::optional<bool> (true))
  9548. headerGearResult = "ERROR hidden after an older project's places";
  9549. older.reset();
  9550. lynx::windowplaces::fromVar (saved);
  9551. auto restored = lynx::makeChannelWindowForShot (e, 0, 0);
  9552. if (headerGearResult == "OK" && shownIn (restored.get()) != std::optional<bool> (false))
  9553. headerGearResult = "ERROR the saved places did not give it back";
  9554. else if (headerGearResult == "OK" && (! lynx::pressChannelHeaderGear (*restored) || shownIn (restored.get()) != std::optional<bool> (true)
  9555. || ! lynx::windowplaces::hiddenHeaders().empty()))
  9556. headerGearResult = "ERROR the gear did not show it again";
  9557. }
  9558. }
  9559. lynx::windowplaces::fromVar ({});
  9560. }
  9561. // round 190pw (PR #259 by FKHR26): the channel window is the size of the tab it shows, as FL's (FL 2026: Sytrus
  9562. // 860 px wide on its plugin tab, 568 on Misc): a Synth channel's window (docked look) on its plugin tab, then Misc
  9563. // (another size), back (the first size again), and with the header hidden by the gear, each less the header
  9564. // round 190qf (PR #260 by codewithamoako): FL 2026.2's effect slots, up to 25 per insert (src/Slots260Shot190qf.inc)
  9565. const auto slots260Result = slots260Checks ({});
  9566. juce::String perTab259Result = "OK";
  9567. {
  9568. lynx::AudioEngine e (false);
  9569. lynx::windowplaces::fromVar ({});
  9570. e.editSong ([] (lynx::Song& s) {
  9571. lynx::ChannelDef d;
  9572. d.instrument = lynx::InstrumentKind::synth;
  9573. d.name = "Synth";
  9574. d.mixerTrack = s.claimFreeInsert();
  9575. s.channels.push_back (d);
  9576. });
  9577. e.dispatchPendingMessages();
  9578. const auto header = lynx::channelFrameHeaderHeight();
  9579. if (auto w = lynx::makeChannelWindowForShot (e, (int) e.getSong().channels.size() - 1, 0))
  9580. {
  9581. const auto first = w->getBounds();
  9582. lynx::showChannelWindowTab (*w, -1);
  9583. const auto misc = w->getBounds();
  9584. lynx::showChannelWindowTab (*w, 0);
  9585. const auto back = w->getBounds();
  9586. lynx::pressChannelHeaderGear (*w);
  9587. const auto hiddenFirst = w->getBounds();
  9588. lynx::showChannelWindowTab (*w, -1);
  9589. const auto hiddenMisc = w->getBounds();
  9590. if (misc.getWidth() == first.getWidth() && misc.getHeight() == first.getHeight())
  9591. perTab259Result = "ERROR Misc has the plugin tab's size " + first.toString();
  9592. else if (back != first)
  9593. perTab259Result = "ERROR back on the plugin tab " + back.toString() + ", first " + first.toString();
  9594. else if (hiddenFirst.getHeight() != first.getHeight() - header || hiddenMisc.getHeight() != misc.getHeight() - header)
  9595. perTab259Result = "ERROR header hidden " + hiddenFirst.toString() + " / " + hiddenMisc.toString();
  9596. }
  9597. else
  9598. perTab259Result = "ERROR no window";
  9599. // round 190qd: FL's Sampler window keeps one size on all its tabs (Sample, Envelope / instrument, Misc)
  9600. e.editSong ([] (lynx::Song& s) {
  9601. lynx::ChannelDef d;
  9602. d.instrument = lynx::InstrumentKind::sampler;
  9603. d.name = "Sampler";
  9604. d.mixerTrack = s.claimFreeInsert();
  9605. s.channels.push_back (d);
  9606. });
  9607. e.dispatchPendingMessages();
  9608. if (auto w = perTab259Result == "OK" ? lynx::makeChannelWindowForShot (e, (int) e.getSong().channels.size() - 1, 0) : nullptr)
  9609. {
  9610. const auto first = w->getBounds();
  9611. lynx::showChannelWindowTab (*w, 1);
  9612. const auto envelope = w->getBounds();
  9613. lynx::showChannelWindowTab (*w, -1);
  9614. const auto misc = w->getBounds();
  9615. if (envelope != first || misc != first)
  9616. perTab259Result = "ERROR Sampler tabs differ " + first.toString() + " / " + envelope.toString() + " / " + misc.toString();
  9617. }
  9618. else if (perTab259Result == "OK")
  9619. perTab259Result = "ERROR no Sampler window";
  9620. lynx::windowplaces::fromVar ({});
  9621. }
  9622. // hotfix 0.1.31.1 (round 190qp): a docked window's place in the dock's coordinates (src/HotfixUi190qp.inc)
  9623. const auto hotfixPlacesResult = hotfixPlaces190qpCheck();
  9624. // round 190pv (issue #258): a cloned channel's own automation clip drives its sound (src/Issue258Test.inc: the app's
  9625. // engine, render-ahead off and on; Transistor Bass when FL Studio is here, LYNX Synth always)
  9626. juce::String issue258Log;
  9627. const auto issue258Result = issue258Check (issue258Log);
  9628. // round 190qp (0.1.31.1, issue #253 / Discord): an imported FL project's mixer volume, send level and Fruity Filter
  9629. // cutoff automation heard and shown through the app's engine, as imported, with a flat lane added and with the
  9630. // clips moved into lanes, render-ahead off / on, Clip-launch's override (src/Hotfix190qpTest.inc)
  9631. juce::String autolive190qpLog;
  9632. const auto autolive190qpResult = autoLiveCheck (autoLiveFlSong(), autolive190qpLog, 2, true);
  9633. // round 190qs (issue #282): FL's trial mark travels with its plugin in Export to FL Studio (src/Issue282Check.inc)
  9634. juce::String issue282Log;
  9635. const auto issue282Result = issue282Check (issue282Log);
  9636. // round 190qr (issues #274-#281): markers' Delete, the rack's time signature, FL's deepest zoom and the samples drawn
  9637. // there, the zoom-around-the-song-position and gain-handle extras (src/Issues190qrCheck.inc)
  9638. juce::String issues190qrLog;
  9639. const auto issues190qrResult = issues190qrCheck (issues190qrLog);
  9640. // round 190rb (0.1.32 quality release): the crash / memory fixes of the crash reports, the sanitizer build and the
  9641. // UI monkey test (src/Qa190rbCheck.inc)
  9642. juce::String qa190rbLog;
  9643. const auto qa190rbResult = qa190rbCheck (qa190rbLog);
  9644. // round 190qh (research190qa R5, Mixer QoL): FL's rule for a switched-off slot through the app's own publish
  9645. // (D2-MX9, REA 190qc: its latency leaves the plan at once, a muted insert keeps it), the theme's own meter
  9646. // thresholds in a .lynxtheme (D2-MX7; none written for the default look), the three unbound actions (D2-MX1, MX8)
  9647. // and the strips' extras (D2-VF5, MX3: off by default, under the read-out when on, the meters shorter by them)
  9648. juce::String mixerqol190qhResult = "OK";
  9649. {
  9650. lynx::AudioEngine e (false);
  9651. const auto before = e.getLatencySamples(); // (the default song's own: its Master limiter)
  9652. e.editSong ([] (lynx::Song& s) {
  9653. auto limiter = lynx::makeEffectSlot (lynx::EffectKind::fruityLimiter);
  9654. limiter.params[3] = 0.401f; // (FL's look-ahead, about 11 ms: round 188e)
  9655. s.mixer[1].effects.push_back (limiter);
  9656. });
  9657. const auto on = e.getLatencySamples();
  9658. e.editSong ([] (lynx::Song& s) { s.mixer[1].effects[0].enabled = false; });
  9659. const auto off = e.getLatencySamples();
  9660. e.editSong ([] (lynx::Song& s) {
  9661. s.mixer[1].effects[0].enabled = true;
  9662. s.mixer[1].muted = true;
  9663. });
  9664. const auto muted = e.getLatencySamples();
  9665. if (on <= before || off != before || muted != on)
  9666. mixerqol190qhResult = "ERROR PDC before / on / off / muted " + juce::String (before) + " / " + juce::String (on) + " / " + juce::String (off) + " / "
  9667. + juce::String (muted);
  9668. lynx::themes::Spec spec;
  9669. const auto plain = lynx::themeui::toJson (spec);
  9670. spec.meterZones = true;
  9671. spec.meterYellowDb = -12.0f;
  9672. spec.meterRedDb = -3.0f;
  9673. const auto back = lynx::themeui::fromJson (lynx::themeui::toJson (spec));
  9674. if (plain.contains ("meterYellowDb") || ! back || ! back->meterZones || back->meterYellowDb != -12.0f || back->meterRedDb != -3.0f
  9675. || lynx::themeui::fromJson (plain)->meterZones)
  9676. mixerqol190qhResult = "ERROR theme meter thresholds";
  9677. for (const auto* id : { "mixer.unsoloAll", "mixer.unmuteAll", "mixer.inputMonitoring" })
  9678. if (const auto* a = lynx::keys::findAction (id); a == nullptr || ! lynx::keys::KeyMap().chordsFor (id).empty())
  9679. mixerqol190qhResult = "ERROR action " + juce::String (id);
  9680. const auto keptPeaks = lynx::MixerStrips::showPeakValues, keptCorrelation = lynx::MixerStrips::showCorrelation;
  9681. {
  9682. lynx::MixerComponent mixer (e);
  9683. mixer.setSize (1400, 800);
  9684. auto& strips = mixer.getStripsForSnapshot();
  9685. strips.setShowPeakValues (false);
  9686. strips.setShowCorrelation (false);
  9687. const auto fader = strips.faderAreaForSnapshot (1);
  9688. const auto none = strips.peakValueAreaForSnapshot (1).isEmpty() && strips.correlationAreaForSnapshot (1).isEmpty();
  9689. strips.setShowPeakValues (true);
  9690. strips.setShowCorrelation (true);
  9691. const auto peak = strips.peakValueAreaForSnapshot (1), corr = strips.correlationAreaForSnapshot (1);
  9692. const auto shorter = strips.faderAreaForSnapshot (1);
  9693. if (! none || peak.isEmpty() || corr.isEmpty() || corr.getY() <= shorter.getBottom() || peak.getY() < corr.getBottom()
  9694. || fader.getHeight() - shorter.getHeight() != lynx::MixerStrips::correlationRowHeight + lynx::MixerStrips::peakRowHeight
  9695. || ! e.getMeters().correlationWanted.load())
  9696. mixerqol190qhResult = "ERROR strip extras " + peak.toString() + " / " + corr.toString() + " / " + fader.toString() + " / " + shorter.toString();
  9697. strips.setShowPeakValues (false);
  9698. strips.setShowCorrelation (false);
  9699. }
  9700. lynx::MixerStrips::showPeakValues = keptPeaks;
  9701. lynx::MixerStrips::showCorrelation = keptCorrelation;
  9702. }
  9703. // round 190qe (TOP-NEXT R1): the edge scroll at FL's speed, the view stack, the zoom glide and anchor, Restore
  9704. // selection, Keep labels on screen, through the real Playlist / Piano roll off screen (src/Feel190qeTest.inc)
  9705. juce::String feel190qeResult;
  9706. runFeel190qeTest ({}, {}, {}, &feel190qeResult);
  9707. // round 190qg: every toolbar item on the toolbar or in its overflow at every preset, Interface size and width
  9708. juce::String toolbar190qgLog;
  9709. const auto toolbar190qgResult = toolbar190qgCheck (toolbar190qgLog);
  9710. // round 190qu (Discord 11-24): automation clips into lanes play what they played (held value between clips, the
  9711. // control's own value before, FL's MIN / MAX), in the engine's first 1024 slots, and back into clips; FL's Split by
  9712. // channel; Convert to Track-only keeps every note; a Track-only instrument track's pencil draws new clips
  9713. juce::String discord190quResult = "OK";
  9714. {
  9715. using namespace lynx;
  9716. auto s = Song::makeDefault();
  9717. s.playlist.clear();
  9718. s.channels.clear();
  9719. s.automations.clear();
  9720. s.channels.push_back (mididrop::newChannel ("Lead"));
  9721. trackmodes::makeInstrumentTrack (s, 2, 0);
  9722. s.channels[0].volume = 0.62f;
  9723. Automation a;
  9724. a.target = { AutomationTargetKind::channelVolume, 0, 0, 0 };
  9725. a.points = { { 0, 0.0f, 0.0f }, { 4 * ppq, 1.0f, 0.0f } };
  9726. a.rangeMin = 0.2f;
  9727. a.rangeMax = 0.6f;
  9728. s.automations.push_back (a);
  9729. for (int k = 0; k < 1030; ++k) // (more automations than the engine's slots after it, on the tempo: no owner track)
  9730. {
  9731. Automation t;
  9732. t.target = { AutomationTargetKind::tempo, 0, 0, 0 };
  9733. t.points = { { 0, 0.5f, 0.0f } };
  9734. s.automations.push_back (t);
  9735. }
  9736. Clip c;
  9737. c.kind = ClipKind::automation;
  9738. c.automation = 0;
  9739. c.track = 5;
  9740. c.start = 4 * ppq;
  9741. c.length = 4 * ppq;
  9742. s.playlist.push_back (c);
  9743. const auto moved = laneview::clipsToLanes (s);
  9744. const auto lane = s.playlistTracks.size() > 2 && ! s.playlistTracks[2].lanes.empty() ? s.playlistTracks[2].lanes[0].automation : -1;
  9745. if (moved != 1 || lane < 0 || lane >= RackState::maxAutomations)
  9746. discord190quResult = "ERROR lane slot " + juce::String (lane);
  9747. else
  9748. {
  9749. const auto& points = s.automations[(std::size_t) lane];
  9750. const auto atStart = points.valueAt ((double) ppq), mid = points.valueAt (6.0 * ppq), held = points.valueAt (20.0 * ppq);
  9751. if (std::abs (atStart - 0.62f) > 1.0e-4f || std::abs (mid - 0.4f) > 1.0e-3f || std::abs (held - 0.6f) > 1.0e-4f)
  9752. discord190quResult = "ERROR lane values " + juce::String (atStart) + " / " + juce::String (mid) + " / " + juce::String (held);
  9753. else if (autolanes::lanesToClips (s) != 1 || laneview::laneCount (s) != 0)
  9754. discord190quResult = "ERROR lanes back to clips";
  9755. }
  9756. auto p = Song::makeDefault();
  9757. p.patterns.assign (1, Pattern {});
  9758. p.patterns[0].notes = { { 0, ticksPerStep, 0, 60 }, { ticksPerStep, ticksPerStep, 2, 60 } };
  9759. Clip pc;
  9760. pc.kind = ClipKind::pattern;
  9761. pc.track = 0;
  9762. pc.length = p.barTicks();
  9763. p.playlist = { pc };
  9764. auto split = p;
  9765. if (discord190quResult == "OK"
  9766. && (splitPatternByChannel (split, 0) != 1 || split.patterns[0].name != split.channels[0].name || split.playlist.size() != 1))
  9767. discord190quResult = "ERROR split by channel";
  9768. const auto report = trackonly::convertProject (p);
  9769. if (discord190quResult == "OK" && (report.patternsSplit != 1 || report.clipsMoved != 2 || trackmodes::instrumentTracksOf (p, 2).empty()))
  9770. discord190quResult = "ERROR convert " + juce::String (report.patternsSplit) + " / " + juce::String (report.clipsMoved);
  9771. const auto layout = layoutstyle::current();
  9772. const auto trackOnly = trackonly::enabled();
  9773. layoutstyle::setCurrent (layoutstyle::Style::pattern);
  9774. trackonly::setEnabled (true);
  9775. const auto home = trackmodes::instrumentTracksOf (p, 0);
  9776. if (discord190quResult == "OK" && (home.empty() || ! trackclips::pencilMakesNewClip (p, home.front())))
  9777. discord190quResult = "ERROR pencil";
  9778. trackonly::setEnabled (trackOnly);
  9779. layoutstyle::setCurrent (layout);
  9780. }
  9781. // round 190ot (research190oe P5): the Simple layout's "Duck under..." and shared Echo send in .lynx (the duck's goal,
  9782. // Amount, side input and level-0 route; the Echo send) and in the copies for 0.1.30 / 0.1.28: the same slot, side input,
  9783. // route and sends (an ordinary Fruity Limiter there), one view line, none for a project without a duck
  9784. // round 190pe (research190oe P20 / P11): a track's versions in .lynx (every version, the active one), a switch as one
  9785. // undo step that restores the song bit for bit, the copies for 0.1.30 / 0.1.28 (only the active version, one line;
  9786. // none without versions), and tracks of another project imported as one undo step
  9787. juce::String tracks190peResult = "OK";
  9788. {
  9789. namespace tv = lynx::trackversions;
  9790. auto song = lynx::Song::makeDefault();
  9791. song.playlist.clear();
  9792. lynx::ChannelDef vox;
  9793. vox.name = "Vox";
  9794. vox.instrument = lynx::InstrumentKind::audioClip;
  9795. vox.samplePath = "vox.wav";
  9796. const auto ins = song.nextFreeInsert(); // (an insert of its own: the version's chain)
  9797. vox.mixerTrack = ins;
  9798. song.channels.push_back (vox);
  9799. song.mixer[(std::size_t) ins].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::eq));
  9800. lynx::Clip c;
  9801. c.kind = lynx::ClipKind::audio;
  9802. c.channel = (int) song.channels.size() - 1;
  9803. c.track = 1;
  9804. c.length = 4 * lynx::ppq;
  9805. song.playlist.push_back (c);
  9806. song.playlistTracks.resize (2);
  9807. song.playlistTracks[1].name = "Vox";
  9808. const auto plain = lynx::ProjectFile::toJson (song);
  9809. tv::add (song, 1, tv::Start::duplicate, "B", "A");
  9810. for (auto& k : song.playlist)
  9811. if (k.track == 1)
  9812. k.length = lynx::ppq;
  9813. song.mixer[(std::size_t) ins].effects[0].enabled = false;
  9814. juce::String why;
  9815. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  9816. if (plain.contains ("playlistTrackVersions"))
  9817. tracks190peResult = "ERROR a project without versions writes the key";
  9818. else if (! back || back->playlistTracks.size() < 2 || back->playlistTracks[1].versions != song.playlistTracks[1].versions
  9819. || back->playlistTracks[1].activeVersion != 1 || back->playlist != song.playlist)
  9820. tracks190peResult = "ERROR .lynx round trip " + why;
  9821. if (tracks190peResult == "OK")
  9822. {
  9823. lynx::AudioEngine e (false);
  9824. e.setSong (song);
  9825. // (editSongStructural first adds the working time so far to the song: the undo step holds that)
  9826. const auto json = [] (lynx::Song s) {
  9827. s.info.workSeconds = 0.0;
  9828. return lynx::ProjectFile::toJson (s);
  9829. };
  9830. const auto before = json (e.getSong());
  9831. e.editSongStructural ([] (lynx::Song& s) { tv::switchTo (s, 1, 0); });
  9832. const auto switched = tv::active (e.getSong(), 1) == 0 && e.getSong().mixer[(std::size_t) ins].effects[0].enabled;
  9833. e.undo();
  9834. if (! switched || json (e.getSong()) != before)
  9835. tracks190peResult = juce::String ("ERROR undo of a version switch (switched ") + (switched ? "yes" : "no") + ")";
  9836. // tracks of another project: one undo step
  9837. if (tracks190peResult == "OK")
  9838. {
  9839. auto other = song;
  9840. lynx::trackimport::Result r;
  9841. e.editSongStructural ([&r, &other] (lynx::Song& s) { r = lynx::trackimport::importTracks (s, other, { 1 }, {}); });
  9842. const auto came = r.ok && r.tracks.size() == 1 && r.inserts.size() == 1 && tv::count (e.getSong(), r.tracks[0]) == 2;
  9843. e.undo();
  9844. if (! came || json (e.getSong()) != before)
  9845. tracks190peResult = juce::String ("ERROR import of a track and its undo (came ") + (came ? "yes" : "no") + ")";
  9846. }
  9847. }
  9848. for (const auto* release : { "0.1.30", "0.1.28" })
  9849. {
  9850. if (tracks190peResult != "OK")
  9851. break;
  9852. const auto copy = lynx::olderlynx::forRelease (song, release);
  9853. const auto lines = std::count_if (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains ("track version"); });
  9854. const auto opened = lynx::ProjectFile::fromJson (copy.json, why);
  9855. if (! copy.ok || lines != 1 || copy.json.contains ("playlistTrackVersions") || ! opened || opened->playlist != song.playlist
  9856. || opened->mixer[(std::size_t) ins].effects[0].enabled)
  9857. tracks190peResult = juce::String ("ERROR the copy for ") + release + " (" + juce::String ((int) lines) + " lines) " + why;
  9858. }
  9859. if (tracks190peResult == "OK")
  9860. {
  9861. const auto copy = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30");
  9862. if (std::any_of (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains ("track version"); }))
  9863. tracks190peResult = "ERROR a version line without versions";
  9864. }
  9865. }
  9866. juce::String simpleDuck190otResult = "OK";
  9867. {
  9868. namespace st = lynx::simpletracks;
  9869. auto song = lynx::Song::makeDefault();
  9870. st::Request q;
  9871. q.kind = st::Kind::audio;
  9872. q.name = "Kick";
  9873. const auto kick = st::addTrack (song, q).insert;
  9874. q.name = "Pad";
  9875. const auto pad = st::addTrack (song, q).insert;
  9876. const auto set = st::setDuck (song, pad, kick, 0.7f) == st::DuckResult::set && st::setEchoSend (song, pad, 0.3f);
  9877. const auto keeps = [&] (const std::optional<lynx::Song>& back) {
  9878. if (! back || (int) back->mixer.size() <= pad)
  9879. return false;
  9880. const auto slot = st::duckSlot (*back, pad);
  9881. return slot >= 0 && st::duckTrigger (*back, pad) == kick && back->routes (kick, pad) && back->routeLevel (kick, pad) == 0.0f
  9882. && std::abs (back->mixer[(std::size_t) pad].effects[(std::size_t) slot].goalAmount - 0.7f) < 1.0e-4f
  9883. && st::sharedEcho (*back) == st::sharedEcho (song) && std::abs (st::echoSend (*back, pad) - 0.3f) < 1.0e-4f;
  9884. };
  9885. juce::String why;
  9886. if (! set || kick <= 0 || pad <= 0)
  9887. simpleDuck190otResult = "ERROR set-up";
  9888. else if (! keeps (lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why)))
  9889. simpleDuck190otResult = "ERROR .lynx round trip " + why;
  9890. for (const auto* release : { "0.1.30", "0.1.28" })
  9891. {
  9892. if (simpleDuck190otResult != "OK")
  9893. break;
  9894. const auto copy = lynx::olderlynx::forRelease (song, release);
  9895. const auto lines = std::count_if (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains ("Duck under"); });
  9896. if (! copy.ok || ! keeps (lynx::ProjectFile::fromJson (copy.json, why)) || lines != 1)
  9897. simpleDuck190otResult = juce::String ("ERROR the copy for ") + release + " (" + juce::String ((int) lines) + " duck lines) " + why;
  9898. }
  9899. if (simpleDuck190otResult == "OK")
  9900. {
  9901. st::setDuck (song, pad, -1);
  9902. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  9903. if (std::any_of (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains ("Duck under"); }))
  9904. simpleDuck190otResult = "ERROR a duck line without a duck";
  9905. }
  9906. }
  9907. // round 190pm (research190oe P19): Note Repeats and Conditions in .lynx (every field), through the online sessions' note
  9908. // codec (optional fields), and in the copies for 0.1.30 / 0.1.28 (ratchets as notes of their own, one view line;
  9909. // conditions dropped, one sound line), none of it for a project without them
  9910. juce::String repeats190pmResult = "OK";
  9911. {
  9912. auto song = lynx::Song::makeDefault();
  9913. if (song.patterns.empty())
  9914. song.patterns.resize (1);
  9915. if (song.channels.empty())
  9916. song.channels.resize (1);
  9917. lynx::Note a;
  9918. a.start = 0;
  9919. a.length = lynx::ppq;
  9920. a.ratchets = 4;
  9921. a.ratchetVelocity = -0.5f;
  9922. lynx::Note b = a;
  9923. b.start = lynx::ppq;
  9924. b.ratchets = 0;
  9925. b.ratchetVelocity = 0.0f;
  9926. b.condition = lynx::notecondition::notFirst;
  9927. b.cycle = 4;
  9928. b.cycleMask = 0b1010;
  9929. song.patterns[0].notes = { a, b };
  9930. juce::String why;
  9931. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  9932. if (! back || back->patterns[0].notes != song.patterns[0].notes)
  9933. repeats190pmResult = "ERROR .lynx round trip " + why;
  9934. for (const auto& n : song.patterns[0].notes)
  9935. if (repeats190pmResult == "OK" && lynx::remote_notes::fromValue (lynx::remote_notes::toValue (n), song.channels.size()) != n)
  9936. repeats190pmResult = "ERROR the online sessions' note codec";
  9937. for (const auto* release : { "0.1.30", "0.1.28" })
  9938. {
  9939. if (repeats190pmResult != "OK")
  9940. break;
  9941. const auto copy = lynx::olderlynx::forRelease (song, release);
  9942. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  9943. const auto lines = std::count_if (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  9944. return juce::String (l.text).contains ("ratchets") || juce::String (l.text).contains ("Condition");
  9945. });
  9946. if (! old || old->patterns[0].notes.size() != 5 || lines != 2)
  9947. repeats190pmResult = juce::String ("ERROR the copy for ") + release + " (" + juce::String ((int) lines) + " lines) " + why;
  9948. }
  9949. song.patterns[0].notes = { lynx::Note {} };
  9950. if (repeats190pmResult == "OK")
  9951. for (const auto& l : lynx::olderlynx::forRelease (song, "0.1.30").lost)
  9952. if (juce::String (l.text).contains ("ratchets") || juce::String (l.text).contains ("Condition"))
  9953. repeats190pmResult = "ERROR a line without ratchets or conditions";
  9954. }
  9955. // round 190ol (research190oe P1 / P6): the Sections lane in .lynx (both arrangements, and a project without sections
  9956. // keeps its JSON with no "sections" key), a section move as one undo step that restores the song bit for bit, the
  9957. // copies for 0.1.30 / 0.1.28 (sections become plain markers at their starts, one view line), and a 4/4 -> 7/8 -> 4/4
  9958. // song's metronome table (core/SignatureEdit.h)
  9959. juce::String sections190olResult = "OK";
  9960. {
  9961. const auto bar = 4 * (std::int64_t) lynx::ppq;
  9962. auto song = lynx::Song::makeDefault();
  9963. song.playlistTracks.resize (std::max<std::size_t> (2, song.playlistTracks.size())); // (std::max: juce::jmax<std::size_t> instantiates SIMDRegister<unsigned long> on macOS arm64)
  9964. lynx::Clip c;
  9965. c.pattern = 0;
  9966. c.track = 0;
  9967. c.length = 2 * bar;
  9968. song.playlist = { c };
  9969. c.start = 2 * bar;
  9970. c.track = 1;
  9971. song.playlist.push_back (c);
  9972. song.sections() = { { 0, 2 * bar, "Intro", 0, 1 }, { 2 * bar, 2 * bar, "Verse", 0xFF336699u, 2 } };
  9973. song.addArrangement ("Second", true);
  9974. song.sections().push_back ({ 4 * bar, bar, "Outro", 0, 3 });
  9975. song.selectArrangement (0);
  9976. juce::String why;
  9977. const auto json = lynx::ProjectFile::toJson (song);
  9978. const auto back = lynx::ProjectFile::fromJson (json, why);
  9979. if (! back || back->arrangements.size() != 2 || back->arrangements[0].sections != song.arrangements[0].sections
  9980. || back->arrangements[1].sections != song.arrangements[1].sections || back->sections().size() != 2 || back->sections()[1].colour != 0xFF336699u)
  9981. sections190olResult = "ERROR round trip " + why;
  9982. else if (lynx::ProjectFile::toJson (lynx::Song::makeDefault()).contains ("\"sections\""))
  9983. sections190olResult = "ERROR a project without sections writes the key";
  9984. // one undo step, bit for bit
  9985. if (sections190olResult == "OK")
  9986. {
  9987. lynx::AudioEngine e (false);
  9988. e.setSong (song);
  9989. const auto before = lynx::ProjectFile::toJson (e.getSong());
  9990. e.editSong ([] (lynx::Song& s) { lynx::sections::move (s, 1, 0); });
  9991. const auto moved = e.getSong().sections().size() == 2 && e.getSong().sections()[0].name == "Verse";
  9992. e.undo();
  9993. if (! moved || lynx::ProjectFile::toJson (e.getSong()) != before)
  9994. sections190olResult = juce::String ("ERROR undo of a section move (moved ") + (moved ? "yes" : "no") + ")";
  9995. }
  9996. // the copies for older LYNX: plain markers at the sections' starts, "sections" gone, one line
  9997. for (const auto* release : { "0.1.30", "0.1.28" })
  9998. {
  9999. if (sections190olResult != "OK")
  10000. break;
  10001. const auto copy = lynx::olderlynx::forRelease (song, release);
  10002. const auto lines = std::count_if (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  10003. return juce::String (l.text).contains ("Sections lane");
  10004. });
  10005. juce::String why2;
  10006. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why2) : std::nullopt;
  10007. if (! copy.ok || copy.json.contains ("\"sections\"") || lines != 1 || ! old)
  10008. sections190olResult = juce::String ("ERROR the copy for ") + release;
  10009. else if (old->arrangements[0].markers.size() != 2 || old->arrangements[0].markers[1].name != "Verse" || old->arrangements[0].markers[1].tick != 2 * bar
  10010. || old->arrangements[1].markers.size() != 3 || ! old->arrangements[0].sections.empty())
  10011. sections190olResult = juce::String ("ERROR the markers in the copy for ") + release;
  10012. }
  10013. // P6: the metronome follows 4/4 -> 7/8 (bar 3) -> 4/4 (bar 5)
  10014. if (sections190olResult == "OK")
  10015. {
  10016. auto meter = lynx::Song::makeDefault();
  10017. const auto seven = 7 * (std::int64_t) lynx::ppq / 2;
  10018. lynx::signatureedit::set (meter, 2 * bar, 7, 8);
  10019. lynx::signatureedit::set (meter, 2 * bar + 2 * seven, 4, 4);
  10020. lynx::AudioEngine e (false);
  10021. e.setSong (meter);
  10022. e.dispatchPendingMessages();
  10023. const auto& t = e.getTransport();
  10024. if (t.signatureCount.load() != 3 || t.signatureTick[1].load() != 2 * bar || t.signatureLength[1].load() != seven
  10025. || t.signatureBeat[1].load() != (std::int64_t) lynx::ppq / 2 || t.signatureTick[2].load() != 2 * bar + 2 * seven
  10026. || t.signatureLength[2].load() != bar || meter.barAt (2 * bar + 2 * seven).number != 5)
  10027. sections190olResult = "ERROR the metronome's signature table (" + juce::String (t.signatureCount.load()) + " entries)";
  10028. }
  10029. }
  10030. // round 190pf (research190oe P13 / P12): the Chord lane in .lynx (both arrangements; a channel's follow mode; a project
  10031. // without chords keeps its JSON without the keys), a chord edit and Smart Tempo's write as one undo step each that
  10032. // restore the song bit for bit, and the copies for 0.1.30 / 0.1.28 (chords become plain markers named after them,
  10033. // "chords" and "followChords" gone, a line each)
  10034. juce::String chordlane190pfResult = "OK";
  10035. {
  10036. const auto bar = 4 * (std::int64_t) lynx::ppq;
  10037. auto song = lynx::Song::makeDefault();
  10038. song.playlistTracks.resize (std::max<std::size_t> (2, song.playlistTracks.size())); // (std::max: juce::jmax<std::size_t> instantiates SIMDRegister<unsigned long> on macOS arm64)
  10039. lynx::Clip c;
  10040. c.pattern = 0;
  10041. c.track = 0;
  10042. c.length = 2 * bar;
  10043. song.playlist = { c };
  10044. const auto chord = [] (int root, int shape, std::int64_t start, std::int64_t length, int bass = -1) {
  10045. auto x = lynx::chordlane::make (root, shape, bass);
  10046. x.start = start;
  10047. x.length = length;
  10048. return x;
  10049. };
  10050. song.chords() = { chord (0, 0, 0, bar), chord (9, 4, bar, bar), chord (7, 2, 2 * bar, bar, 11) };
  10051. lynx::chordlane::normalize (song.chords());
  10052. song.addArrangement ("Second", true);
  10053. song.chords().push_back (chord (5, 3, 4 * bar, bar));
  10054. lynx::chordlane::normalize (song.chords());
  10055. song.selectArrangement (0);
  10056. song.channels.front().followChords = lynx::chordlane::followBass;
  10057. juce::String why;
  10058. const auto json = lynx::ProjectFile::toJson (song);
  10059. const auto back = lynx::ProjectFile::fromJson (json, why);
  10060. if (! back || back->arrangements.size() != 2 || back->arrangements[0].chords != song.arrangements[0].chords
  10061. || back->arrangements[1].chords != song.arrangements[1].chords || back->chords().size() != 3 || back->chords()[2].bass != 11
  10062. || back->channels.front().followChords != lynx::chordlane::followBass)
  10063. chordlane190pfResult = "ERROR round trip " + why;
  10064. else if (const auto plain = lynx::ProjectFile::toJson (lynx::Song::makeDefault()); plain.contains ("\"chords\"") || plain.contains ("followChords"))
  10065. chordlane190pfResult = "ERROR a project without chords writes the keys";
  10066. if (chordlane190pfResult == "OK")
  10067. {
  10068. lynx::AudioEngine e (false);
  10069. e.setSong (song);
  10070. const auto before = lynx::ProjectFile::toJson (e.getSong());
  10071. e.editSong ([bar] (lynx::Song& s) { lynx::chordlane::move (s.chords(), 0, 3 * bar); });
  10072. const auto moved = e.getSong().chords().back().start == 3 * bar;
  10073. e.undo();
  10074. if (! moved || lynx::ProjectFile::toJson (e.getSong()) != before)
  10075. chordlane190pfResult = juce::String ("ERROR undo of a chord move (moved ") + (moved ? "yes" : "no") + ")";
  10076. }
  10077. for (const auto* release : { "0.1.30", "0.1.28" })
  10078. {
  10079. if (chordlane190pfResult != "OK")
  10080. break;
  10081. const auto copy = lynx::olderlynx::forRelease (song, release);
  10082. const auto lines = std::count_if (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  10083. return juce::String (l.text).contains ("Chord lane");
  10084. });
  10085. juce::String why2;
  10086. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why2) : std::nullopt;
  10087. if (! copy.ok || copy.json.contains ("\"chords\"") || copy.json.contains ("followChords") || lines != 2 || ! old)
  10088. chordlane190pfResult = juce::String ("ERROR the copy for ") + release + " (" + juce::String ((int) lines) + " lines)";
  10089. else if (old->arrangements[0].markers.size() != 3 || old->arrangements[0].markers[1].name != "Am7" || old->arrangements[0].markers[2].name != "G7/B"
  10090. || old->arrangements[0].markers[1].tick != bar || old->arrangements[1].markers.size() != 4 || ! old->arrangements[0].chords.empty())
  10091. chordlane190pfResult = juce::String ("ERROR the markers in the copy for ") + release;
  10092. }
  10093. // Smart Tempo: one undo step, bit for bit (the plan of a steady 120 BPM pulse on a clip at bar 2)
  10094. if (chordlane190pfResult == "OK")
  10095. {
  10096. auto take = lynx::Song::makeDefault();
  10097. take.playlist.clear();
  10098. lynx::ChannelDef audio;
  10099. audio.instrument = lynx::InstrumentKind::audioClip;
  10100. take.channels.push_back (audio);
  10101. lynx::Clip a;
  10102. a.kind = lynx::ClipKind::audio;
  10103. a.channel = (int) take.channels.size() - 1;
  10104. a.start = bar;
  10105. a.length = 8 * bar;
  10106. take.playlist.push_back (a);
  10107. std::vector<double> bars;
  10108. for (int k = 0; k <= 8; ++k)
  10109. bars.push_back (0.25 + k * 2.1);
  10110. const auto plan = lynx::smarttempo::plan (take, 0, bars, 20.0);
  10111. lynx::AudioEngine e (false);
  10112. e.setSong (take);
  10113. const auto before = lynx::ProjectFile::toJson (e.getSong());
  10114. auto ok = false;
  10115. e.editSong ([&] (lynx::Song& s) { ok = lynx::smarttempo::apply (s, 0, plan); });
  10116. const auto written = lynx::tempomarkers::list (e.getSong()).size();
  10117. e.undo();
  10118. if (! ok || written != 8 || lynx::ProjectFile::toJson (e.getSong()) != before)
  10119. chordlane190pfResult = "ERROR Smart Tempo's undo (" + juce::String ((int) written) + " markers)";
  10120. }
  10121. }
  10122. // round 190dr: the Session mixer's sections come back from a project (a project without them: Live's defaults);
  10123. // a device dragged to another track and a Warp switch are one undo step each in a real engine
  10124. juce::String livescr190drResult = "OK";
  10125. {
  10126. auto song = lynx::Song::makeDefault();
  10127. lynx::launcher::ensureGrid (song);
  10128. juce::String why;
  10129. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  10130. song.clipGrid->mixerView.io = false;
  10131. song.clipGrid->mixerView.trackOptions = true;
  10132. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  10133. if (! plain || ! plain->clipGrid || ! (plain->clipGrid->mixerView == lynx::SessionMixerView {}))
  10134. livescr190drResult = "ERROR view defaults " + why;
  10135. else if (! back || ! back->clipGrid || back->clipGrid->mixerView.io || ! back->clipGrid->mixerView.trackOptions || ! back->clipGrid->mixerView.shown)
  10136. livescr190drResult = "ERROR view round trip " + why;
  10137. lynx::AudioEngine e (false);
  10138. e.editSong ([] (lynx::Song& s) {
  10139. if (s.mixer.size() < 4)
  10140. s.mixer.resize (4);
  10141. s.mixer[2].effects.clear();
  10142. s.mixer[3].effects.clear();
  10143. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  10144. {
  10145. lynx::EffectSlot fx;
  10146. fx.kind = kind;
  10147. s.mixer[2].effects.push_back (fx);
  10148. }
  10149. lynx::Automation a;
  10150. a.target = { lynx::AutomationTargetKind::effectMix, 2, 1, 0 };
  10151. s.automations.push_back (a);
  10152. }, false);
  10153. const auto id = e.getSong().mixer[2].effects[1].instance.id;
  10154. const auto automations = e.getSong().automations.size();
  10155. e.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  10156. const auto& moved = e.getSong();
  10157. if (livescr190drResult == "OK"
  10158. && (moved.mixer[2].effects.size() != 1 || moved.mixer[3].effects.size() != 1 || moved.mixer[3].effects[0].instance.id != id
  10159. || moved.automations.size() != automations || moved.automations.back().target.index != 3 || moved.automations.back().target.slot != 0))
  10160. livescr190drResult = "ERROR device move";
  10161. e.undo();
  10162. const auto& undone = e.getSong();
  10163. if (livescr190drResult == "OK"
  10164. && (undone.mixer[2].effects.size() != 2 || undone.mixer[3].effects.size() != 0 || undone.mixer[2].effects[1].instance.id != id
  10165. || undone.automations.back().target.index != 2 || undone.automations.back().target.slot != 1))
  10166. livescr190drResult = "ERROR device move undo";
  10167. e.editSong ([] (lynx::Song& s) {
  10168. s.channels.resize (std::max<std::size_t> (s.channels.size(), 1));
  10169. s.channels[0].sampler.stretchBeats = 16.0f;
  10170. lynx::Clip c;
  10171. c.kind = lynx::ClipKind::audio;
  10172. c.channel = 0;
  10173. c.offset = 4 * lynx::ppq;
  10174. c.length = 8 * lynx::ppq;
  10175. lynx::launcher::setClip (s, 0, 0, c);
  10176. }, false);
  10177. e.editSong ([] (lynx::Song& s) { lynx::clipsample::setWarp (s, 0, false, 4.0); });
  10178. const auto* off = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  10179. if (livescr190drResult == "OK" && (e.getSong().channels[0].sampler.stretchBeats != 0.0f || off == nullptr || off->length != (std::int64_t) std::llround (8.0 * lynx::ppq * (4.0 * e.getSong().bpm / 60.0) / 16.0)))
  10180. livescr190drResult = "ERROR warp off";
  10181. e.undo();
  10182. const auto* on = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  10183. if (livescr190drResult == "OK" && (e.getSong().channels[0].sampler.stretchBeats != 16.0f || on == nullptr || on->length != 8 * lynx::ppq))
  10184. livescr190drResult = "ERROR warp undo";
  10185. }
  10186. // round 190ef: the map modes' storage (.lynx round trip of key / MIDI mappings and a link's Min / Max; an older
  10187. // reader keeps the plain link), and in a real engine: a link's range, MIDI Map Mode catching the control instead
  10188. // of moving anything, a slot's MIDI mapping firing on its press and release
  10189. juce::String livewf190efResult = "OK";
  10190. {
  10191. using namespace lynx::remotemap;
  10192. auto song = lynx::Song::makeDefault();
  10193. lynx::launcher::ensureGrid (song);
  10194. const lynx::AutomationTarget vol { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
  10195. assignMidi (song, Target::parameter (vol), { 0, 20, -1 });
  10196. assignMidi (song, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, 2 });
  10197. assignKey (song, Target::sceneLaunch (0), 'S');
  10198. assignKey (song, Target::parameter ({ lynx::AutomationTargetKind::tempo, 0, 0, 0 }), 'T');
  10199. setRange (song, rows (song, Mode::midi)[0], 0.25f, 0.75f);
  10200. setRange (song, rows (song, Mode::key)[1], 0.9f, 0.1f);
  10201. juce::String why;
  10202. const auto json = lynx::ProjectFile::toJson (song);
  10203. const auto back = lynx::ProjectFile::fromJson (json, why);
  10204. if (! back || back->remoteMappings != song.remoteMappings || back->midiLinks != song.midiLinks)
  10205. livewf190efResult = "ERROR round trip " + why;
  10206. auto parsed = juce::JSON::parse (json);
  10207. if (auto* o = parsed.getDynamicObject())
  10208. {
  10209. o->removeProperty ("remoteMappings");
  10210. o->removeProperty ("midiLinkSettings");
  10211. }
  10212. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  10213. if (livewf190efResult == "OK" && (! older || ! older->remoteMappings.empty() || older->midiLinks.size() != 1 || older->midiLinks[0].max != 1.0f))
  10214. livewf190efResult = "ERROR older reader";
  10215. const auto plain = lynx::ProjectFile::toJson (lynx::Song::makeDefault());
  10216. if (livewf190efResult == "OK" && plain.contains ("remoteMappings"))
  10217. livewf190efResult = "ERROR written without mappings";
  10218. lynx::AudioEngine e (false);
  10219. e.editSong ([vol] (lynx::Song& s) {
  10220. if (s.mixer.size() < 3)
  10221. s.mixer.resize (3);
  10222. lynx::MidiLink l { 20, 0, vol };
  10223. l.min = 0.25f;
  10224. l.max = 0.75f;
  10225. s.midiLinks = { l };
  10226. lynx::launcher::ensureGrid (s);
  10227. assignMidi (s, Target::slot (0, 0), { 0, 21, -1 });
  10228. });
  10229. e.injectControllerForTest (20, 0, 127);
  10230. const auto top = e.currentTargetValue (vol);
  10231. e.injectControllerForTest (20, 0, 0);
  10232. const auto bottom = e.currentTargetValue (vol);
  10233. if (livewf190efResult == "OK" && (std::abs (top - 0.75f) > 0.01f || std::abs (bottom - 0.25f) > 0.01f))
  10234. livewf190efResult = "ERROR range " + juce::String (bottom) + " " + juce::String (top);
  10235. std::vector<Fire> fired;
  10236. e.onRemoteFire = [&fired] (const Fire& f) { fired.push_back (f); };
  10237. e.injectControllerForTest (21, 0, 127);
  10238. e.injectControllerForTest (21, 0, 127); // (still down: no new press)
  10239. e.injectControllerForTest (21, 0, 0);
  10240. if (livewf190efResult == "OK"
  10241. && (fired.size() != 2 || fired[0].edge != Edge::press || fired[1].edge != Edge::release || ! (fired[0].target == Target::slot (0, 0))))
  10242. livewf190efResult = "ERROR slot fire " + juce::String ((int) fired.size());
  10243. e.setMapMode (Mode::midi);
  10244. fired.clear();
  10245. e.injectControllerForTest (20, 0, 127);
  10246. e.injectControllerForTest (21, 0, 127);
  10247. const auto caught = e.takeMapCapture();
  10248. if (livewf190efResult == "OK" && (std::abs (e.currentTargetValue (vol) - 0.25f) > 0.01f || ! fired.empty()))
  10249. livewf190efResult = "ERROR mappings acted in MIDI Map Mode";
  10250. else if (livewf190efResult == "OK" && (! caught || caught->number != 21 || caught->channel != 0 || e.takeMapCapture().has_value()))
  10251. livewf190efResult = "ERROR map capture";
  10252. e.setMapMode (Mode::off);
  10253. e.onRemoteFire = nullptr;
  10254. }
  10255. // round 190em: a scene's time signature denominator (.lynx round trip; an older file without it reads n/4; a
  10256. // launch of a 6 / 8 scene gives the song a 3-beat bar), and Capture MIDI in the clip grid of a real engine: the
  10257. // armed track, the selected scene's slot, the tempo from a phrase played while stopped (8 notes at 148 BPM), the
  10258. // new clip launched and the transport started
  10259. juce::String livewf190emResult = "OK";
  10260. {
  10261. auto song = lynx::Song::makeDefault();
  10262. auto& grid = lynx::launcher::ensureGrid (song);
  10263. grid.scenes.resize (3);
  10264. lynx::session::setSceneSignature (song, 1, 6, 8);
  10265. lynx::session::setSceneTempo (song, 1, 100.0);
  10266. juce::String why;
  10267. const auto json = lynx::ProjectFile::toJson (song);
  10268. const auto back = lynx::ProjectFile::fromJson (json, why);
  10269. if (! back || ! back->clipGrid || back->clipGrid->scenes != song.clipGrid->scenes || back->clipGrid->scenes[1].beatUnit != 8)
  10270. livewf190emResult = "ERROR round trip " + why;
  10271. {
  10272. // a captured clip's blank label (ClipGridSlot::blankName) survives the round trip
  10273. auto withClip = song;
  10274. lynx::Clip c;
  10275. c.pattern = 0;
  10276. c.length = 4 * lynx::ppq;
  10277. if (withClip.patterns.empty())
  10278. withClip.patterns.emplace_back();
  10279. const auto slot = lynx::launcher::setClip (withClip, 0, 0, c);
  10280. if (slot >= 0)
  10281. withClip.clipGrid->slots[(std::size_t) slot].blankName = true;
  10282. const auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (withClip), why);
  10283. const auto* keptClip = again && again->clipGrid ? lynx::launcher::clipAt (*again->clipGrid, 0, 0) : nullptr;
  10284. const auto* kept = keptClip != nullptr ? &again->clipGrid->slots[(std::size_t) keptClip->gridSlot] : nullptr;
  10285. if (livewf190emResult == "OK" && (slot < 0 || kept == nullptr || ! kept->blankName))
  10286. livewf190emResult = "ERROR blank clip name round trip";
  10287. }
  10288. auto parsed = juce::JSON::parse (json);
  10289. if (auto* scenes = parsed.getProperty ("clipGrid", {}).getProperty ("scenes", {}).getArray(); scenes != nullptr && scenes->size() > 1)
  10290. if (auto* o = (*scenes)[1].getDynamicObject())
  10291. o->removeProperty ("beatUnit");
  10292. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  10293. if (livewf190emResult == "OK" && (! older || ! older->clipGrid || older->clipGrid->scenes.size() < 2 || older->clipGrid->scenes[1].beatUnit != 4
  10294. || older->clipGrid->scenes[1].beatsPerBar != 6))
  10295. livewf190emResult = "ERROR older reader";
  10296. if (livewf190emResult == "OK" && lynx::ProjectFile::toJson (lynx::Song::makeDefault()).contains ("beatUnit"))
  10297. livewf190emResult = "ERROR beatUnit written by default";
  10298. // round 190fg: the song meter's denominator round-trips through .lynx; a file without it reads n/4
  10299. {
  10300. auto six = lynx::Song::makeDefault();
  10301. six.beatsPerBar = 6;
  10302. six.beatUnit = 8;
  10303. const auto text = lynx::ProjectFile::toJson (six);
  10304. juce::String why2;
  10305. const auto back = lynx::ProjectFile::fromJson (text, why2);
  10306. auto json = juce::JSON::parse (text);
  10307. if (auto* o = json.getDynamicObject())
  10308. o->removeProperty ("beatUnit");
  10309. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (json), why2);
  10310. if (livewf190emResult == "OK" && (! back || back->beatsPerBar != 6 || back->beatUnit != 8 || ! old || old->beatsPerBar != 6 || old->beatUnit != 4))
  10311. livewf190emResult = "ERROR song meter round trip";
  10312. }
  10313. lynx::AudioEngine e (false);
  10314. e.editSong ([] (lynx::Song& s) {
  10315. s.bpm = 120.0;
  10316. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  10317. auto& g = lynx::launcher::ensureGrid (s);
  10318. g.scenes.resize (3);
  10319. lynx::session::setSceneSignature (s, 2, 6, 8);
  10320. lynx::session::setSceneTempo (s, 2, 90.0);
  10321. }, false);
  10322. e.launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, 2 });
  10323. // (round 190fg: the song takes the scene's 6 / 8 as it is: six eighths a bar, 3 quarters long)
  10324. if (livewf190emResult == "OK" && (e.getSong().beatsPerBar != 6 || e.getSong().beatUnit != 8 || e.getSong().barTicks() != 3 * lynx::ppq
  10325. || e.getSong().bpm != 90.0))
  10326. livewf190emResult = "ERROR scene launch " + juce::String (e.getSong().beatsPerBar) + "/" + juce::String (e.getSong().beatUnit) + " "
  10327. + juce::String (e.getSong().bpm);
  10328. e.stop();
  10329. e.editSong ([] (lynx::Song& s) {
  10330. s.bpm = 120.0;
  10331. s.beatsPerBar = 4;
  10332. s.beatUnit = 4;
  10333. }, false);
  10334. e.setGridTrackArmed (2, true, true);
  10335. const auto now = juce::Time::getMillisecondCounterHiRes();
  10336. const auto beat = 60000.0 / 148.0;
  10337. for (int i = 0; i < 8; ++i)
  10338. {
  10339. const auto at = now - 9.0 * beat + i * beat;
  10340. e.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  10341. e.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  10342. }
  10343. int placed = -1;
  10344. bool into = true;
  10345. const auto r = e.captureMidiToSlot (2, 1, placed, into);
  10346. const auto& g = *e.getSong().clipGrid;
  10347. const auto* clip = lynx::launcher::clipAt (g, 2, 1);
  10348. if (livewf190emResult == "OK" && (r.notes != 8 || placed != 1 || into || clip == nullptr || clip->length != 8 * lynx::ppq))
  10349. livewf190emResult = "ERROR capture " + juce::String (r.notes) + " " + juce::String (placed) + (clip == nullptr ? " no clip" : " " + juce::String ((int) clip->length));
  10350. else if (livewf190emResult == "OK" && std::abs (e.getSong().bpm - 148.0) > 0.5)
  10351. livewf190emResult = "ERROR tempo " + juce::String (e.getSong().bpm, 2);
  10352. else if (livewf190emResult == "OK" && ! e.getTransport().playing.load())
  10353. livewf190emResult = "ERROR the capture did not start the transport";
  10354. e.stop();
  10355. }
  10356. const auto mixerBasics = lynx::mixerbasics::run();
  10357. // issue #142: every font has a typeface, and one without does not crash (fonts get theirs through the
  10358. // look and feel, as in the app)
  10359. auto& lookBefore = juce::LookAndFeel::getDefaultLookAndFeel();
  10360. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  10361. const auto fontsResult = lynx::theme::fontSelfTest();
  10362. auto paintCachesResult = lynx::theme::paintCacheSelfTest(); // (round 190gr)
  10363. if (paintCachesResult.startsWith ("OK")) // (round 190ki: the Pattern toolbar's cached FL tiles, the pixels of painting them straight)
  10364. {
  10365. const auto tiles = lynx::flTileCacheSelfTest();
  10366. paintCachesResult = tiles == "OK" ? paintCachesResult + ", FL tiles exact at x1 / x2" : tiles;
  10367. }
  10368. // round 190ne (0.1.31, core/TrackClips.h): track clips. A .lynx round trip keeps the flags and an older file opens
  10369. // unchanged; in a real engine a track clip goes with its last clip in the same undo step (Undo brings both back),
  10370. // ordinary patterns stay; the copy for 0.1.28 drops the flags with a loss line; an .flp export merges identical
  10371. // track clips.
  10372. juce::String trackclips190neResult = "OK";
  10373. {
  10374. auto song = lynx::Song::makeDefault();
  10375. if (song.patterns.empty())
  10376. song.patterns.emplace_back().name = "Pattern 1";
  10377. lynx::ChannelDef synth;
  10378. synth.name = "Lead";
  10379. song.channels.push_back (synth);
  10380. const auto channel = (int) song.channels.size() - 1;
  10381. lynx::trackmodes::makeInstrumentTrack (song, 2, channel);
  10382. lynx::trackclips::setOwnClips (song, 2, true);
  10383. const auto a = lynx::trackclips::newClip (song, 2, 4 * lynx::ppq);
  10384. song.patterns[(std::size_t) a].notes.push_back ({});
  10385. song.patterns[(std::size_t) a].notes.back().channel = channel;
  10386. song.patterns[(std::size_t) a].notes.back().key = 60;
  10387. song.patterns[(std::size_t) a].notes.back().length = lynx::ppq;
  10388. const auto b = lynx::trackclips::newClip (song, 2, 4 * lynx::ppq);
  10389. song.patterns[(std::size_t) b].notes = song.patterns[(std::size_t) a].notes;
  10390. for (const auto p : { a, a, b })
  10391. {
  10392. lynx::Clip c;
  10393. c.pattern = p;
  10394. c.track = 2;
  10395. c.start = (std::int64_t) song.playlist.size() * 4 * lynx::ppq;
  10396. c.length = 4 * lynx::ppq;
  10397. song.playlist.push_back (c);
  10398. }
  10399. juce::String why;
  10400. const auto json = lynx::ProjectFile::toJson (song);
  10401. const auto back = lynx::ProjectFile::fromJson (json, why);
  10402. if (! back || back->patterns != song.patterns || back->playlistTracks.size() <= 2 || ! back->playlistTracks[2].ownClips
  10403. || ! back->patterns[(std::size_t) a].trackClip || back->playlist.size() != song.playlist.size())
  10404. trackclips190neResult = "ERROR round trip " + why;
  10405. // an older project (no flags): opens unchanged, nothing becomes a track clip
  10406. const auto plain = lynx::Song::makeDefault();
  10407. const auto plainJson = lynx::ProjectFile::toJson (plain);
  10408. if (trackclips190neResult == "OK" && (plainJson.contains ("trackClip") || plainJson.contains ("playlistOwnClips")))
  10409. trackclips190neResult = "ERROR flags written for a project without track clips";
  10410. if (const auto reread = lynx::ProjectFile::fromJson (plainJson, why); trackclips190neResult == "OK"
  10411. && (! reread || lynx::trackclips::count (*reread) != 0 || lynx::ProjectFile::toJson (*reread) != plainJson))
  10412. trackclips190neResult = "ERROR an older project changed";
  10413. // the copy for 0.1.28: no flags, one loss line
  10414. const auto copy = lynx::olderlynx::forRelease (song, "0.1.28");
  10415. const auto said = [&copy] (const char* text) {
  10416. return std::any_of (copy.lost.begin(), copy.lost.end(), [text] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains (text); });
  10417. };
  10418. if (trackclips190neResult == "OK" && (! copy.ok || copy.json.contains ("\"trackClip\"") || copy.json.contains ("playlistOwnClips") || ! said ("track clip(s) show as ordinary patterns")))
  10419. trackclips190neResult = "ERROR copy for 0.1.28";
  10420. // .flp export: clips a and b hold the same notes: one pattern in FL, every clip kept
  10421. lynx::flpexport::Report flpReport;
  10422. const auto flp = flp::parseProject (lynx::flpexport::exportFlp (song, {}, flpReport));
  10423. auto other = song; // (b with other notes: nothing to merge)
  10424. other.patterns[(std::size_t) b].notes.front().key += 1;
  10425. const auto flpOther = flp::parseProject (lynx::flpexport::exportFlp (other, {}, flpReport));
  10426. if (trackclips190neResult == "OK" && flp.patterns.size() + 1 != flpOther.patterns.size())
  10427. trackclips190neResult = "ERROR flp merge " + juce::String ((int) flp.patterns.size()) + " / " + juce::String ((int) flpOther.patterns.size());
  10428. // a real engine: delete the last clip of b -> b goes in the same undo step; Undo brings it back
  10429. lynx::AudioEngine e (false);
  10430. e.editSong ([&song] (lynx::Song& s) { s = song; });
  10431. const auto before = e.getSong().patterns.size();
  10432. e.editSong ([] (lynx::Song& s) { s.playlist.pop_back(); }); // (the only clip of b)
  10433. if (trackclips190neResult == "OK" && (e.getSong().patterns.size() + 1 != before || e.getSong().playlist.size() != 2))
  10434. trackclips190neResult = "ERROR auto-delete " + juce::String ((int) e.getSong().patterns.size());
  10435. e.undo();
  10436. if (trackclips190neResult == "OK" && (e.getSong().patterns.size() != before || e.getSong().playlist.size() != 3))
  10437. trackclips190neResult = "ERROR undo of the auto-delete";
  10438. // an ordinary pattern without clips stays (FL)
  10439. e.editSong ([] (lynx::Song& s) { s.patterns.emplace_back().name = "Kept"; });
  10440. e.editSong ([] (lynx::Song& s) { s.playlist.erase (s.playlist.begin()); }); // (a's first clip: a still has one)
  10441. if (trackclips190neResult == "OK" && (e.getSong().patterns.size() != before + 1 || e.getSong().patterns.back().name != "Kept"))
  10442. trackclips190neResult = "ERROR an ordinary pattern or a linked clip went";
  10443. }
  10444. // round 190op (P4 / P7, LYNX extras): Hide and Deactivate tracks, Capture automation. Renders in a real engine: a
  10445. // hidden track plays the same (null), a deactivated channel and a deactivated insert are silent, Reactivate gives
  10446. // the same audio back (null), each in one undo step; the .lynx round trip keeps the flags and writes nothing for
  10447. // a project without them; the copy for 0.1.30 drops them with loss lines (deactivated units come back muted);
  10448. // the .flp export reports them; Capture automation writes the last gesture of each moved control in one undo step.
  10449. juce::String trackstates190opResult = "OK";
  10450. {
  10451. lynx::Song song;
  10452. song.mixer = lynx::Song::defaultMixer (4);
  10453. song.bpm = 120.0;
  10454. for (int c = 0; c < 2; ++c)
  10455. {
  10456. lynx::ChannelDef d;
  10457. d.name = c == 0 ? "Lead" : "Bass";
  10458. d.instrument = lynx::InstrumentKind::synth;
  10459. d.mixerTrack = c + 1;
  10460. song.channels.push_back (d);
  10461. }
  10462. song.patterns.clear();
  10463. auto& p = song.patterns.emplace_back();
  10464. p.name = "Both";
  10465. for (int i = 0; i < 4; ++i)
  10466. for (int c = 0; c < 2; ++c)
  10467. {
  10468. lynx::Note n;
  10469. n.channel = c;
  10470. n.key = c == 0 ? 72 + i : 40 + i;
  10471. n.start = i * lynx::ppq;
  10472. n.length = lynx::ppq / 2;
  10473. p.notes.push_back (n);
  10474. }
  10475. song.playlist.clear();
  10476. lynx::Clip clip;
  10477. clip.pattern = 0;
  10478. clip.track = 1;
  10479. clip.start = 0;
  10480. clip.length = 4 * lynx::ppq;
  10481. song.playlist.push_back (clip);
  10482. clip.track = 2;
  10483. clip.start = 24 * lynx::ppq; // (past the renders: the song is seven bars long, Capture's ticks don't fold)
  10484. song.playlist.push_back (clip);
  10485. song.mode = lynx::PlayMode::song;
  10486. const auto render = [] (lynx::AudioEngine& engine) {
  10487. std::vector<float> out;
  10488. lynx::AudioEngine::RenderOptions o;
  10489. o.seconds = 2.5;
  10490. o.sampleRate = 44100.0;
  10491. o.capture = [&out] (const float* l, const float* r, int n) {
  10492. for (int i = 0; i < n; ++i)
  10493. {
  10494. out.push_back (l[i]);
  10495. out.push_back (r[i]);
  10496. }
  10497. };
  10498. engine.renderOffline (o);
  10499. return out;
  10500. };
  10501. const auto peak = [] (const std::vector<float>& v) {
  10502. float m = 0.0f;
  10503. for (const auto x : v)
  10504. m = std::max (m, std::abs (x));
  10505. return m;
  10506. };
  10507. // (every comparison renders the first time on its engine: see the note below)
  10508. const auto renderSong = [&render] (const lynx::Song& s) {
  10509. lynx::AudioEngine fresh (false);
  10510. fresh.setSong (s);
  10511. return render (fresh);
  10512. };
  10513. const auto plain = renderSong (song);
  10514. lynx::AudioEngine e (false);
  10515. e.setSong (song);
  10516. // hide: the same samples, one undo step
  10517. e.editSong ([] (lynx::Song& s) { lynx::trackstates::setHidden (s, { 1 }, true); });
  10518. const auto hidden = renderSong (e.getSong());
  10519. if (peak (plain) < 0.01f || hidden != plain)
  10520. trackstates190opResult = "ERROR hidden track render differs (peak " + juce::String (peak (plain), 4) + ")";
  10521. e.undo();
  10522. if (trackstates190opResult == "OK" && lynx::trackstates::isHidden (e.getSong(), 1))
  10523. trackstates190opResult = "ERROR undo of Hide";
  10524. // (each render below is the first of its engine: a second render of one engine here plays nothing — the
  10525. // notes of a render are not scheduled again — so every state gets its own engine)
  10526. // deactivate the Bass channel (the real menu path: states captured first, one undo step): Lead alone
  10527. auto lead = song;
  10528. lead.channels[1].muted = true;
  10529. const auto leadOnly = renderSong (lead);
  10530. lynx::AudioEngine e1 (false);
  10531. e1.setSong (song);
  10532. e1.setDeactivated ({ 1 }, {}, true);
  10533. const auto noBass = render (e1);
  10534. float diff = 0.0f;
  10535. for (std::size_t i = 0; i < std::min (noBass.size(), leadOnly.size()); ++i)
  10536. diff = std::max (diff, std::abs (noBass[i] - leadOnly[i]));
  10537. if (trackstates190opResult == "OK"
  10538. && (! e1.channelDeactivated (1) || noBass.size() != leadOnly.size() || diff > 1.0e-6f || peak (noBass) < 0.01f))
  10539. trackstates190opResult = "ERROR deactivated channel is not silent (diff " + juce::String (diff, 7) + ")";
  10540. // then insert 1, into which Lead plays (Lead goes with it): silence
  10541. lynx::AudioEngine e2 (false);
  10542. e2.setSong (song);
  10543. e2.setDeactivated ({ 1 }, {}, true);
  10544. e2.setDeactivated ({}, { 1 }, true);
  10545. const auto silent = render (e2);
  10546. if (trackstates190opResult == "OK" && (! e2.channelDeactivated (0) || ! e2.insertDeactivated (1) || peak (silent) > 1.0e-6f))
  10547. trackstates190opResult = "ERROR deactivated insert is not silent (peak " + juce::String (peak (silent), 7) + ")";
  10548. // Reactivate (two undo steps) on an engine that ran the placeholders: its first render nulls with the plain
  10549. // song's (a placeholder kept for a reactivated unit would play nothing)
  10550. lynx::AudioEngine e3 (false);
  10551. e3.setSong (song);
  10552. const auto opened = e3.getSong(); // (as the engine holds it: ids given)
  10553. e3.setDeactivated ({ 1 }, {}, true);
  10554. e3.capturePluginStates(); // (as a save in between does: the shape keeps the placeholders)
  10555. e3.setDeactivated ({}, { 1 }, true);
  10556. e3.undo();
  10557. e3.undo();
  10558. const auto back = render (e3);
  10559. float backDiff = back.size() == plain.size() ? 0.0f : 1.0f;
  10560. for (std::size_t i = 0; i < std::min (back.size(), plain.size()); ++i)
  10561. backDiff = std::max (backDiff, std::abs (back[i] - plain[i]));
  10562. if (trackstates190opResult == "OK"
  10563. && (backDiff > 1.0e-6f || e3.channelDeactivated (1) || e3.insertDeactivated (1) || e3.getSong().channels != opened.channels
  10564. || e3.getSong().mixer != opened.mixer))
  10565. trackstates190opResult = "ERROR reactivated render differs (peak " + juce::String (peak (back), 4) + " / " + juce::String (peak (plain), 4)
  10566. + ", diff " + juce::String (backDiff, 8) + ", channels " + juce::String (e3.getSong().channels == opened.channels ? "same" : "differ")
  10567. + ", mixer " + juce::String (e3.getSong().mixer == opened.mixer ? "same" : "differ") + ")";
  10568. // the .lynx round trip, an older project, the copy for 0.1.30, the .flp report
  10569. auto flagged = song;
  10570. lynx::trackstates::setHidden (flagged, { 3 }, true);
  10571. flagged.channels[1].deactivated = true;
  10572. flagged.mixer[2].deactivated = true;
  10573. juce::String why;
  10574. const auto json = lynx::ProjectFile::toJson (flagged);
  10575. const auto reread = lynx::ProjectFile::fromJson (json, why);
  10576. if (trackstates190opResult == "OK"
  10577. && (! reread || ! lynx::trackstates::isHidden (*reread, 3) || ! reread->channels[1].deactivated || ! reread->mixer[2].deactivated
  10578. || reread->channels[0].deactivated || reread->mixer[1].deactivated))
  10579. trackstates190opResult = "ERROR round trip " + why;
  10580. const auto plainJson = lynx::ProjectFile::toJson (song);
  10581. if (trackstates190opResult == "OK" && (plainJson.contains ("playlistTracksHidden") || plainJson.contains ("\"deactivated\"")))
  10582. trackstates190opResult = "ERROR flags written for a project without them";
  10583. const auto copy = lynx::olderlynx::forRelease (flagged, "0.1.30");
  10584. const auto said = [&copy] (const char* text) {
  10585. return std::any_of (copy.lost.begin(), copy.lost.end(), [text] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains (text); });
  10586. };
  10587. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::nullopt;
  10588. if (trackstates190opResult == "OK"
  10589. && (! copy.ok || copy.json.contains ("playlistTracksHidden") || copy.json.contains ("\"deactivated\"") || ! said ("hidden Playlist track(s) show again")
  10590. || ! said ("Deactivated channels and inserts") || ! old || ! old->channels[1].muted || ! old->mixer[2].muted || old->channels[0].muted))
  10591. trackstates190opResult = "ERROR copy for 0.1.30";
  10592. const auto copy28 = lynx::olderlynx::forRelease (flagged, "0.1.28");
  10593. if (trackstates190opResult == "OK" && (! copy28.ok || copy28.json.contains ("playlistTracksHidden") || copy28.json.contains ("\"deactivated\"")))
  10594. trackstates190opResult = "ERROR copy for 0.1.28";
  10595. lynx::flpexport::Report flpReport;
  10596. (void) lynx::flpexport::exportFlp (flagged, {}, flpReport);
  10597. const auto noted = [&flpReport] (const char* text) {
  10598. return std::any_of (flpReport.notes.begin(), flpReport.notes.end(), [text] (const std::string& n) { return n.find (text) != std::string::npos; });
  10599. };
  10600. if (trackstates190opResult == "OK" && (! noted ("Hidden tracks: 1 track(s) written visible") || ! noted ("Deactivated: Bass")))
  10601. trackstates190opResult = "ERROR flp export report";
  10602. // Capture automation: two controls moved while playing (Song mode, Pattern layout, lanes off): two automation
  10603. // clips with the last gesture's ticks, one undo step; a second capture takes nothing
  10604. lynx::AudioEngine cap (false);
  10605. cap.setSong (song);
  10606. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
  10607. const lynx::AutomationTarget pan { lynx::AutomationTargetKind::mixerPan, 2, 0, 0 };
  10608. const auto bar = (double) song.barTicks();
  10609. auto sample = [&cap] (const lynx::AutomationTarget& t, double ms, double tick, float v) {
  10610. lynx::captureauto::Entry x;
  10611. x.target = t;
  10612. x.ms = ms;
  10613. x.tick = tick;
  10614. x.value = v;
  10615. cap.addAutomationCaptureSample (x);
  10616. };
  10617. sample (volume, 1000.0, 0.0, 0.2f); // gesture 1 (dropped: a gap of three bars follows)
  10618. sample (volume, 1100.0, 0.25 * bar, 0.3f);
  10619. sample (volume, 3000.0, 3.25 * bar, 0.5f); // gesture 2: the one captured
  10620. sample (volume, 3100.0, 3.5 * bar, 0.7f);
  10621. sample (pan, 3200.0, 3.5 * bar, 0.1f);
  10622. sample (pan, 3300.0, 3.75 * bar, 0.9f);
  10623. const auto automations = cap.getSong().automations.size();
  10624. const auto undoBefore = cap.getHistoryPosition();
  10625. const auto r = cap.captureAutomation();
  10626. const auto& as = cap.getSong().automations;
  10627. const auto clipOf = [&cap] (int automation) {
  10628. for (const auto& c : cap.getSong().playlist)
  10629. if (c.kind == lynx::ClipKind::automation && c.automation == automation)
  10630. return c;
  10631. return lynx::Clip {};
  10632. };
  10633. if (trackstates190opResult == "OK" && (r.controls != 2 || as.size() != automations + 2 || cap.getHistoryPosition() != undoBefore + 1))
  10634. trackstates190opResult = "ERROR capture " + juce::String (r.controls) + " controls, " + juce::String ((int) (as.size() - automations)) + " automations";
  10635. else if (trackstates190opResult == "OK")
  10636. {
  10637. const auto a = (int) automations;
  10638. const auto c0 = clipOf (a), c1 = clipOf (a + 1);
  10639. if (! (as[(std::size_t) a].target == volume) || ! (as[(std::size_t) a + 1].target == pan) || c0.kind != lynx::ClipKind::automation
  10640. || c0.start - c0.offset + (as[(std::size_t) a].points.empty() ? 0 : as[(std::size_t) a].points.front().tick) != (std::int64_t) (3.25 * bar)
  10641. || c1.start - c1.offset + (as[(std::size_t) a + 1].points.empty() ? 0 : as[(std::size_t) a + 1].points.front().tick) != (std::int64_t) (3.5 * bar))
  10642. trackstates190opResult = "ERROR capture ticks: clip " + juce::String (c0.start) + " first point "
  10643. + juce::String (as[(std::size_t) a].points.empty() ? -1 : as[(std::size_t) a].points.front().tick);
  10644. }
  10645. if (trackstates190opResult == "OK" && cap.captureAutomation().controls != 0)
  10646. trackstates190opResult = "ERROR a second capture took the same moves again";
  10647. }
  10648. // round 190pa (research190oe P21 / P14, LYNX extras): automation write modes and range edits on chosen tracks. The
  10649. // .lynx round trip keeps the mode and the range and writes neither for a project without them; the copies for
  10650. // 0.1.30 / 0.1.28 drop them with a line each; Capture automation in a real engine with Latch holds the gesture's
  10651. // last value to where its play pass stopped and Write writes its first value from where the pass started (Read
  10652. // as before); a range Delete / Duplicate on two tracks changes only them and is one undo step, undone bit for bit.
  10653. juce::String automodes190paResult = "OK";
  10654. {
  10655. const auto bar = (std::int64_t) 4 * lynx::ppq;
  10656. lynx::Song song;
  10657. song.mixer = lynx::Song::defaultMixer (4);
  10658. song.bpm = 120.0;
  10659. song.mode = lynx::PlayMode::song;
  10660. song.patterns.resize (4);
  10661. for (int t = 0; t < 4; ++t)
  10662. {
  10663. lynx::Clip c;
  10664. c.pattern = t;
  10665. c.track = t;
  10666. c.start = 0;
  10667. c.length = 16 * bar;
  10668. song.playlist.push_back (c);
  10669. }
  10670. song.playlistTracks.resize (4);
  10671. juce::String why;
  10672. const auto plainJson = lynx::ProjectFile::toJson (song);
  10673. if (plainJson.contains ("trackRange") || plainJson.contains ("automationWriteMode"))
  10674. automodes190paResult = "ERROR written for a project without them";
  10675. auto flagged = song;
  10676. flagged.automationWriteMode = 2;
  10677. flagged.trackRange = lynx::rangeedit::fromCorners (4 * bar, 8 * bar, 1, 2);
  10678. const auto reread = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (flagged), why);
  10679. if (automodes190paResult == "OK" && (! reread || reread->automationWriteMode != 2 || ! (reread->trackRange == flagged.trackRange)))
  10680. automodes190paResult = "ERROR round trip " + why;
  10681. for (const char* release : { "0.1.30", "0.1.28" })
  10682. {
  10683. const auto copy = lynx::olderlynx::forRelease (flagged, release);
  10684. const auto said = [&copy] (const char* text) {
  10685. return std::any_of (copy.lost.begin(), copy.lost.end(), [text] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains (text); });
  10686. };
  10687. if (automodes190paResult == "OK"
  10688. && (! copy.ok || copy.json.contains ("trackRange") || copy.json.contains ("automationWriteMode") || ! said ("automation write mode")
  10689. || ! said ("range selected on some Playlist tracks")))
  10690. automodes190paResult = "ERROR copy for " + juce::String (release);
  10691. }
  10692. // Capture automation per mode: one gesture of insert 1's volume at bars 2..2.5 of a pass that played 1..4
  10693. for (int mode = 0; mode < 4 && automodes190paResult == "OK"; ++mode)
  10694. {
  10695. lynx::AudioEngine cap (false);
  10696. auto s = song;
  10697. s.automationWriteMode = mode;
  10698. cap.setSong (s);
  10699. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
  10700. auto& buffer = cap.automationCaptureForTests();
  10701. buffer.notePlaying ((double) bar);
  10702. for (int i = 0; i <= 4; ++i)
  10703. {
  10704. lynx::captureauto::Entry x;
  10705. x.target = volume;
  10706. x.ms = 1000.0 + 100.0 * i;
  10707. x.tick = (double) (2 * bar) + i * (double) bar / 8.0;
  10708. x.value = 0.2f + 0.15f * (float) i;
  10709. x.pass = buffer.currentPass();
  10710. buffer.notePlaying (x.tick);
  10711. cap.addAutomationCaptureSample (x);
  10712. }
  10713. buffer.notePlaying ((double) (4 * bar));
  10714. buffer.noteStopped();
  10715. if (cap.captureAutomation().controls != 1)
  10716. {
  10717. automodes190paResult = "ERROR capture in mode " + juce::String (mode);
  10718. break;
  10719. }
  10720. const auto& song2 = cap.getSong();
  10721. const auto& a = song2.automations.back();
  10722. const lynx::Clip* clip = nullptr;
  10723. for (const auto& c : song2.playlist)
  10724. if (c.kind == lynx::ClipKind::automation && c.automation == (int) song2.automations.size() - 1)
  10725. clip = &c;
  10726. if (clip == nullptr)
  10727. {
  10728. automodes190paResult = "ERROR no automation clip in mode " + juce::String (mode);
  10729. break;
  10730. }
  10731. const auto valueAt = [&] (double songTick) { return a.valueAt (songTick - (double) clip->start + (double) clip->offset); };
  10732. const auto lastPoint = a.points.empty() ? (std::int64_t) -1 : a.points.back().tick + clip->start - clip->offset;
  10733. const auto firstPoint = a.points.empty() ? (std::int64_t) -1 : a.points.front().tick + clip->start - clip->offset;
  10734. const auto holds = std::abs (valueAt (3.5 * (double) bar) - 0.8f) < 0.01f && lastPoint >= 4 * bar - 1;
  10735. const auto fromStart = firstPoint <= bar && std::abs (valueAt (1.5 * (double) bar) - 0.2f) < 0.01f;
  10736. const bool ok = mode == 0 || mode == 1 ? (! holds && ! fromStart && firstPoint == 2 * bar)
  10737. : mode == 2 ? (holds && ! fromStart && firstPoint == 2 * bar)
  10738. : (holds && fromStart);
  10739. if (! ok)
  10740. automodes190paResult = "ERROR capture curve in mode " + juce::String (mode) + " (first " + juce::String (firstPoint) + ", last "
  10741. + juce::String (lastPoint) + ")";
  10742. }
  10743. // range edits on tracks 2-3 (1, 2): one undo step each, the other tracks untouched, undo bit for bit
  10744. if (automodes190paResult == "OK")
  10745. {
  10746. lynx::AudioEngine e (false);
  10747. e.setSong (song);
  10748. const auto before = e.getSong().playlist;
  10749. e.editSong ([bar] (lynx::Song& s) { s.trackRange = lynx::rangeedit::fromCorners (4 * bar, 8 * bar, 1, 2); }, false);
  10750. const auto steps = e.getHistoryPosition();
  10751. e.editSong ([] (lynx::Song& s) { lynx::rangeedit::clearRange (s, s.trackRange); });
  10752. const auto& after = e.getSong().playlist;
  10753. const auto count = [] (const std::vector<lynx::Clip>& list, int track) {
  10754. return (int) std::count_if (list.begin(), list.end(), [track] (const lynx::Clip& c) { return c.track == track; });
  10755. };
  10756. if (e.getHistoryPosition() != steps + 1 || count (after, 0) != 1 || count (after, 3) != 1 || count (after, 1) != 2 || count (after, 2) != 2)
  10757. automodes190paResult = "ERROR range delete";
  10758. e.undo();
  10759. if (automodes190paResult == "OK" && ! (e.getSong().playlist == before))
  10760. automodes190paResult = "ERROR range delete undo";
  10761. e.editSong ([] (lynx::Song& s) { s.trackRange = lynx::rangeedit::duplicateRange (s, s.trackRange); });
  10762. if (automodes190paResult == "OK" && (e.getSong().trackRange.from != 8 * bar || count (e.getSong().playlist, 1) != 3 || count (e.getSong().playlist, 0) != 1))
  10763. automodes190paResult = "ERROR range duplicate";
  10764. e.undo();
  10765. if (automodes190paResult == "OK" && (! (e.getSong().playlist == before) || e.getSong().trackRange.from != 4 * bar))
  10766. automodes190paResult = "ERROR range duplicate undo";
  10767. }
  10768. }
  10769. // round 190nw (0.1.31): the tracker. Its settings are saved only when changed (an older project's file stays the
  10770. // same bytes) and come back; the copies for 0.1.30 / 0.1.28 drop them with one loss line; a module imports in a
  10771. // real engine (one note, one Sampler channel, its sample written) and its notes render.
  10772. juce::String tracker190nwResult = "OK", tracker190obResult = "OK", tracker190omResult = "OK";
  10773. {
  10774. auto song = lynx::Song::makeDefault();
  10775. juce::String why;
  10776. const auto plainJson = lynx::ProjectFile::toJson (song);
  10777. if (plainJson.contains ("\"tracker\""))
  10778. tracker190nwResult = "ERROR settings written for a project that never changed them";
  10779. if (const auto reread = lynx::ProjectFile::fromJson (plainJson, why); tracker190nwResult == "OK" && (! reread || lynx::ProjectFile::toJson (*reread) != plainJson))
  10780. tracker190nwResult = "ERROR an older project changed";
  10781. for (int c = 0; c < 2; ++c)
  10782. song.channels.emplace_back().name = "T" + std::to_string (c);
  10783. lynx::uids::normalize (song);
  10784. song.tracker.rowsPerBeat = 8;
  10785. song.tracker.showPan = true;
  10786. song.tracker.groups.push_back ({ "Drums", { song.channels[song.channels.size() - 2].uid, song.channels.back().uid } });
  10787. const auto json = lynx::ProjectFile::toJson (song);
  10788. const auto back = lynx::ProjectFile::fromJson (json, why);
  10789. if (tracker190nwResult == "OK" && (! back || ! (back->tracker == song.tracker)))
  10790. tracker190nwResult = "ERROR round trip " + why;
  10791. for (const auto* release : { "0.1.30", "0.1.28" })
  10792. {
  10793. const auto copy = lynx::olderlynx::forRelease (song, release);
  10794. const auto said = std::any_of (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains ("tracker's view settings"); });
  10795. if (tracker190nwResult == "OK" && (! copy.ok || copy.json.contains ("\"tracker\"") || ! said))
  10796. tracker190nwResult = "ERROR copy for " + juce::String (release);
  10797. }
  10798. // a ProTracker module of one note, through the engine's import (its sample written beside it)
  10799. const auto folder = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-190nw-" + juce::String (juce::Time::currentTimeMillis()));
  10800. folder.createDirectory();
  10801. std::vector<std::uint8_t> mod (1084 + 1024 + 128, 0);
  10802. std::memcpy (mod.data(), "selftest", 8);
  10803. mod[20 + 22] = 0, mod[20 + 23] = 64, mod[20 + 25] = 64, mod[20 + 29] = 1; // sample 1: 128 bytes, volume 64, no loop
  10804. for (int k = 1; k < 31; ++k)
  10805. mod[(std::size_t) (20 + k * 30 + 29)] = 1;
  10806. mod[950] = 1, mod[951] = 127;
  10807. std::memcpy (mod.data() + 1080, "M.K.", 4);
  10808. mod[1084] = 0x01, mod[1085] = 0xAC, mod[1086] = 0x10; // row 0: C-2 (428), sample 1
  10809. for (int i = 0; i < 128; ++i)
  10810. mod[(std::size_t) (1084 + 1024 + i)] = (std::uint8_t) (std::int8_t) std::lround (90.0 * std::sin (i * 0.39));
  10811. const auto modFile = folder.getChildFile ("one note.mod");
  10812. modFile.replaceWithData (mod.data(), mod.size());
  10813. lynx::AudioEngine e (false);
  10814. juce::String error;
  10815. if (tracker190nwResult == "OK" && ! e.importFlpFile (modFile, error))
  10816. tracker190nwResult = "ERROR module import: " + error;
  10817. const auto& imported = e.getSong();
  10818. if (tracker190nwResult == "OK" && (imported.channels.size() != 1 || imported.patterns.empty() || imported.patterns.front().notes.size() != 1
  10819. || ! folder.getChildFile ("one note samples").getChildFile ("01-01.wav").existsAsFile()))
  10820. tracker190nwResult = "ERROR module import: " + juce::String ((int) imported.channels.size()) + " channel(s), "
  10821. + juce::String (imported.patterns.empty() ? 0 : (int) imported.patterns.front().notes.size()) + " note(s)";
  10822. if (tracker190nwResult == "OK")
  10823. {
  10824. const auto peak = e.renderOffline (1.0, 44100.0, nullptr);
  10825. if (peak < 0.01f)
  10826. tracker190nwResult = "ERROR the imported note is silent (peak " + juce::String (peak) + ")";
  10827. }
  10828. // round 190ob: the same note, its sample looping, with a volume set on row 1 (C10, no note): its channel's
  10829. // Volume multiplier automation comes in, is saved and read back the same, and the note still sounds
  10830. if (tracker190obResult == "OK")
  10831. {
  10832. mod[1084 + 16 + 2] = 0x0C, mod[1084 + 16 + 3] = 0x10;
  10833. mod[20 + 28] = 0, mod[20 + 29] = 64; // (the sample loops whole: the note still sounds on row 1)
  10834. const auto volumeFile = folder.getChildFile ("one note volume.mod");
  10835. volumeFile.replaceWithData (mod.data(), mod.size());
  10836. lynx::AudioEngine ve (false);
  10837. if (! ve.importFlpFile (volumeFile, error))
  10838. tracker190obResult = "ERROR module import: " + error;
  10839. else
  10840. {
  10841. const auto& vs = ve.getSong();
  10842. const auto automation = std::find_if (vs.automations.begin(), vs.automations.end(), [] (const lynx::Automation& a) {
  10843. return a.target.kind == lynx::AutomationTargetKind::channelAdjust && a.target.param == lynx::leveladjust::volume && a.target.index == 0;
  10844. });
  10845. // (round 190om: a pattern played once changes its volume as pattern events of the multiplier)
  10846. const auto events = std::any_of (vs.patterns.begin(), vs.patterns.end(), [] (const lynx::Pattern& p) {
  10847. return std::any_of (p.events.begin(), p.events.end(), [] (const lynx::PatternEvents& l) {
  10848. return l.target.kind == lynx::AutomationTargetKind::channelAdjust && l.target.param == lynx::leveladjust::volume && l.target.index == 0
  10849. && l.events.size() >= 2;
  10850. });
  10851. });
  10852. if ((automation == vs.automations.end() || automation->points.size() < 2) && ! events)
  10853. tracker190obResult = "ERROR no volume automation";
  10854. else if (const auto reread = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (vs), why); ! reread || reread->automations != vs.automations
  10855. || reread->patterns != vs.patterns)
  10856. tracker190obResult = "ERROR the automation changed on the .lynx round trip " + why;
  10857. else if (ve.renderOffline (1.0, 44100.0, nullptr) < 0.001f)
  10858. tracker190obResult = "ERROR the note is silent";
  10859. }
  10860. }
  10861. // round 190om: a pitch slide (102 on row 1) on that note: its pitch curve and the volume set's pattern events
  10862. // come in, are saved and read back the same, and it sounds; SimSynth's velocity law and its copy for 0.1.30
  10863. {
  10864. mod[1084 + 16 + 2] = 0x01, mod[1084 + 16 + 3] = 0x02;
  10865. mod[1084 + 32 + 2] = 0x0C, mod[1084 + 32 + 3] = 0x10;
  10866. const auto slideFile = folder.getChildFile ("one note slide.mod");
  10867. slideFile.replaceWithData (mod.data(), mod.size());
  10868. lynx::AudioEngine se (false);
  10869. if (! se.importFlpFile (slideFile, error))
  10870. tracker190omResult = "ERROR module import: " + error;
  10871. else
  10872. {
  10873. const auto& ss = se.getSong();
  10874. const auto curved = std::any_of (ss.patterns.begin(), ss.patterns.end(), [] (const lynx::Pattern& p) {
  10875. return std::any_of (p.notes.begin(), p.notes.end(), [] (const lynx::Note& n) { return n.curves.has() && n.curves->moves (lynx::NoteCurveLane::pitch); });
  10876. });
  10877. const auto events = std::any_of (ss.patterns.begin(), ss.patterns.end(), [] (const lynx::Pattern& p) { return ! p.events.empty(); });
  10878. if (! curved || ! events)
  10879. tracker190omResult = juce::String ("ERROR import: ") + (curved ? "" : "no pitch curve ") + (events ? "" : "no pattern events");
  10880. else if (const auto reread = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (ss), why); ! reread || reread->patterns != ss.patterns)
  10881. tracker190omResult = "ERROR the curves or events changed on the .lynx round trip " + why;
  10882. else if (se.renderOffline (1.0, 44100.0, nullptr) < 0.001f)
  10883. tracker190omResult = "ERROR the note is silent";
  10884. }
  10885. }
  10886. if (tracker190omResult == "OK")
  10887. {
  10888. auto song = lynx::Song::makeDefault();
  10889. auto& sim = song.channels.emplace_back();
  10890. sim.name = "Sim";
  10891. sim.instrument = lynx::InstrumentKind::simsynth;
  10892. sim.pluginState = lynx::simsynth::defaultState();
  10893. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  10894. const auto said = std::any_of (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains ("SimSynth plays every note at full level"); });
  10895. auto older = song;
  10896. older.channels.back().engineRev = 1;
  10897. const auto olderCopy = lynx::olderlynx::forRelease (older, "0.1.30");
  10898. const auto olderSaid = std::any_of (olderCopy.lost.begin(), olderCopy.lost.end(), [] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains ("SimSynth plays every note"); });
  10899. juce::String why2;
  10900. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why2);
  10901. if (sim.engineRev < 2 || ! copy.ok || ! said || olderSaid || ! back || back->channels.back().engineRev != sim.engineRev) // (≥ 2: round 190pr's 3 too)
  10902. tracker190omResult = "ERROR SimSynth revision: copy " + juce::String (said ? "said" : "silent") + (olderSaid ? ", old one said" : "");
  10903. }
  10904. folder.deleteRecursively();
  10905. }
  10906. // round 190oo (design review 2, PAT-7; core/RackAutomation.h): the automation clips' Channel rack rows. A .lynx
  10907. // round trip keeps each clip's place; a clip without one (every clip of an older file) writes nothing and reads
  10908. // back after the channels; the copy for 0.1.30 drops the key without a loss line.
  10909. juce::String rackauto190ooResult = "OK";
  10910. {
  10911. auto song = lynx::Song::makeDefault();
  10912. for (int c = 0; c < 3; ++c)
  10913. song.channels.emplace_back().name = "R" + std::to_string (c);
  10914. lynx::Automation placed, appended;
  10915. placed.name = "placed";
  10916. placed.points = { { 0, 0.2f, 0.0f }, { lynx::ppq, 0.8f, 0.0f } };
  10917. placed.rackSlot = 1;
  10918. appended = placed;
  10919. appended.name = "appended";
  10920. appended.rackSlot = -1;
  10921. song.automations.push_back (placed);
  10922. song.automations.push_back (appended);
  10923. juce::String why;
  10924. const auto json = lynx::ProjectFile::toJson (song);
  10925. const auto back = lynx::ProjectFile::fromJson (json, why);
  10926. if (! back || back->automations.size() != 2 || back->automations[0].rackSlot != 1 || back->automations[1].rackSlot != -1
  10927. || lynx::rackauto::order (*back) != lynx::rackauto::order (song))
  10928. rackauto190ooResult = "ERROR round trip " + why;
  10929. const auto plain = lynx::Song::makeDefault();
  10930. const auto plainJson = lynx::ProjectFile::toJson (plain);
  10931. if (rackauto190ooResult == "OK" && plainJson.contains ("rackSlot"))
  10932. rackauto190ooResult = "ERROR rackSlot written for a project without placed clips";
  10933. auto older = song;
  10934. older.automations[0].rackSlot = -1; // (as a file saved before round 190oo)
  10935. if (const auto reread = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (older), why); rackauto190ooResult == "OK"
  10936. && (! reread || reread->automations.size() != 2 || reread->automations[0].rackSlot != -1 || lynx::ProjectFile::toJson (older).contains ("rackSlot")))
  10937. rackauto190ooResult = "ERROR an older project's clips";
  10938. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  10939. if (rackauto190ooResult == "OK" && (! copy.ok || copy.json.contains ("rackSlot")))
  10940. rackauto190ooResult = "ERROR copy for 0.1.30";
  10941. }
  10942. // round 190ow (PAT-7 rest, details DE-123; core/RackAutomation.h): what the automation clip rows play. A .lynx round
  10943. // trip keeps the steps / notes on the rows (Pattern::autoNotes), the clips' MIN / MAX and their mute light; a
  10944. // project without them writes none of the keys; the copy for 0.1.30 drops the steps (a loss line: 0.1.30 starts
  10945. // no clip from a pattern), writes the MIN / MAX into the points (the same values play there) and leaves a muted
  10946. // clip without a target (it stays silent), with a loss line each.
  10947. juce::String rackauto190owResult = "OK";
  10948. {
  10949. auto song = lynx::Song::makeDefault();
  10950. lynx::Automation duck;
  10951. duck.name = "duck";
  10952. duck.points = { { 0, 0.0f, 0.0f }, { lynx::ppq, 1.0f, 0.0f } };
  10953. duck.target = { lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 };
  10954. duck.rangeMin = 0.25f;
  10955. duck.rangeMax = 0.75f;
  10956. auto quiet = duck;
  10957. quiet.name = "quiet";
  10958. quiet.rangeMin = 0.0f;
  10959. quiet.rangeMax = 1.0f;
  10960. quiet.muted = true;
  10961. song.automations = { duck, quiet };
  10962. song.patterns[0].toggleAutoStep (0, 0);
  10963. song.patterns[0].toggleAutoStep (0, 4);
  10964. lynx::Note held;
  10965. held.start = 8 * lynx::ticksPerStep;
  10966. held.length = 0; // (FL's step of no length)
  10967. held.channel = 1;
  10968. held.key = 64;
  10969. song.patterns[0].autoNotes.push_back (held);
  10970. song.patterns[0].sortNotes();
  10971. juce::String why;
  10972. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  10973. if (! back || back->patterns.empty() || back->patterns[0].autoNotes != song.patterns[0].autoNotes || back->automations.size() != 2
  10974. || back->automations[0].rangeMin != 0.25f || back->automations[0].rangeMax != 0.75f || back->automations[1].muted != true
  10975. || back->automations[0].muted || ! back->patterns[0].hasAutoStep (0, 4))
  10976. rackauto190owResult = "ERROR round trip " + why;
  10977. const auto plainJson = lynx::ProjectFile::toJson (lynx::Song::makeDefault());
  10978. if (rackauto190owResult == "OK" && (plainJson.contains ("autoNotes") || plainJson.contains ("\"range\"")))
  10979. rackauto190owResult = "ERROR keys written for a project without them";
  10980. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  10981. int lossLines = 0;
  10982. for (const auto& l : copy.lost)
  10983. lossLines += juce::String (l.text).contains ("automation clip") || juce::String (l.text).contains ("Muted automation") ? 1 : 0;
  10984. if (rackauto190owResult == "OK" && (! copy.ok || copy.json.contains ("autoNotes") || copy.json.contains ("\"range\"") || lossLines < 2))
  10985. rackauto190owResult = "ERROR copy for 0.1.30 (" + juce::String (lossLines) + " loss lines)";
  10986. if (rackauto190owResult == "OK")
  10987. if (const auto old = lynx::ProjectFile::fromJson (copy.json, why); ! old || old->automations.size() != 2
  10988. || std::abs (old->automations[0].points[0].value - 0.25f) > 1.0e-3f || std::abs (old->automations[0].points[1].value - 0.75f) > 1.0e-3f
  10989. || old->automations[1].target.kind != lynx::AutomationTargetKind::none)
  10990. rackauto190owResult = "ERROR the copy's values";
  10991. const auto copy28 = lynx::olderlynx::forRelease (song, "0.1.28");
  10992. if (rackauto190owResult == "OK" && (! copy28.ok || copy28.json.contains ("autoNotes")))
  10993. rackauto190owResult = "ERROR copy for 0.1.28";
  10994. }
  10995. const auto motionOverlayResult = lynx::ui::MotionOverlay::selfTest(); // (round 190ip)
  10996. // round 190bm (0.1.25 showed the Mixer and the Playlist black): their cached pictures shown on native and
  10997. // software targets against straight paints (ui/PictureCheck.h; --picturetest runs more sizes and scales)
  10998. juce::String picturesResult = "OK";
  10999. {
  11000. lynx::AudioEngine pictureEngine (false);
  11001. auto pictureFailures = 0;
  11002. juce::String lines;
  11003. {
  11004. lynx::PlaylistComponent playlist (pictureEngine);
  11005. playlist.setBounds (0, 0, 1200, 700);
  11006. playlist.setVisible (true);
  11007. lines << lynx::ui::picturecheck::run (playlist, "Playlist 1200 x 700", { 1.0f, 1.5f }, pictureFailures, {});
  11008. }
  11009. {
  11010. lynx::MixerComponent mixer (pictureEngine);
  11011. mixer.setBounds (0, 0, 1200, 500);
  11012. mixer.setVisible (true);
  11013. lines << lynx::ui::picturecheck::run (mixer, "Mixer 1200 x 500", { 1.0f, 1.5f }, pictureFailures, {});
  11014. }
  11015. if (pictureFailures > 0 || ! lines.contains (": ok"))
  11016. picturesResult = "ERROR " + lines.trim().replace ("\n", "; ");
  11017. }
  11018. // round 190ci (the 0.1.26 release candidate ended when an FPC channel was added): every built-in generator and
  11019. // effect, its editor built as the Channel Rack / mixer opens it and painted once. The report file names the
  11020. // plugin being opened, so a run that dies there says which one.
  11021. const auto editorsResult = lynx::pluginthumbs::checkEditors ([&reportPath] (const juce::String& key) {
  11022. if (reportPath.isNotEmpty())
  11023. juce::File (reportPath).replaceWithText ("(opening the editor of " + key + ")\n");
  11024. });
  11025. // round 190ci: a fault leaves a crash file, also on a stack Windows cannot walk (that FPC fault left none)
  11026. const auto faultResult = faultReportSelfTest();
  11027. const auto stemsResult = stemsSinglePassSelfTest(); // round 190gj
  11028. const auto exportFormatsResult = lynx::shortexport::formatsCheck(); // AIFF and M4A (owner decision D5)
  11029. const auto hotfix190qpWfResult = hotfix190qpWfCheck(); // round 190qp (0.1.31.1): track clips' notes, Export... with folders
  11030. const auto renderAgainResult = lynx::renderagain::check(); // round 190ou: offline renders made again
  11031. const auto determinismResult = lynx::determinism190po::check(); // round 190po: one render on any threads (Windows' x87)
  11032. juce::LookAndFeel::setDefaultLookAndFeel (&lookBefore);
  11033. const auto ok = editorsResult.startsWith ("OK") && ! faultResult.startsWith ("ERROR") && stemsResult == "OK" && exportFormatsResult.startsWith ("OK")
  11034. && mixerBasics == "OK" && fontsResult == "OK" && paintCachesResult.startsWith ("OK") && picturesResult == "OK" && audioOk && projectOk && trackModes122Ok && richOk && hwOutOk && hostKeysOk && pluginLevelsOk && flp168jOk && clipFades180dOk && blocksOk && takeoverOk && compOk && polyOk && latencyOk && preSendOk && lowLatencyOk && previewInTimeOk && substituteOk && patcherOk && rackResult == "OK" && nativesOk && undoOk && projectSaveOk && recordOk && recordUndoOk && cancelRecordOk && midiOk && packageOk
  11035. && sessionResult == "OK" && liveResult.startsWith ("OK")
  11036. && wavpack != "ERROR" && effectsOk && driverPanel == "OK" && deviceChange.startsWith ("OK") && exportParity.startsWith ("OK") && exportLive.startsWith ("OK") && midiHotplug.startsWith ("OK") && midiOutPorts.startsWith ("OK") && metronomeOk && artResult == "OK" && effectParamsResult == "OK"
  11037. && sidechainResult == "OK" && lanesResult == "OK" && arrange190cgResult == "OK" && livescr190drResult == "OK" && livewf190efResult == "OK" && livewf190emResult == "OK" && trackclips190neResult == "OK" && tracker190nwResult == "OK" && tracker190obResult == "OK" && rackauto190ooResult == "OK" && tracker190omResult == "OK" && rackauto190owResult == "OK" && versionsResult == "OK" && pluginsOffResult == "OK" && missingFilesResult == "OK"
  11038. && midigen190fmResult == "OK" && clipenv190giResult == "OK" && beatslaw190gxResult == "OK" && warplaw190ikResult == "OK" && editorScale190heResult == "OK" && sfModBase190heResult == "OK" && trackauto190gzResult == "OK" && community190hqResult == "OK" && rollup030Result == "OK" && rollup031Result == "OK" && rollup031s2Result == "OK"
  11039. && keys190nuResult == "OK" && rollup031s3Result == "OK"
  11040. && helix4khs190ocResult == "OK" && rollup031s4Result == "OK" && sections190olResult == "OK" && rollup031s5Result == "OK" && simpleDuck190otResult == "OK" && tracks190peResult == "OK" && issue258Result == "OK" && issues190qrResult == "OK" && qa190rbResult == "OK" && repeats190pmResult == "OK" && mixerqol190qhResult == "OK" && autolive190qpResult == "OK" && issue282Result == "OK" && feel190qeResult == "OK" && toolbar190qgResult == "OK" && extras190qkResult == "OK" && discord190quResult == "OK" && chordlane190pfResult == "OK" && autolinks190ovResult == "OK"
  11041. && trackstates190opResult == "OK" && rollup031s6Result == "OK" // (round 190op's item, reported but not counted in its branch: rollup 0.1.31 step 6)
  11042. && rollup031s7Result == "OK" && rollup031s8Result == "OK" && rollup032Result == "OK" && headerGearResult == "OK" && perTab259Result == "OK" && slots260Result == "OK" && hotfixPlacesResult == "OK" // (round 190qf: slots260) (rollup 0.1.31 step 7, round 190pw; and the three rounds' items its branches reported but did not count:)
  11043. && slides190piResult == "OK" && automodes190paResult == "OK" && heldSteps190ozResult == "OK"
  11044. && issues190qoResult == "OK" // (round 190qo)
  11045. && flparity190prResult == "OK"
  11046. && hotfix190qpWfResult == "OK" // (round 190qp)
  11047. && renderAgainResult.startsWith ("OK") && determinismResult.startsWith ("OK")
  11048. && remoteHistoryResult.startsWith ("OK") && hostedStateLockResult.startsWith ("OK")
  11049. && hostedStateContentionResult.startsWith ("OK") && modulators190oxResult == "OK"
  11050. && generatorSmartResult.startsWith ("OK") && jsfxResult.startsWith ("OK") && jsfxFpResult == "OK"
  11051. && danceWindowResult == "OK" && clickActivationResult == "OK" && motionOverlayResult.startsWith ("OK")
  11052. && editorHolesResult.startsWith ("OK") && picker190qiResult == "OK";
  11053. juce::String report;
  11054. report << "connections=" << offline.getNumGraphConnections() << "\n"
  11055. << "peak=" << peak << "\n"
  11056. << "stems_single_pass=" << stemsResult << "\n"
  11057. << "export_formats=" << exportFormatsResult << "\n"
  11058. << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
  11059. << "playlist_track_modes_roundtrip=" << (trackModes122Ok ? "OK" : "ERROR") << "\n"
  11060. << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
  11061. << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
  11062. << "plugin_host_keys_option=" << (hostKeysOk ? "OK" : "ERROR") << "\n"
  11063. << "plugin_levels_new_project=" << (pluginLevelsOk ? "OK" : "ERROR") << "\n"
  11064. << "flp168j_fields=" << (flp168jOk ? "OK" : "ERROR") << "\n"
  11065. << "clip_fades_180d=" << (clipFades180dOk ? "OK" : "ERROR") << "\n"
  11066. << "pattern_blocks=" << (blocksOk ? "OK" : "ERROR") << "\n"
  11067. << "pattern_clip_takeover=" << (takeoverOk ? "OK" : "ERROR") << "\n"
  11068. << "comp_crossfades=" << (compOk ? "OK" : "ERROR") << "\n"
  11069. << "channel_polyphony=" << (polyOk ? "OK" : "ERROR") << "\n"
  11070. << "track_latency=" << (latencyOk ? "OK" : "ERROR") << "\n"
  11071. << "pre_fader_sends=" << (preSendOk ? "OK" : "ERROR") << "\n"
  11072. << "low_latency_recording=" << (lowLatencyOk ? "OK" : "ERROR") << "\n"
  11073. << "preview_in_time=" << (previewInTimeOk ? "OK" : "ERROR") << " (2 s loop prepared in " << juce::String (previewPrepareMs, 1) << " ms)\n"
  11074. << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
  11075. << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
  11076. << "racks=" << rackResult << "\n"
  11077. << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
  11078. << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
  11079. << "mixer_basics=" << mixerBasics << "\n"
  11080. << "remote_history=" << remoteHistoryResult << "\n"
  11081. << "hosted_state_lock=" << hostedStateLockResult << "\n"
  11082. << "hosted_state_contention=" << hostedStateContentionResult << "\n"
  11083. << "modulators190ox=" << modulators190oxResult << "\n"
  11084. << "generator_smart_disable=" << generatorSmartResult << "\n"
  11085. << "fonts=" << fontsResult << "\n"
  11086. << "paint_caches=" << paintCachesResult << "\n"
  11087. << "motion_overlay=" << motionOverlayResult << "\n"
  11088. << "cached_pictures=" << picturesResult << "\n"
  11089. << "plugin_editors=" << editorsResult << "\n"
  11090. << "fault_report=" << faultResult << "\n"
  11091. << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
  11092. << "cancel_recording=" << (cancelRecordOk ? "OK" : "ERROR") << "\n"
  11093. << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
  11094. << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
  11095. << "projectSave=" << (projectSaveOk ? "OK" : "ERROR") << "\n"
  11096. << "online_session=" << sessionResult << "\n"
  11097. << "live_session=" << liveResult << "\n"
  11098. << "wavpack=" << wavpack << "\n"
  11099. << "effects=" << (effectsOk ? "OK" : "NONFINITE") << "\n"
  11100. << "effect_params_saved=" << effectParamsResult << "\n"
  11101. << "driver_panel=" << driverPanel << "\n"
  11102. << "device_change=" << deviceChange << "\n"
  11103. << "export_parity=" << exportParity << "\n"
  11104. << "export_live=" << exportLive << "\n"
  11105. << "midi_hotplug=" << midiHotplug << "\n"
  11106. << "midi_out_ports=" << midiOutPorts.replace ("\n", " | ").trimCharactersAtEnd (" |") << "\n"
  11107. << "plugin_art=" << artResult << "\n"
  11108. << "plugin_sidechain=" << sidechainResult << "\n"
  11109. << "jsfx190pj=" << jsfxResult << "\n"
  11110. << "jsfx_fp_environment=" << jsfxFpResult << "\n"
  11111. << "picker190qi=" << picker190qiResult << "\n"
  11112. << "versions_panel=" << versionsResult << "\n"
  11113. << "plugins_off=" << pluginsOffResult << "\n"
  11114. << "missing_files_rows=" << missingFilesResult << "\n"
  11115. << "dance_window=" << danceWindowResult << "\n"
  11116. << "dance_window_detail=" << danceWindowDetail << "\n"
  11117. << "click_activation=" << clickActivationResult << "\n"
  11118. << "editor_holes=" << editorHolesResult << "\n"
  11119. << "lanes_saved=" << lanesResult << "\n"
  11120. << "arrange190cg_saved=" << arrange190cgResult << "\n"
  11121. << "livescr190dr=" << livescr190drResult << "\n"
  11122. << "livewf190ef=" << livewf190efResult << "\n"
  11123. << "livewf190em=" << livewf190emResult << "\n"
  11124. << "trackclips190ne=" << trackclips190neResult << "\n"
  11125. << "trackstates190op=" << trackstates190opResult << "\n"
  11126. << "automodes190pa=" << automodes190paResult << "\n"
  11127. << "tracker190nw=" << tracker190nwResult << "\n"
  11128. << "tracker190ob=" << tracker190obResult << "\n"
  11129. << "rackauto190oo=" << rackauto190ooResult << "\n"
  11130. << "tracker190om=" << tracker190omResult << "\n"
  11131. << "rackauto190ow=" << rackauto190owResult << "\n"
  11132. << "midigen190fm_saved=" << midigen190fmResult << "\n"
  11133. << "trackauto190gz_saved=" << trackauto190gzResult << "\n"
  11134. << "clipenv190gi_saved=" << clipenv190giResult << "\n"
  11135. << "beatslaw190gx_saved=" << beatslaw190gxResult << "\n"
  11136. << "warplaw190ik_saved=" << warplaw190ikResult << "\n"
  11137. << "editor_scale190he_saved=" << editorScale190heResult << "\n"
  11138. << "sf_mod_base190he=" << sfModBase190heResult << "\n"
  11139. << "community190hq_saved=" << community190hqResult << "\n"
  11140. << "rollup030_copy_for_0128=" << rollup030Result << "\n"
  11141. << "rollup031_copy_for_0130=" << rollup031Result << "\n"
  11142. << "rollup031s2_copy_for_0130=" << rollup031s2Result << "\n"
  11143. << "keys190nu_key_markers=" << keys190nuResult << "\n"
  11144. << "rollup031s3_copy_for_0130=" << rollup031s3Result << "\n"
  11145. << "helix4_khs190oc_copy_for_0130=" << helix4khs190ocResult << "\n"
  11146. << "rollup031s4_copy_for_0130=" << rollup031s4Result << "\n"
  11147. << "rollup031s5_copy_for_0130=" << rollup031s5Result << "\n"
  11148. << "rollup031s6_copy_for_0130=" << rollup031s6Result << "\n"
  11149. << "rollup031s7_copy_for_0130=" << rollup031s7Result << "\n"
  11150. << "rollup031s8_copy_for_0130=" << rollup031s8Result << "\n"
  11151. << "rollup032_copy_for_0131=" << rollup032Result << "\n"
  11152. << "headergear248=" << headerGearResult << "\n"
  11153. << "pertab259=" << perTab259Result << "\n"
  11154. << "slots260=" << slots260Result << "\n"
  11155. << "simpleduck190ot=" << simpleDuck190otResult << "\n"
  11156. << "tracks190pe=" << tracks190peResult << "\n"
  11157. << "feel190qe=" << feel190qeResult << "\n"
  11158. << "issue258=" << issue258Result << "\n"
  11159. << "autolive190qp=" << autolive190qpResult << "\n"
  11160. << "issue282=" << issue282Result << (issue282Result == "OK" ? juce::String() : " | " + issue282Log.replace ("\n", "; ")) << "\n"
  11161. << "issues190qr=" << issues190qrResult << "\n"
  11162. << "qa190rb=" << qa190rbResult << "\n"
  11163. << "repeats190pm=" << repeats190pmResult << "\n"
  11164. << "mixerqol190qh=" << mixerqol190qhResult << "\n"
  11165. << "hotfixplaces190qp=" << hotfixPlacesResult << "\n"
  11166. << "toolbar_overflow_190qg=" << toolbar190qgResult << "\n"
  11167. << "extras190qk=" << extras190qkResult << "\n"
  11168. << "discord190qu=" << discord190quResult << "\n"
  11169. << "autolinks190ov=" << autolinks190ovResult << "\n"
  11170. << "sections190ol=" << sections190olResult << "\n"
  11171. << "heldsteps190oz=" << heldSteps190ozResult << "\n"
  11172. << "slides190pi=" << slides190piResult << "\n"
  11173. << "issues190qo=" << issues190qoResult << "\n"
  11174. << "flparity190pr=" << flparity190prResult << "\n"
  11175. << "chordlane190pf=" << chordlane190pfResult << "\n"
  11176. << "renderagain190ou=" << renderAgainResult << "\n"
  11177. << "determinism190po=" << determinismResult << "\n"
  11178. << "hotfix190qp_wf=" << hotfix190qpWfResult << "\n"
  11179. << "metronome=" << metronomeResult << " (FL sounds " << metronomeFlSounds << "/" << lynx::metronome::soundCount
  11180. << ", downbeat peak " << juce::String (metronomeMaster, 4) << ")\n";
  11181. // issue #138 (round 190c): a short note at the very start of the Playlist against the same note at bar 2, through
  11182. // the Export window's path (its own thread while the message loop runs: the report is finished from there)
  11183. if (reportPath.isNotEmpty())
  11184. juce::File (reportPath).replaceWithText (report + "(short_export running)\n");
  11185. lynx::shortexport::run (false, 1, {}, {}, [this, report, ok, reportPath] (juce::String shortExport) {
  11186. const auto all = ok && shortExport.startsWith ("OK");
  11187. const auto text = report + "short_export=" + shortExport + "\nresult=" + (all ? "OK" : "FAILED") + "\n";
  11188. if (reportPath.isNotEmpty())
  11189. juce::File (reportPath).replaceWithText (text);
  11190. setApplicationReturnValue (all ? 0 : 1);
  11191. if (selfTestTemp != juce::File())
  11192. selfTestTemp.deleteRecursively(); // (round 190mo: this run's own temp folder)
  11193. quit();
  11194. });
  11195. }
  11196. // Every built-in effect in its native editor: random / extreme parameters, mouse drags over the editor, the editor
  11197. // painted, audio rendered at 44.1 / 48 / 96 kHz. Returns false when an effect output NaN / inf (muted by the
  11198. // renderer's guard). The report lists each effect. Used by --fxfuzz and (a short run) by --selftest.
  11199. bool runEffectFuzz (int rounds, const juce::String& reportPath, bool drags = false)
  11200. {
  11201. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11202. lynx::setNativeEditorDemo (true);
  11203. juce::String report;
  11204. auto allFinite = true;
  11205. {
  11206. lynx::AudioEngine offline (false);
  11207. juce::Random random (111);
  11208. const auto value = [&] { const auto r = random.nextInt (6); return r == 0 ? 0.0f : r == 1 ? 1.0f : random.nextFloat(); };
  11209. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  11210. {
  11211. const auto kind = (lynx::EffectKind) k;
  11212. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher) // (the Patcher's editor is a graph window)
  11213. continue;
  11214. const auto before = lynx::RackRenderer::nonFiniteEffectBlocks();
  11215. const auto& info = lynx::effectInfo (kind);
  11216. // (FL engines: a fresh instance as the menus make it, from the user's FL installation; round 142)
  11217. auto fx = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  11218. int dragged = 0; // parameter changes made by the mouse drags
  11219. for (int round = 0; round < rounds; ++round)
  11220. {
  11221. if (round > 0)
  11222. for (std::size_t p = 0; p < info.params.size(); ++p)
  11223. fx.params[p] = round == 1 ? 0.0f : round == 2 ? 1.0f : value();
  11224. auto song = lynx::Song::makeDefault(); // its demo beat feeds the effect
  11225. song.mixer.resize (2);
  11226. song.mixer[0].name = "Master";
  11227. song.mixer[1].name = "Insert 1";
  11228. song.mixer[1].effects.assign (1, fx);
  11229. for (auto& channel : song.channels)
  11230. channel.mixerTrack = 1;
  11231. offline.setSong (std::move (song));
  11232. offline.dispatchPendingMessages();
  11233. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  11234. for (int page = 0; page < pages; ++page)
  11235. {
  11236. auto editor = kind == lynx::EffectKind::facetEq ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  11237. : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  11238. if (editor == nullptr || editor->getWidth() <= 0 || editor->getHeight() <= 0)
  11239. continue;
  11240. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  11241. const auto paint = [&] {
  11242. juce::Graphics g (image);
  11243. editor->paintEntireComponent (g, false);
  11244. };
  11245. paint();
  11246. // drags from a grid of points, as a user moving every control (plain left button)
  11247. if (round >= 3 && drags)
  11248. {
  11249. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  11250. const auto step = juce::jmax (12, juce::jmin (editor->getWidth(), editor->getHeight()) / 8);
  11251. for (int y = step / 2; y < editor->getHeight(); y += step)
  11252. for (int x = step / 2; x < editor->getWidth(); x += step)
  11253. {
  11254. auto* target = editor->getComponentAt (x, y);
  11255. if (target == nullptr)
  11256. continue;
  11257. const auto at = target->getLocalPoint (editor.get(), juce::Point<float> ((float) x, (float) y));
  11258. const auto now = juce::Time::getCurrentTime();
  11259. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods) {
  11260. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, at, now, 1, false);
  11261. };
  11262. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  11263. const juce::Component::SafePointer<juce::Component> alive (target);
  11264. target->mouseDown (event (at, down));
  11265. const auto dy = (float) (random.nextBool() ? 400 : -400), dx = (float) (random.nextInt (401) - 200);
  11266. if (alive != nullptr)
  11267. target->mouseDrag (event (at + juce::Point<float> (dx * 0.5f, dy * 0.5f), down));
  11268. if (alive != nullptr)
  11269. target->mouseDrag (event (at + juce::Point<float> (dx, dy), down));
  11270. if (alive != nullptr)
  11271. target->mouseUp (event (at + juce::Point<float> (dx, dy), juce::ModifierKeys()));
  11272. juce::PopupMenu::dismissAllActiveMenus();
  11273. offline.dispatchPendingMessages();
  11274. }
  11275. paint();
  11276. }
  11277. }
  11278. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  11279. offline.renderOffline (0.05, rate);
  11280. if (round == 0 || round >= 3) // keep what the drags set for the next round
  11281. if (offline.getSong().mixer.size() > 1 && ! offline.getSong().mixer[1].effects.empty())
  11282. {
  11283. const auto& now = offline.getSong().mixer[1].effects[0];
  11284. for (std::size_t p = 0; p < fx.params.size(); ++p)
  11285. dragged += now.params[p] != fx.params[p] ? 1 : 0;
  11286. dragged += now.state != fx.state ? 1 : 0;
  11287. fx = now;
  11288. }
  11289. }
  11290. const auto broken = lynx::RackRenderer::nonFiniteEffectBlocks() - before;
  11291. allFinite = allFinite && broken == 0;
  11292. report << info.name << ": " << (broken == 0 ? juce::String ("OK") : "non-finite output in " + juce::String ((juce::int64) broken) + " blocks")
  11293. << " (" << dragged << " changes by mouse)\n";
  11294. if (reportPath.isNotEmpty())
  11295. juce::File (reportPath).replaceWithText (report + "(running)\n"); // what was reached, if it crashes
  11296. }
  11297. }
  11298. lynx::setNativeEditorDemo (false);
  11299. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  11300. report << "result=" << (allFinite ? "OK" : "NONFINITE") << "\n";
  11301. if (reportPath.isNotEmpty())
  11302. juce::File (reportPath).replaceWithText (report);
  11303. return allFinite;
  11304. }
  11305. // --opentest (round 157a): see the command line. Runs on the message loop (the editors' timers, animations and
  11306. // native windows are real); one step per timer tick.
  11307. void runOpenTest (const juce::String& reportPath, bool visible, std::function<void (bool)> done)
  11308. {
  11309. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11310. struct OpenTest final : juce::Timer
  11311. {
  11312. juce::String reportPath, report;
  11313. bool visible = false, ok = true;
  11314. std::function<void (bool)> done;
  11315. std::unique_ptr<lynx::AudioEngine> engine;
  11316. std::vector<std::pair<juce::String, std::function<void()>>> steps;
  11317. std::size_t next = 0;
  11318. std::atomic<std::int64_t> lastStep { 0 };
  11319. std::atomic<bool> finished { false };
  11320. std::thread watchdog;
  11321. juce::String current;
  11322. std::mutex currentLock;
  11323. int opened = 0, painted = 0;
  11324. // LYNX_OPENTEST_TIMEOUT (seconds): longer for sanitizer builds
  11325. const std::int64_t timeoutMs = 1000 * juce::jmax (5, juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_TIMEOUT", "20").getIntValue());
  11326. static std::int64_t now() { return (std::int64_t) juce::Time::getMillisecondCounter(); }
  11327. void write (const juce::String& tail = {}) { juce::File (reportPath).replaceWithText (report + tail); }
  11328. ~OpenTest() override
  11329. {
  11330. finished = true;
  11331. if (watchdog.joinable())
  11332. watchdog.join();
  11333. }
  11334. void start()
  11335. {
  11336. lastStep = now();
  11337. // the UI hang watch runs during the whole test (5 s): a slow step leaves its stack next to the report
  11338. const auto folder = juce::File (reportPath).getParentDirectory().getChildFile ("opentest-hang");
  11339. folder.deleteRecursively();
  11340. folder.createDirectory();
  11341. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString(), 5000);
  11342. watchdog = std::thread ([this] {
  11343. while (! finished)
  11344. {
  11345. std::this_thread::sleep_for (std::chrono::milliseconds (200));
  11346. if (now() - lastStep.load() > timeoutMs)
  11347. {
  11348. juce::String at;
  11349. {
  11350. const std::lock_guard<std::mutex> l (currentLock);
  11351. at = current;
  11352. }
  11353. juce::File (reportPath).replaceWithText (report + "HANG at " + at + " (no progress for " + juce::String (timeoutMs / 1000) + " s; stack in opentest-hang)\nresult=HANG\n");
  11354. lynx::crashguard::exitNow (3);
  11355. }
  11356. }
  11357. });
  11358. startTimer (30);
  11359. }
  11360. // every LYNX window but none of the main one (there is none here): moved off-screen, painted once into an image
  11361. void touchWindows (bool resize, bool large)
  11362. {
  11363. auto& desktop = juce::Desktop::getInstance();
  11364. for (int i = desktop.getNumComponents(); --i >= 0;)
  11365. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible())
  11366. {
  11367. if (! visible && c->getScreenX() > -3000)
  11368. c->setTopLeftPosition (-6000, -6000);
  11369. if (resize)
  11370. if (auto* w = dynamic_cast<juce::ResizableWindow*> (c))
  11371. {
  11372. const auto b = w->getBounds();
  11373. w->setSize (large ? b.getWidth() * 2 : juce::jmax (40, b.getWidth() / 3), large ? b.getHeight() * 2 : juce::jmax (40, b.getHeight() / 3));
  11374. }
  11375. if (c->getWidth() > 0 && c->getHeight() > 0 && c->getWidth() < 8000 && c->getHeight() < 8000)
  11376. {
  11377. juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
  11378. juce::Graphics g (image);
  11379. c->paintEntireComponent (g, false);
  11380. ++painted;
  11381. // LYNX_OPENTEST_SHOTS=folder: each window as first painted (before the resizes), for a look
  11382. if (const auto shots = juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_SHOTS", {}); shots.isNotEmpty() && ! resize)
  11383. {
  11384. juce::FileOutputStream out (juce::File (shots).getChildFile (juce::String (painted).paddedLeft ('0', 4) + ".png"));
  11385. if (out.openedOk())
  11386. {
  11387. out.setPosition (0), out.truncate();
  11388. juce::PNGImageFormat().writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  11389. }
  11390. }
  11391. }
  11392. }
  11393. }
  11394. void timerCallback() override
  11395. {
  11396. if (next >= steps.size())
  11397. {
  11398. stopTimer();
  11399. lynx::NativeEffectWindows::closeAll();
  11400. lynx::closeChannelSettings();
  11401. // the UI hang watch itself: the message thread spins past the stall time; the watcher must write the stack
  11402. {
  11403. const auto before = lynx::crashguard::lastHangFile();
  11404. for (const auto until = now() + 7000; now() < until;)
  11405. lastStep = now(); // (busy: no heartbeat; the test's own watchdog stays quiet)
  11406. for (const auto until = now() + 1500; now() < until && lynx::crashguard::lastHangFile() == before;)
  11407. std::this_thread::sleep_for (std::chrono::milliseconds (20));
  11408. lynx::crashguard::stopHangWatch();
  11409. const juce::File hang (juce::String::fromUTF8 (lynx::crashguard::lastHangFile().c_str()));
  11410. const auto text = hang.loadFileAsString();
  11411. const auto frames = juce::StringArray::fromLines (text).size() - 2;
  11412. #if JUCE_WINDOWS
  11413. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && text.contains ("LYNX.exe+0x") && frames >= 3;
  11414. #else
  11415. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && frames >= 3;
  11416. #endif
  11417. report << "hang watch: " << (hangOk ? "OK" : "FAIL") << " (" << hang.getFileName() << ", " << frames << " lines"
  11418. << (before.empty() ? juce::String() : "; a step stalled > 5 s earlier: " + juce::String::fromUTF8 (before.c_str())) << ")\n";
  11419. ok = ok && hangOk;
  11420. }
  11421. report << "windows opened: " << opened << ", paints: " << painted << "\nresult=" << (ok ? "OK" : "FAIL") << "\n";
  11422. write();
  11423. finished = true;
  11424. if (done)
  11425. done (ok);
  11426. return;
  11427. }
  11428. auto& [label, fn] = steps[next++];
  11429. {
  11430. const std::lock_guard<std::mutex> l (currentLock);
  11431. current = label;
  11432. }
  11433. fn();
  11434. lastStep = now();
  11435. lynx::crashguard::heartbeat();
  11436. }
  11437. };
  11438. auto* test = new OpenTest();
  11439. test->reportPath = reportPath;
  11440. test->visible = visible;
  11441. test->engine = std::make_unique<lynx::AudioEngine> (false);
  11442. test->done = [test, done] (bool ok) {
  11443. juce::MessageManager::callAsync ([test, done, ok] {
  11444. delete test;
  11445. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  11446. done (ok);
  11447. });
  11448. };
  11449. auto& engine = *test->engine;
  11450. lynx::setNativeEditorDemo (true); // live displays animate without an audio device
  11451. const auto songWith = [] (const lynx::EffectSlot& fx) {
  11452. auto song = lynx::Song::makeDefault();
  11453. song.mixer.resize (2);
  11454. song.mixer[0].name = "Master";
  11455. song.mixer[1].name = "Insert 1";
  11456. song.mixer[1].effects.assign (1, fx);
  11457. for (auto& channel : song.channels)
  11458. channel.mixerTrack = 1;
  11459. return song;
  11460. };
  11461. // an older project's slot: its parameter list cut to `count` and read back by the project reader (the
  11462. // parameters a newer LYNX added after them take their defaults)
  11463. const auto oldState = [songWith] (const lynx::EffectSlot& fx, std::size_t count) -> std::optional<lynx::Song> {
  11464. auto json = juce::JSON::parse (lynx::ProjectFile::toJson (songWith (fx)));
  11465. if (auto* mixer = json["mixer"].getArray(); mixer != nullptr && mixer->size() > 1)
  11466. if (auto* effects = (*mixer)[1]["effects"].getArray(); effects != nullptr && ! effects->isEmpty())
  11467. if (auto* params = (*effects)[0]["params"].getArray())
  11468. params->removeRange ((int) count, params->size());
  11469. juce::String error;
  11470. return lynx::ProjectFile::fromJson (juce::JSON::toString (json), error);
  11471. };
  11472. auto& steps = test->steps;
  11473. juce::Random random (157);
  11474. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  11475. {
  11476. const auto kind = (lynx::EffectKind) k;
  11477. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
  11478. continue;
  11479. const auto& info = lynx::effectInfo (kind);
  11480. const auto base = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  11481. const auto n = info.params.size();
  11482. std::vector<std::pair<juce::String, std::function<std::optional<lynx::Song>()>>> variants;
  11483. variants.push_back ({ "default", [=] { return std::optional<lynx::Song> (songWith (base)); } });
  11484. for (const auto value : { 0.0f, 1.0f })
  11485. variants.push_back ({ value == 0.0f ? "all 0" : "all 1", [=] {
  11486. auto fx = base;
  11487. for (std::size_t p = 0; p < n; ++p) fx.params[p] = value;
  11488. return std::optional<lynx::Song> (songWith (fx));
  11489. } });
  11490. const auto seed = random.nextInt64();
  11491. variants.push_back ({ "random", [=] {
  11492. juce::Random r (seed);
  11493. auto fx = base;
  11494. for (std::size_t p = 0; p < n; ++p) fx.params[p] = r.nextFloat();
  11495. return std::optional<lynx::Song> (songWith (fx));
  11496. } });
  11497. std::vector<std::size_t> cuts { n / 2 };
  11498. for (const auto c : { (std::size_t) 90, (std::size_t) 114, (std::size_t) 128, (std::size_t) 160 }) // (Facet's 90 → 114 params; the 128 → 160 → 192 slot)
  11499. if (c < n) cuts.push_back (c);
  11500. for (const auto c : cuts)
  11501. variants.push_back ({ "old project (" + juce::String ((int) c) + " of " + juce::String ((int) n) + " params)", [=] { return oldState (base, c); } });
  11502. for (const auto& [variant, makeSong] : variants)
  11503. {
  11504. const auto label = juce::String::fromUTF8 (info.name) + " / " + variant;
  11505. steps.push_back ({ label + ": open", [test, &engine, label, makeSong = makeSong] {
  11506. auto song = makeSong();
  11507. if (! song)
  11508. {
  11509. test->report << "FAIL " << label << ": project reader refused the state\n";
  11510. test->ok = false;
  11511. return;
  11512. }
  11513. engine.setSong (std::move (*song));
  11514. engine.dispatchPendingMessages();
  11515. lynx::NativeEffectWindows::open (engine, 1, 0);
  11516. ++test->opened;
  11517. test->touchWindows (false, false);
  11518. } });
  11519. steps.push_back ({ label + ": run", [test, &engine] {
  11520. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  11521. engine.renderOffline (0.03, rate);
  11522. test->touchWindows (false, false);
  11523. } });
  11524. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  11525. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  11526. steps.push_back ({ label + ": close", [test, label] {
  11527. lynx::NativeEffectWindows::closeAll();
  11528. test->report << label << ": OK\n";
  11529. test->write ("(running)\n");
  11530. } });
  11531. }
  11532. }
  11533. // instruments: the channel window the Channel rack opens (Patcher: its graph window, not here)
  11534. for (int k = 0; k <= (int) lynx::InstrumentKind::soundfont; ++k)
  11535. {
  11536. const auto kind = (lynx::InstrumentKind) k;
  11537. if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
  11538. continue;
  11539. for (const auto* variant : { "default", "old project (saved and read back)", "odd settings" })
  11540. {
  11541. if (juce::String (variant) == "odd settings" && kind != lynx::InstrumentKind::soundfont)
  11542. continue;
  11543. const auto label = "instrument " + juce::String (k) + " / " + variant;
  11544. steps.push_back ({ label + ": open", [test, &engine, kind, label, variant = juce::String (variant), old = juce::String (variant) != "default"] {
  11545. auto song = lynx::Song::makeDefault();
  11546. auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
  11547. lynx::ChannelDef def;
  11548. def.instrument = kind;
  11549. def.name = "Test";
  11550. song.channels.push_back (channel ? *channel : def);
  11551. if (kind == lynx::InstrumentKind::soundfont && variant != "default")
  11552. {
  11553. // a real font when FL's is there; NaN / huge / truncated settings
  11554. const auto& roots = lynx::flStudioAccess().roots;
  11555. if (! roots.data.empty())
  11556. song.channels.back().samplePath = (juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  11557. .getChildFile ("Patches/Soundfonts/STR_Ensemble.sf2"))
  11558. .getFullPathName().toStdString();
  11559. if (variant == "odd settings")
  11560. song.channels.back().modelParams = { NAN, 1.0e9f, -1.0e9f, 0.5f, 7.0f };
  11561. }
  11562. if (old)
  11563. {
  11564. juce::String error;
  11565. if (auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error))
  11566. song = std::move (*again);
  11567. }
  11568. const auto index = (int) song.channels.size() - 1;
  11569. engine.setSong (std::move (song));
  11570. engine.dispatchPendingMessages();
  11571. lynx::openChannelSettings (engine, index);
  11572. ++test->opened;
  11573. test->touchWindows (false, false);
  11574. } });
  11575. steps.push_back ({ label + ": run", [test, &engine] {
  11576. engine.renderOffline (0.03, 48000.0);
  11577. test->touchWindows (false, false);
  11578. } });
  11579. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  11580. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  11581. steps.push_back ({ label + ": close", [test, label] {
  11582. lynx::closeChannelSettings();
  11583. test->report << label << ": OK\n";
  11584. test->write ("(running)\n");
  11585. } });
  11586. }
  11587. }
  11588. test->start();
  11589. }
  11590. void runPluginOptionsTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath)
  11591. {
  11592. struct Test final : juce::Timer
  11593. {
  11594. juce::String reportPath, report;
  11595. juce::File shots;
  11596. std::unique_ptr<lynx::AudioEngine> engine;
  11597. std::unique_ptr<juce::DocumentWindow> mainWindow, other; // LYNX's main window stand-in; another secondary window
  11598. bool instrument = false, ok = true;
  11599. int channelIndex = -1, phase = 0;
  11600. juce::uint32 phaseStart = 0;
  11601. juce::AudioPluginInstance* instance = nullptr;
  11602. std::function<void (bool)> done;
  11603. void step (const juce::String& line)
  11604. {
  11605. report << line << "\n";
  11606. juce::File (reportPath).replaceWithText (report);
  11607. }
  11608. void expect (const juce::String& name, bool value)
  11609. {
  11610. step (name + "=" + juce::String ((int) value));
  11611. ok = ok && value;
  11612. }
  11613. void next (int to)
  11614. {
  11615. phase = to;
  11616. phaseStart = juce::Time::getMillisecondCounter();
  11617. }
  11618. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  11619. lynx::PluginRef* ref (lynx::Song& song) const
  11620. {
  11621. if (instrument)
  11622. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  11623. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  11624. }
  11625. const lynx::PluginRef& refNow() const { return *ref (const_cast<lynx::Song&> (engine->getSong())); }
  11626. juce::AudioPluginInstance* find()
  11627. {
  11628. if (instrument)
  11629. {
  11630. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  11631. return &p->getInstance();
  11632. }
  11633. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  11634. return &p->getInstance();
  11635. return nullptr;
  11636. }
  11637. void openWindow()
  11638. {
  11639. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  11640. : std::shared_ptr<void> (engine->getEffect (1, 0));
  11641. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  11642. { engine.get(), [this] (lynx::Song& song) { return ref (song); }, instrument, instrument ? -1 : 1,
  11643. instrument ? -1 : 0, {}, {} });
  11644. }
  11645. void shot (const char* name, bool settingsPage = false)
  11646. {
  11647. if (shots != juce::File() && instance != nullptr)
  11648. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  11649. }
  11650. // the plugin window is in front of the other secondary window
  11651. bool pluginInFront()
  11652. {
  11653. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  11654. #if JUCE_WINDOWS
  11655. return plug != nullptr && lynx::nativechild::isAbove (plug, other->getWindowHandle());
  11656. #else
  11657. auto& desktop = juce::Desktop::getInstance();
  11658. for (int i = 0; i < desktop.getNumComponents(); ++i)
  11659. if (auto* c = desktop.getComponent (i); c->getWindowHandle() == plug)
  11660. return c->isAlwaysOnTop() || desktop.getComponent (desktop.getNumComponents() - 1) == c;
  11661. return false;
  11662. #endif
  11663. }
  11664. void timerCallback() override
  11665. {
  11666. if (phase == 0) // waiting for the engine to host the plugin
  11667. {
  11668. instance = find();
  11669. if (instance == nullptr)
  11670. {
  11671. if (elapsed() > 20000)
  11672. finish ("not hosted");
  11673. return;
  11674. }
  11675. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  11676. openWindow();
  11677. next (1);
  11678. return;
  11679. }
  11680. if (phase == 1 && elapsed() >= 800) // Pin on top: off for a new plugin
  11681. {
  11682. expect ("pin_off_by_default", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  11683. shot ("pin-off");
  11684. const auto history = engine->getHistoryPosition();
  11685. lynx::PluginWindows::setPinnedOnTop (*instance, true);
  11686. expect ("pin_set", lynx::PluginWindows::isPinnedOnTop (*instance) && refNow().pinned);
  11687. expect ("pin_no_undo_step_project_modified", engine->getHistoryPosition() == history && engine->isModified());
  11688. // another secondary window brought in front of it
  11689. other = std::make_unique<juce::DocumentWindow> ("Another LYNX window", juce::Colours::darkslategrey, juce::DocumentWindow::closeButton);
  11690. other->setUsingNativeTitleBar (true);
  11691. other->setBounds (mainWindow->getX() + 60, mainWindow->getY() + 60, 420, 300);
  11692. other->setVisible (true);
  11693. lynx::keepAboveMainWindow (*other);
  11694. lynx::forceForegroundForTest (*other);
  11695. other->toFront (true);
  11696. next (2);
  11697. return;
  11698. }
  11699. if (phase == 2 && elapsed() >= 1200)
  11700. {
  11701. expect ("pinned_stays_in_front_of_a_clicked_window", pluginInFront());
  11702. shot ("pin-on");
  11703. // closed and opened again: the pin comes back from the project
  11704. lynx::PluginWindows::close (*instance);
  11705. openWindow();
  11706. next (3);
  11707. return;
  11708. }
  11709. if (phase == 3 && elapsed() >= 600)
  11710. {
  11711. expect ("pin_remembered_when_reopened", lynx::PluginWindows::isPinnedOnTop (*instance));
  11712. lynx::PluginWindows::setPinnedOnTop (*instance, false);
  11713. expect ("pin_cleared", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  11714. other->toFront (true);
  11715. next (4);
  11716. return;
  11717. }
  11718. if (phase == 4 && elapsed() >= 1000)
  11719. {
  11720. #if JUCE_WINDOWS
  11721. expect ("unpinned_goes_behind_a_clicked_window", ! pluginInFront());
  11722. #endif
  11723. other = nullptr;
  11724. // the wrapper settings page: LYNX's Velocity row in the MIDI group (instruments), default = follow
  11725. expect ("velocity_follows_midi_settings_by_default", refNow().velocityMode == lynx::prefs::pluginVelocityFollow
  11726. && refNow().fixedVelocity == lynx::prefs::defaultFixedVelocity);
  11727. shot ("wrapper-velocity-default", true);
  11728. engine->editSong ([this] (lynx::Song& song) {
  11729. if (auto* r = ref (song))
  11730. {
  11731. r->velocityMode = lynx::prefs::pluginVelocityFixed;
  11732. r->fixedVelocity = 96;
  11733. }
  11734. });
  11735. next (5);
  11736. return;
  11737. }
  11738. if (phase == 5 && elapsed() >= 400)
  11739. {
  11740. expect ("velocity_change_keeps_the_running_plugin", find() == instance);
  11741. shot ("wrapper-velocity-fixed", true);
  11742. engine->undo();
  11743. expect ("velocity_undo", refNow().velocityMode == lynx::prefs::pluginVelocityFollow && find() == instance);
  11744. // the preset menu's "Play a note when a preset loads": off by default, a user setting
  11745. expect ("audition_off_by_default", ! lynx::pluginpresetui::auditionOnLoad());
  11746. lynx::pluginpresetui::setAuditionOnLoad (true);
  11747. expect ("audition_menu_opened", lynx::PluginWindows::showPresetMenu (*instance));
  11748. next (6);
  11749. return;
  11750. }
  11751. if (phase == 6 && elapsed() >= 500) // the menu, as drawn
  11752. {
  11753. auto found = false;
  11754. auto& desktop = juce::Desktop::getInstance();
  11755. for (int c = desktop.getNumComponents(); --c >= 0 && ! found;)
  11756. if (auto* menu = desktop.getComponent (c); dynamic_cast<juce::TopLevelWindow*> (menu) == nullptr && menu->isVisible()
  11757. && menu->getHeight() > 60 && shots != juce::File())
  11758. {
  11759. const auto image = menu->createComponentSnapshot (menu->getLocalBounds(), true, 1.0f);
  11760. juce::FileOutputStream out (shots.getChildFile ("preset-menu-audition.png"));
  11761. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  11762. }
  11763. step ("shot_preset-menu-audition=" + juce::String ((int) found));
  11764. juce::PopupMenu::dismissAllActiveMenus();
  11765. // a preset loaded while the song is stopped: the note waits a moment, sounds, ends
  11766. const auto asked = engine->auditionPreset (*instance);
  11767. expect ("audition_only_for_channel_instruments", asked == instrument);
  11768. expect ("audition_waits_first", ! instrument || engine->auditionState() == 1);
  11769. next (7);
  11770. return;
  11771. }
  11772. if (phase == 7 && elapsed() >= 300)
  11773. {
  11774. expect ("audition_sounds", ! instrument || engine->auditionState() == 2);
  11775. next (8);
  11776. return;
  11777. }
  11778. if (phase == 8 && elapsed() >= 700)
  11779. {
  11780. expect ("audition_ends", engine->auditionState() == 0);
  11781. engine->getTransport().playing.store (true); // the song plays: no audition
  11782. expect ("no_audition_while_playing", ! engine->auditionPreset (*instance) && engine->auditionState() == 0);
  11783. engine->getTransport().playing.store (false);
  11784. lynx::pluginpresetui::setAuditionOnLoad (false);
  11785. expect ("audition_setting_off_again", ! lynx::pluginpresetui::auditionOnLoad());
  11786. finish ({});
  11787. }
  11788. }
  11789. void finish (const juce::String& failure)
  11790. {
  11791. stopTimer();
  11792. if (failure.isNotEmpty())
  11793. step ("failed=" + failure);
  11794. ok = ok && failure.isEmpty();
  11795. step (ok ? "result=OK" : "result=FAILED");
  11796. lynx::PluginWindows::closeAll();
  11797. done (ok);
  11798. }
  11799. };
  11800. auto* test = new Test();
  11801. test->reportPath = reportPath;
  11802. if (shotsPath.isNotEmpty())
  11803. {
  11804. test->shots = juce::File (shotsPath);
  11805. test->shots.createDirectory();
  11806. }
  11807. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11808. test->done = [this, test] (bool ok) {
  11809. setApplicationReturnValue (ok ? 0 : 1);
  11810. juce::MessageManager::callAsync ([this, test] {
  11811. lynx::setMainWindowForOwnership (nullptr);
  11812. test->other = nullptr;
  11813. test->mainWindow = nullptr;
  11814. test->engine = nullptr;
  11815. delete test;
  11816. quit();
  11817. });
  11818. };
  11819. test->engine = std::make_unique<lynx::AudioEngine> (false);
  11820. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  11821. test->mainWindow->setBounds (20, 20, 300, 200);
  11822. test->mainWindow->setVisible (true);
  11823. lynx::setMainWindowForOwnership (test->mainWindow.get());
  11824. auto& host = test->engine->getPluginHost();
  11825. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  11826. std::optional<juce::PluginDescription> chosen;
  11827. for (const auto& type : host.getKnownPlugins().getTypes())
  11828. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath
  11829. || (pluginPath.endsWithIgnoreCase (".lv2") && type.pluginFormatName == "LV2")) // (round 190rf: an LV2 bundle's plugin, known by URI)
  11830. {
  11831. chosen = type;
  11832. break;
  11833. }
  11834. if (! chosen)
  11835. {
  11836. test->step ("result=FAILED (no plugin)");
  11837. test->done (false);
  11838. return;
  11839. }
  11840. test->instrument = chosen->isInstrument;
  11841. lynx::PluginRef ref;
  11842. ref.id = chosen->createIdentifierString().toStdString();
  11843. ref.name = chosen->name.toStdString();
  11844. test->engine->editSong ([&] (lynx::Song& song) {
  11845. if (test->instrument)
  11846. {
  11847. lynx::ChannelDef c;
  11848. c.name = ref.name;
  11849. c.instrument = lynx::InstrumentKind::plugin;
  11850. c.plugin = ref;
  11851. test->channelIndex = (int) song.channels.size();
  11852. song.channels.push_back (c);
  11853. }
  11854. else
  11855. {
  11856. while (song.mixer.size() < 2)
  11857. song.mixer.emplace_back();
  11858. lynx::EffectSlot slot;
  11859. slot.kind = lynx::EffectKind::plugin;
  11860. slot.plugin = ref;
  11861. song.mixer[1].effects.push_back (slot);
  11862. }
  11863. });
  11864. test->engine->markSaved();
  11865. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  11866. test->next (0);
  11867. test->startTimerHz (20);
  11868. }
  11869. void runReloadTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath, bool waitKill)
  11870. {
  11871. struct Test final : juce::Timer
  11872. {
  11873. juce::String reportPath, report;
  11874. juce::File shots;
  11875. std::unique_ptr<lynx::AudioEngine> engine;
  11876. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  11877. bool instrument = false, waitKill = false, ok = true;
  11878. int channelIndex = -1, phase = 0, round = 0;
  11879. juce::uint32 phaseStart = 0;
  11880. int firstPid = 0, pid = 0, historyBefore = 0;
  11881. bool modifiedBefore = false;
  11882. float captured = -1.0f;
  11883. juce::AudioPluginInstance* instance = nullptr;
  11884. std::vector<lynx::ChannelDef> channelsBefore;
  11885. std::function<void (bool)> done;
  11886. lynx::AudioEngine::HostedSlot where() const { return instrument ? lynx::AudioEngine::HostedSlot { channelIndex, -1, -1 } : lynx::AudioEngine::HostedSlot { -1, 1, 0 }; }
  11887. void step (const juce::String& line)
  11888. {
  11889. report << line << "\n";
  11890. juce::File (reportPath).replaceWithText (report);
  11891. }
  11892. void expect (const juce::String& name, bool value)
  11893. {
  11894. step (name + "=" + juce::String ((int) value));
  11895. ok = ok && value;
  11896. }
  11897. void next (int to)
  11898. {
  11899. phase = to;
  11900. phaseStart = juce::Time::getMillisecondCounter();
  11901. }
  11902. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  11903. juce::AudioPluginInstance* find()
  11904. {
  11905. if (instrument)
  11906. {
  11907. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  11908. return &p->getInstance();
  11909. }
  11910. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  11911. return &p->getInstance();
  11912. return nullptr;
  11913. }
  11914. // a few blocks through the plugin (the offline engine has no audio thread): they carry parameter changes to
  11915. // the plugin's process and its values back
  11916. void pump (int blocks)
  11917. {
  11918. std::vector<float> l (512), r (512);
  11919. lynx::EffectParams none {};
  11920. for (int b = 0; b < blocks; ++b)
  11921. {
  11922. std::fill (l.begin(), l.end(), 0.0f);
  11923. std::fill (r.begin(), r.end(), 0.0f);
  11924. if (instrument)
  11925. {
  11926. if (auto in = engine->getChannelInstrument (channelIndex))
  11927. in->render (l.data(), r.data(), 512, 1.0f, 1.0f);
  11928. }
  11929. else if (auto fx = engine->getEffect (1, 0))
  11930. fx->process (l.data(), r.data(), 512, none, 120.0);
  11931. }
  11932. }
  11933. juce::AudioProcessorParameter* firstParam()
  11934. {
  11935. if (instance != nullptr)
  11936. for (auto* candidate : instance->getParameters())
  11937. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  11938. return candidate;
  11939. return nullptr;
  11940. }
  11941. void openWindow()
  11942. {
  11943. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  11944. : std::shared_ptr<void> (engine->getEffect (1, 0));
  11945. lynx::PluginWindows::WrapperContext context { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  11946. if (instrument)
  11947. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  11948. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  11949. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  11950. }, instrument, instrument ? -1 : 1, instrument ? -1 : 0, {}, {} };
  11951. context.reload = [] {}; // (the test reloads by itself; with it the window shows the notice)
  11952. lynx::PluginWindows::open (owner, *instance, instance->getName(), std::move (context));
  11953. }
  11954. void shot (const char* name, bool settingsPage = false)
  11955. {
  11956. if (shots != juce::File() && instance != nullptr)
  11957. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  11958. }
  11959. void timerCallback() override
  11960. {
  11961. if (phase == 0) // waiting for the engine to host the plugin
  11962. {
  11963. instance = find();
  11964. if (instance == nullptr)
  11965. {
  11966. if (elapsed() > 20000)
  11967. finish ("not hosted");
  11968. return;
  11969. }
  11970. pid = firstPid = lynx::sandboxedPluginProcessId (*instance);
  11971. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName + " pid=" + juce::String (pid));
  11972. expect ("separate_process", lynx::isSandboxedPlugin (*instance) && pid != 0);
  11973. expect ("running", ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  11974. // a setting that is captured (what a save or a backup does), then one that is not
  11975. if (auto* param = firstParam())
  11976. {
  11977. param->setValue (param->getValue() > 0.5f ? 0.13f : 0.87f);
  11978. pump (4);
  11979. engine->capturePluginStates();
  11980. captured = param->getValue();
  11981. param->setValue (captured > 0.5f ? 0.31f : 0.69f);
  11982. pump (4);
  11983. step ("param=" + param->getName (64) + " captured=" + juce::String (captured, 4) + " then=" + juce::String (param->getValue(), 4));
  11984. }
  11985. else
  11986. {
  11987. engine->capturePluginStates();
  11988. step ("param=none");
  11989. }
  11990. channelsBefore = engine->getSong().channels;
  11991. historyBefore = engine->getHistoryPosition();
  11992. modifiedBefore = engine->isModified();
  11993. if (shots != juce::File())
  11994. openWindow();
  11995. next (1);
  11996. return;
  11997. }
  11998. if (phase == 1 && elapsed() >= 600) // the plugin's process goes
  11999. {
  12000. shot (round == 0 ? "window-running" : "window-reloaded");
  12001. if (waitKill && round == 0)
  12002. {
  12003. juce::File (reportPath + ".pid").replaceWithText (juce::String (pid));
  12004. step ("waiting_for_kill pid=" + juce::String (pid));
  12005. }
  12006. else
  12007. lynx::crashSandboxedPluginForTest (*instance);
  12008. next (2);
  12009. return;
  12010. }
  12011. if (phase == 2) // LYNX notices
  12012. {
  12013. if (! engine->hostedPluginDown (where()))
  12014. {
  12015. pump (1); // (as the audio thread would: a block that gets no answer marks it too)
  12016. if (elapsed() > (waitKill && round == 0 ? 120000 : 10000))
  12017. finish ("the plugin never went down");
  12018. return;
  12019. }
  12020. step ("down_after_ms=" + juce::String (elapsed()));
  12021. const auto down = engine->downHostedPlugins();
  12022. expect ("listed_down", down.size() == 1 && down.front() == where());
  12023. expect ("listed_by_name", engine->downHostedPlugins (nameInSong()).size() == 1 && engine->downHostedPlugins ("no such plugin").empty());
  12024. next (3);
  12025. return;
  12026. }
  12027. if (phase == 3 && elapsed() >= 1500) // nothing reloads by itself
  12028. {
  12029. expect ("still_down_without_asking", engine->hostedPluginDown (where()) && find() == instance
  12030. && lynx::sandboxedPluginProcessId (*instance) == pid);
  12031. shot (round == 0 ? "reload-notice" : "reload-notice-again");
  12032. if (shots != juce::File() && round == 0)
  12033. {
  12034. lynx::PluginWindows::close (*instance);
  12035. lynx::PluginWindows::promptReload (*engine, where(), {});
  12036. next (4);
  12037. return;
  12038. }
  12039. next (5);
  12040. return;
  12041. }
  12042. if (phase == 4 && elapsed() >= 500) // the prompt a click on the channel / slot shows
  12043. {
  12044. auto found = false;
  12045. for (int c = juce::Desktop::getInstance().getNumComponents(); --c >= 0;)
  12046. if (auto* alert = dynamic_cast<juce::AlertWindow*> (juce::Desktop::getInstance().getComponent (c)))
  12047. {
  12048. const auto image = alert->createComponentSnapshot (alert->getLocalBounds(), true, 1.0f);
  12049. juce::FileOutputStream out (shots.getChildFile ("reload-prompt.png"));
  12050. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  12051. alert->exitModalState (0); // Close: nothing reloads
  12052. break;
  12053. }
  12054. step ("shot_reload-prompt=" + juce::String ((int) found));
  12055. next (45);
  12056. return;
  12057. }
  12058. if (phase == 45 && elapsed() >= 300)
  12059. {
  12060. expect ("still_down_after_close", engine->hostedPluginDown (where()));
  12061. next (5);
  12062. return;
  12063. }
  12064. if (phase == 5) // Reload, as the notice's button / the prompt / the menu item do
  12065. {
  12066. auto* old = instance;
  12067. const auto running = lynx::PluginWindows::reload (*engine, { where() });
  12068. instance = find();
  12069. const auto newPid = instance != nullptr ? lynx::sandboxedPluginProcessId (*instance) : 0;
  12070. expect ("reloaded", running == 1 && instance != nullptr && ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  12071. expect ("new_process", newPid != 0 && newPid != pid);
  12072. step ("pid=" + juce::String (newPid) + " same_object=" + juce::String ((int) (instance == old)));
  12073. expect ("old_window_closed", ! lynx::PluginWindows::isOpen (*old) || instance == old);
  12074. pid = newPid;
  12075. if (instance != nullptr)
  12076. {
  12077. pump (4);
  12078. if (auto* param = firstParam(); param != nullptr && captured >= 0.0f)
  12079. {
  12080. step ("param_after_reload=" + juce::String (param->getValue(), 4));
  12081. expect ("state_captured_last", std::abs (param->getValue() - captured) < 0.02f);
  12082. }
  12083. }
  12084. expect ("song_untouched", engine->getSong().channels == channelsBefore);
  12085. expect ("no_undo_step", engine->getHistoryPosition() == historyBefore && engine->isModified() == modifiedBefore);
  12086. if (instance == nullptr)
  12087. {
  12088. finish ("no instance after the reload");
  12089. return;
  12090. }
  12091. if (shots != juce::File())
  12092. openWindow();
  12093. if (round == 0) // once more: a plugin that crashes again waits for the user again
  12094. {
  12095. round = 1;
  12096. next (1);
  12097. return;
  12098. }
  12099. next (6);
  12100. return;
  12101. }
  12102. if (phase == 6 && elapsed() >= 400) // an edit and its undo keep the reloaded plugin
  12103. {
  12104. shot ("window-reloaded-twice");
  12105. auto* before = find();
  12106. engine->editSong ([] (lynx::Song& song) { song.bpm += 1.0f; });
  12107. engine->undo();
  12108. expect ("undo_keeps_the_reloaded_plugin", find() == before && ! engine->hostedPluginDown (where()));
  12109. lynx::PluginWindows::closeAll();
  12110. finish ({});
  12111. }
  12112. }
  12113. std::string nameInSong() const
  12114. {
  12115. const auto& song = engine->getSong();
  12116. return instrument ? song.channels[(size_t) channelIndex].plugin.name : song.mixer[1].effects[0].plugin.name;
  12117. }
  12118. void finish (const juce::String& failure)
  12119. {
  12120. stopTimer();
  12121. if (failure.isNotEmpty())
  12122. step ("failed=" + failure);
  12123. ok = ok && failure.isEmpty();
  12124. step (ok ? "result=OK" : "result=FAILED");
  12125. lynx::PluginWindows::closeAll();
  12126. done (ok);
  12127. }
  12128. };
  12129. lynx::setPluginSandboxAlerts (true); // (the deaths are recorded as in the app; no box: there is no main component)
  12130. auto* test = new Test();
  12131. test->reportPath = reportPath;
  12132. test->waitKill = waitKill;
  12133. if (shotsPath.isNotEmpty())
  12134. {
  12135. test->shots = juce::File (shotsPath);
  12136. test->shots.createDirectory();
  12137. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12138. }
  12139. juce::File (reportPath + ".pid").deleteFile();
  12140. test->done = [this, test] (bool ok) {
  12141. setApplicationReturnValue (ok ? 0 : 1);
  12142. juce::MessageManager::callAsync ([this, test] {
  12143. lynx::setMainWindowForOwnership (nullptr);
  12144. test->mainWindow = nullptr;
  12145. test->engine = nullptr;
  12146. delete test;
  12147. quit();
  12148. });
  12149. };
  12150. test->engine = std::make_unique<lynx::AudioEngine> (false);
  12151. if (shotsPath.isNotEmpty())
  12152. {
  12153. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  12154. test->mainWindow->setBounds (20, 20, 300, 200);
  12155. test->mainWindow->setVisible (true);
  12156. lynx::setMainWindowForOwnership (test->mainWindow.get());
  12157. }
  12158. auto& host = test->engine->getPluginHost();
  12159. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  12160. std::optional<juce::PluginDescription> chosen;
  12161. for (const auto& type : host.getKnownPlugins().getTypes())
  12162. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath
  12163. || (pluginPath.endsWithIgnoreCase (".lv2") && type.pluginFormatName == "LV2")) // (round 190rf: an LV2 bundle's plugin, known by URI)
  12164. {
  12165. chosen = type;
  12166. break;
  12167. }
  12168. if (! chosen)
  12169. {
  12170. test->step ("result=FAILED (no plugin)");
  12171. test->done (false);
  12172. return;
  12173. }
  12174. test->instrument = chosen->isInstrument;
  12175. lynx::PluginRef ref;
  12176. ref.separateProcess = true;
  12177. ref.id = chosen->createIdentifierString().toStdString();
  12178. ref.name = chosen->name.toStdString();
  12179. test->engine->editSong ([&] (lynx::Song& song) {
  12180. if (test->instrument)
  12181. {
  12182. lynx::ChannelDef c;
  12183. c.name = ref.name;
  12184. c.instrument = lynx::InstrumentKind::plugin;
  12185. c.plugin = ref;
  12186. test->channelIndex = (int) song.channels.size();
  12187. song.channels.push_back (c);
  12188. }
  12189. else
  12190. {
  12191. while (song.mixer.size() < 2)
  12192. song.mixer.emplace_back();
  12193. lynx::EffectSlot slot;
  12194. slot.kind = lynx::EffectKind::plugin;
  12195. slot.plugin = ref;
  12196. song.mixer[1].effects.push_back (slot);
  12197. }
  12198. });
  12199. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  12200. test->next (0);
  12201. test->startTimerHz (20);
  12202. }
  12203. void runPlugWinTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only, int seconds)
  12204. {
  12205. struct Test final : juce::Timer
  12206. {
  12207. juce::String reportPath, report;
  12208. std::unique_ptr<lynx::AudioEngine> engine;
  12209. bool instrument = false;
  12210. int phase = 0, ticks = 0, seconds = 15, dockStep = 0;
  12211. juce::uint32 phaseStartMs = 0; // (phase 1 counts real time: the timer's ticks ran faster than 20 Hz here)
  12212. juce::AudioPluginInstance* instance = nullptr;
  12213. juce::AudioProcessorParameter* checked = nullptr;
  12214. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  12215. lynx::Workspace* workspace = nullptr; // LYNX_PLUGWIN_DOCK=1: the real main window's desktop (issue #116)
  12216. int channelIndex = -1; // an instrument: its channel (added after the song's own channels)
  12217. int stepMs = 3000; // dock mode: each state held that long (screenshots)
  12218. bool keysDone = false;
  12219. bool dockOk = true;
  12220. std::function<void (bool)> done;
  12221. // LYNX_PLUGWIN_DROP=<sample> (issue #174): a Sample browser window beside the plugin window with that file
  12222. // selected. The report gives the row's and the editor's places on screen with what LYNX sees there (for a
  12223. // real drag by xdotool / SendInput in that time), and, before the plugin is removed, whether the plugin took
  12224. // the file (its saved state names it).
  12225. juce::File dropFile;
  12226. std::unique_ptr<juce::DocumentWindow> dropWindow;
  12227. lynx::BrowserComponent* dropBrowser = nullptr;
  12228. int dropStage = 0;
  12229. juce::uint32 dropReadyMs = 0; // (the Browser may take long to list a big library: the time counts from here)
  12230. void dropTick (int elapsedMs)
  12231. {
  12232. if (dropStage == 0 && elapsedMs >= 1000)
  12233. {
  12234. lynx::externaldrag::install();
  12235. auto content = lynx::BrowserComponent::makeSampleBrowserContent (*engine, [this] (lynx::BrowserComponent& b) { dropBrowser = &b; });
  12236. dropWindow = std::make_unique<juce::DocumentWindow> ("LYNX test sample browser", juce::Colours::darkgrey, 0);
  12237. dropWindow->setContentOwned (content.release(), false);
  12238. dropWindow->setBounds (20, 240, 340, 520);
  12239. dropWindow->setVisible (true);
  12240. if (dropBrowser != nullptr)
  12241. {
  12242. dropBrowser->showFilterForSnapshot (dropFile.getParentDirectory(), lynx::browserview::ContentFilter::all);
  12243. step ("drop_locate=" + juce::String ((int) dropBrowser->locateFile (dropFile)));
  12244. }
  12245. dropStage = 1;
  12246. }
  12247. else if (dropStage == 1 && elapsedMs >= 2500)
  12248. {
  12249. using namespace lynx::externaldrag;
  12250. const auto row = dropBrowser != nullptr ? dropBrowser->selectedRowScreenBounds() : juce::Rectangle<int>();
  12251. const auto from = row.getCentre();
  12252. // (physical pixels too: SendInput / xdotool work in those)
  12253. auto physical = [] (juce::Point<int> p) {
  12254. const auto q = juce::Desktop::getInstance().getDisplays().logicalToPhysical (p);
  12255. return " phys=" + juce::String (q.x) + "," + juce::String (q.y);
  12256. };
  12257. step ("drop_source=" + juce::String (from.x) + "," + juce::String (from.y) + " place=" + placeName (placeAt (from)) + physical (from));
  12258. if (const auto pid = lynx::sandboxedPluginProcessId (*instance); pid != 0)
  12259. step ("drop_target_pid=" + juce::String (pid)); // (its window is the other process's)
  12260. else if (auto* editor = instance->getActiveEditor())
  12261. {
  12262. const auto to = editor->getScreenBounds().getCentre();
  12263. step ("drop_target=" + juce::String (to.x) + "," + juce::String (to.y) + " place=" + placeName (placeAt (to)) + physical (to));
  12264. }
  12265. const auto files = filesOf (juce::String (lynx::BrowserComponent::dragDescription) + "|" + dropFile.getFullPathName(), nullptr);
  12266. step ("drop_files=" + files.joinIntoString (";"));
  12267. dropStage = 2;
  12268. dropReadyMs = juce::Time::getMillisecondCounter();
  12269. }
  12270. }
  12271. void dropResult()
  12272. {
  12273. juce::MemoryBlock state;
  12274. instance->getStateInformation (state);
  12275. const auto name = dropFile.getFileNameWithoutExtension().toStdString();
  12276. auto holds = [&name] (const juce::MemoryBlock& block) {
  12277. const auto* bytes = static_cast<const char*> (block.getData());
  12278. return ! name.empty() && std::search (bytes, bytes + block.getSize(), name.begin(), name.end()) != bytes + block.getSize();
  12279. };
  12280. auto received = holds (state);
  12281. // (JUCE's VST3 host keeps the plugin's own state base64-encoded inside an XML of its own)
  12282. auto xml = juce::AudioProcessor::getXmlFromBinary (state.getData(), (int) state.getSize());
  12283. if (xml == nullptr)
  12284. xml = juce::parseXML (state.toString());
  12285. if (! received && xml != nullptr)
  12286. for (auto* e : xml->getChildIterator())
  12287. {
  12288. juce::MemoryBlock inner;
  12289. if (inner.fromBase64Encoding (e->getAllSubText().trim()) && holds (inner))
  12290. received = true;
  12291. }
  12292. step ("drop_received=" + juce::String ((int) received));
  12293. }
  12294. // issue #116 (with LYNX_DOCKED_PLUGINS=1 and LYNX_PLUGWIN_DOCK=1), FL's f116 sequence for every floating
  12295. // panel: the docked plugin window goes behind a clicked panel and comes back in front when clicked; a
  12296. // panel called by its key comes in front too; Detached reopens it as a window of its own, which stays above
  12297. // every panel clicked (it is owned by the main window).
  12298. const std::array<lynx::workspace::Panel, 4> dockPanels { lynx::workspace::Panel::channelRack, lynx::workspace::Panel::playlist,
  12299. lynx::workspace::Panel::pianoRoll, lynx::workspace::Panel::mixer };
  12300. const int dockSteps = 2 * 4 + 18; // (the last one reports dock_result)
  12301. int danceChannel = -1; // issue #116 slice 4: a dance channel's dancer over the docked plugin
  12302. lynx::MainComponent* ui = nullptr; // dock mode: the real main window's contents
  12303. struct ScaleSpy final : juce::ComponentPeer::ScaleFactorListener
  12304. {
  12305. int calls = 0;
  12306. double last = 0.0;
  12307. void nativeScaleFactorChanged (double s) override { ++calls; last = s; }
  12308. } scaleSpy;
  12309. juce::ComponentPeer* spiedPeer = nullptr;
  12310. void* panelHandle (lynx::workspace::Panel p) const { return workspace->getFrame (p).getWindowHandle(); }
  12311. void dockCheck (int at)
  12312. {
  12313. using lynx::workspace::Panel;
  12314. auto* main = mainWindow->getWindowHandle();
  12315. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  12316. auto expect = [this] (const juce::String& name, bool value) {
  12317. step (name + "=" + juce::String ((int) value));
  12318. dockOk = dockOk && value;
  12319. };
  12320. auto id = [] (Panel p) { return juce::String (lynx::workspace::panelId (p)); };
  12321. if (at == 0)
  12322. {
  12323. expect ("docked", lynx::PluginWindows::isDocked (*instance));
  12324. expect ("plugin_native_child", plug != nullptr && lynx::nativechild::parentOf (plug) == main);
  12325. for (auto p : dockPanels)
  12326. {
  12327. auto* h = panelHandle (p);
  12328. expect (id (p) + "_visible", workspace->isPanelVisible (p));
  12329. expect (id (p) + "_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  12330. expect ("plugin_above_" + id (p) + "_when_opened", lynx::nativechild::isAbove (plug, h));
  12331. }
  12332. expect ("browser_plain", ! workspace->isNativePanel (Panel::browser));
  12333. }
  12334. if (at < 2 * 4)
  12335. {
  12336. const auto p = dockPanels[at / 2];
  12337. if (at % 2 == 0)
  12338. {
  12339. workspace->activate (p); // a click on the panel
  12340. expect (id (p) + "_above_plugin_after_its_click", lynx::nativechild::isAbove (panelHandle (p), plug));
  12341. // the plugin stays above the panels nobody clicked
  12342. for (auto other : dockPanels)
  12343. if (other != p)
  12344. expect ("plugin_above_" + id (other) + "_after_" + id (p) + "_click", lynx::nativechild::isAbove (plug, panelHandle (other)));
  12345. }
  12346. else
  12347. {
  12348. lynx::PluginWindows::open ({}, *instance, {}); // (open again = a click on the plugin)
  12349. expect ("plugin_above_" + id (p) + "_after_plugin_click", lynx::nativechild::isAbove (plug, panelHandle (p)));
  12350. }
  12351. return;
  12352. }
  12353. if (at == 8)
  12354. {
  12355. // a layout change elsewhere (a panel resized, the Browser shown) keeps the plugin in front; a panel
  12356. // called by its key comes in front of it
  12357. workspace->hide (Panel::browser);
  12358. workspace->show (Panel::browser);
  12359. for (auto p : dockPanels)
  12360. expect ("plugin_above_" + id (p) + "_after_layout_change", lynx::nativechild::isAbove (plug, panelHandle (p)));
  12361. workspace->show (Panel::mixer);
  12362. expect ("mixer_above_plugin_after_show", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  12363. }
  12364. else if (at == 9)
  12365. {
  12366. // the setup wizard (Options › Setup wizard; first start) in front of the native panels and the plugin
  12367. ui->showSetupWizard();
  12368. }
  12369. else if (at == 10)
  12370. {
  12371. auto* overlay = ui->setupOverlayForTest();
  12372. auto* h = overlay != nullptr ? overlay->getWindowHandle() : nullptr;
  12373. expect ("setup_overlay_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  12374. expect ("setup_overlay_above_plugin", lynx::nativechild::isAbove (h, plug));
  12375. for (auto p : dockPanels)
  12376. expect ("setup_overlay_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  12377. workspace->activate (Panel::playlist); // (a panel brought in front by code: the overlay stays in front)
  12378. lynx::PluginWindows::open ({}, *instance, {});
  12379. expect ("setup_overlay_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::playlist)));
  12380. }
  12381. else if (at == 11)
  12382. {
  12383. ui->closeSetupWizardForSnapshot();
  12384. expect ("setup_overlay_closed", ui->setupOverlayForTest() == nullptr);
  12385. // drops: JUCE's list of windows in the native stacking order once a drag starts
  12386. workspace->activate (Panel::mixer);
  12387. workspace->hide (Panel::browser);
  12388. workspace->show (Panel::browser);
  12389. lynx::matchWindowOrderToScreen();
  12390. auto children = lynx::nativechild::attachedChildren (main);
  12391. auto& desktop = juce::Desktop::getInstance();
  12392. int last = -1;
  12393. bool ordered = children.size() >= 5;
  12394. for (auto* c : children)
  12395. if (c->isVisible())
  12396. {
  12397. int at2 = -1;
  12398. for (int k = 0; k < desktop.getNumComponents(); ++k)
  12399. if (desktop.getComponent (k) == c)
  12400. at2 = k;
  12401. ordered = ordered && at2 > last;
  12402. last = at2;
  12403. }
  12404. expect ("drop_order_matches_screen", ordered);
  12405. }
  12406. else if (at == 12)
  12407. {
  12408. // the main window's scale changes (a display with another scale): every native child placed again in
  12409. // physical pixels, the docked editor's window told (JUCE tells child windows nothing by itself)
  12410. for (int i = 0; i < juce::ComponentPeer::getNumPeers(); ++i)
  12411. if (auto* peer = juce::ComponentPeer::getPeer (i); peer != nullptr && peer->getNativeHandle() == plug)
  12412. spiedPeer = peer;
  12413. if (spiedPeer != nullptr)
  12414. spiedPeer->addScaleFactorListener (&scaleSpy);
  12415. lynx::nativechild::notifyScaleListenersForTest (*mainWindow);
  12416. juce::Desktop::getInstance().setGlobalScaleFactor (1.25f); // and LYNX's own UI zoom
  12417. }
  12418. else if (at == 13)
  12419. {
  12420. bool placed = true;
  12421. for (auto* c : lynx::nativechild::attachedChildren (main))
  12422. placed = placed && (! c->isVisible() || lynx::nativechild::placedPhysically (*c));
  12423. expect ("native_children_placed_at_125", placed);
  12424. expect ("docked_editor_told_the_scale", scaleSpy.calls > 0 && spiedPeer != nullptr
  12425. && std::abs (scaleSpy.last - spiedPeer->getPlatformScaleFactor()) < 0.001);
  12426. if (spiedPeer != nullptr && juce::ComponentPeer::isValidPeer (spiedPeer))
  12427. spiedPeer->removeScaleFactorListener (&scaleSpy);
  12428. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  12429. lynx::PluginWindows::setDetached (*instance, true);
  12430. }
  12431. else if (at == 14)
  12432. {
  12433. expect ("detached_reopened", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance));
  12434. expect ("detached_owned_by_main", plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  12435. expect ("detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  12436. for (auto p : dockPanels)
  12437. workspace->activate (p);
  12438. }
  12439. else if (at == 15)
  12440. {
  12441. // (an owned top-level window: above the main window and so above all its child windows)
  12442. expect ("detached_stays_above_clicked_panels", plug != nullptr && lynx::nativechild::ownerOf (plug) == main
  12443. && lynx::nativechild::parentOf (plug) != main && lynx::PluginWindows::isOpen (*instance));
  12444. lynx::PluginWindows::setDetached (*instance, false);
  12445. }
  12446. else if (at == 16)
  12447. {
  12448. // issue #116 slice 4: a Fruity Dance dancer standing on the docked plugin window, in front of it
  12449. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  12450. juce::Rectangle<int> over;
  12451. for (auto* c : lynx::nativechild::attachedChildren (main))
  12452. if (c->getWindowHandle() == plug)
  12453. over = ui->getLocalArea (nullptr, c->getScreenBounds());
  12454. expect ("dance_stage", stage != nullptr && ! over.isEmpty());
  12455. lynx::dance::Settings s;
  12456. s.move = lynx::dance::held; // (a still pose: the pixels tested below stay where they are)
  12457. s.x = over.getCentreX();
  12458. s.y = over.getCentreY() + 70;
  12459. const auto state = lynx::dance::toState (s);
  12460. engine->editSongStructural ([this, state] (lynx::Song& song) {
  12461. lynx::ChannelDef c;
  12462. c.name = "Fruity Dance";
  12463. c.instrument = lynx::InstrumentKind::fruitydance;
  12464. c.pluginState = state;
  12465. danceChannel = (int) song.channels.size();
  12466. song.channels.push_back (c);
  12467. });
  12468. engine->dispatchPendingMessages();
  12469. if (stage != nullptr)
  12470. stage->update();
  12471. }
  12472. else if (at == 17)
  12473. {
  12474. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  12475. auto* w = stage != nullptr ? stage->windowOf (danceChannel) : nullptr;
  12476. auto* h = w != nullptr ? w->getWindowHandle() : nullptr;
  12477. expect ("dancer_window_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  12478. expect ("dancer_window_layered", lynx::nativechild::isLayered (h));
  12479. expect ("dancer_above_plugin", lynx::nativechild::isAbove (h, plug));
  12480. for (auto p : dockPanels)
  12481. expect ("dancer_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  12482. // panels and the plugin brought in front (clicks, keys): the dancer stays in front of them
  12483. workspace->activate (Panel::mixer);
  12484. workspace->show (Panel::pianoRoll);
  12485. lynx::PluginWindows::open ({}, *instance, {});
  12486. expect ("dancer_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::mixer))
  12487. && lynx::nativechild::isAbove (h, panelHandle (Panel::pianoRoll)));
  12488. // the mouse: the dancer's body takes it, its window's transparent pixels let it through
  12489. if (w != nullptr)
  12490. {
  12491. const auto picture = w->createComponentSnapshot (w->getLocalBounds(), true, 1.0f);
  12492. const auto body = stage->bodyOf (danceChannel) - (w->getScreenPosition() - stage->getScreenPosition());
  12493. juce::Point<int> solid { -1, -1 }, clear { -1, -1 };
  12494. for (int y = body.getCentreY() - 10; y < body.getBottom() && solid.x < 0; ++y)
  12495. for (int x = body.getX(); x < body.getRight() && solid.x < 0; ++x)
  12496. if (picture.getBounds().contains (x, y) && picture.getPixelAt (x, y).getAlpha() == 255)
  12497. solid = { x, y };
  12498. for (int y = 0; y < picture.getHeight() && clear.x < 0; y += 2)
  12499. for (int x = 0; x < picture.getWidth() && clear.x < 0; x += 2)
  12500. if (picture.getPixelAt (x, y).getAlpha() == 0 && ! body.expanded (8).contains (x, y))
  12501. clear = { x, y };
  12502. step ("dancer_window=" + w->getBounds().toString() + " solid=" + solid.toString() + " clear=" + clear.toString());
  12503. auto* atSolid = lynx::nativechild::windowAt (*w, solid);
  12504. auto* atClear = lynx::nativechild::windowAt (*w, clear);
  12505. expect ("dancer_takes_its_body_clicks", solid.x >= 0 && atSolid == h);
  12506. expect ("dancer_lets_clicks_through", clear.x >= 0 && atClear != nullptr && atClear != h);
  12507. expect ("stage_leaves_the_mouse", ! stage->hitTest (stage->bodyOf (danceChannel).getCentreX(), stage->bodyOf (danceChannel).getCentreY()));
  12508. }
  12509. }
  12510. else if (at == 18)
  12511. {
  12512. // no dance channel: no dancer window (nothing drawn, no cost)
  12513. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  12514. engine->editSongStructural ([this] (lynx::Song& song) {
  12515. if (danceChannel >= 0 && danceChannel < (int) song.channels.size())
  12516. song.channels.erase (song.channels.begin() + danceChannel);
  12517. });
  12518. engine->dispatchPendingMessages();
  12519. if (stage != nullptr)
  12520. stage->update();
  12521. expect ("dancer_window_gone", stage != nullptr && stage->windowCount() == 0);
  12522. }
  12523. else if (at == 19 || at == 20)
  12524. {
  12525. // round 190ev (issue #152, "flickering windows"): on Windows a docked panel no longer fades by its
  12526. // window's alpha (each fade switched its drawing surface twice and the panel flashed); it shows and
  12527. // hides at once, as FL's docked windows. Elsewhere round 190i's fade stays.
  12528. auto& frame = workspace->getFrame (Panel::mixer);
  12529. if (at == 19)
  12530. {
  12531. workspace->show (Panel::mixer);
  12532. expect ("mixer_above_plugin_when_shown", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  12533. workspace->hide (Panel::mixer);
  12534. expect ("mixer_hides_at_once", ! frame.isVisible() && workspace->nativeFadeDirection (Panel::mixer) == 0
  12535. && frame.getAlpha() == 1.0f && ! lynx::nativechild::isLayered (frame.getWindowHandle()));
  12536. }
  12537. else
  12538. {
  12539. workspace->show (Panel::mixer);
  12540. expect ("mixer_shows_at_once", frame.isVisible() && frame.getAlpha() == 1.0f && workspace->nativeFadeDirection (Panel::mixer) == 0
  12541. && ! lynx::nativechild::isLayered (frame.getWindowHandle())
  12542. && lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  12543. }
  12544. }
  12545. else if (at >= 21 && at <= 23)
  12546. {
  12547. // round 190ev (issue #152, "the Channel rack almost never comes to the front"): LYNX's own editor
  12548. // windows (here a channel's settings) are docked like FL's plugin windows, so a click on the rack
  12549. // brings the rack in front of them and a click on one brings it back; a click inside a docked
  12550. // plugin's own view (a native window JUCE never hears of) brings that plugin window in front.
  12551. auto docked = [] {
  12552. auto& desktop = juce::Desktop::getInstance();
  12553. for (int i = 0; i < desktop.getNumComponents(); ++i)
  12554. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible() && (bool) c->getProperties()["lynxDockedWindow"])
  12555. return c;
  12556. return (juce::Component*) nullptr;
  12557. };
  12558. auto* rack = panelHandle (Panel::channelRack);
  12559. if (at == 21)
  12560. {
  12561. lynx::openChannelSettings (*engine, 0);
  12562. auto* ed = docked();
  12563. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  12564. expect ("editor_docked", h != nullptr && lynx::nativechild::parentOf (h) == main && lynx::nativechild::ownerOf (h) == nullptr);
  12565. expect ("editor_above_rack_when_opened", h != nullptr && lynx::nativechild::isAbove (h, rack));
  12566. workspace->activate (Panel::channelRack); // a click on the rack
  12567. expect ("rack_above_editor_after_its_click", h != nullptr && lynx::nativechild::isAbove (rack, h));
  12568. // a real click (a message to the editor's own window) on its title bar, at a point where the editor
  12569. // can be seen. Round 190fc (0.1.27 RC M1): JUCE takes a button-down only where the system says its
  12570. // window is the one under the point (HWNDComponentPeer::contains asks WindowFromPoint), so the old
  12571. // fixed point (60, 8) was dropped whenever the rack, raised just above, covered it there: the
  12572. // check read 0 while real clicks (on what can be seen) raise the editor.
  12573. if (h != nullptr && ed != nullptr)
  12574. {
  12575. juce::Point<int> at (-1, -1);
  12576. for (int x = 30; x < ed->getWidth() - 40 && at.x < 0; x += 12)
  12577. if (lynx::nativechild::windowAt (*ed, { x, 8 }) == h)
  12578. at = { x, 8 };
  12579. step (juce::String ("editor_title_visible_at=") + juce::String (at.x));
  12580. if (at.x >= 0)
  12581. {
  12582. const auto scale = ed->getPeer() != nullptr ? ed->getPeer()->getPlatformScaleFactor() * (double) ed->getDesktopScaleFactor() : 1.0;
  12583. lynx::nativechild::postClickForTest (h, (at.toDouble() * scale).roundToInt());
  12584. }
  12585. }
  12586. }
  12587. else if (at == 22)
  12588. {
  12589. auto* ed = docked();
  12590. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  12591. expect ("editor_above_rack_after_its_click", h != nullptr && lynx::nativechild::isAbove (h, rack));
  12592. workspace->activate (Panel::channelRack);
  12593. expect ("rack_above_plugin_after_its_click", lynx::nativechild::isAbove (rack, plug));
  12594. auto* view = lynx::nativechild::innermostChild (plug);
  12595. step (juce::String ("plugin_view_window=") + (view != nullptr ? "1" : "0"));
  12596. if (view != nullptr) // a click in the plugin's own view, near its top-left corner
  12597. lynx::nativechild::postClickForTest (view, { 2, 2 });
  12598. }
  12599. else
  12600. {
  12601. if (lynx::nativechild::innermostChild (plug) != nullptr)
  12602. expect ("plugin_above_rack_after_click_in_its_view", lynx::nativechild::isAbove (plug, rack));
  12603. lynx::closeChannelSettings();
  12604. // FL's Tools > Macros > Switch all plugin editors to > Detached (round 190i)
  12605. lynx::PluginWindows::setAllDetached (*engine, true);
  12606. }
  12607. }
  12608. else if (at == 24)
  12609. {
  12610. expect ("macro_detached_the_open_editor", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance)
  12611. && plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  12612. expect ("macro_detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  12613. lynx::PluginWindows::setAllDetached (*engine, false); // ... > Attached
  12614. }
  12615. else
  12616. {
  12617. expect ("docked_again", lynx::PluginWindows::isDocked (*instance) && engineRef() != nullptr && ! engineRef()->detached);
  12618. step (juce::String ("dock_result=") + (dockOk ? "OK" : "FAILED"));
  12619. }
  12620. }
  12621. const lynx::PluginRef* engineRef() const
  12622. {
  12623. const auto& song = engine->getSong();
  12624. if (instrument)
  12625. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  12626. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  12627. }
  12628. void step (const juce::String& line)
  12629. {
  12630. report << line << "\n";
  12631. juce::File (reportPath).replaceWithText (report);
  12632. }
  12633. juce::AudioPluginInstance* find()
  12634. {
  12635. if (instrument)
  12636. {
  12637. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  12638. return &p->getInstance();
  12639. }
  12640. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  12641. return &p->getInstance();
  12642. return nullptr;
  12643. }
  12644. void timerCallback() override
  12645. {
  12646. ++ticks;
  12647. if (phase == 0) // waiting for the engine to host the plugin
  12648. {
  12649. instance = find();
  12650. if (instance == nullptr)
  12651. {
  12652. if (ticks > 200)
  12653. {
  12654. step ("result=FAILED (not hosted)");
  12655. stopTimer();
  12656. done (false);
  12657. }
  12658. return;
  12659. }
  12660. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  12661. step ("programs=" + juce::String (instance->getNumPrograms()));
  12662. for (int p = 0; p < juce::jmin (5, instance->getNumPrograms()); ++p)
  12663. step ("program" + juce::String (p) + "=" + instance->getProgramName (p));
  12664. step ("save_formats=" + lynx::pluginpresetui::saveWildcard (*instance));
  12665. // preset round trip: save, change the first parameter, load, compare
  12666. juce::AudioProcessorParameter* param = nullptr;
  12667. for (auto* candidate : instance->getParameters())
  12668. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  12669. {
  12670. param = candidate;
  12671. break;
  12672. }
  12673. if (param != nullptr)
  12674. {
  12675. step ("param=" + param->getName (64));
  12676. checked = param;
  12677. const auto file = lynx::pluginpresetui::folderFor (instance->getName()).getChildFile ("plugwintest.lynxpreset");
  12678. juce::String error;
  12679. const auto before = param->getValue();
  12680. const auto saved = lynx::pluginpresetui::save (*instance, file, "plugwintest", error);
  12681. param->setValueNotifyingHost (before > 0.5f ? 0.1f : 0.9f);
  12682. const auto changed = param->getValue();
  12683. const auto loaded = saved && lynx::pluginpresetui::load (*instance, file, error);
  12684. step ("preset_roundtrip saved=" + juce::String ((int) saved) + " loaded=" + juce::String ((int) loaded) + " param0 before="
  12685. + juce::String (before, 4) + " changed=" + juce::String (changed, 4) + " after=" + juce::String (param->getValue(), 4)
  12686. + (error.isNotEmpty() ? " error=" + error : juce::String()));
  12687. for (const auto* ext : { "fxp", "fxb", "vstpreset" })
  12688. {
  12689. juce::String e2;
  12690. const auto f2 = file.withFileExtension (ext);
  12691. const auto ok2 = lynx::pluginpresetui::save (*instance, f2, "plugwintest", e2) && lynx::pluginpresetui::load (*instance, f2, e2);
  12692. step (juce::String ("preset_") + ext + "=" + juce::String ((int) ok2) + (e2.isNotEmpty() ? " (" + e2 + ")" : juce::String()));
  12693. f2.deleteFile();
  12694. }
  12695. step ("browser_lists=" + juce::String (lynx::pluginpresetui::userPresets (instance->getName()).size()));
  12696. }
  12697. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  12698. : std::shared_ptr<void> (engine->getEffect (1, 0));
  12699. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  12700. { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  12701. if (instrument)
  12702. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  12703. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  12704. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  12705. }, instrument });
  12706. owner.reset();
  12707. step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  12708. phase = 1;
  12709. ticks = 0;
  12710. phaseStartMs = juce::Time::getMillisecondCounter();
  12711. return;
  12712. }
  12713. if (phase == 1 && ticks >= 30 && ! keysDone && juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_KEYS", {}).isNotEmpty() && instance->getActiveEditor() != nullptr)
  12714. keysDone = ! lynx::pluginKeysTestTick (*instance->getActiveEditor(),
  12715. [this] (bool on) {
  12716. engine->editSong ([this, on] (lynx::Song& song) {
  12717. (instrument ? song.channels[(size_t) channelIndex].plugin : song.mixer[1].effects[0].plugin).hostKeysFirst = on;
  12718. });
  12719. },
  12720. [this] (const juce::String& line) { step (line); });
  12721. const auto elapsedMs = (int) (juce::Time::getMillisecondCounter() - phaseStartMs);
  12722. if (phase == 1 && ticks == 20 && checked != nullptr)
  12723. step ("param_after_1s=" + juce::String (checked->getValue(), 4));
  12724. // round 190in: LYNX_PLUGWIN_MENU=<png>: FL's ▸ wrapper menu of the open window (two columns for a channel)
  12725. if (const auto menuShot = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_MENU", {}); phase == 1 && ticks == 10 && menuShot.isNotEmpty())
  12726. if (const auto menu = lynx::PluginWindows::wrapperMenuForSnapshot (*instance))
  12727. {
  12728. juce::PopupMenu left, right;
  12729. auto* to = &left;
  12730. for (juce::PopupMenu::MenuItemIterator it (*menu); it.next();)
  12731. {
  12732. to->addItem (it.getItem());
  12733. if (it.getItem().shouldBreakAfter)
  12734. to = &right;
  12735. }
  12736. juce::StringArray names { "Plugin" };
  12737. std::vector<juce::PopupMenu> menus { left };
  12738. if (right.getNumItems() > 0)
  12739. {
  12740. names.add ("Channel");
  12741. menus.push_back (right);
  12742. }
  12743. LynxApplication::saveMenus (names, menus, menuShot);
  12744. step ("wrapper_menu_items=" + juce::String (left.getNumItems()) + "+" + juce::String (right.getNumItems()));
  12745. }
  12746. // (3 s apart: time for screenshots of each state)
  12747. if (phase == 1 && workspace != nullptr && dockStep < dockSteps && elapsedMs >= (dockStep + 1) * stepMs)
  12748. dockCheck (dockStep++);
  12749. if (phase == 1 && dropFile.existsAsFile())
  12750. dropTick (elapsedMs);
  12751. // (with LYNX_PLUGWIN_DROP: `seconds` after the drop places were reported, time for the drag)
  12752. const auto dropDone = ! dropFile.existsAsFile()
  12753. || (dropStage == 2 && (int) (juce::Time::getMillisecondCounter() - dropReadyMs) >= seconds * 1000);
  12754. if (phase == 1 && elapsedMs >= seconds * 1000 && dropDone && (workspace == nullptr || dockStep >= dockSteps)) // remove the plugin from the song
  12755. {
  12756. if (dropFile.existsAsFile())
  12757. dropResult();
  12758. engine->editSong ([this] (lynx::Song& song) {
  12759. if (instrument)
  12760. {
  12761. if (channelIndex >= 0 && channelIndex < (int) song.channels.size())
  12762. song.channels.erase (song.channels.begin() + channelIndex);
  12763. }
  12764. else
  12765. song.mixer[1].effects.clear();
  12766. });
  12767. step ("removed");
  12768. phase = 2;
  12769. ticks = 0;
  12770. return;
  12771. }
  12772. if (phase == 2 && ticks >= 40)
  12773. {
  12774. const auto open = lynx::PluginWindows::isOpen (*instance);
  12775. step ("window_open_after_remove=" + juce::String ((int) open));
  12776. step (open || ! dockOk ? "result=FAILED" : "result=OK");
  12777. stopTimer();
  12778. lynx::PluginWindows::closeAll();
  12779. done (! open && dockOk);
  12780. }
  12781. }
  12782. };
  12783. // round 190in: LYNX_PLUGWIN_ZOOM=<percent>: LYNX's interface zoom for the run (the wrapper's header at 150 %)
  12784. if (const auto zoom = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_ZOOM", {}).getIntValue(); zoom >= 50 && zoom <= 300)
  12785. juce::Desktop::getInstance().setGlobalScaleFactor ((float) zoom / 100.0f);
  12786. auto* test = new Test();
  12787. test->reportPath = reportPath;
  12788. test->seconds = seconds;
  12789. if (const auto drop = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DROP", {}); drop.isNotEmpty())
  12790. test->dropFile = juce::File (drop);
  12791. test->done = [this, test] (bool ok) {
  12792. setApplicationReturnValue (ok ? 0 : 1);
  12793. juce::MessageManager::callAsync ([this, test] {
  12794. lynx::setMainWindowForOwnership (nullptr);
  12795. lynx::PluginWindows::setDockWorkspace (nullptr);
  12796. test->dropWindow = nullptr; // (its Browser before the engine)
  12797. test->workspace = nullptr;
  12798. test->mainWindow = nullptr; // (dock mode: the main component with it, before the engine)
  12799. test->engine = nullptr;
  12800. delete test;
  12801. quit();
  12802. });
  12803. };
  12804. test->engine = std::make_unique<lynx::AudioEngine> (false);
  12805. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  12806. test->mainWindow->setBounds (20, 20, 300, 200);
  12807. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DOCK", {}) == "1" && lynx::nativechild::dockingEnabled())
  12808. {
  12809. // the real main window's contents (it docks plugin windows in its own desktop), so the panels are real
  12810. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12811. auto* ui = new lynx::MainComponent (*test->engine, false);
  12812. test->mainWindow->setUsingNativeTitleBar (true);
  12813. test->mainWindow->setContentOwned (ui, false);
  12814. test->mainWindow->setBounds (20, 20, 1500, 900);
  12815. test->workspace = &ui->workspaceForTest();
  12816. test->ui = ui;
  12817. if (const auto ms = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_STEP_MS", {}).getIntValue(); ms > 0)
  12818. test->stepMs = ms;
  12819. }
  12820. test->mainWindow->setVisible (true);
  12821. lynx::setMainWindowForOwnership (test->mainWindow.get());
  12822. if (test->workspace != nullptr)
  12823. {
  12824. using lynx::workspace::Panel;
  12825. for (auto p : { Panel::playlist, Panel::mixer, Panel::pianoRoll, Panel::channelRack })
  12826. test->workspace->show (p);
  12827. test->step ("dock_test=2 rack_visible=" + juce::String ((int) test->workspace->isPanelVisible (Panel::channelRack)));
  12828. }
  12829. auto& host = test->engine->getPluginHost();
  12830. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  12831. std::optional<juce::PluginDescription> chosen;
  12832. for (const auto& type : host.getKnownPlugins().getTypes())
  12833. if ((juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath
  12834. || (pluginPath.endsWithIgnoreCase (".lv2") && type.pluginFormatName == "LV2")) // (round 190rf: an LV2 bundle's plugin, known by URI)
  12835. && (only.isEmpty() || type.name == only))
  12836. {
  12837. chosen = type;
  12838. break;
  12839. }
  12840. if (! chosen)
  12841. {
  12842. test->step ("result=FAILED (no plugin)");
  12843. test->done (false);
  12844. return;
  12845. }
  12846. test->instrument = chosen->isInstrument;
  12847. lynx::PluginRef ref;
  12848. ref.separateProcess = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_SEPARATE", {}) == "1"; // (issue #96's other-process check)
  12849. ref.id = chosen->createIdentifierString().toStdString();
  12850. ref.name = chosen->name.toStdString();
  12851. test->engine->editSong ([&] (lynx::Song& song) {
  12852. if (test->instrument)
  12853. {
  12854. lynx::ChannelDef c;
  12855. c.name = ref.name;
  12856. c.instrument = lynx::InstrumentKind::plugin;
  12857. c.plugin = ref;
  12858. test->channelIndex = (int) song.channels.size();
  12859. song.channels.push_back (c);
  12860. }
  12861. else
  12862. {
  12863. while (song.mixer.size() < 2)
  12864. song.mixer.emplace_back();
  12865. lynx::EffectSlot slot;
  12866. slot.kind = lynx::EffectKind::plugin;
  12867. slot.plugin = ref;
  12868. song.mixer[1].effects.push_back (slot);
  12869. }
  12870. });
  12871. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  12872. test->startTimerHz (20);
  12873. }
  12874. void runEditorCrashTest (const juce::String& pluginPath, const juce::String& reportPath)
  12875. {
  12876. struct CrashTest final : juce::Timer
  12877. {
  12878. juce::String reportPath, report;
  12879. std::unique_ptr<lynx::PluginHost> host;
  12880. juce::AudioPluginInstance* plugin = nullptr;
  12881. std::shared_ptr<juce::AudioPluginInstance> keep; // a window whose plugin nobody else holds is closed as orphaned
  12882. std::function<void (bool)> done;
  12883. int ticks = 0, crashesBefore = 0;
  12884. void step (const juce::String& line)
  12885. {
  12886. report << line << "\n";
  12887. juce::File (reportPath).replaceWithText (report); // at each step: a crash leaves the last one
  12888. }
  12889. void timerCallback() override
  12890. {
  12891. ++ticks;
  12892. const auto crashes = lynx::PluginWindows::editorCrashCount() - crashesBefore;
  12893. const auto open = lynx::PluginWindows::isOpen (*plugin);
  12894. if ((crashes > 0 && ! open) || ticks >= 50) // 100 ms ticks: up to 5 s
  12895. {
  12896. stopTimer();
  12897. step ("editor_crashes=" + juce::String (crashes) + " window_open=" + juce::String ((int) open) + " ticks=" + juce::String (ticks));
  12898. bool traced = false;
  12899. if (crashes > 0)
  12900. {
  12901. const auto last = lynx::PluginWindows::editorCrashes().back();
  12902. traced = last.traceFile.existsAsFile() && last.traceFile.loadFileAsString().contains ("LYNX Test Crash");
  12903. step ("plugin=" + last.plugin + " detail=" + last.detail + " trace=" + last.traceFile.getFileName() + " traced="
  12904. + juce::String ((int) traced));
  12905. last.traceFile.deleteFile();
  12906. }
  12907. // still alive: one more message through the loop after the fault
  12908. juce::MessageManager::callAsync ([this, ok = crashes == 1 && ! open && traced] {
  12909. step ("message_loop_after_fault=1");
  12910. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  12911. done (ok);
  12912. });
  12913. }
  12914. }
  12915. };
  12916. auto* test = new CrashTest();
  12917. test->reportPath = reportPath;
  12918. test->done = [this, test] (bool ok)
  12919. {
  12920. setApplicationReturnValue (ok ? 0 : 1);
  12921. juce::MessageManager::callAsync ([this, test] { lynx::PluginWindows::closeAll(); delete test; quit(); });
  12922. };
  12923. #if ! JUCE_WINDOWS
  12924. test->step ("result=SKIPPED (Windows only: on macOS / Linux a plugin fault is a signal, see docs/analise/REA_rodada174a.md)");
  12925. test->done (true);
  12926. return;
  12927. #else
  12928. _putenv_s ("LYNX_TEST_CRASH", "editor");
  12929. test->host = std::make_unique<lynx::PluginHost> (false);
  12930. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  12931. std::shared_ptr<juce::AudioPluginInstance> instance;
  12932. for (const auto& type : test->host->getKnownPlugins().getTypes())
  12933. {
  12934. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName())
  12935. continue;
  12936. juce::String error;
  12937. instance = std::shared_ptr<juce::AudioPluginInstance> (lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error).release());
  12938. test->step ("plugin=" + type.name + (instance == nullptr ? " error=" + error : juce::String()));
  12939. break;
  12940. }
  12941. if (instance == nullptr || ! instance->hasEditor())
  12942. {
  12943. test->step ("result=FAILED (no plugin with an editor)");
  12944. test->done (false);
  12945. return;
  12946. }
  12947. lynx::preparePlugin (*instance, 48000.0, 512);
  12948. test->plugin = instance.get();
  12949. test->keep = instance;
  12950. test->crashesBefore = lynx::PluginWindows::editorCrashCount();
  12951. lynx::PluginWindows::open (instance, *instance, instance->getName()); // (the window keeps the plugin alive)
  12952. test->step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  12953. test->startTimer (100);
  12954. #endif
  12955. }
  12956. void runEditorTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only)
  12957. {
  12958. struct EditorTest final : juce::Timer
  12959. {
  12960. juce::String reportPath, report;
  12961. std::unique_ptr<lynx::PluginHost> host;
  12962. std::unique_ptr<juce::AudioPluginInstance> plugin;
  12963. std::unique_ptr<juce::DocumentWindow> window;
  12964. std::function<void (bool)> done;
  12965. void step (const juce::String& line)
  12966. {
  12967. report << line << "\n";
  12968. juce::File (reportPath).replaceWithText (report); // written at each step: a crash leaves the last one
  12969. }
  12970. void timerCallback() override
  12971. {
  12972. stopTimer();
  12973. window = nullptr;
  12974. step ("step=closed");
  12975. plugin = nullptr;
  12976. step ("result=OK");
  12977. done (true);
  12978. }
  12979. };
  12980. auto* test = new EditorTest();
  12981. test->reportPath = reportPath;
  12982. test->done = [this, test] (bool ok)
  12983. {
  12984. setApplicationReturnValue (ok ? 0 : 1);
  12985. juce::MessageManager::callAsync ([this, test] { delete test; quit(); });
  12986. };
  12987. test->host = std::make_unique<lynx::PluginHost> (false);
  12988. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  12989. test->step ("exe=" + juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
  12990. for (const auto& type : test->host->getKnownPlugins().getTypes())
  12991. {
  12992. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  12993. || (only.isNotEmpty() && type.name != only))
  12994. continue;
  12995. juce::String error;
  12996. test->plugin = lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error);
  12997. test->step ("plugin=" + type.name + (test->plugin == nullptr ? " error=" + error : juce::String()));
  12998. break;
  12999. }
  13000. if (test->plugin == nullptr)
  13001. {
  13002. test->step ("result=FAILED");
  13003. test->done (false);
  13004. return;
  13005. }
  13006. lynx::preparePlugin (*test->plugin, 48000.0, 512);
  13007. test->step ("step=create_editor");
  13008. test->window = std::make_unique<juce::DocumentWindow> (test->plugin->getName(), juce::Colours::black, juce::DocumentWindow::closeButton);
  13009. test->window->setUsingNativeTitleBar (true);
  13010. if (auto* editor = test->plugin->createEditorIfNeeded())
  13011. test->window->setContentOwned (editor, true);
  13012. else
  13013. test->step ("no_editor");
  13014. test->step ("step=show");
  13015. test->window->centreWithSize (test->window->getWidth(), test->window->getHeight());
  13016. test->window->setVisible (true);
  13017. test->step ("step=shown");
  13018. test->startTimer (4000);
  13019. }
  13020. void runFitTest (const juce::String& reportPath, int percent)
  13021. {
  13022. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13023. struct FitTest final : juce::Timer
  13024. {
  13025. juce::String path, report;
  13026. bool ok = true;
  13027. int step = 0, percent = 150;
  13028. std::unique_ptr<juce::DocumentWindow> tall, big;
  13029. std::function<void()> done;
  13030. // `whole`: the window must fit entirely (a resizable one); else its title bar and close button must be on the screen
  13031. void check (const juce::String& what, juce::Component& w, bool whole)
  13032. {
  13033. juce::BorderSize<int> frame;
  13034. if (auto* peer = w.getPeer())
  13035. if (const auto f = peer->getFrameSizeIfPresent())
  13036. frame = *f;
  13037. auto outer = frame.addedTo (w.getBounds());
  13038. const auto* display = juce::Desktop::getInstance().getDisplays().getDisplayForRect (outer);
  13039. const auto area = display != nullptr ? display->userArea : outer;
  13040. #if JUCE_LINUX
  13041. // round 164: a compositor that draws the frame itself (WSLg's Weston) reports its invisible shadow in
  13042. // the frame (59 px on top, 38 around at 100%): only what is visible is checked, give or take 4 px
  13043. const auto shadow = frame.getLeft() >= 16 ? frame.getLeft() : 0;
  13044. outer = outer.reduced (shadow);
  13045. const auto slack = shadow > 0 ? 4 : 0;
  13046. #else
  13047. const auto slack = 0;
  13048. #endif
  13049. const auto passed = outer.getY() >= area.getY() - slack && outer.getRight() <= area.getRight() + slack && outer.getX() >= area.getX() - slack
  13050. && (! whole || outer.getBottom() <= area.getBottom() + 1 + slack);
  13051. report << (passed ? "ok " : "FAIL ") << what << " window=" << outer.toString() << " (frame " << frame.getTop() << ","
  13052. << frame.getLeft() << ") screen=" << area.toString() << "\n";
  13053. ok = ok && passed;
  13054. }
  13055. void start()
  13056. {
  13057. report << "scale=" << percent << "%\n";
  13058. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  13059. // a tool window taller than the screen, centred (its title bar would be above the screen)
  13060. tall = std::make_unique<juce::DocumentWindow> ("LYNX fit test - tall", lynx::theme::colour::bg2, juce::DocumentWindow::closeButton);
  13061. tall->setUsingNativeTitleBar (true);
  13062. auto* content = new juce::Component();
  13063. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  13064. content->setSize (500, area.getHeight() + 200);
  13065. tall->setContentOwned (content, true);
  13066. tall->setCentrePosition (area.getCentre());
  13067. tall->setVisible (true);
  13068. lynx::keepAboveMainWindow (*tall);
  13069. // LYNX_FITTEST_MS: how long each window stays (default 700 ms; longer to take screenshots of them)
  13070. startTimer (juce::jlimit (300, 60000, juce::SystemStats::getEnvironmentVariable ("LYNX_FITTEST_MS", "700").getIntValue()));
  13071. }
  13072. void timerCallback() override
  13073. {
  13074. ++step;
  13075. if (step == 1)
  13076. {
  13077. check ("tall tool window: title bar and close button on the screen", *tall, false);
  13078. tall.reset();
  13079. // round 164: a fixed-size LYNX tool window whose content is taller than the screen: it scrolls
  13080. auto content = std::make_unique<juce::Component>();
  13081. const auto screen = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  13082. content->setSize (520, screen.getHeight() + 300);
  13083. lynx::openToolWindow (std::move (content), "LYNX fit test - fixed size", "fittest-fixed");
  13084. return;
  13085. }
  13086. if (step == 2)
  13087. {
  13088. if (auto* w = lynx::findToolWindow ("fittest-fixed"))
  13089. {
  13090. check ("fixed-size tool window taller than the screen: fits (its content scrolls)", *w, true);
  13091. const auto scrolls = w->getContentComponent() != nullptr && w->getContentComponent()->getNumChildComponents() > 0
  13092. && dynamic_cast<juce::Viewport*> (w->getContentComponent()->getChildComponent (0)) != nullptr;
  13093. report << (scrolls ? "ok " : "FAIL ") << "its content is in a scrolling viewport\n";
  13094. ok = ok && scrolls;
  13095. }
  13096. else
  13097. {
  13098. report << "FAIL fixed-size tool window not found\n";
  13099. ok = false;
  13100. }
  13101. lynx::closeAllToolWindows();
  13102. // a resizable window that fits at 100%, then the zoom goes up (the main window's case)
  13103. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  13104. big = std::make_unique<juce::DocumentWindow> ("LYNX fit test - zoom", lynx::theme::colour::bg2, juce::DocumentWindow::allButtons);
  13105. big->setUsingNativeTitleBar (true);
  13106. big->setResizable (true, false);
  13107. big->setResizeLimits (400, 300, 10000, 10000);
  13108. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  13109. big->setBounds (area.getX() + 40, area.getY() + 60, area.getWidth() * 9 / 10 - 40, area.getHeight() * 9 / 10 - 60);
  13110. big->setVisible (true);
  13111. return;
  13112. }
  13113. if (step == 3)
  13114. {
  13115. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  13116. juce::Timer::callAfterDelay (200, [] { lynx::fitAllWindowsOnScreen(); });
  13117. return;
  13118. }
  13119. if (step == 4)
  13120. {
  13121. check ("resizable window after the zoom change: fits the screen", *big, true);
  13122. big.reset();
  13123. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  13124. juce::File (path).replaceWithText (report);
  13125. stopTimer();
  13126. if (done)
  13127. done();
  13128. }
  13129. }
  13130. };
  13131. static std::unique_ptr<FitTest> test;
  13132. test = std::make_unique<FitTest>();
  13133. test->path = reportPath;
  13134. test->percent = juce::jlimit (50, 300, percent);
  13135. test->done = [this] { juce::MessageManager::callAsync ([this] { test.reset(); quit(); }); };
  13136. test->start();
  13137. }
  13138. void runFocusTest (const juce::String& reportPath)
  13139. {
  13140. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13141. struct FocusTest final : juce::Timer
  13142. {
  13143. juce::String reportPath, report;
  13144. bool ok = true;
  13145. int stepIndex = 0;
  13146. std::unique_ptr<lynx::AudioEngine> engine;
  13147. lynx::MainComponent* ui = nullptr;
  13148. std::unique_ptr<juce::DocumentWindow> main;
  13149. std::function<void()> done;
  13150. void line (const juce::String& text)
  13151. {
  13152. report << text << "\n";
  13153. juce::File (reportPath).replaceWithText (report);
  13154. }
  13155. void check (const juce::String& what, bool passed)
  13156. {
  13157. line ((passed ? "ok " : "FAIL ") + what);
  13158. ok = ok && passed;
  13159. }
  13160. juce::ComponentPeer* mainPeer() const { return main != nullptr ? main->getPeer() : nullptr; }
  13161. bool focusInMain() const
  13162. {
  13163. auto* f = juce::Component::getCurrentlyFocusedComponent();
  13164. return f != nullptr && main->isParentOf (f);
  13165. }
  13166. // a click (press and release) at the middle of the panel's content, through the native window it is in
  13167. static void click (juce::Component& frame, bool right)
  13168. {
  13169. auto* peer = frame.getPeer();
  13170. if (peer == nullptr)
  13171. return;
  13172. const auto at = peer->getComponent().getLocalPoint (&frame, frame.getLocalBounds().getCentre().toFloat());
  13173. const auto button = right ? juce::ModifierKeys::rightButtonModifier : juce::ModifierKeys::leftButtonModifier;
  13174. const auto now = juce::Time::currentTimeMillis();
  13175. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (button), 1.0f, 0.0f, now);
  13176. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  13177. }
  13178. bool space()
  13179. {
  13180. auto* peer = mainPeer(); // (the system sends the key to the window with the focus: the main one)
  13181. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  13182. }
  13183. juce::TextEditor* firstField (juce::Component& c)
  13184. {
  13185. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && t->getWantsKeyboardFocus())
  13186. return t;
  13187. for (auto* child : c.getChildren())
  13188. if (auto* t = firstField (*child))
  13189. return t;
  13190. return nullptr;
  13191. }
  13192. // the user tabs away and comes back with a click in `panel`
  13193. void backWithClickIn (lynx::workspace::Panel panel, bool right)
  13194. {
  13195. auto& frame = ui->workspaceForTest().getFrame (panel);
  13196. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  13197. auto* peer = mainPeer();
  13198. line (name + ": native child window=" + juce::String ((int) lynx::nativechild::isAttached (frame)));
  13199. check (name + ": the main window has the keys before", ui->hasKeyboardFocus (true));
  13200. peer->handleFocusLoss(); // (another app is in front: the main window lost the system focus)
  13201. check (name + ": nothing in LYNX has the keys while it is in the background", ! focusInMain());
  13202. // the cause: JUCE answers the system's "activate?" from the panel's own component, which takes no focus on a click
  13203. line (name + ": JUCE's answer alone would activate the window=" + juce::String ((int) frame.getMouseClickGrabsKeyboardFocus()));
  13204. const auto activates = lynx::nativechild::clickActivatesWindow (frame, false);
  13205. check (name + ": a click in it activates the inactive main window", activates);
  13206. #if JUCE_WINDOWS
  13207. if (lynx::nativechild::isAttached (frame))
  13208. check (name + ": its native window answers WM_MOUSEACTIVATE with MA_ACTIVATE",
  13209. lynx::nativechild::mouseActivateAnswerForTest (frame, true) == 1 /* MA_ACTIVATE */);
  13210. #endif
  13211. if (activates)
  13212. peer->handleFocusGain(); // (the system activates the main window and gives it the focus)
  13213. click (frame, right);
  13214. }
  13215. void spacePlays (lynx::workspace::Panel panel, bool right)
  13216. {
  13217. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  13218. check (name + ": the main window has the keys after the click", ui->hasKeyboardFocus (true));
  13219. auto& transport = engine->getTransport();
  13220. if (transport.playing.load())
  13221. engine->stop();
  13222. const auto used = space();
  13223. check (name + ": Space starts playback", used && transport.playing.load());
  13224. engine->stop();
  13225. }
  13226. void timerCallback() override
  13227. {
  13228. using lynx::workspace::Panel;
  13229. auto& ws = ui->workspaceForTest();
  13230. switch (stepIndex++)
  13231. {
  13232. case 0:
  13233. line ("docking=" + juce::String ((int) lynx::nativechild::dockingEnabled()));
  13234. ws.show (Panel::playlist);
  13235. ws.show (Panel::pianoRoll);
  13236. ui->grabKeyboardFocus();
  13237. break;
  13238. case 1: backWithClickIn (Panel::playlist, false); break;
  13239. case 2: spacePlays (Panel::playlist, false); ui->grabKeyboardFocus(); break;
  13240. case 3: backWithClickIn (Panel::pianoRoll, false); break;
  13241. case 4: spacePlays (Panel::pianoRoll, false); ui->grabKeyboardFocus(); break;
  13242. case 5: backWithClickIn (Panel::playlist, true); break;
  13243. case 6:
  13244. juce::PopupMenu::dismissAllActiveMenus(); // (the right click's menu)
  13245. spacePlays (Panel::playlist, true);
  13246. break;
  13247. case 7:
  13248. {
  13249. // a text field (the Browser's search box) keeps the keys through a switch to another app and back:
  13250. // nothing in LYNX takes them from it (no periodic grab); inside the active window the click's
  13251. // activation answer is unchanged, and a click in the Playlist ends the typing as before (issue #9,
  13252. // as FL ends typing in its search field)
  13253. auto* field = firstField (*ui);
  13254. line ("text field found=" + juce::String ((int) (field != nullptr)));
  13255. if (field != nullptr)
  13256. {
  13257. auto& frame = ws.getFrame (Panel::playlist);
  13258. field->grabKeyboardFocus();
  13259. check ("the text field has the keys", field->hasKeyboardFocus (false));
  13260. mainPeer()->handleFocusLoss();
  13261. mainPeer()->handleFocusGain(); // (back with Alt+Tab, or a click that activates the window)
  13262. check ("the text field gets the keys back with the window", field->hasKeyboardFocus (false));
  13263. check ("active window: a click in a panel does not activate it again", ! lynx::nativechild::clickActivatesWindow (frame, true));
  13264. click (frame, false);
  13265. check ("a click in the Playlist ends the typing: the main window has the keys", ui->hasKeyboardFocus (true) && ! field->hasKeyboardFocus (false));
  13266. }
  13267. line (ok ? "result=OK" : "result=FAILED");
  13268. stopTimer();
  13269. done();
  13270. break;
  13271. }
  13272. default:
  13273. break;
  13274. }
  13275. }
  13276. };
  13277. auto* test = new FocusTest();
  13278. test->reportPath = reportPath;
  13279. startFocusTestWindow (*test);
  13280. test->startTimer (600);
  13281. }
  13282. // --simplekeytest (round 190fc, 0.1.27 RC H2): in the Simple layout Space often did nothing after a click in the
  13283. // window (the dock, a track header, the grid, the Lyrics button) or after a demo opened from Welcome › Start from. The
  13284. // main window in the Simple layout; each step clicks as the system would (through the native window under the point)
  13285. // and presses Space where the system sends it (the native window of the component with the focus): playback must
  13286. // start, except while a text field the user clicked into has the keys (it types). Shows a window (Windows: GUI lock).
  13287. void runSimpleKeyTest (const juce::String& reportPath)
  13288. {
  13289. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13290. struct KeyTest final : juce::Timer
  13291. {
  13292. juce::String reportPath, report;
  13293. bool ok = true;
  13294. int stepIndex = 0, instrumentTrack = 0;
  13295. std::unique_ptr<lynx::AudioEngine> engine;
  13296. lynx::MainComponent* ui = nullptr;
  13297. std::unique_ptr<juce::DocumentWindow> main;
  13298. std::function<void()> done;
  13299. void line (const juce::String& text)
  13300. {
  13301. report << text << "\n";
  13302. juce::File (reportPath).replaceWithText (report);
  13303. }
  13304. void check (const juce::String& what, bool passed)
  13305. {
  13306. line ((passed ? "ok " : "FAIL ") + what);
  13307. ok = ok && passed;
  13308. }
  13309. static juce::String describe (juce::Component* c)
  13310. {
  13311. if (c == nullptr)
  13312. return "nothing";
  13313. juce::String path;
  13314. for (auto* p = c; p != nullptr && path.length() < 160; p = p->getParentComponent())
  13315. {
  13316. auto name = p->getComponentID().isNotEmpty() ? p->getComponentID() : p->getName();
  13317. if (name.isEmpty())
  13318. name = juce::String (typeid (*p).name()).fromLastOccurrenceOf ("::", false, false).substring (0, 28);
  13319. path << (path.isEmpty() ? "" : " < ") << name;
  13320. }
  13321. return path;
  13322. }
  13323. // the first showing component with this ID in the main window or a native child window of it
  13324. juce::Component* find (const juce::String& id)
  13325. {
  13326. std::function<juce::Component* (juce::Component&)> in = [&] (juce::Component& root) -> juce::Component* {
  13327. if (root.getComponentID() == id && root.isShowing())
  13328. return &root;
  13329. for (auto* c : root.getChildren())
  13330. if (auto* f = in (*c))
  13331. return f;
  13332. return nullptr;
  13333. };
  13334. if (auto* f = in (*main))
  13335. return f;
  13336. if (auto* peer = main->getPeer())
  13337. for (auto* attached : lynx::nativechild::attachedChildren (peer->getNativeHandle()))
  13338. if (auto* f = in (*attached))
  13339. return f;
  13340. return nullptr;
  13341. }
  13342. // a click (press and release) at `local` in `c`, through the native window it is in
  13343. juce::String lastHit;
  13344. void click (juce::Component& c, juce::Point<int> local)
  13345. {
  13346. auto* peer = c.getPeer();
  13347. if (peer == nullptr)
  13348. return;
  13349. const auto at = peer->getComponent().getLocalPoint (&c, local.toFloat());
  13350. lastHit = describe (peer->getComponent().getComponentAt (at.roundToInt()));
  13351. line (" click at " + local.toString() + " in " + describe (&c).upToFirstOccurrenceOf (" < ", false, false) + " -> " + lastHit);
  13352. const auto now = juce::Time::currentTimeMillis();
  13353. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, now);
  13354. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  13355. }
  13356. void click (juce::Component& c) { click (c, c.getLocalBounds().getCentre()); }
  13357. // Space where the system sends it: the native window of the focused component (else the main one)
  13358. bool space()
  13359. {
  13360. // Windows: posted to the window with the system's focus, as a real key goes (the system's own routing)
  13361. if (lynx::nativechild::pressSpaceForTest (main->getWindowHandle()))
  13362. return true;
  13363. auto* focused = juce::Component::getCurrentlyFocusedComponent();
  13364. auto* peer = focused != nullptr && focused->getPeer() != nullptr ? focused->getPeer() : main->getPeer();
  13365. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  13366. }
  13367. void spacePlays (const juce::String& after)
  13368. {
  13369. line (" keys at: " + describe (juce::Component::getCurrentlyFocusedComponent()));
  13370. auto& transport = engine->getTransport();
  13371. if (transport.playing.load())
  13372. engine->stop();
  13373. space();
  13374. check ("Space plays after " + after, transport.playing.load());
  13375. engine->stop();
  13376. }
  13377. void timerCallback() override
  13378. {
  13379. auto* simple = ui->getSimpleWorkflowForSnapshot();
  13380. auto& playlist = ui->getPlaylistForSnapshot();
  13381. switch (stepIndex++)
  13382. {
  13383. case 0:
  13384. ui->setLayoutStyle (lynx::layoutstyle::Style::simple);
  13385. ui->grabKeyboardFocus();
  13386. break;
  13387. case 1:
  13388. check ("the Simple workflow is up", simple != nullptr);
  13389. if (simple == nullptr)
  13390. return finish();
  13391. spacePlays ("the layout came up");
  13392. simple->showWelcome();
  13393. break;
  13394. case 2:
  13395. if (auto* demo = find ("tour.welcome.demo"))
  13396. click (*demo); // Welcome › Open a demo song: the Start from list
  13397. else
  13398. check ("Welcome > Open a demo song found", false);
  13399. break;
  13400. case 3:
  13401. {
  13402. if (! simple->isStartFromShowing()) // (X11: a child window just mapped may miss the first click)
  13403. if (auto* demo = find ("tour.welcome.demo"))
  13404. {
  13405. line (" the first click was not taken: once more");
  13406. click (*demo);
  13407. }
  13408. check ("Start from is up", simple->isStartFromShowing());
  13409. if (auto* start = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot()))
  13410. check ("a demo song opens from it", start->openForSnapshot (1));
  13411. break;
  13412. }
  13413. case 4:
  13414. check ("Start from closed with the demo open", ! simple->isStartFromShowing() && ! engine->getSong().playlist.empty());
  13415. spacePlays ("a demo opened from Welcome > Start from");
  13416. instrumentTrack = [] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  13417. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  13418. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  13419. return t;
  13420. return 0;
  13421. } (engine->getSong());
  13422. line ("instrument track: " + juce::String (instrumentTrack));
  13423. playlist.selectTrack (instrumentTrack);
  13424. simple->trackSelected (instrumentTrack);
  13425. break;
  13426. case 5:
  13427. if (auto* dock = simple->dockForSnapshot(); dock != nullptr && dock->isShowing())
  13428. {
  13429. click (*dock, { dock->getWidth() - 6, dock->getHeight() - 6 }); // (its empty corner)
  13430. spacePlays ("a click in the dock");
  13431. }
  13432. else
  13433. check ("the dock shows", false);
  13434. break;
  13435. case 6:
  13436. if (auto* tab = find ("simple.dock.keyboard"))
  13437. {
  13438. click (*tab);
  13439. spacePlays ("a click on a dock tab (Keyboard)");
  13440. }
  13441. if (auto* tab = find ("simple.dock.editor"))
  13442. {
  13443. click (*tab);
  13444. spacePlays ("a click on a dock tab (Editor)");
  13445. }
  13446. break;
  13447. case 7:
  13448. if (auto* lyrics = find ("simple.lyrics"))
  13449. {
  13450. click (*lyrics);
  13451. spacePlays ("a click on the Lyrics button");
  13452. }
  13453. else
  13454. check ("the Lyrics button found", false);
  13455. break;
  13456. case 8:
  13457. {
  13458. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  13459. click (playlist, { juce::jmax (4, playlist.headerWidth / 2), lane.getCentreY() });
  13460. spacePlays ("a click on a track header");
  13461. click (playlist, lane.getCentre() + juce::Point<int> (40, 0));
  13462. spacePlays ("a click in the Playlist grid");
  13463. break;
  13464. }
  13465. case 9:
  13466. {
  13467. // a text field the user clicks into keeps its typing keys; a click outside gives Space back
  13468. // a dock knob clicked keeps the arrow keys, and Space still plays from it
  13469. for (auto tab : { lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::instrument })
  13470. {
  13471. juce::Component* knob = nullptr;
  13472. std::function<void (juce::Component&)> seek = [&] (juce::Component& c) {
  13473. if (knob == nullptr && c.isShowing() && (bool) c.getProperties().getWithDefault ("lynxClickKeepsKeys", false))
  13474. knob = &c;
  13475. for (auto* child : c.getChildren())
  13476. seek (*child);
  13477. };
  13478. if (auto* dock = simple->dockForSnapshot())
  13479. {
  13480. dock->setTab (tab);
  13481. seek (*dock);
  13482. }
  13483. if (knob != nullptr)
  13484. {
  13485. click (*knob);
  13486. spacePlays ("a click on a dock knob");
  13487. break;
  13488. }
  13489. }
  13490. if (auto* dock = simple->dockForSnapshot())
  13491. dock->setTab (lynx::SimpleDock::Tab::instrument);
  13492. juce::TextEditor* field = nullptr;
  13493. std::function<void (juce::Component&)> look = [&] (juce::Component& c) {
  13494. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && field == nullptr)
  13495. field = t;
  13496. for (auto* child : c.getChildren())
  13497. look (*child);
  13498. };
  13499. if (auto* dock = simple->dockForSnapshot())
  13500. look (*dock);
  13501. line ("text field in the dock found=" + juce::String ((int) (field != nullptr)));
  13502. if (field != nullptr)
  13503. {
  13504. click (*field);
  13505. const auto before = field->getText();
  13506. space();
  13507. check ("Space types into the text field the user clicked", field->getText() != before && ! engine->getTransport().playing.load());
  13508. engine->stop();
  13509. field->clear();
  13510. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  13511. click (playlist, lane.getCentre() + juce::Point<int> (60, 0));
  13512. spacePlays ("a click in the grid after typing");
  13513. }
  13514. // H1: the first-song tour's card in front of the native panels, taking no keys (started on the demo
  13515. // as it is: Help's question about a new project is a dialog)
  13516. if (auto* tour = simple->tourForSnapshot())
  13517. tour->start();
  13518. break;
  13519. }
  13520. case 10:
  13521. {
  13522. auto* tour = simple->tourForSnapshot();
  13523. auto* card = tour != nullptr ? tour->cardForSnapshot() : nullptr;
  13524. check ("the tour runs", tour != nullptr && tour->isRunning() && card != nullptr && card->isVisible());
  13525. if (card == nullptr)
  13526. return finish();
  13527. auto& frame = ui->workspaceForTest().getFrame (lynx::workspace::Panel::playlist);
  13528. const auto native = lynx::nativechild::dockingEnabled() && lynx::nativechild::isAttached (frame);
  13529. line ("playlist native child window=" + juce::String ((int) native) + ", tour card native child window="
  13530. + juce::String ((int) lynx::nativechild::isAttached (*card)));
  13531. if (native)
  13532. {
  13533. check ("the tour card is a native child window of the main window (not under the panels)", lynx::nativechild::isAttached (*card));
  13534. #if JUCE_WINDOWS
  13535. check ("the tour card is above the Playlist's native window", lynx::nativechild::isAbove (card->getWindowHandle(), frame.getWindowHandle()));
  13536. juce::Component* layer = nullptr;
  13537. for (auto* c : lynx::nativechild::attachedChildren (main->getPeer()->getNativeHandle()))
  13538. if (c != nullptr && c->getComponentID() == "tour.layer")
  13539. layer = c;
  13540. check ("the ring's layer is above the Playlist too", layer != nullptr && lynx::nativechild::isAbove (layer->getWindowHandle(), frame.getWindowHandle()));
  13541. check ("the ring's layer lets clicks through to the Playlist",
  13542. layer != nullptr && lynx::nativechild::windowAt (*layer, layer->getLocalBounds().getCentre()) != layer->getWindowHandle());
  13543. #endif
  13544. }
  13545. check ("the tour card took no keys", ! card->hasKeyboardFocus (true));
  13546. spacePlays ("the tour came up");
  13547. if (auto* next = card->findChildWithID ("tour.next"); next != nullptr && next->isShowing())
  13548. {
  13549. click (*next);
  13550. check ("a click on the card took no keys", ! card->hasKeyboardFocus (true));
  13551. spacePlays ("a click on the tour card");
  13552. }
  13553. finish();
  13554. break;
  13555. }
  13556. default:
  13557. break;
  13558. }
  13559. }
  13560. void finish()
  13561. {
  13562. line (ok ? "result=OK" : "result=FAILED");
  13563. stopTimer();
  13564. done();
  13565. }
  13566. };
  13567. auto* test = new KeyTest();
  13568. test->reportPath = reportPath;
  13569. startFocusTestWindow (*test);
  13570. // Windows: kept above other apps' windows for its few seconds (JUCE takes a button-down only where the system finds
  13571. // its window under the point, and the test clicks through LYNX's own peers, not the system's input)
  13572. #if JUCE_WINDOWS
  13573. test->main->setAlwaysOnTop (true); // (Linux: JUCE makes the X11 window again for it; the private X server has no other windows)
  13574. #endif
  13575. test->startTimer (700);
  13576. }
  13577. template <typename Test>
  13578. void startFocusTestWindow (Test& t)
  13579. {
  13580. auto* test = &t;
  13581. test->engine = std::make_unique<lynx::AudioEngine> (false);
  13582. test->main = std::make_unique<juce::DocumentWindow> ("LYNX focus test", lynx::theme::window, juce::DocumentWindow::allButtons);
  13583. test->main->setUsingNativeTitleBar (true);
  13584. test->ui = new lynx::MainComponent (*test->engine, false);
  13585. test->main->setContentOwned (test->ui, true);
  13586. test->main->setResizable (true, true);
  13587. test->main->centreWithSize (1280, 760);
  13588. test->main->setVisible (true);
  13589. lynx::setMainWindowForOwnership (test->main.get());
  13590. test->done = [this, test] {
  13591. setApplicationReturnValue (test->ok ? 0 : 1);
  13592. juce::MessageManager::callAsync ([this, test] {
  13593. lynx::setMainWindowForOwnership (nullptr);
  13594. test->main = nullptr;
  13595. delete test;
  13596. quit();
  13597. });
  13598. };
  13599. }
  13600. void runWindowTest (const juce::String& reportPath)
  13601. {
  13602. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13603. struct WindowTest final : juce::Timer
  13604. {
  13605. juce::String reportPath, report;
  13606. bool ok = true;
  13607. int stepIndex = 0;
  13608. std::unique_ptr<lynx::AudioEngine> engine;
  13609. lynx::MainComponent* ui = nullptr;
  13610. std::unique_ptr<juce::DocumentWindow> main, pluginLike;
  13611. juce::TextEditor* pluginField = nullptr;
  13612. std::unique_ptr<juce::AlertWindow> nameDialog;
  13613. std::function<void()> done;
  13614. void line (const juce::String& text)
  13615. {
  13616. report << text << "\n";
  13617. juce::File (reportPath).replaceWithText (report);
  13618. }
  13619. void check (const juce::String& what, bool passed)
  13620. {
  13621. line ((passed ? "ok " : "FAIL ") + what);
  13622. ok = ok && passed;
  13623. }
  13624. bool isAbove (juce::Component* w) { return w != nullptr && lynx::isAboveMainWindow (*w); }
  13625. bool focusIn (juce::Component* w)
  13626. {
  13627. auto* f = juce::Component::getCurrentlyFocusedComponent();
  13628. return w != nullptr && f != nullptr && (f == w || w->isParentOf (f));
  13629. }
  13630. void timerCallback() override
  13631. {
  13632. switch (stepIndex++)
  13633. {
  13634. case 0:
  13635. line ("foreground=" + juce::String (juce::Process::isForegroundProcess() ? 1 : 0));
  13636. ui->openQuickAddForTest();
  13637. break;
  13638. case 1:
  13639. {
  13640. auto* w = lynx::findToolWindow ("quickadd");
  13641. check ("quick-add palette open", w != nullptr);
  13642. check ("quick-add palette active", w != nullptr && w->isActiveWindow());
  13643. check ("quick-add palette owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  13644. check ("quick-add palette above the main window", isAbove (w));
  13645. auto* f = juce::Component::getCurrentlyFocusedComponent();
  13646. check ("quick-add search box has the keyboard focus", focusIn (w) && dynamic_cast<juce::TextEditor*> (f) != nullptr && f->hasKeyboardFocus (false) && w->isActiveWindow());
  13647. lynx::closeAllToolWindows();
  13648. lynx::openAudioEditor (*engine);
  13649. break;
  13650. }
  13651. case 2:
  13652. {
  13653. auto* w = lynx::findToolWindow ("audioeditor");
  13654. check ("audio editor open", w != nullptr);
  13655. check ("audio editor active", w != nullptr && w->isActiveWindow());
  13656. check ("audio editor owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  13657. check ("audio editor above the main window", isAbove (w));
  13658. lynx::forceForegroundForTest (*main); // the user clicks the main window
  13659. break;
  13660. }
  13661. case 3:
  13662. {
  13663. auto* w = lynx::findToolWindow ("audioeditor");
  13664. check ("audio editor stays above the main window after clicking it", isAbove (w));
  13665. lynx::closeAllToolWindows();
  13666. // a plugin editor's window: its own controls keep the keyboard focus
  13667. pluginLike = std::make_unique<juce::DocumentWindow> ("Plugin", juce::Colours::black, juce::DocumentWindow::closeButton);
  13668. pluginLike->setUsingNativeTitleBar (true);
  13669. auto* field = new juce::TextEditor();
  13670. field->setSize (300, 120);
  13671. pluginLike->setContentOwned (field, true);
  13672. pluginLike->centreWithSize (300, 120);
  13673. pluginLike->setVisible (true);
  13674. lynx::keepAboveMainWindow (*pluginLike);
  13675. pluginLike->toFront (true);
  13676. field->grabKeyboardFocus();
  13677. pluginField = field;
  13678. break;
  13679. }
  13680. case 4:
  13681. check ("plugin window active", pluginLike->isActiveWindow());
  13682. check ("plugin window keeps the keyboard focus", pluginField->hasKeyboardFocus (false) && pluginLike->isActiveWindow());
  13683. check ("plugin window above the main window", isAbove (pluginLike.get()));
  13684. pluginLike = nullptr;
  13685. lynx::forceForegroundForTest (*main);
  13686. juce::Component::unfocusAllComponents();
  13687. break;
  13688. case 5:
  13689. check ("main window takes the keyboard focus back when it is active", ui->hasKeyboardFocus (true));
  13690. // round 165q: a name dialog (F4's next empty pattern, Rename and color...) opens ready to type
  13691. nameDialog = lynx::makeNameAndColourDialog ("Rename pattern", "Pattern 2", 0xff808080u);
  13692. nameDialog->enterModalState (true, nullptr, false);
  13693. lynx::keepAboveMainWindow (*nameDialog);
  13694. break;
  13695. case 6:
  13696. {
  13697. auto* f = juce::Component::getCurrentlyFocusedComponent();
  13698. auto* field = dynamic_cast<juce::TextEditor*> (f);
  13699. check ("name dialog: its text field has the keyboard focus", field != nullptr && focusIn (nameDialog.get()));
  13700. if (field != nullptr)
  13701. field->keyPressed (juce::KeyPress ('x', {}, 'x'));
  13702. check ("name dialog: typing replaces the name", nameDialog->getTextEditorContents ("name") == "x");
  13703. nameDialog->exitModalState (0);
  13704. nameDialog = nullptr;
  13705. line (ok ? "result=OK" : "result=FAILED");
  13706. stopTimer();
  13707. done();
  13708. break;
  13709. }
  13710. default:
  13711. break;
  13712. }
  13713. }
  13714. };
  13715. auto* test = new WindowTest();
  13716. test->reportPath = reportPath;
  13717. test->engine = std::make_unique<lynx::AudioEngine> (false);
  13718. test->main = std::make_unique<juce::DocumentWindow> ("LYNX window test", lynx::theme::window, juce::DocumentWindow::allButtons);
  13719. test->main->setUsingNativeTitleBar (true);
  13720. test->ui = new lynx::MainComponent (*test->engine, false);
  13721. test->main->setContentOwned (test->ui, true);
  13722. test->main->setResizable (true, true);
  13723. test->main->centreWithSize (1280, 760);
  13724. test->main->setVisible (true);
  13725. lynx::setMainWindowForOwnership (test->main.get());
  13726. lynx::forceForegroundForTest (*test->main);
  13727. test->main->toFront (true);
  13728. test->done = [this, test] {
  13729. setApplicationReturnValue (test->ok ? 0 : 1);
  13730. juce::MessageManager::callAsync ([this, test] {
  13731. lynx::closeAllToolWindows();
  13732. lynx::setMainWindowForOwnership (nullptr);
  13733. test->main = nullptr;
  13734. delete test;
  13735. quit();
  13736. });
  13737. };
  13738. test->startTimer (1500);
  13739. }
  13740. // --minimizeclicktest (issue #188): see the option. The main window holds a component that counts its mouse-downs.
  13741. void runMinimizeClickTest (const juce::String& reportPath)
  13742. {
  13743. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13744. struct ClickPad final : juce::Component
  13745. {
  13746. int downs = 0;
  13747. void paint (juce::Graphics& g) override { g.fillAll (juce::Colours::darkslategrey); }
  13748. void mouseDown (const juce::MouseEvent&) override { ++downs; }
  13749. };
  13750. struct MinimizeTest final : juce::Timer
  13751. {
  13752. juce::String reportPath, report;
  13753. bool ok = true;
  13754. int stepIndex = 0, waits = 0;
  13755. std::unique_ptr<juce::DocumentWindow> main;
  13756. ClickPad* pad = nullptr;
  13757. juce::DocumentWindow* tool = nullptr;
  13758. juce::Point<int> inside, outside; // screen points: where the tool window is, and beside it
  13759. std::function<void()> done;
  13760. void line (const juce::String& text)
  13761. {
  13762. report << text << "\n";
  13763. juce::File (reportPath).replaceWithText (report);
  13764. }
  13765. void check (const juce::String& what, bool passed)
  13766. {
  13767. line ((passed ? "ok " : "FAIL ") + what);
  13768. ok = ok && passed;
  13769. }
  13770. // a left click at a screen point through the main window's peer: the path an X ButtonPress takes
  13771. bool clickReachesPad (juce::Point<int> screen)
  13772. {
  13773. auto* peer = main->getPeer();
  13774. if (peer == nullptr)
  13775. return false;
  13776. const auto before = pad->downs;
  13777. const auto local = peer->globalToLocal (screen.toFloat());
  13778. const auto now = juce::Time::currentTimeMillis();
  13779. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier),
  13780. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation, now);
  13781. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, juce::ModifierKeys(),
  13782. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation, now + 1);
  13783. return pad->downs == before + 1;
  13784. }
  13785. bool toolMinimised() const { return tool != nullptr && tool->getPeer() != nullptr && tool->getPeer()->isMinimised(); }
  13786. void timerCallback() override
  13787. {
  13788. switch (stepIndex)
  13789. {
  13790. case 0:
  13791. {
  13792. auto content = std::make_unique<juce::Component>();
  13793. content->setSize (420, 300);
  13794. tool = lynx::openToolWindow (std::move (content), "Tap tempo (test)", "minimizetest");
  13795. ++stepIndex;
  13796. return;
  13797. }
  13798. case 1:
  13799. {
  13800. check ("tool window open", tool != nullptr && tool->isShowing());
  13801. if (tool == nullptr)
  13802. break;
  13803. const auto r = tool->getScreenBounds();
  13804. inside = r.getCentre();
  13805. outside = { main->getScreenBounds().getX() + 40, main->getScreenBounds().getBottom() - 40 };
  13806. line ("main " + main->getScreenBounds().toString() + " tool " + r.toString());
  13807. lynx::matchWindowOrderToScreen();
  13808. check ("a click beside the tool window reaches the main window", clickReachesPad (outside));
  13809. check ("a click on the shown tool window does not reach the main window", ! clickReachesPad (inside));
  13810. tool->setMinimised (true);
  13811. ++stepIndex;
  13812. return;
  13813. }
  13814. case 2:
  13815. if (! toolMinimised() && ++waits < 20)
  13816. return;
  13817. check ("the window manager minimised the tool window", toolMinimised());
  13818. check ("the tool window stays visible for JUCE (as in the report)", tool->isVisible());
  13819. main->toFront (true); // a click on the main window: LYNX puts its secondary windows back above it in JUCE's list
  13820. lynx::matchWindowOrderToScreen();
  13821. ++stepIndex;
  13822. return;
  13823. case 3:
  13824. check ("a click where the minimised tool window was reaches the main window", clickReachesPad (inside));
  13825. check ("a click beside it still reaches the main window", clickReachesPad (outside));
  13826. tool->setMinimised (false);
  13827. waits = 0;
  13828. ++stepIndex;
  13829. return;
  13830. case 4:
  13831. if (toolMinimised() && ++waits < 20)
  13832. return;
  13833. tool->toFront (false);
  13834. lynx::matchWindowOrderToScreen();
  13835. ++stepIndex;
  13836. return;
  13837. case 5:
  13838. check ("the tool window is back", ! toolMinimised());
  13839. check ("a click on the restored tool window does not reach the main window", ! clickReachesPad (inside));
  13840. break;
  13841. default:
  13842. return;
  13843. }
  13844. line (ok ? "result=OK" : "result=FAILED");
  13845. stopTimer();
  13846. done();
  13847. }
  13848. };
  13849. auto* test = new MinimizeTest();
  13850. test->reportPath = reportPath;
  13851. test->main = std::make_unique<juce::DocumentWindow> ("LYNX minimise test", lynx::theme::window, juce::DocumentWindow::allButtons);
  13852. test->main->setUsingNativeTitleBar (true);
  13853. test->pad = new ClickPad();
  13854. test->pad->setSize (1200, 760);
  13855. test->main->setContentOwned (test->pad, true);
  13856. test->main->setTopLeftPosition (60, 60);
  13857. test->main->setVisible (true);
  13858. lynx::setMainWindowForOwnership (test->main.get());
  13859. test->main->toFront (true);
  13860. test->done = [this, test] {
  13861. setApplicationReturnValue (test->ok ? 0 : 1);
  13862. juce::MessageManager::callAsync ([this, test] {
  13863. lynx::closeAllToolWindows();
  13864. lynx::setMainWindowForOwnership (nullptr);
  13865. test->main = nullptr;
  13866. delete test;
  13867. quit();
  13868. });
  13869. };
  13870. test->startTimer (700);
  13871. }
  13872. // LYNX.exe --plugintest plugin.vst3 report.txt ["name"]: loads the plugin (or the one named in a shell), plays notes if it is an
  13873. // instrument (and runs audio through it if it is an effect) and measures the audio.
  13874. // Round 190fw: an instrument plugin file on channel 5 of an offline engine (Image-Line's "FL Studio VSTi", which
  13875. // runs FL Studio inside it). Without a project: four chords at 137 BPM, rendered (notes.wav), the plugin's state
  13876. // saved in <folder>/vstitest.lynx. With a project (one saved by LYNX with the plugin on a channel, e.g. after its
  13877. // window was used): that project. Then: the project loaded back from the file renders the same (reload.wav) and
  13878. // gives the same state back; the project's own notes removed, rendered at 100 and 150 BPM (tempo-100/150.wav), the
  13879. // onsets of what the plugin plays by itself must follow the host tempo; and the outputs the plugin offers.
  13880. void runVstiTest (const juce::String& pluginPath, const juce::String& folderPath, const juce::String& projectPath)
  13881. {
  13882. juce::String report;
  13883. auto ok = true;
  13884. const juce::File folder (folderPath);
  13885. folder.createDirectory();
  13886. const auto check = [&] (const juce::String& name, bool passed) {
  13887. report << name << "=" << (passed ? "OK" : "FAILED") << "\n";
  13888. ok = ok && passed;
  13889. };
  13890. struct Take
  13891. {
  13892. float peak = 0.0f;
  13893. std::vector<float> left;
  13894. };
  13895. // renders `song` with the plugin file known to the engine's host; `wav` (in the folder) gets the audio
  13896. const auto render = [&] (const lynx::Song& song, double seconds, const juce::String& wav, std::function<void (lynx::AudioEngine&)> after = {}) {
  13897. Take take;
  13898. lynx::AudioEngine engine (false);
  13899. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  13900. engine.setSong (song);
  13901. const auto file = folder.getChildFile (wav);
  13902. file.deleteFile();
  13903. std::unique_ptr<juce::AudioFormatWriter> writer;
  13904. if (auto stream = file.createOutputStream())
  13905. {
  13906. juce::WavAudioFormat format;
  13907. writer.reset (format.createWriterFor (stream.get(), 48000.0, 2, 24, {}, 0));
  13908. if (writer != nullptr)
  13909. stream.release();
  13910. }
  13911. lynx::AudioEngine::RenderOptions o;
  13912. o.seconds = seconds;
  13913. o.sampleRate = 48000.0;
  13914. o.output = writer.get();
  13915. o.capture = [&take] (const float* l, const float*, int n) { take.left.insert (take.left.end(), l, l + n); };
  13916. take.peak = engine.renderOffline (o);
  13917. writer.reset();
  13918. if (after)
  13919. after (engine);
  13920. return take;
  13921. };
  13922. // the channel that holds the plugin
  13923. const auto pluginChannel = [&] (const lynx::Song& song) {
  13924. for (std::size_t c = 0; c < song.channels.size(); ++c)
  13925. if (song.channels[c].instrument == lynx::InstrumentKind::plugin
  13926. && juce::String (song.channels[c].plugin.name).containsIgnoreCase (juce::File (pluginPath).getFileNameWithoutExtension().upToFirstOccurrenceOf (" (", false, false)))
  13927. return (int) c;
  13928. return -1;
  13929. };
  13930. lynx::Song song;
  13931. const auto saved = folder.getChildFile ("vstitest.lynx");
  13932. if (projectPath.isEmpty())
  13933. {
  13934. lynx::AudioEngine scanner (false);
  13935. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  13936. std::optional<juce::PluginDescription> type;
  13937. for (const auto& t : scanner.getPluginHost().getKnownPlugins().getTypes())
  13938. if (t.isInstrument && juce::File (t.fileOrIdentifier) == juce::File (pluginPath))
  13939. type = t;
  13940. check ("instrument_found", type.has_value());
  13941. if (! type)
  13942. {
  13943. juce::File (folder.getChildFile ("report.txt")).replaceWithText (report + "result=FAILED\n");
  13944. setApplicationReturnValue (1);
  13945. quit();
  13946. return;
  13947. }
  13948. report << "plugin=" << type->name << " (" << type->manufacturerName << ") outputs=" << type->numOutputChannels << "\n";
  13949. song = lynx::Song::makeDefault();
  13950. song.bpm = 137.0;
  13951. auto& c = song.channels[4];
  13952. c.instrument = lynx::InstrumentKind::plugin;
  13953. c.plugin = {};
  13954. c.plugin.id = type->createIdentifierString().toStdString();
  13955. c.plugin.name = type->name.toStdString();
  13956. c.name = type->name.toStdString();
  13957. c.volume = 1.0f;
  13958. for (std::size_t k = 0; k < song.channels.size(); ++k)
  13959. song.channels[k].muted = k != 4;
  13960. song.patterns[0].notes.clear();
  13961. for (int beat = 0; beat < 8; ++beat) // a chord per beat, two bars
  13962. for (int key : { 60, 64, 67 })
  13963. song.patterns[0].notes.push_back ({ (std::int64_t) beat * lynx::ppq, lynx::ppq / 2, 4, key + (beat / 4) * 5, 0.9f });
  13964. song.patterns[0].sortNotes();
  13965. const auto notes = render (song, 4.0, "notes.wav", [&song] (lynx::AudioEngine& engine) {
  13966. engine.capturePluginStates();
  13967. song = engine.getSong();
  13968. });
  13969. report << "notes_peak=" << notes.peak << "\n";
  13970. check ("notes_play", notes.peak > 0.001f && notes.peak < 10.0f);
  13971. juce::String error;
  13972. check ("project_saved", lynx::ProjectFile::save (song, saved, error));
  13973. }
  13974. else
  13975. {
  13976. juce::String error;
  13977. const auto loaded = lynx::ProjectFile::load (juce::File (projectPath), error);
  13978. check ("project_loaded", loaded.has_value());
  13979. if (loaded)
  13980. song = *loaded;
  13981. juce::File (projectPath).copyFileTo (saved);
  13982. }
  13983. const auto channel = pluginChannel (song);
  13984. check ("plugin_channel", channel >= 0);
  13985. if (channel >= 0)
  13986. {
  13987. const auto& plugin = song.channels[(std::size_t) channel].plugin;
  13988. juce::MemoryBlock state;
  13989. state.fromBase64Encoding (juce::String (plugin.state));
  13990. report << "channel=" << channel + 1 << " state_bytes=" << (int) state.getSize() << "\n";
  13991. check ("state_saved", state.getSize() > 0);
  13992. // the project read back from the file: the same sound, and the same state handed back
  13993. juce::String error;
  13994. const auto again = lynx::ProjectFile::load (saved, error);
  13995. check ("project_reloaded", again.has_value());
  13996. if (again)
  13997. {
  13998. std::string stateBack;
  13999. const auto first = render (*again, 4.0, "reload-a.wav");
  14000. const auto second = render (*again, 4.0, "reload-b.wav", [&] (lynx::AudioEngine& engine) {
  14001. engine.capturePluginStates();
  14002. stateBack = engine.getSong().channels[(std::size_t) channel].plugin.state;
  14003. });
  14004. // two loads of the same project: the same audio (sample for sample, or within -60 dB for a plugin
  14005. // with free-running modulation)
  14006. double energy = 0.0, difference = 0.0;
  14007. const auto n = std::min (first.left.size(), second.left.size());
  14008. for (std::size_t k = 0; k < n; ++k)
  14009. {
  14010. energy += (double) first.left[k] * first.left[k];
  14011. difference += ((double) first.left[k] - second.left[k]) * ((double) first.left[k] - second.left[k]);
  14012. }
  14013. const auto ratioDb = energy > 0.0 ? 10.0 * std::log10 (std::max (difference, 1e-30) / energy) : 0.0;
  14014. report << "reload_peak=" << first.peak << " reload_difference_db=" << juce::String (ratioDb, 1) << "\n";
  14015. check ("reload_plays", first.peak > 0.001f);
  14016. check ("reload_same_sound", energy > 0.0 && ratioDb < -60.0);
  14017. juce::MemoryBlock back;
  14018. back.fromBase64Encoding (juce::String (stateBack));
  14019. report << "state_back_bytes=" << (int) back.getSize() << " identical=" << (int) (back == state) << "\n";
  14020. check ("state_handed_back", back.getSize() > 0);
  14021. }
  14022. // the host tempo: what the plugin plays by itself (FL Studio's own patterns inside FL Studio VSTi) at two
  14023. // tempos, without the project's notes
  14024. auto self = song;
  14025. for (std::size_t k = 0; k < self.channels.size(); ++k)
  14026. self.channels[k].muted = (int) k != channel;
  14027. for (auto& pattern : self.patterns)
  14028. pattern.notes.erase (std::remove_if (pattern.notes.begin(), pattern.notes.end(), [channel] (const lynx::Note& n) { return n.channel == channel; }),
  14029. pattern.notes.end());
  14030. const auto onsets = [] (const std::vector<float>& x) {
  14031. // envelope rises over a threshold (10 ms hold-off of 60 ms): the times in seconds
  14032. std::vector<double> at;
  14033. float peak = 0.0f;
  14034. for (const auto v : x)
  14035. peak = std::max (peak, std::abs (v));
  14036. const auto threshold = peak * 0.3f;
  14037. auto quietFor = 1 << 30;
  14038. for (std::size_t k = 0; k < x.size(); ++k)
  14039. {
  14040. const auto loud = std::abs (x[k]) >= threshold;
  14041. if (loud && quietFor >= 48000 * 60 / 1000)
  14042. at.push_back ((double) k / 48000.0);
  14043. quietFor = loud ? 0 : quietFor + 1;
  14044. }
  14045. return at;
  14046. };
  14047. const auto medianGap = [] (const std::vector<double>& at) {
  14048. std::vector<double> gaps;
  14049. for (std::size_t k = 1; k < at.size(); ++k)
  14050. gaps.push_back (at[k] - at[k - 1]);
  14051. if (gaps.empty())
  14052. return 0.0;
  14053. std::sort (gaps.begin(), gaps.end());
  14054. return gaps[gaps.size() / 2];
  14055. };
  14056. self.bpm = 100.0;
  14057. const auto slow = render (self, 6.0, "tempo-100.wav");
  14058. self.bpm = 150.0;
  14059. const auto fast = render (self, 6.0, "tempo-150.wav");
  14060. const auto gapSlow = medianGap (onsets (slow.left)), gapFast = medianGap (onsets (fast.left));
  14061. report << "self_peak_100=" << slow.peak << " self_peak_150=" << fast.peak << " onsets_100=" << (int) onsets (slow.left).size()
  14062. << " onsets_150=" << (int) onsets (fast.left).size() << " gap_100=" << juce::String (gapSlow, 4) << " gap_150="
  14063. << juce::String (gapFast, 4) << "\n";
  14064. if (slow.peak > 0.001f && gapFast > 0.0)
  14065. {
  14066. report << "tempo_ratio=" << juce::String (gapSlow / gapFast, 3) << " (expected 1.5)\n";
  14067. check ("follows_host_tempo", std::abs (gapSlow / gapFast - 1.5) < 0.05);
  14068. }
  14069. else
  14070. report << "tempo: the plugin plays nothing by itself in this project\n";
  14071. // the outputs it offers (FL Studio VSTi (Multi): FL's mixer tracks as separate outputs)
  14072. lynx::AudioEngine engine (false);
  14073. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  14074. engine.setSong (song);
  14075. engine.renderOffline (0.2, 48000.0);
  14076. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (channel)))
  14077. {
  14078. report << "outputs=" << (int) instrument->outputs().size() << ":";
  14079. for (const auto& o : instrument->outputs())
  14080. report << " [" << o.name << "]";
  14081. report << "\n";
  14082. check ("outputs_listed", ! instrument->outputs().empty());
  14083. }
  14084. else
  14085. check ("instrument_loaded", false);
  14086. }
  14087. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  14088. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  14089. folder.getChildFile ("report.txt").replaceWithText (report);
  14090. setApplicationReturnValue (ok ? 0 : 1);
  14091. quit();
  14092. }
  14093. void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only = {})
  14094. {
  14095. juce::String report;
  14096. bool ok = false;
  14097. {
  14098. lynx::AudioEngine offline (false);
  14099. auto& host = offline.getPluginHost();
  14100. const auto added = host.addPluginFile (juce::File (pluginPath));
  14101. report << "plugins_in_file=" << added << "\n";
  14102. juce::PluginDescription instrument, effect;
  14103. bool hasInstrument = false, hasEffect = false;
  14104. for (const auto& type : host.getKnownPlugins().getTypes())
  14105. {
  14106. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  14107. || (only.isNotEmpty() && type.name != only))
  14108. continue;
  14109. report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
  14110. << ") in " << type.fileOrIdentifier << "\n";
  14111. if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
  14112. if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
  14113. }
  14114. auto song = lynx::Song::makeDefault();
  14115. if (hasInstrument)
  14116. {
  14117. auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
  14118. c.instrument = lynx::InstrumentKind::plugin;
  14119. c.plugin.id = instrument.createIdentifierString().toStdString();
  14120. c.plugin.name = instrument.name.toStdString();
  14121. c.volume = 1.0f;
  14122. for (int i = 0; i < 4; ++i) // one chord per beat
  14123. for (int key : { 60, 64, 67 })
  14124. song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
  14125. song.patterns[0].sortNotes();
  14126. }
  14127. if (hasEffect)
  14128. {
  14129. lynx::EffectSlot slot;
  14130. slot.kind = lynx::EffectKind::plugin;
  14131. slot.plugin.id = effect.createIdentifierString().toStdString();
  14132. slot.plugin.name = effect.name.toStdString();
  14133. song.mixer[0].effects.push_back (slot);
  14134. }
  14135. const auto effectSlot = (int) song.mixer[0].effects.size() - 1; // (the default master may hold effects already)
  14136. offline.setSong (song);
  14137. // after a render: the rack (and its plugins) is built when the engine is prepared
  14138. const auto peak = offline.renderOffline (3.0, 48000.0);
  14139. const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
  14140. const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, effectSlot).get());
  14141. report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
  14142. << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
  14143. if (host.getLoadFailures().size() > 0) // why: the host's own message (license, missing file, load failure)
  14144. report << "load_failures=" << host.getLoadFailures().joinIntoString (" | ") << "\n";
  14145. report << "peak=" << peak << "\n";
  14146. // plugins that crashed inside a call, were caught and switched off (round 111)
  14147. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  14148. for (const auto& c : lynx::pluginCrashes())
  14149. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  14150. offline.capturePluginStates();
  14151. const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
  14152. report << "state_bytes_base64=" << (int) stateSize << "\n";
  14153. ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
  14154. && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
  14155. }
  14156. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  14157. juce::File (reportPath).replaceWithText (report);
  14158. setApplicationReturnValue (ok ? 0 : 1);
  14159. quit();
  14160. }
  14161. // Round 190gg (B4): --crashguardtest plugin report.txt thread | ui. "thread": the plugin's own thread faults in its 40th
  14162. // block (Linux / macOS): that thread is parked, LYNX switches the plugin off (as the main window's timer does) and goes
  14163. // on; the other inserts play; Reload brings it back. "ui": the calls the UI makes into a plugin, under the guard: a
  14164. // preset load that crashes (the Plugin window's preset menu path) and making the editor (PluginWindows::open, the CLAP
  14165. // test plugin's "editor-create": a display is needed, e.g. Xvfb); each switches the plugin off, LYNX goes on.
  14166. void runCrashGuardThreadOrUiTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
  14167. {
  14168. juce::String report;
  14169. bool ok = true;
  14170. const auto expect = [&] (const char* name, bool value) {
  14171. report << name << "=" << (value ? 1 : 0) << "\n";
  14172. ok = ok && value;
  14173. };
  14174. const auto setEnv = [] (const char* name, const char* value) {
  14175. #if JUCE_WINDOWS
  14176. _putenv_s (name, value);
  14177. #else
  14178. setenv (name, value, 1);
  14179. #endif
  14180. };
  14181. const auto render = [] (lynx::AudioEngine& engine, double seconds, float* peak) {
  14182. lynx::AudioEngine::RenderOptions o;
  14183. o.seconds = seconds;
  14184. o.sampleRate = 48000.0;
  14185. o.pluginWarmUp = false;
  14186. if (peak != nullptr)
  14187. o.capture = [peak] (const float* l, const float* r, int n) {
  14188. for (int k = 0; k < n; ++k)
  14189. *peak = std::max (*peak, std::max (std::abs (l[k]), std::abs (r[k])));
  14190. };
  14191. return engine.renderOffline (o);
  14192. };
  14193. report << "mode=" << mode << "\nthread_guard=" << (lynx::crashguard::pluginThreadFaultsCaught() ? "on" : "off") << "\n";
  14194. setEnv ("LYNX_TEST_CRASH", mode == "thread" ? "thread" : "");
  14195. setEnv ("LYNX_TEST_CRASH_AFTER", "40");
  14196. const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
  14197. .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  14198. tmp.createDirectory();
  14199. {
  14200. lynx::AudioEngine offline (false);
  14201. auto& host = offline.getPluginHost();
  14202. host.addPluginFile (juce::File (pluginPath));
  14203. juce::PluginDescription effect;
  14204. bool found = false;
  14205. for (const auto& type : host.getKnownPlugins().getTypes())
  14206. if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  14207. {
  14208. effect = type;
  14209. found = true;
  14210. }
  14211. expect ("plugin_found", found);
  14212. auto song = lynx::Song::makeDefault();
  14213. lynx::EffectSlot slot;
  14214. slot.kind = lynx::EffectKind::plugin;
  14215. slot.plugin.id = effect.createIdentifierString().toStdString();
  14216. slot.plugin.name = effect.name.toStdString();
  14217. song.mixer[1].effects.push_back (slot);
  14218. offline.setSong (song);
  14219. const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
  14220. render (offline, 0.05, nullptr);
  14221. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  14222. render (offline, 0.05, nullptr);
  14223. auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  14224. expect ("plugin_loaded", first != nullptr);
  14225. const auto crashesBefore = lynx::pluginCrashCount();
  14226. if (mode == "thread")
  14227. {
  14228. const auto faultsBefore = lynx::crashguard::pluginThreadFaultCount();
  14229. float peak = 0.0f;
  14230. render (offline, 3.0, &peak); // (the plugin starts its faulting thread in its 40th block)
  14231. for (int i = 0; i < 200 && lynx::crashguard::pluginThreadFaultCount() == faultsBefore; ++i)
  14232. juce::Thread::sleep (10);
  14233. const auto faults = lynx::crashguard::pluginThreadFaults();
  14234. expect ("thread_fault_parked", lynx::crashguard::pluginThreadFaultCount() == faultsBefore + 1 && ! faults.empty());
  14235. if (! faults.empty())
  14236. report << "thread_fault=" << faults.back().where << " (" << lynx::crashguard::describe (faults.back().code) << ")\n";
  14237. expect ("not_yet_counted_as_a_call_crash", lynx::pluginCrashCount() == crashesBefore);
  14238. // what the main window's timer does
  14239. // (every instance of that module: the engine may hold more than the slot's, e.g. the offline render's)
  14240. if (first != nullptr)
  14241. report << "slot_file=" << first->getInstance().getPluginDescription().fileOrIdentifier << "\n";
  14242. const auto switched = lynx::switchOffPluginsOfThreadFaults();
  14243. report << "switched_off=" << switched << "\n";
  14244. expect ("plugin_switched_off", switched >= 1 && first != nullptr && first->hasCrashed() && lynx::pluginCrashCount() == crashesBefore + switched);
  14245. expect ("only_once", lynx::switchOffPluginsOfThreadFaults() == 0);
  14246. const auto down = offline.downHostedPlugins();
  14247. expect ("slot_down", down.size() == 1 && down[0] == where);
  14248. float after = 0.0f;
  14249. render (offline, 1.0, &after);
  14250. report << "peak_after=" << after << "\n";
  14251. expect ("audio_after_fault", after > 0.01f);
  14252. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
  14253. float others = 0.0f;
  14254. render (offline, 1.0, &others);
  14255. expect ("other_inserts_play", others > 0.01f);
  14256. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  14257. const auto running = offline.reloadHostedPlugins (down);
  14258. auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  14259. float reloaded = 0.0f;
  14260. render (offline, 1.0, &reloaded);
  14261. expect ("reloaded_plays", running == 1 && again != nullptr && again != first && ! again->hasCrashed() && reloaded > 0.01f);
  14262. }
  14263. else
  14264. {
  14265. // a preset that crashes the plugin (the preset menu's load), saved first from the running plugin
  14266. auto& instance = first->getInstance();
  14267. const auto preset = tmp.getChildFile ("crash.lynxpreset");
  14268. juce::String error;
  14269. expect ("preset_saved", lynx::pluginpresetui::save (instance, preset, "crash", error) && preset.existsAsFile());
  14270. setEnv ("LYNX_TEST_CRASH", "state");
  14271. const auto loaded = lynx::pluginpresetui::load (instance, preset, error);
  14272. setEnv ("LYNX_TEST_CRASH", "");
  14273. report << "preset_error=" << error << "\n";
  14274. expect ("preset_crash_caught", ! loaded && lynx::pluginCrashCount() == crashesBefore + 1 && first->hasCrashed());
  14275. expect ("preset_plugin_down", offline.hostedPluginDown (where) && lynx::pluginInstanceDown (instance));
  14276. expect ("not_called_again", ! lynx::callPluginFromUi (instance, "test", [] {}) && lynx::pluginCrashCount() == crashesBefore + 1);
  14277. float after = 0.0f;
  14278. render (offline, 1.0, &after);
  14279. expect ("audio_after_preset_crash", after > 0.01f);
  14280. // Reload; then its editor crashes as it is made (PluginWindows::open): no window, the plugin is down
  14281. setEnv ("LYNX_TEST_CRASH", "editor-create");
  14282. const auto running = offline.reloadHostedPlugins (offline.downHostedPlugins());
  14283. auto held = offline.getEffect (1, 0);
  14284. auto* again = dynamic_cast<lynx::PluginEffect*> (held.get());
  14285. expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
  14286. if (again != nullptr)
  14287. {
  14288. lynx::PluginWindows::open (held, again->getInstance(), "crash test", {});
  14289. expect ("editor_crash_caught", lynx::pluginCrashCount() == crashesBefore + 2 && again->hasCrashed());
  14290. expect ("no_window", ! lynx::PluginWindows::isOpen (again->getInstance()));
  14291. float editorAfter = 0.0f;
  14292. render (offline, 1.0, &editorAfter);
  14293. expect ("audio_after_editor_crash", editorAfter > 0.01f);
  14294. }
  14295. setEnv ("LYNX_TEST_CRASH", "");
  14296. }
  14297. }
  14298. setEnv ("LYNX_TEST_CRASH", "");
  14299. // LYNX's own faults (also on its own threads) stay crashes (child processes; the selftest runs the same)
  14300. const auto own = faultReportSelfTest();
  14301. report << "own_faults=" << own << "\n";
  14302. ok = ok && ! own.startsWith ("ERROR");
  14303. for (const auto& c : lynx::pluginCrashes())
  14304. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  14305. tmp.deleteRecursively();
  14306. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  14307. juce::File (reportPath).replaceWithText (report);
  14308. setApplicationReturnValue (ok ? 0 : 1);
  14309. quit();
  14310. }
  14311. // LYNX --crashguardtest plugin report.txt [process|memcpy] (round 190dt): see the dispatch in initialise().
  14312. void runCrashGuardTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
  14313. {
  14314. if (mode == "thread" || mode == "ui")
  14315. {
  14316. runCrashGuardThreadOrUiTest (pluginPath, reportPath, mode);
  14317. return;
  14318. }
  14319. juce::String report;
  14320. bool ok = true;
  14321. const auto expect = [&] (const char* name, bool value) {
  14322. report << name << "=" << (value ? 1 : 0) << "\n";
  14323. ok = ok && value;
  14324. };
  14325. const auto setEnv = [] (const char* name, const char* value) {
  14326. #if JUCE_WINDOWS
  14327. _putenv_s (name, value);
  14328. #else
  14329. setenv (name, value, 1);
  14330. #endif
  14331. };
  14332. // renders without the plugin warm-up (its silent blocks would count towards the crash)
  14333. const auto render = [] (lynx::AudioEngine& engine, double seconds, const std::function<void (const float*, const float*, int)>& capture) {
  14334. lynx::AudioEngine::RenderOptions o;
  14335. o.seconds = seconds;
  14336. o.sampleRate = 48000.0;
  14337. o.pluginWarmUp = false;
  14338. o.capture = capture;
  14339. return engine.renderOffline (o);
  14340. };
  14341. const auto peakOf = [] (float& peak) {
  14342. return [&peak] (const float* l, const float* r, int n) {
  14343. for (int k = 0; k < n; ++k)
  14344. peak = std::max (peak, std::max (std::abs (l[k]), std::abs (r[k])));
  14345. };
  14346. };
  14347. report << "guard=" << (lynx::crashguard::pluginFaultsCaught() ? "on" : "off") << "\nmode=" << mode << "\n";
  14348. setEnv ("LYNX_TEST_CRASH", mode == "memcpy" ? "memcpy" : "process");
  14349. setEnv ("LYNX_TEST_CRASH_AFTER", "40");
  14350. const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
  14351. .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  14352. tmp.createDirectory();
  14353. std::optional<lynx::Song> saved;
  14354. std::string savedState;
  14355. {
  14356. lynx::AudioEngine offline (false);
  14357. auto& host = offline.getPluginHost();
  14358. host.addPluginFile (juce::File (pluginPath));
  14359. juce::PluginDescription effect;
  14360. bool found = false;
  14361. for (const auto& type : host.getKnownPlugins().getTypes())
  14362. if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  14363. {
  14364. effect = type;
  14365. found = true;
  14366. }
  14367. expect ("plugin_found", found);
  14368. // the plugin on insert 1 (the kick's); the clap and the hat play on inserts 2 and 3
  14369. auto song = lynx::Song::makeDefault();
  14370. lynx::EffectSlot slot;
  14371. slot.kind = lynx::EffectKind::plugin;
  14372. slot.plugin.id = effect.createIdentifierString().toStdString();
  14373. slot.plugin.name = effect.name.toStdString();
  14374. song.mixer[1].effects.push_back (slot);
  14375. offline.setSong (song);
  14376. const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
  14377. // the rack is published at the engine's rate and an offline render runs at its own (48 kHz) without publishing:
  14378. // one edit after a first render puts the rack (and the plugin) at the render's rate, so later edits keep it
  14379. render (offline, 0.05, {}); // (a few blocks, far from the 40th)
  14380. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  14381. render (offline, 0.05, {});
  14382. auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  14383. expect ("plugin_loaded", first != nullptr);
  14384. offline.capturePluginStates();
  14385. savedState = offline.getSong().mixer[1].effects[0].plugin.state;
  14386. expect ("state_captured", ! savedState.empty());
  14387. // the crash: 3 s, the plugin faults in its 40th block
  14388. const auto crashesBefore = lynx::pluginCrashCount();
  14389. juce::int64 position = 0, crashAt = -1;
  14390. float peakAfter = 0.0f;
  14391. const auto afterPeak = peakOf (peakAfter);
  14392. const auto peak = render (offline, 3.0, [&] (const float* l, const float* r, int n) {
  14393. if (crashAt < 0 && lynx::pluginCrashCount() != crashesBefore)
  14394. crashAt = position;
  14395. else if (crashAt >= 0)
  14396. afterPeak (l, r, n);
  14397. position += n;
  14398. });
  14399. report << "peak=" << peak << "\ncrash_at_sample=" << crashAt << "\npeak_after_crash=" << peakAfter << "\n";
  14400. const auto crashes = lynx::pluginCrashes();
  14401. expect ("crash_caught", lynx::pluginCrashCount() == crashesBefore + 1 && ! crashes.empty() && ! crashes.back().onLoad);
  14402. if (! crashes.empty())
  14403. report << "crash=" << crashes.back().plugin << " (" << lynx::crashguard::describe (crashes.back().code) << ")\n";
  14404. expect ("slot_marked_crashed", first != nullptr && offline.getEffect (1, 0).get() == first && first->hasCrashed());
  14405. const auto down = offline.downHostedPlugins();
  14406. expect ("slot_down", down.size() == 1 && down[0] == where);
  14407. expect ("audio_after_crash", crashAt >= 0 && peakAfter > 0.01f);
  14408. // the other inserts: with the kick (through the crashed slot) silent, the clap and the hat still play
  14409. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
  14410. float othersPeak = 0.0f;
  14411. render (offline, 1.0, peakOf (othersPeak));
  14412. report << "other_inserts_peak=" << othersPeak << "\n";
  14413. expect ("other_inserts_play", othersPeak > 0.01f);
  14414. expect ("nothing_reloads_by_itself", offline.hostedPluginDown (where) && offline.getEffect (1, 0).get() == first);
  14415. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  14416. // the project saves with the settings the plugin had before it crashed, and opens again
  14417. offline.capturePluginStates();
  14418. expect ("state_kept", offline.getSong().mixer[1].effects[0].plugin.state == savedState);
  14419. const auto file = tmp.getChildFile ("crashed.lynx");
  14420. juce::String error;
  14421. expect ("project_saved", lynx::ProjectFile::save (offline.getSong(), file, error) && file.existsAsFile());
  14422. saved = lynx::ProjectFile::load (file, error);
  14423. expect ("project_reopens", saved.has_value() && saved->mixer.size() > 1 && saved->mixer[1].effects.size() == 1
  14424. && saved->mixer[1].effects[0].plugin.state == savedState);
  14425. // Reload (the prompt's button, round 190ao): a new instance; the module's block count is past 40 now
  14426. const auto running = offline.reloadHostedPlugins (down);
  14427. auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  14428. expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
  14429. float reloadedPeak = 0.0f;
  14430. render (offline, 1.0, peakOf (reloadedPeak));
  14431. report << "reloaded_peak=" << reloadedPeak << "\n";
  14432. expect ("reloaded_plays", reloadedPeak > 0.01f && lynx::pluginCrashCount() == crashesBefore + 1 && again != nullptr && ! again->hasCrashed());
  14433. }
  14434. // the saved project opens again with the plugin crashing on its saved settings: left out, the rest plays, the
  14435. // settings stay in the project
  14436. setEnv ("LYNX_TEST_CRASH", "state");
  14437. if (saved.has_value())
  14438. {
  14439. lynx::AudioEngine reopened (false);
  14440. reopened.getPluginHost().addPluginFile (juce::File (pluginPath));
  14441. const auto before = lynx::pluginCrashCount();
  14442. reopened.setSong (*saved);
  14443. float reopenedPeak = 0.0f;
  14444. render (reopened, 1.0, peakOf (reopenedPeak));
  14445. const auto crashes = lynx::pluginCrashes();
  14446. report << "reopened_peak=" << reopenedPeak << "\n";
  14447. if (reopened.getPluginHost().getLoadFailures().size() > 0)
  14448. report << "load_failures=" << reopened.getPluginHost().getLoadFailures().joinIntoString (" | ") << "\n";
  14449. expect ("state_crash_caught", lynx::pluginCrashCount() == before + 1 && ! crashes.empty() && crashes.back().onLoad);
  14450. expect ("state_crash_left_out", dynamic_cast<lynx::PluginEffect*> (reopened.getEffect (1, 0).get()) == nullptr);
  14451. expect ("state_crash_project_plays", reopenedPeak > 0.01f);
  14452. reopened.capturePluginStates();
  14453. expect ("state_crash_settings_kept", reopened.getSong().mixer[1].effects.size() == 1
  14454. && reopened.getSong().mixer[1].effects[0].plugin.state == savedState);
  14455. }
  14456. setEnv ("LYNX_TEST_CRASH", "");
  14457. // LYNX's own faults inside a guarded call stay crashes (child processes; the selftest runs the same)
  14458. const auto own = faultReportSelfTest();
  14459. report << "own_faults=" << own << "\n";
  14460. ok = ok && ! own.startsWith ("ERROR");
  14461. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  14462. for (const auto& c : lynx::pluginCrashes())
  14463. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << (c.onLoad ? ", loading its state" : "") << ")\n";
  14464. tmp.deleteRecursively();
  14465. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  14466. juce::File (reportPath).replaceWithText (report);
  14467. setApplicationReturnValue (ok ? 0 : 1);
  14468. quit();
  14469. }
  14470. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108): a hosted CLAP
  14471. // instrument with the wrapper's MPE switch on gets each note on its own member channel, its fine pitch / Mod X /
  14472. // Mod Y as tuning / brightness / pressure note expressions before the note on, and a sounding note's expression
  14473. // on that note's channel alone. The plugin writes down what it received; no window, no audio device.
  14474. // Round 190hy: see --mpeplaytest190hy. Note A (C4, 1 s): its pitch curve holds 0 for 0.5 s, rises an octave over
  14475. // 0.25 s and holds it; then note B (G4, 0.5 s), no curve: it must not inherit A's bend. The frequencies come from the
  14476. // rendered audio's zero crossings (a silent logging plugin: its log shows the expressions instead).
  14477. void runMpePlayTest190hy (const juce::String& pluginPath, const juce::String& reportPath)
  14478. {
  14479. const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  14480. log.deleteFile();
  14481. #if JUCE_WINDOWS
  14482. _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
  14483. #else
  14484. setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
  14485. #endif
  14486. juce::String report;
  14487. auto ok = false;
  14488. const auto wavFile = juce::File (reportPath).withFileExtension ("wav");
  14489. constexpr double rate = 44100.0;
  14490. {
  14491. lynx::AudioEngine offline (false);
  14492. auto& host = offline.getPluginHost();
  14493. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  14494. const auto wanted = juce::File (pluginPath).hasFileExtension ("clap") ? "CLAP" : "VST3";
  14495. std::optional<juce::PluginDescription> type;
  14496. for (const auto& t : host.getKnownPlugins().getTypes())
  14497. if (t.pluginFormatName == wanted && t.isInstrument && ! type)
  14498. type = t;
  14499. report << "format=" << wanted << " found=" << (type ? type->name : juce::String ("none")) << "\n";
  14500. if (type)
  14501. {
  14502. lynx::Song s;
  14503. s.mixer = lynx::Song::defaultMixer (2);
  14504. s.bpm = 120.0;
  14505. lynx::ChannelDef c;
  14506. c.name = type->name.toStdString();
  14507. c.instrument = lynx::InstrumentKind::plugin;
  14508. c.plugin.id = type->createIdentifierString().toStdString();
  14509. c.plugin.name = type->name.toStdString();
  14510. c.plugin.mpe = true;
  14511. c.mixerTrack = 1;
  14512. s.channels.push_back (c);
  14513. s.patterns.emplace_back();
  14514. auto& p = s.patterns[0];
  14515. lynx::Note a;
  14516. a.channel = 0;
  14517. a.key = 60;
  14518. a.length = 2 * lynx::ppq;
  14519. a.velocity = 0.8f;
  14520. lynx::NoteCurves curves;
  14521. curves.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { (float) lynx::ppq, 0.0f }, { 1.5f * (float) lynx::ppq, 1200.0f },
  14522. { 2.0f * (float) lynx::ppq, 1200.0f } };
  14523. a.curves = curves;
  14524. auto b = a;
  14525. b.key = 67;
  14526. b.start = 2 * lynx::ppq;
  14527. b.length = lynx::ppq;
  14528. b.curves.clear();
  14529. p.notes = { a, b };
  14530. p.lengthTicks = 16 * lynx::ppq; // (one pass: the notes play once in the 1.2 s rendered)
  14531. offline.setSong (std::move (s));
  14532. wavFile.deleteFile();
  14533. juce::WavAudioFormat wav;
  14534. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (wavFile.createOutputStream().release(), rate, 2, 24, {}, 0));
  14535. const auto peak = writer != nullptr ? offline.renderOffline (1.6, rate, writer.get()) : 0.0f;
  14536. writer.reset();
  14537. report << "peak=" << peak << "\n";
  14538. ok = writer == nullptr && wavFile.existsAsFile();
  14539. }
  14540. } // (the plugin writes its log, if any, as it is destroyed)
  14541. // the frequency of [from, to) seconds of the left channel from its rising zero crossings
  14542. juce::AudioBuffer<float> audio;
  14543. {
  14544. juce::AudioFormatManager formats;
  14545. formats.registerBasicFormats();
  14546. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (wavFile)); reader != nullptr)
  14547. {
  14548. audio.setSize (1, (int) reader->lengthInSamples);
  14549. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, false);
  14550. }
  14551. }
  14552. const auto frequency = [&audio] (double from, double to) {
  14553. const auto* x = audio.getReadPointer (0);
  14554. const auto n = audio.getNumSamples();
  14555. long first = -1, last = -1;
  14556. auto crossings = 0;
  14557. for (auto i = juce::jmax (1, (int) (from * rate)); i < juce::jmin (n, (int) (to * rate)); ++i)
  14558. if (x[i - 1] <= 0.0f && x[i] > 0.0f)
  14559. {
  14560. if (first < 0)
  14561. first = i;
  14562. else
  14563. ++crossings, last = i;
  14564. }
  14565. return crossings > 0 ? crossings * rate / (double) (last - first) : 0.0;
  14566. };
  14567. if (audio.getNumSamples() > 0 && audio.getMagnitude (0, 0, audio.getNumSamples()) > 0.001f)
  14568. {
  14569. const auto before = frequency (0.1, 0.45), during = frequency (0.55, 0.7), after = frequency (0.8, 0.98), next = frequency (1.1, 1.45);
  14570. report << "a_before_hz=" << before << " a_rising_hz=" << during << " a_after_hz=" << after << " b_hz=" << next << "\n";
  14571. report << "a_after_over_before=" << (before > 0.0 ? after / before : 0.0) << " (an octave: 2)\n";
  14572. report << "b_over_a_before=" << (before > 0.0 ? next / before : 0.0) << " (a fifth: 1.498)\n";
  14573. }
  14574. else
  14575. report << "audio=silent\n";
  14576. if (log.existsAsFile())
  14577. report << "--- plugin log ---\n" << log.loadFileAsString();
  14578. report << "result=" << (ok ? "RENDERED" : "FAILED") << "\n";
  14579. juce::File (reportPath).replaceWithText (report);
  14580. setApplicationReturnValue (ok ? 0 : 1);
  14581. quit();
  14582. }
  14583. void runMpeTest (const juce::String& pluginPath, const juce::String& reportPath)
  14584. {
  14585. const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  14586. log.deleteFile();
  14587. #if JUCE_WINDOWS
  14588. _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
  14589. #else
  14590. setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
  14591. #endif
  14592. juce::String report;
  14593. auto failures = 0;
  14594. {
  14595. lynx::AudioEngine engine (false);
  14596. auto& host = engine.getPluginHost();
  14597. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  14598. std::optional<juce::PluginDescription> clap;
  14599. for (const auto& type : host.getKnownPlugins().getTypes())
  14600. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  14601. clap = type;
  14602. lynx::PluginRef ref;
  14603. if (clap)
  14604. {
  14605. ref.id = clap->createIdentifierString().toStdString();
  14606. ref.name = clap->name.toStdString();
  14607. }
  14608. ref.mpe = true;
  14609. juce::String error;
  14610. auto instrument = clap ? host.makeInstrument (ref, 48000.0, &error) : nullptr;
  14611. report << "instrument_loaded=" << (instrument != nullptr ? "yes" : "no") << (error.isNotEmpty() ? " (" + error + ")" : juce::String()) << "\n";
  14612. if (instrument != nullptr)
  14613. {
  14614. std::vector<float> l (256), r (256);
  14615. auto block = [&] { instrument->render (l.data(), r.data(), 256, 1.0f, 1.0f); };
  14616. block(); // (the zone's setup)
  14617. instrument->setNextNoteFinePitch (30.0f); // +30 cents
  14618. instrument->setNextNoteModulation (0.75f, 1.0f); // timbre 0.75, full pressure
  14619. instrument->noteOn (60, 0.8f);
  14620. instrument->noteOn (64, 0.5f); // a second note: its own channel, centre values
  14621. block();
  14622. instrument->noteExpression (60, (int) lynx::vfx::Prop::pitch, 200.0f, 0.0f);
  14623. instrument->noteExpression (64, (int) lynx::vfx::Prop::modX, 0.25f, 0.0f);
  14624. instrument->noteExpression (60, (int) lynx::vfx::Prop::modY, 0.75f, 0.0f);
  14625. block();
  14626. instrument->noteOff (60);
  14627. instrument->noteOff (64);
  14628. block();
  14629. }
  14630. else
  14631. ++failures;
  14632. } // (the plugin writes its log as it is destroyed)
  14633. struct Line
  14634. {
  14635. juce::String kind;
  14636. int a = 0, b = 0, c = 0, d = 0;
  14637. };
  14638. std::vector<Line> lines;
  14639. for (const auto& text : juce::StringArray::fromLines (log.loadFileAsString()))
  14640. {
  14641. const auto t = juce::StringArray::fromTokens (text, " ", "");
  14642. if (t.size() >= 3)
  14643. lines.push_back ({ t[0], t[1].getIntValue(), t[2].getIntValue(), t.size() > 3 ? t[3].getIntValue() : 0, t.size() > 4 ? t[4].getIntValue() : 0 });
  14644. }
  14645. report << "plugin_events=" << (int) lines.size() << "\n";
  14646. // the first line at or after `from` that matches (−1 = none); `value` within `tolerance` (thousandths)
  14647. auto find = [&lines] (const juce::String& kind, int a, int b, int value, int tolerance, int from = 0) {
  14648. for (auto i = (std::size_t) from; i < lines.size(); ++i)
  14649. {
  14650. const auto& x = lines[i];
  14651. const auto v = kind == "expr" ? x.d : x.c;
  14652. if (x.kind == kind && x.a == a && x.b == b && std::abs (v - value) <= tolerance)
  14653. return (int) i;
  14654. }
  14655. return -1;
  14656. };
  14657. auto check = [&] (const char* what, bool ok) {
  14658. report << what << "=" << (ok ? "ok" : "FAILED") << "\n";
  14659. failures += ok ? 0 : 1;
  14660. };
  14661. // (CLAP expression ids: 2 tuning in semitones, 5 brightness, 6 pressure; channels 0-based: the first member = 1)
  14662. const auto on60 = find ("on", 1, 60, 800, 5), on64 = find ("on", 2, 64, 500, 5);
  14663. check ("zone_setup_sent", find ("midi", 176, 6, 15, 0) >= 0 && find ("midi", 177, 6, 48, 0) >= 0);
  14664. check ("notes_on_their_own_channels", on60 >= 0 && on64 > on60);
  14665. const auto tune = find ("expr", 2, 1, 300, 3), bright = find ("expr", 5, 1, 756, 4), press = find ("expr", 6, 1, 1000, 1);
  14666. check ("expression_before_the_note_on", tune >= 0 && bright >= 0 && press >= 0 && tune < on60 && bright < on60 && press < on60);
  14667. check ("second_note_starts_centred", find ("expr", 2, 2, 0, 1) >= 0 && find ("expr", 5, 2, 504, 4) >= 0 && find ("expr", 6, 2, 0, 1) >= 0);
  14668. const auto later = std::max (on60, on64) + 1;
  14669. check ("sounding_note_expression", later > 0 && find ("expr", 2, 1, 2000, 3, later) >= 0 && find ("expr", 5, 2, 252, 4, later) >= 0
  14670. && find ("expr", 6, 1, 504, 4, later) >= 0);
  14671. check ("other_note_untouched", later > 0 && find ("expr", 2, 2, 2000, 3, later) < 0 && find ("expr", 6, 2, 504, 4, later) < 0);
  14672. check ("notes_off_on_their_channels", find ("off", 1, 60, 0, 100000) >= 0 && find ("off", 2, 64, 0, 100000) >= 0);
  14673. auto expressionAsMidi = false; // (a CLAP-dialect plugin gets no raw bend / pressure / CC 74 on a member channel)
  14674. for (const auto& x : lines)
  14675. if (x.kind == "midi" && (x.a & 0x0f) != 0 && ((x.a & 0xf0) == 0xe0 || (x.a & 0xf0) == 0xd0 || ((x.a & 0xf0) == 0xb0 && x.b == 74)))
  14676. expressionAsMidi = true;
  14677. check ("no_duplicate_midi_expression", ! expressionAsMidi);
  14678. report << "--- plugin log ---\n" << log.loadFileAsString() << "result=" << (failures == 0 ? "OK" : "FAILED") << "\n";
  14679. juce::File (reportPath).replaceWithText (report);
  14680. setApplicationReturnValue (failures == 0 ? 0 : 1);
  14681. quit();
  14682. }
  14683. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c, PR #29): a
  14684. // CLAP effect on the Master that asks for a restart every 8 blocks while an export renders on a thread of its own
  14685. // (the message thread is free to run the restarts, as with the Export window). The plugin aborts the process when
  14686. // start / stop_processing run off the audio thread or activate / deactivate off the main thread (issue #46, as u-he
  14687. // Presswerk does; an export at 44.1 kHz and prepare calls from the export's thread check the latter) and counts deactivations that
  14688. // landed inside its process() call (must be none), the restarts must happen, and the delay compensation must end on
  14689. // the latency the plugin reports after its last restart.
  14690. void runClapRestartTest (const juce::String& pluginPath, const juce::String& reportPath)
  14691. {
  14692. struct Run
  14693. {
  14694. std::unique_ptr<lynx::AudioEngine> engine;
  14695. juce::String report;
  14696. int slot = -1;
  14697. std::thread render;
  14698. std::atomic<bool> done { false };
  14699. double renderSeconds = 0.0;
  14700. };
  14701. auto run = std::make_shared<Run>();
  14702. const auto counters = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  14703. counters.deleteFile();
  14704. #if JUCE_WINDOWS
  14705. _putenv_s ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8());
  14706. #else
  14707. setenv ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8(), 1);
  14708. #endif
  14709. const auto fail = [this, reportPath] (juce::String report) {
  14710. report << "result=FAILED\n";
  14711. juce::File (reportPath).replaceWithText (report);
  14712. setApplicationReturnValue (1);
  14713. quit();
  14714. };
  14715. run->engine = std::make_unique<lynx::AudioEngine> (false);
  14716. auto& host = run->engine->getPluginHost();
  14717. run->report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  14718. std::optional<juce::PluginDescription> clap;
  14719. for (const auto& type : host.getKnownPlugins().getTypes())
  14720. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  14721. clap = type;
  14722. if (! clap)
  14723. {
  14724. fail (run->report + "no CLAP plugin in the file\n");
  14725. return;
  14726. }
  14727. auto song = lynx::Song::makeDefault();
  14728. lynx::EffectSlot slot;
  14729. slot.kind = lynx::EffectKind::plugin;
  14730. slot.plugin.id = clap->createIdentifierString().toStdString();
  14731. slot.plugin.name = clap->name.toStdString();
  14732. slot.smartDisable = false; // (processed every block, as with music playing: the export itself is silent)
  14733. song.mixer[0].effects = { slot }; // alone on the Master: the delay compensation is the plugin's latency
  14734. run->slot = (int) song.mixer[0].effects.size() - 1;
  14735. run->engine->setSong (song);
  14736. run->engine->renderOffline (0.1, 48000.0); // builds the rack (and the plugin) on the message thread
  14737. if (dynamic_cast<lynx::PluginEffect*> (run->engine->getEffect (0, run->slot).get()) == nullptr)
  14738. {
  14739. fail (run->report + "effect_loaded=no\n");
  14740. return;
  14741. }
  14742. auto effect = std::dynamic_pointer_cast<lynx::PluginEffect> (run->engine->getEffect (0, run->slot));
  14743. run->render = std::thread ([run, effect] () mutable {
  14744. const auto start = juce::Time::getMillisecondCounterHiRes();
  14745. run->engine->renderOffline (30.0, 48000.0);
  14746. run->renderSeconds = (juce::Time::getMillisecondCounterHiRes() - start) * 0.001;
  14747. // issue #46: an export at another rate / block size prepares the plugin from the export's thread; the
  14748. // plugin aborts unless activate / deactivate reach the main thread
  14749. auto& instance = effect->getInstance();
  14750. instance.prepareToPlay (44100.0, 1024);
  14751. instance.releaseResources();
  14752. instance.prepareToPlay (48000.0, 512);
  14753. run->engine->renderOffline (3.0, 44100.0); // (the engine rebuilds its rack at that rate)
  14754. // The engine has replaced this instance (made for 48 kHz) by then, so this is its last reference: it is
  14755. // deleted here, on the export's thread, and its deactivate / destroy go to the message thread, which this
  14756. // waits for. That has to happen before `done`: once the message thread sees it, it blocks in join() until
  14757. // this thread ends, and an instance deleted after that waited 10 s for it and then deactivated the plugin
  14758. // right here, off the main thread (the plugin aborts: about 1 run in 40 under load, round 190au).
  14759. effect.reset();
  14760. run->done = true;
  14761. });
  14762. // after the render: a second for the restarts still queued and the engine's timer (the new PDC plan)
  14763. auto finish = std::make_shared<std::function<void()>>();
  14764. *finish = [this, run, counters, reportPath, fail, finish] {
  14765. if (! run->done)
  14766. {
  14767. juce::Timer::callAfterDelay (50, *finish);
  14768. return;
  14769. }
  14770. run->render.join();
  14771. juce::Timer::callAfterDelay (1000, [this, run, counters, reportPath, fail] {
  14772. auto report = run->report;
  14773. int pluginLatency = -1;
  14774. if (const auto effect = run->engine->getEffect (0, run->slot)) // (not held past the engine's reset)
  14775. pluginLatency = effect->latencySamples();
  14776. const auto pdc = run->engine->getLatencySamples();
  14777. report << "render_seconds=" << juce::String (run->renderSeconds, 2) << "\n"
  14778. << "plugin_latency=" << pluginLatency << "\npdc_total=" << pdc << "\n"
  14779. << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  14780. run->engine.reset(); // destroys the plugin: it writes its counters
  14781. // one line per plugin instance (the engine may have made more than one): none may have been
  14782. // deactivated inside process(), and the one that rendered must have restarted
  14783. int overlapped = 0, inactive = 0, requests = 0, activations = 0, lines = 0, wrongThread = 0, misordered = 0, unstopped = 0;
  14784. bool otherRate = false;
  14785. for (const auto& line : juce::StringArray::fromLines (counters.loadFileAsString()))
  14786. {
  14787. juce::StringPairArray values;
  14788. for (const auto& token : juce::StringArray::fromTokens (line, " ", ""))
  14789. if (token.contains ("="))
  14790. values.set (token.upToFirstOccurrenceOf ("=", false, false), token.fromFirstOccurrenceOf ("=", false, false));
  14791. if (values.size() == 0)
  14792. continue;
  14793. ++lines;
  14794. report << "instance: " << line << "\n";
  14795. overlapped += values["overlapped"].getIntValue();
  14796. inactive += values["inactive_blocks"].getIntValue();
  14797. // issue #46: activate / deactivate on the main thread, start / stop_processing on the audio thread
  14798. // (the plugin aborts the process otherwise, as u-he's do), in order, every start stopped
  14799. wrongThread += values["wrong_thread"].getIntValue();
  14800. misordered += values["misordered"].getIntValue();
  14801. unstopped += values["starts"].getIntValue() - values["stops"].getIntValue();
  14802. otherRate = otherRate || values["last_rate"].getIntValue() == 44100;
  14803. if (values["requests"].getIntValue() > requests)
  14804. {
  14805. requests = values["requests"].getIntValue();
  14806. activations = values["activations"].getIntValue();
  14807. }
  14808. }
  14809. report << "wrong_thread=" << wrongThread << "\nmisordered=" << misordered << "\nunstopped=" << unstopped
  14810. << "\nactivated_at_44100=" << (otherRate ? "yes" : "no") << "\n";
  14811. const auto ok = lines > 0 && requests > 0 && activations > requests / 2 && overlapped == 0 && inactive == 0
  14812. && wrongThread == 0 && misordered == 0 && unstopped == 0 && otherRate
  14813. && pluginLatency > 0 && pdc == pluginLatency && lynx::pluginCrashCount() == 0;
  14814. if (! ok)
  14815. {
  14816. fail (report);
  14817. return;
  14818. }
  14819. report << "result=OK\n";
  14820. juce::File (reportPath).replaceWithText (report);
  14821. setApplicationReturnValue (0);
  14822. quit();
  14823. });
  14824. };
  14825. juce::Timer::callAfterDelay (50, *finish);
  14826. }
  14827. // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
  14828. // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
  14829. // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
  14830. void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
  14831. {
  14832. juce::String report;
  14833. bool ok = false;
  14834. {
  14835. lynx::AudioEngine offline (false);
  14836. auto& host = offline.getPluginHost();
  14837. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  14838. std::optional<juce::PluginDescription> vst2;
  14839. for (const auto& type : host.getKnownPlugins().getTypes())
  14840. if (type.pluginFormatName == "VST")
  14841. vst2 = type;
  14842. auto render = [&] (float gain, float& tempoSeen, int& adopted) {
  14843. lynx::FlVst2State state;
  14844. state.flags = 8;
  14845. state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
  14846. std::memcpy (state.chunk.data() + 4, &gain, 4);
  14847. auto song = lynx::Song::makeDefault();
  14848. song.bpm = 137.0;
  14849. auto& f = song.channels[4].plugin.foreign;
  14850. f.format = lynx::ForeignPlugin::Format::vst2;
  14851. f.vst2Id = (std::uint32_t) vst2->uniqueId;
  14852. f.name = "Some other name"; // found by the VST2 ID
  14853. f.state = lynx::writeFlVst2State (state);
  14854. song.channels[4].volume = 1.0f;
  14855. song.patterns[0].notes.clear();
  14856. song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
  14857. for (std::size_t c = 0; c < song.channels.size(); ++c)
  14858. if (c != 4)
  14859. song.channels[c].muted = true;
  14860. adopted = host.adoptFlPlugins (song);
  14861. offline.setSong (song);
  14862. const auto peak = offline.renderOffline (1.0, 48000.0);
  14863. offline.capturePluginStates();
  14864. juce::MemoryBlock saved;
  14865. saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
  14866. lynx::FlVst2State back;
  14867. tempoSeen = 0.0f;
  14868. if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
  14869. && back.chunk.size() >= 12)
  14870. std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
  14871. return peak;
  14872. };
  14873. if (vst2)
  14874. {
  14875. report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
  14876. float tempoA = 0, tempoB = 0;
  14877. int adoptedA = 0, adoptedB = 0;
  14878. const auto quiet = render (0.1f, tempoA, adoptedA);
  14879. const auto loud = render (0.4f, tempoB, adoptedB);
  14880. report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
  14881. << " tempo_seen=" << tempoB * 1000.0f << "\n";
  14882. ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
  14883. && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
  14884. }
  14885. }
  14886. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  14887. juce::File (reportPath).replaceWithText (report);
  14888. setApplicationReturnValue (ok ? 0 : 1);
  14889. quit();
  14890. }
  14891. // LYNX --vst3noteidtest "LYNX Test Synth.vst3" report.txt (round 190fg, cmake/LynxPatchJuce.cmake fix 26): the VST3
  14892. // test synth (tools/testplugin/lynx_test_synth_vst3.cpp: voices kept by noteId, its log the ids it got) plays two
  14893. // overlapping pairs of one key on one channel: FIFO (A 0-4, B 2-6 beats, key 60) and LIFO (C 8-14, D 10-12, key 64).
  14894. // Each note off must carry its own note on's id (FL: each note ends its own voice, round 190ej): the inner note D's
  14895. // end ends D. A second render with the tag hook off shows fix 14 alone (the oldest id: D's end carries C's id).
  14896. void runVst3NoteIdTest (const juce::String& pluginPath, const juce::String& reportPath)
  14897. {
  14898. juce::String report;
  14899. bool ok = false;
  14900. const auto logBase = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-noteid-" + juce::String (juce::Time::currentTimeMillis()));
  14901. // (read by each new instance)
  14902. #if JUCE_WINDOWS
  14903. _putenv_s ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8());
  14904. #else
  14905. setenv ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8(), 1);
  14906. #endif
  14907. struct E
  14908. {
  14909. bool on = false;
  14910. int key = 0, id = -1;
  14911. };
  14912. // (the lines each render added: a running instance keeps its log file open, so the files stay until the end)
  14913. std::map<juce::String, int> linesRead;
  14914. const auto readLog = [&logBase, &linesRead] {
  14915. std::vector<E> events;
  14916. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  14917. {
  14918. juce::StringArray lines;
  14919. f.readLines (lines);
  14920. auto& done = linesRead[f.getFullPathName()];
  14921. for (int i = done; i < lines.size(); ++i)
  14922. {
  14923. const auto p = juce::StringArray::fromTokens (lines[i], " ", {});
  14924. if (p.size() >= 5 && p[0].startsWith ("E"))
  14925. events.push_back ({ p[1] == "on", p[2].getIntValue(), p[4].getIntValue() });
  14926. }
  14927. done = lines.size() - (lines.isEmpty() || lines[lines.size() - 1].isNotEmpty() ? 0 : 1);
  14928. }
  14929. return events;
  14930. };
  14931. {
  14932. lynx::AudioEngine offline (false);
  14933. auto& host = offline.getPluginHost();
  14934. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  14935. std::optional<juce::PluginDescription> vst3;
  14936. for (const auto& type : host.getKnownPlugins().getTypes())
  14937. if (type.pluginFormatName == "VST3" && type.isInstrument)
  14938. vst3 = type;
  14939. const auto render = [&] (bool tags) {
  14940. auto song = lynx::Song::makeDefault();
  14941. song.bpm = 120.0;
  14942. auto& c = song.channels[0];
  14943. c.instrument = lynx::InstrumentKind::plugin;
  14944. c.plugin.id = vst3->createIdentifierString().toStdString();
  14945. c.plugin.name = vst3->name.toStdString();
  14946. for (std::size_t k = 1; k < song.channels.size(); ++k)
  14947. song.channels[k].muted = true;
  14948. auto& notes = song.patterns[0].notes;
  14949. notes.clear();
  14950. const auto beat = (std::int64_t) lynx::ppq;
  14951. notes.push_back ({ 0, 4 * beat, 0, 60, 0.8f }); // A
  14952. notes.push_back ({ 2 * beat, 4 * beat, 0, 60, 0.8f }); // B
  14953. notes.push_back ({ 8 * beat, 6 * beat, 0, 64, 0.8f }); // C
  14954. notes.push_back ({ 10 * beat, 2 * beat, 0, 64, 0.8f }); // D (inside C)
  14955. song.patterns[0].sortNotes();
  14956. song.patterns[0].lengthTicks = 16 * beat;
  14957. offline.setSong (song);
  14958. offline.dispatchPendingMessages();
  14959. if (! tags)
  14960. juce::lynxNoteTagHook = nullptr; // (fix 14 alone: the oldest sounding id; the next instance sets it again)
  14961. offline.renderOffline (7.9, 48000.0); // (C ends at 7 s; the 8 s pattern does not loop yet)
  14962. return readLog();
  14963. };
  14964. const auto check = [&report] (const char* name, const std::vector<E>& events, bool expectOwn) {
  14965. // ons and offs of each key in the order the plugin got them
  14966. std::map<int, std::vector<int>> ons, offs;
  14967. for (const auto& e : events)
  14968. (e.on ? ons : offs)[e.key].push_back (e.id);
  14969. const auto& a = ons[60]; const auto& o60 = offs[60];
  14970. const auto& c = ons[64]; const auto& o64 = offs[64];
  14971. report << name << ": key 60 ons";
  14972. for (auto id : a) report << " " << id;
  14973. report << " offs";
  14974. for (auto id : o60) report << " " << id;
  14975. report << "; key 64 ons";
  14976. for (auto id : c) report << " " << id;
  14977. report << " offs";
  14978. for (auto id : o64) report << " " << id;
  14979. report << "\n";
  14980. if (a.size() != 2 || o60.size() != 2 || c.size() != 2 || o64.size() != 2 || a[0] < 0 || c[0] < 0)
  14981. return false;
  14982. const auto fifo = o60[0] == a[0] && o60[1] == a[1]; // A ends first: A's id either way
  14983. // LIFO: D (c[1]) ends first; its own id with the tags, C's (the oldest) without
  14984. const auto lifo = expectOwn ? (o64[0] == c[1] && o64[1] == c[0]) : (o64[0] == c[0] && o64[1] == c[1]);
  14985. return fifo && lifo;
  14986. };
  14987. if (vst3)
  14988. {
  14989. report << "plugin=" << vst3->name << "\n";
  14990. const auto withTags = render (true);
  14991. const auto okTags = check ("with_tags", withTags, true);
  14992. const auto withoutTags = render (false);
  14993. const auto okBefore = check ("fix14_only", withoutTags, false);
  14994. report << "own_ids=" << (okTags ? "yes" : "NO") << " fix14_only_oldest=" << (okBefore ? "yes" : "NO") << "\n";
  14995. ok = okTags && okBefore;
  14996. }
  14997. }
  14998. if (ok) // (a failure leaves the logs for a look: their path is in the report)
  14999. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  15000. f.deleteFile();
  15001. else
  15002. report << "synth_logs=" << logBase.getFullPathName() << ".*\n";
  15003. #if JUCE_WINDOWS
  15004. _putenv_s ("LYNX_TEST_SYNTH_LOG", "");
  15005. #else
  15006. unsetenv ("LYNX_TEST_SYNTH_LOG");
  15007. #endif
  15008. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  15009. juce::File (reportPath).replaceWithText (report);
  15010. setApplicationReturnValue (ok ? 0 : 1);
  15011. quit();
  15012. }
  15013. // Round 181c: a wrapper MIDI option changed on a running plugin must act like the same option on a new one. For each
  15014. // option: a control engine whose plugin is created with the option set (proves the test can see it), then an engine
  15015. // whose plugin is already running when the option changes through editSong, as the wrapper page does it. What the
  15016. // plugin received comes from the test plugin's own log. The running instance must also stay the same one.
  15017. void runWrapperMidiTest (const juce::String& pluginPath, const juce::String& reportPath)
  15018. {
  15019. juce::String report;
  15020. auto ok = true;
  15021. const juce::File logFile (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_VST2_MIDILOG", {}));
  15022. struct Event { juce::String instance; int status, data1, data2; };
  15023. auto take = [&] {
  15024. std::vector<Event> out;
  15025. juce::StringArray lines;
  15026. logFile.readLines (lines);
  15027. for (const auto& line : lines)
  15028. {
  15029. const auto p = juce::StringArray::fromTokens (line, " ", {});
  15030. if (p.size() == 4)
  15031. out.push_back ({ p[0], p[1].getIntValue(), p[2].getIntValue(), p[3].getIntValue() });
  15032. }
  15033. logFile.deleteFile();
  15034. return out;
  15035. };
  15036. auto count = [] (const std::vector<Event>& events, int status, int data1, int data2) {
  15037. int n = 0;
  15038. for (const auto& e : events)
  15039. n += (e.status & 0xF0) == status && (data1 < 0 || e.data1 == data1) && (data2 < 0 || e.data2 == data2) ? 1 : 0;
  15040. return n;
  15041. };
  15042. struct Option
  15043. {
  15044. const char* name;
  15045. std::function<void (lynx::PluginRef&)> before, change;
  15046. std::function<juce::String (const std::vector<Event>&)> seen;
  15047. };
  15048. const Option options[] = {
  15049. { "Send note release velocity off", {}, [] (lynx::PluginRef& r) { r.releaseVelocity = false; },
  15050. [&] (const std::vector<Event>& e) { return "offs_with_release_32=" + juce::String (count (e, 0x80, 69, 32)) + " offs_at_0=" + juce::String (count (e, 0x80, 69, 0)); } },
  15051. { "Send pitch bend range on", {}, [] (lynx::PluginRef& r) { r.sendBendRange = true; },
  15052. [&] (const std::vector<Event>& e) { return "rpn_range_12=" + juce::String (count (e, 0xB0, 6, 12)); } },
  15053. { "Pitch bend range 24", [] (lynx::PluginRef& r) { r.sendBendRange = true; }, [] (lynx::PluginRef& r) { r.bendRange = 24; },
  15054. [&] (const std::vector<Event>& e) { return "rpn_range_24=" + juce::String (count (e, 0xB0, 6, 24)); } },
  15055. { "Send MOD X as polyphonic aftertouch on", {}, [] (lynx::PluginRef& r) { r.modXAftertouch = true; },
  15056. [&] (const std::vector<Event>& e) { return "aftertouch=" + juce::String (count (e, 0xA0, 69, -1)); } },
  15057. { "Send All Notes Off when playback stops off", {}, [] (lynx::PluginRef& r) { r.allNotesOffOnStop = false; },
  15058. [&] (const std::vector<Event>& e) { return "cc123=" + juce::String (count (e, 0xB0, 123, -1)); } },
  15059. };
  15060. // each phase has its own engine: an engine keeps the running instance across setSong, so one engine would
  15061. // carry the control's plugin into the "before" phase
  15062. lynx::AudioEngine scanner (false);
  15063. auto& host = scanner.getPluginHost();
  15064. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  15065. std::optional<juce::PluginDescription> vst2;
  15066. for (const auto& type : host.getKnownPlugins().getTypes())
  15067. if (type.pluginFormatName == "VST")
  15068. vst2 = type;
  15069. if (! vst2 || logFile.getFullPathName().isEmpty())
  15070. ok = false;
  15071. else
  15072. for (const auto& option : options)
  15073. {
  15074. auto makeSong = [&] (bool changed) {
  15075. auto song = lynx::Song::makeDefault();
  15076. auto& channel = song.channels[0];
  15077. channel.instrument = lynx::InstrumentKind::plugin;
  15078. channel.plugin = {};
  15079. channel.plugin.id = vst2->createIdentifierString().toStdString();
  15080. channel.plugin.name = vst2->name.toStdString();
  15081. if (option.before)
  15082. option.before (channel.plugin);
  15083. if (changed)
  15084. option.change (channel.plugin);
  15085. song.patterns[0].notes.clear();
  15086. lynx::Note note;
  15087. note.start = 0;
  15088. note.length = lynx::ppq;
  15089. note.channel = 0;
  15090. note.key = 69;
  15091. note.velocity = 1.0f;
  15092. note.release = 0.25f; // 32 of 127
  15093. note.modX = 0.75f;
  15094. song.patterns[0].notes.push_back (note);
  15095. for (std::size_t c = 1; c < song.channels.size(); ++c)
  15096. song.channels[c].muted = true;
  15097. return song;
  15098. };
  15099. // a block of the song, then a note held across "playback stopped", as the options act on either
  15100. auto play = [&] (lynx::AudioEngine& engine) {
  15101. logFile.deleteFile();
  15102. engine.renderOffline (1.0, 48000.0);
  15103. if (auto instrument = engine.getChannelInstrument (0))
  15104. {
  15105. instrument->noteOn (60, 1.0f);
  15106. instrument->transportStopped();
  15107. }
  15108. engine.renderOffline (0.1, 48000.0);
  15109. return take();
  15110. };
  15111. auto newEngine = [&] {
  15112. auto engine = std::make_unique<lynx::AudioEngine> (false);
  15113. engine->getPluginHost().addPluginFile (juce::File (pluginPath));
  15114. return engine;
  15115. };
  15116. std::vector<Event> control;
  15117. {
  15118. auto engine = newEngine();
  15119. engine->setSong (makeSong (true));
  15120. control = play (*engine);
  15121. }
  15122. auto engine = newEngine();
  15123. engine->setSong (makeSong (false));
  15124. const auto before = play (*engine);
  15125. const auto instrumentBefore = engine->getChannelInstrument (0).get();
  15126. engine->capturePluginStates(); // as the wrapper page does
  15127. engine->editSong ([&] (lynx::Song& song) { option.change (song.channels[0].plugin); });
  15128. const auto after = play (*engine);
  15129. const auto sameInstance = engine->getChannelInstrument (0).get() == instrumentBefore;
  15130. // the counts differ between phases (how many blocks the note spans, how many instances the phase made):
  15131. // what matters is whether each kind of event is there at all
  15132. auto shape = [] (const juce::String& seen) {
  15133. juce::String out;
  15134. for (const auto& token : juce::StringArray::fromTokens (seen, " ", {}))
  15135. out << token.upToFirstOccurrenceOf ("=", false, false) << (token.fromFirstOccurrenceOf ("=", false, false).getIntValue() > 0 ? "=yes " : "=no ");
  15136. return out;
  15137. };
  15138. auto instances = [] (const std::vector<Event>& events) {
  15139. std::set<juce::String> made;
  15140. for (const auto& e : events)
  15141. made.insert (e.instance);
  15142. return (int) made.size();
  15143. };
  15144. const auto a = option.seen (control) + " instances=" + juce::String (instances (control)),
  15145. b = option.seen (before) + " instances=" + juce::String (instances (before)),
  15146. c = option.seen (after) + " instances=" + juce::String (instances (after));
  15147. const auto visible = shape (option.seen (control)) != shape (option.seen (before));
  15148. const auto works = shape (option.seen (after)) == shape (option.seen (control));
  15149. report << option.name << ": control " << a << " | before " << b << " | after the change " << c << " | same_instance=" << (int) sameInstance
  15150. << " | test_sees_the_option=" << (int) visible << " | " << (! visible ? "NOT PROVEN" : works ? "acts on the plugin" : "DEAD until re-created") << "\n";
  15151. ok = ok && visible && works;
  15152. }
  15153. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  15154. juce::File (reportPath).replaceWithText (report);
  15155. setApplicationReturnValue (ok ? 0 : 1);
  15156. quit();
  15157. }
  15158. // LYNX.exe --wrappershot "LYNX Test Drums.dll" <folder> (round 188d): the wrapper's Processing tab drawn offscreen
  15159. // (no window, no focus) for the FL | LYNX review: wrap-default.png (a fresh plugin), wrap-automap.png (Auto map
  15160. // outputs, output 3 off: FL's shot b23), wrap-settings.png. Scale 1.5 (FL's shots are at 150 %).
  15161. // (round 190oh, --wrappershot190oh: the steps run from a timer, so the editors' windows get their messages)
  15162. struct WrapperShot190oh final : juce::Timer
  15163. {
  15164. std::function<bool()> step; // false: done
  15165. void timerCallback() override
  15166. {
  15167. if (! step())
  15168. stopTimer();
  15169. }
  15170. };
  15171. std::unique_ptr<WrapperShot190oh> wrapperShot190oh;
  15172. void runWrapperShot190oh (const juce::String& pluginPath, const juce::String& folderPath, bool openEditors)
  15173. {
  15174. struct State
  15175. {
  15176. juce::File folder;
  15177. juce::String report;
  15178. bool ok = true;
  15179. std::shared_ptr<lynx::AudioEngine> engine;
  15180. std::optional<juce::PluginDescription> type;
  15181. int phase = 0, wait = 0;
  15182. void expect (const char* name, bool value)
  15183. {
  15184. report << name << "=" << (value ? 1 : 0) << "\n";
  15185. ok = ok && value;
  15186. }
  15187. static lynx::PluginRef* find (lynx::Song& s)
  15188. {
  15189. return s.mixer.size() < 2 || s.mixer[1].effects.empty() ? nullptr : &s.mixer[1].effects[0].plugin;
  15190. }
  15191. std::shared_ptr<lynx::PluginEffect> effect() { return std::dynamic_pointer_cast<lynx::PluginEffect> (engine->getEffect (1, 0)); }
  15192. bool save (const juce::String& name, float scale)
  15193. {
  15194. auto fx = effect();
  15195. if (fx == nullptr)
  15196. return false;
  15197. const auto image = lynx::wrapperSettingsSnapshot (*engine, &State::find, fx->getInstance(), false, 0, scale, 1, 0);
  15198. auto file = folder.getChildFile (name);
  15199. file.deleteFile();
  15200. juce::FileOutputStream out (file);
  15201. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  15202. }
  15203. void open()
  15204. {
  15205. if (auto fx = effect())
  15206. {
  15207. lynx::PluginWindows::WrapperContext context;
  15208. context.engine = engine.get();
  15209. context.find = &State::find;
  15210. context.track = 1;
  15211. context.slot = 0;
  15212. lynx::PluginWindows::open (fx, fx->getInstance(), type->name, context);
  15213. }
  15214. }
  15215. // what the open editor was marked with and (Windows) the DPI awareness of its window and of the windows
  15216. // inside it (the plugin's own)
  15217. void describe (const char* tag)
  15218. {
  15219. auto fx = effect();
  15220. if (fx == nullptr)
  15221. return;
  15222. auto& instance = fx->getInstance();
  15223. auto* editor = instance.getActiveEditor();
  15224. report << tag << ".editor=" << (editor != nullptr ? 1 : 0);
  15225. if (editor != nullptr)
  15226. report << " size=" << editor->getWidth() << "x" << editor->getHeight()
  15227. << " unaware_mark=" << (int) (bool) editor->getProperties()["lynxDpiUnaware"]
  15228. << " dims_mark=" << (int) (bool) editor->getProperties()["lynxScaleEditorDimensions"];
  15229. report << " docked=" << (int) lynx::PluginWindows::isDocked (instance);
  15230. int windows = 0;
  15231. if (const auto unaware = lynx::platform::dpiUnawareWindowCount (lynx::PluginWindows::hostWindowHandle (instance), windows); unaware >= 0)
  15232. {
  15233. report << " windows=" << windows << " unaware_windows=" << unaware;
  15234. expect ((juce::String (tag) + "_unaware_as_set").toRawUTF8(),
  15235. juce::String (tag) == "default" ? unaware == 0 : (windows > 0 && unaware == windows));
  15236. }
  15237. report << "\n";
  15238. lynx::PluginWindows::close (instance);
  15239. }
  15240. void change()
  15241. {
  15242. engine->editSong ([] (lynx::Song& s) {
  15243. s.mixer[1].effects[0].plugin.dpiAware = false;
  15244. s.mixer[1].effects[0].plugin.scaleEditorDimensions = true;
  15245. });
  15246. engine->renderOffline (0.05, 48000.0); // ("DPI aware" reloads the plugin)
  15247. }
  15248. };
  15249. auto st = std::make_shared<State>();
  15250. st->folder = juce::File (folderPath);
  15251. st->folder.createDirectory();
  15252. st->engine = std::make_shared<lynx::AudioEngine> (false);
  15253. st->engine->getPluginHost().addPluginFile (juce::File (pluginPath));
  15254. for (const auto& t : st->engine->getPluginHost().getKnownPlugins().getTypes())
  15255. if (! st->type && (juce::File (t.fileOrIdentifier) == juce::File (pluginPath) || juce::File (pluginPath).isAChildOf (juce::File (t.fileOrIdentifier))
  15256. || juce::File (t.fileOrIdentifier).isAChildOf (juce::File (pluginPath))))
  15257. st->type = t;
  15258. st->expect ("plugin_found", st->type.has_value());
  15259. if (st->type)
  15260. {
  15261. st->report << "plugin=" << st->type->name << " (" << st->type->pluginFormatName << ")\n";
  15262. auto song = lynx::Song::makeDefault();
  15263. auto slot = lynx::makeEffectSlot (lynx::EffectKind::plugin);
  15264. slot.plugin.id = st->type->createIdentifierString().toStdString();
  15265. slot.plugin.name = st->type->name.toStdString();
  15266. song.mixer[1].effects = { slot };
  15267. st->engine->setSong (song);
  15268. st->engine->renderOffline (0.05, 48000.0);
  15269. const auto* ref = State::find (const_cast<lynx::Song&> (st->engine->getSong()));
  15270. st->expect ("fl_defaults", ref != nullptr && ref->dpiAware && ! ref->scaleEditorDimensions);
  15271. st->expect ("shot_default_100", st->save ("gui-default.png", 1.0f));
  15272. st->expect ("shot_default_150", st->save ("gui-default@150.png", 1.5f));
  15273. }
  15274. auto finish = [this, st] {
  15275. st->folder.getChildFile ("report.txt").replaceWithText (st->report + "result=" + (st->ok ? "OK" : "FAIL") + "\n");
  15276. st->engine.reset();
  15277. setApplicationReturnValue (st->ok ? 0 : 1);
  15278. quit();
  15279. };
  15280. if (! st->type || ! openEditors)
  15281. {
  15282. if (st->type)
  15283. {
  15284. st->change();
  15285. st->expect ("shot_changed_100", st->save ("gui-changed.png", 1.0f));
  15286. st->expect ("shot_changed_150", st->save ("gui-changed@150.png", 1.5f));
  15287. }
  15288. finish();
  15289. return;
  15290. }
  15291. // with --open: open the editor (default settings), look after 1 s, close; change; open again, look, close
  15292. wrapperShot190oh = std::make_unique<WrapperShot190oh>();
  15293. wrapperShot190oh->step = [st, finish] {
  15294. if (st->wait-- > 0)
  15295. return true;
  15296. switch (st->phase++)
  15297. {
  15298. case 0: st->open(); st->wait = 10; return true;
  15299. case 1: st->describe ("default"); st->wait = 3; return true;
  15300. case 2:
  15301. st->change();
  15302. st->expect ("shot_changed_100", st->save ("gui-changed.png", 1.0f));
  15303. st->expect ("shot_changed_150", st->save ("gui-changed@150.png", 1.5f));
  15304. st->open();
  15305. st->wait = 10;
  15306. return true;
  15307. case 3: st->describe ("changed"); st->wait = 3; return true;
  15308. default: finish(); return false;
  15309. }
  15310. };
  15311. wrapperShot190oh->startTimer (100);
  15312. }
  15313. void runWrapperShot (const juce::String& pluginPath, const juce::String& folderPath)
  15314. {
  15315. const juce::File folder (folderPath);
  15316. folder.createDirectory();
  15317. auto ok = false;
  15318. lynx::AudioEngine engine (false);
  15319. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  15320. std::optional<juce::PluginDescription> vst2;
  15321. for (const auto& type : engine.getPluginHost().getKnownPlugins().getTypes())
  15322. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  15323. vst2 = type; // (the profile may know other test plugins)
  15324. if (vst2 && ! vst2->isInstrument)
  15325. {
  15326. // an effect (round 188d): on insert 1, with insert 2 routed there as a sidechain (FL's k65 / k78 shots):
  15327. // wrap-fx-default.png, wrap-fx-automap.png (Auto map inputs and outputs)
  15328. auto song = lynx::Song::makeDefault();
  15329. if (song.mixer.size() < 4)
  15330. song.mixer.resize (4);
  15331. auto slot = lynx::makeEffectSlot (lynx::EffectKind::plugin);
  15332. slot.plugin.id = vst2->createIdentifierString().toStdString();
  15333. slot.plugin.name = vst2->name.toStdString();
  15334. song.mixer[1].effects = { slot };
  15335. lynx::mixerops::sidechainTo (song, 2, 1);
  15336. engine.setSong (song);
  15337. engine.renderOffline (0.05, 48000.0);
  15338. if (auto fx = std::dynamic_pointer_cast<lynx::PluginEffect> (engine.getEffect (1, 0)))
  15339. {
  15340. auto find = [] (lynx::Song& s) -> lynx::PluginRef* {
  15341. return s.mixer.size() < 2 || s.mixer[1].effects.empty() ? nullptr : &s.mixer[1].effects[0].plugin;
  15342. };
  15343. auto save = [&] (const char* name) {
  15344. const auto image = lynx::wrapperSettingsSnapshot (engine, find, fx->getInstance(), false, 1, 1.5f, 1, 0);
  15345. juce::FileOutputStream out (folder.getChildFile (name));
  15346. out.setPosition (0);
  15347. out.truncate();
  15348. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  15349. };
  15350. ok = save ("wrap-fx-default.png");
  15351. engine.editSong ([] (lynx::Song& s) {
  15352. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.inputs, 2);
  15353. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.outputs, 2);
  15354. s.mixer[1].effects[0].sidechain = lynx::mixerops::sidechainIndexSource (s, 1, 1);
  15355. });
  15356. ok = ok && save ("wrap-fx-automap.png") && engine.getSong().mixer[1].effects[0].sidechain == 2;
  15357. }
  15358. }
  15359. else if (vst2)
  15360. {
  15361. auto song = lynx::Song::makeDefault();
  15362. auto& channel = song.channels[0];
  15363. channel.instrument = lynx::InstrumentKind::plugin;
  15364. channel.plugin = {};
  15365. channel.plugin.id = vst2->createIdentifierString().toStdString();
  15366. channel.plugin.name = vst2->name.toStdString();
  15367. channel.mixerTrack = 5;
  15368. engine.setSong (song);
  15369. engine.renderOffline (0.05, 48000.0); // (the plugin is hosted by then)
  15370. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  15371. {
  15372. auto find = [] (lynx::Song& s) -> lynx::PluginRef* { return s.channels.empty() ? nullptr : &s.channels[0].plugin; };
  15373. auto save = [&] (const char* name, int tab) {
  15374. const auto image = lynx::wrapperSettingsSnapshot (engine, find, instrument->getInstance(), true, tab, 1.5f);
  15375. juce::FileOutputStream out (folder.getChildFile (name));
  15376. out.setPosition (0);
  15377. out.truncate();
  15378. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  15379. };
  15380. ok = save ("wrap-default.png", 1) && save ("wrap-settings.png", 0);
  15381. engine.editSong ([] (lynx::Song& s) {
  15382. lynx::autoMapOutputs (s.channels[0].plugin.outputs, 8);
  15383. s.channels[0].plugin.outputs.resize (8);
  15384. s.channels[0].plugin.outputs[2].active = 0;
  15385. s.channels[0].plugin.processInactive = false; // (as an LED click does, FL's b23)
  15386. });
  15387. ok = ok && save ("wrap-automap.png", 1);
  15388. }
  15389. }
  15390. setApplicationReturnValue (ok ? 0 : 1);
  15391. quit();
  15392. }
  15393. // LYNX.exe --multiouttest "LYNX Test Drums.dll" report.txt (round 188d, issue #114): a multi-output VST2
  15394. // (tools/testplugin/lynx_test_drums_vst2.c: key 36 = output 1 at 110 Hz, key 37 = output 2 at 220 Hz) on a
  15395. // channel routed to insert 1; the wrapper's Processing › Connections as FL plays them [EXEC fl188d]: every output
  15396. // on the channel's insert by default, an offset to another insert, an inactive output silent, the channel's
  15397. // volume on all of them. Measured on the master with insert 1 muted or not.
  15398. void runMultiOutTest (const juce::String& pluginPath, const juce::String& reportPath)
  15399. {
  15400. juce::String report;
  15401. auto ok = true;
  15402. lynx::AudioEngine scanner (false);
  15403. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  15404. std::optional<juce::PluginDescription> vst2;
  15405. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  15406. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  15407. vst2 = type; // (the profile may know other test plugins)
  15408. struct Case
  15409. {
  15410. const char* name;
  15411. std::vector<lynx::PluginOutputRoute> routes;
  15412. bool muteInsert1;
  15413. float volume;
  15414. bool kick, snare; // expected on the master
  15415. };
  15416. const Case cases[] = {
  15417. { "defaults", {}, false, -1.0f, true, true },
  15418. { "defaults, insert 1 muted", {}, true, -1.0f, false, false },
  15419. { "auto map, insert 1 muted", { { 0, 1 }, { 1, 1 } }, true, -1.0f, false, true },
  15420. { "auto map", { { 0, 1 }, { 1, 1 } }, false, -1.0f, true, true },
  15421. { "output 2 inactive", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, false },
  15422. { "output 1 inactive", { { 0, 0 } }, false, -1.0f, false, true },
  15423. { "auto map, channel volume 0", { { 0, 1 }, { 1, 1 } }, false, 0.0f, false, false },
  15424. { "output 2 inactive, Process inactive inputs and outputs on", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, true },
  15425. };
  15426. auto tone = [] (const std::vector<float>& x, double hz) {
  15427. // Goertzel magnitude over the buffer (normalised to a sine's amplitude)
  15428. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 48000.0;
  15429. double s1 = 0.0, s2 = 0.0;
  15430. for (const auto v : x)
  15431. {
  15432. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  15433. s2 = s1;
  15434. s1 = s0;
  15435. }
  15436. return std::sqrt (s1 * s1 + s2 * s2 - 2.0 * std::cos (w) * s1 * s2) * 2.0 / (double) std::max<std::size_t> (1, x.size());
  15437. };
  15438. if (! vst2)
  15439. ok = false;
  15440. else
  15441. for (const auto& c : cases)
  15442. {
  15443. lynx::AudioEngine engine (false);
  15444. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  15445. auto song = lynx::Song::makeDefault();
  15446. auto& channel = song.channels[0];
  15447. channel.instrument = lynx::InstrumentKind::plugin;
  15448. channel.plugin = {};
  15449. channel.plugin.id = vst2->createIdentifierString().toStdString();
  15450. channel.plugin.name = vst2->name.toStdString();
  15451. channel.plugin.outputs = c.routes;
  15452. // (FL's "Process inactive inputs and outputs" plays an inactive output: off but for the case named so)
  15453. channel.plugin.processInactive = juce::String (c.name).contains ("Process inactive");
  15454. channel.mixerTrack = 1;
  15455. if (c.volume >= 0.0f)
  15456. channel.volume = c.volume;
  15457. for (std::size_t k = 1; k < song.channels.size(); ++k)
  15458. song.channels[k].muted = true;
  15459. if (song.mixer.size() < 4)
  15460. song.mixer.resize (4);
  15461. song.mixer[1].muted = c.muteInsert1;
  15462. song.patterns[0].notes.clear();
  15463. for (const auto key : { 36, 37 })
  15464. {
  15465. lynx::Note note;
  15466. note.start = 0;
  15467. note.length = lynx::ppq;
  15468. note.channel = 0;
  15469. note.key = key;
  15470. note.velocity = 1.0f;
  15471. song.patterns[0].notes.push_back (note);
  15472. }
  15473. engine.setSong (song);
  15474. std::vector<float> master;
  15475. lynx::AudioEngine::RenderOptions options;
  15476. options.seconds = 0.25;
  15477. options.sampleRate = 48000.0;
  15478. options.capture = [&master] (const float* l, const float*, int n) { master.insert (master.end(), l, l + n); };
  15479. engine.renderOffline (options);
  15480. const auto kick = tone (master, 110.0), snare = tone (master, 220.0);
  15481. const auto pass = (kick > 0.01) == c.kick && (snare > 0.01) == c.snare;
  15482. report << c.name << ": kick_110Hz=" << juce::String (kick, 4) << " snare_220Hz=" << juce::String (snare, 4) << " expected kick="
  15483. << (int) c.kick << " snare=" << (int) c.snare << (pass ? " OK" : " FAILED") << "\n";
  15484. ok = ok && pass;
  15485. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  15486. if (&c == &cases[0])
  15487. {
  15488. report << "outputs=" << (int) instrument->outputs().size();
  15489. for (const auto& o : instrument->outputs())
  15490. report << " [" << o.name << " ch" << o.channel << "x" << o.channels << "]";
  15491. report << "\n";
  15492. ok = ok && instrument->outputs().size() == 8 && instrument->outputs()[1].name == "Snare";
  15493. }
  15494. }
  15495. // round 189j: "LYNX Test SC.dll" next to it (tools/testplugin/lynx_test_sc_vst2.c) as an effect on insert 1
  15496. const auto sc = juce::File (pluginPath).getSiblingFile ("LYNX Test SC.dll");
  15497. if (sc.existsAsFile())
  15498. ok = runEffectConnectionsTest (sc, report) && ok;
  15499. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  15500. juce::File (reportPath).replaceWithText (report);
  15501. setApplicationReturnValue (ok ? 0 : 1);
  15502. quit();
  15503. }
  15504. // Round 189j: a hosted effect's Processing › Connections against FL 2026's own renders of the same projects
  15505. // [EXEC fxconn189j: FL /R renders of LYNX's .flp exports, docs/analise/REA_rodada189j.md]. Insert 1: a 440 Hz
  15506. // sampler and "LYNX Test SC" (output 1 = input 1, output 2 = input 2); inserts 2 (1000 Hz) and 3 (1500 Hz) routed
  15507. // to insert 1 at level 0 only; insert 4 a 2500 Hz reference on the Master; insert 1 routed to the Master and at
  15508. // level 0 to inserts 5 (panned left) and 6 (right). Each tone's level per side, in dB from the reference's, must be
  15509. // FL's within 0.5 dB (absent: 50 dB under it).
  15510. bool runEffectConnectionsTest (const juce::File& scFile, juce::String& report)
  15511. {
  15512. lynx::AudioEngine scanner (false);
  15513. scanner.getPluginHost().addPluginFile (scFile);
  15514. std::optional<juce::PluginDescription> sc;
  15515. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  15516. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == scFile)
  15517. sc = type;
  15518. report << "effect_plugin=" << (sc ? sc->name : juce::String ("not found")) << "\n";
  15519. if (! sc)
  15520. return false;
  15521. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-fxconn189j");
  15522. dir.createDirectory();
  15523. const double tones[] = { 440.0, 1000.0, 1500.0, 2500.0 };
  15524. for (const auto hz : tones)
  15525. {
  15526. const auto wav = dir.getChildFile ("sine" + juce::String ((int) hz) + ".wav");
  15527. if (wav.existsAsFile())
  15528. continue;
  15529. juce::AudioBuffer<float> sine (1, 44100 * 3);
  15530. for (int i = 0; i < sine.getNumSamples(); ++i)
  15531. sine.setSample (0, i, 0.25f * (float) std::sin (2.0 * juce::MathConstants<double>::pi * hz * i / 44100.0));
  15532. juce::WavAudioFormat format;
  15533. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  15534. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  15535. {
  15536. out.release();
  15537. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  15538. writer->writeFromAudioSampleBuffer (sine, 0, sine.getNumSamples());
  15539. }
  15540. }
  15541. using Route = lynx::PluginOutputRoute;
  15542. constexpr float none = -999.0f;
  15543. struct Case
  15544. {
  15545. const char* name;
  15546. std::vector<Route> inputs, outputs;
  15547. int tweak; // 1 no Master route, 2 insert 1 fader at 0.4, 3 Process inactive off, 4 Master route level 0, 5 route
  15548. // to 7 too, 6 insert 2 fader at 0.4, 7 insert 2 muted, 8 insert 2 panned left
  15549. float level[3][2]; // 440 / 1000 / 1500 Hz, left / right: dB from the reference, FL's
  15550. };
  15551. const Route d { 0, 1 };
  15552. const Case cases[] = {
  15553. { "e00 FL defaults", { d, d }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  15554. { "e01 input 1 at 1", { { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  15555. { "e02 input 1 at 2", { { 2, 1 } }, {}, 0, { { 0, 0 }, { none, none }, { 0, 0 } } },
  15556. { "e03 input 2 at 1", { d, { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  15557. { "e04 output 2 at 1 (Master)", { d, { 1, 1 } }, { d, { 1, 1 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  15558. { "e05 output 2 at 2 (insert 5)", { d, { 1, 1 } }, { d, { 2, 1 } }, 0, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  15559. { "e06 output 1 at 1", {}, { { 1, 1 } }, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  15560. { "e07 output 2 at 5 (past the list)", { d, { 1, 1 } }, { d, { 5, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  15561. { "e08 inputs 1 and 2 at 1", { { 1, 1 }, { 1, 1 } }, {}, 0, { { none, none }, { 6.1f, 6.1f }, { none, none } } },
  15562. { "e09 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  15563. { "e10 input 1 at 5 (past the list)", { { 5, 1 } }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  15564. { "e11 output 2 at 3 (insert 6)", { d, { 1, 1 } }, { d, { 3, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  15565. { "e13 no Master route, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 1, { { none, none }, { 3.0f, none }, { none, none } } },
  15566. { "e14 insert 1 fader 0.4, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 2, { { -12.7f, -12.7f }, { 0, 0 }, { none, none } } },
  15567. { "e15 input 2 inactive", { d, { 1, 0 } }, { d, d }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  15568. { "e16 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  15569. { "e18 route to 7 too, output 2 at 3", { d, { 1, 1 } }, { d, { 3, 1 } }, 5, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  15570. { "e19 Master route at 0, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 4, { { none, none }, { 0, 0 }, { none, none } } },
  15571. { "e22 input 1 at 1 inactive", { { 1, 0 } }, {}, 3, { { 0, 0 }, { none, none }, { none, none } } },
  15572. { "e23 output 2 at -1, insert 1 fader 0.4", { d, { 1, 1 } }, { d, { -1, 1 } }, 2, { { -12.7f, -12.7f }, { 0, 0 }, { none, none } } },
  15573. { "e24 input 1 at 1, insert 2 fader 0.4", { { 1, 1 } }, {}, 6, { { 0, 0 }, { -12.7f, -12.7f }, { none, none } } },
  15574. { "e25 input 1 at 1, insert 2 muted", { { 1, 1 } }, {}, 7, { { 0, 0 }, { none, none }, { none, none } } },
  15575. { "e26 input 1 at 1, insert 2 panned left", { { 1, 1 } }, {}, 8, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  15576. };
  15577. auto goertzel = [] (const std::vector<float>& x, double hz) {
  15578. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 44100.0;
  15579. double s1 = 0.0, s2 = 0.0;
  15580. for (const auto v : x)
  15581. {
  15582. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  15583. s2 = s1;
  15584. s1 = s0;
  15585. }
  15586. const auto a = std::sqrt (juce::jmax (0.0, s1 * s1 + s2 * s2 - 2.0 * std::cos (w) * s1 * s2)) * 2.0 / (double) std::max<std::size_t> (1, x.size());
  15587. return a > 1e-7 ? 20.0 * std::log10 (a) : -140.0;
  15588. };
  15589. auto ok = true;
  15590. for (const auto& c : cases)
  15591. {
  15592. lynx::AudioEngine engine (false);
  15593. engine.getPluginHost().addPluginFile (scFile);
  15594. auto song = lynx::Song::makeDefault();
  15595. song.bpm = 120.0;
  15596. song.channels.clear();
  15597. song.automations.clear();
  15598. for (auto& p : song.patterns)
  15599. p.notes.clear();
  15600. for (int k = 0; k < 4; ++k)
  15601. {
  15602. lynx::ChannelDef ch;
  15603. ch.name = "S" + std::to_string ((int) tones[k]);
  15604. ch.instrument = lynx::InstrumentKind::sampler;
  15605. ch.samplePath = dir.getChildFile ("sine" + juce::String ((int) tones[k]) + ".wav").getFullPathName().toStdString();
  15606. ch.mixerTrack = k + 1;
  15607. song.channels.push_back (ch);
  15608. lynx::Note note;
  15609. note.start = 0;
  15610. note.length = 8 * lynx::ppq;
  15611. note.channel = k;
  15612. note.key = 60;
  15613. note.velocity = 0.78f;
  15614. song.patterns[0].notes.push_back (note);
  15615. }
  15616. if (song.mixer.size() < 10)
  15617. song.mixer.resize (10);
  15618. for (auto& t : song.mixer)
  15619. {
  15620. t.effects.clear();
  15621. t.sends.clear();
  15622. t.toMaster = true;
  15623. }
  15624. lynx::EffectSlot fx;
  15625. fx.kind = lynx::EffectKind::plugin;
  15626. fx.plugin.id = sc->createIdentifierString().toStdString();
  15627. fx.plugin.name = sc->name.toStdString();
  15628. fx.plugin.inputs = c.inputs;
  15629. fx.plugin.outputs = c.outputs;
  15630. fx.plugin.processInactive = c.tweak != 3;
  15631. auto& one = song.mixer[1];
  15632. one.effects.push_back (fx);
  15633. one.sends = { { 5, 0.0f }, { 6, 0.0f } };
  15634. for (const int t : { 2, 3 })
  15635. {
  15636. song.mixer[(std::size_t) t].toMaster = false;
  15637. song.mixer[(std::size_t) t].sends = { { 1, 0.0f } };
  15638. }
  15639. song.mixer[5].pan = -1.0f;
  15640. song.mixer[6].pan = 1.0f;
  15641. one.toMaster = c.tweak != 1;
  15642. if (c.tweak == 2)
  15643. one.volume = 0.4f;
  15644. if (c.tweak == 4)
  15645. one.masterLevel = 0.0f;
  15646. if (c.tweak == 6)
  15647. song.mixer[2].volume = 0.4f;
  15648. song.mixer[2].muted = c.tweak == 7;
  15649. song.mixer[2].pan = c.tweak == 8 ? -1.0f : 0.0f;
  15650. if (c.tweak == 5)
  15651. {
  15652. one.sends = { { 7, 0.0f }, { 5, 0.0f }, { 6, 0.0f } };
  15653. song.mixer[7].pan = 0.5f;
  15654. }
  15655. // (input 2's index sets the slot's side input source, as the Connections page and the import do)
  15656. if (c.inputs.size() > 1 && c.inputs[1].offset > 0)
  15657. one.effects[0].sidechain = lynx::mixerops::sidechainIndexSource (song, 1, c.inputs[1].offset);
  15658. engine.setSong (song);
  15659. std::vector<float> left, right;
  15660. lynx::AudioEngine::RenderOptions options;
  15661. options.seconds = 1.2;
  15662. options.sampleRate = 44100.0;
  15663. options.capture = [&] (const float* l, const float* r, int n) {
  15664. left.insert (left.end(), l, l + n);
  15665. right.insert (right.end(), r, r + n);
  15666. };
  15667. engine.renderOffline (options);
  15668. const auto from = (std::size_t) 22050, to = (std::size_t) 44100;
  15669. if (right.size() < to)
  15670. {
  15671. report << c.name << ": rendered " << (int) right.size() << " samples FAILED\n";
  15672. ok = false;
  15673. continue;
  15674. }
  15675. const std::vector<float> l (left.begin() + (std::ptrdiff_t) from, left.begin() + (std::ptrdiff_t) to);
  15676. const std::vector<float> r (right.begin() + (std::ptrdiff_t) from, right.begin() + (std::ptrdiff_t) to);
  15677. const auto ref = 0.5 * (goertzel (l, 2500.0) + goertzel (r, 2500.0));
  15678. auto pass = ref > -60.0;
  15679. report << c.name << ": ref=" << juce::String (ref, 1);
  15680. for (int k = 0; k < 3; ++k)
  15681. for (int side = 0; side < 2; ++side)
  15682. {
  15683. const auto got = goertzel (side == 0 ? l : r, tones[k]) - ref;
  15684. const auto want = c.level[k][side];
  15685. const auto good = want == none ? got < -50.0 : std::abs (got - want) < 0.5;
  15686. pass = pass && good;
  15687. report << " " << (int) tones[k] << (side == 0 ? "L" : "R") << "=" << (got < -50.0 ? juce::String ("-") : juce::String (got, 1))
  15688. << (good ? "" : "(FL " + (want == none ? juce::String ("-") : juce::String (want, 1)) + ")");
  15689. }
  15690. report << (pass ? " OK" : " FAILED") << "\n";
  15691. ok = ok && pass;
  15692. }
  15693. return ok;
  15694. }
  15695. // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
  15696. // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
  15697. // that the plugin comes back with the changed parameter.
  15698. void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
  15699. {
  15700. juce::String report;
  15701. bool ok = false;
  15702. {
  15703. lynx::AudioEngine offline (false);
  15704. auto& host = offline.getPluginHost();
  15705. host.addPluginFile (juce::File (pluginPath));
  15706. const juce::PluginDescription* vst3 = nullptr;
  15707. const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
  15708. for (const auto& type : types)
  15709. if (type.pluginFormatName == "VST3" && type.isInstrument)
  15710. vst3 = &type;
  15711. if (vst3 != nullptr)
  15712. {
  15713. juce::String error;
  15714. auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
  15715. auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
  15716. if (parameter != nullptr)
  15717. {
  15718. const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
  15719. parameter->setValueNotifyingHost (target);
  15720. juce::MemoryBlock juceState;
  15721. plugin->getStateInformation (juceState);
  15722. report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
  15723. // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
  15724. std::vector<std::uint8_t> flState;
  15725. auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
  15726. auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
  15727. put32 (id);
  15728. put32 ((std::uint32_t) data.getSize());
  15729. put32 (0);
  15730. flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
  15731. };
  15732. put32 (1);
  15733. record (1, juce::MemoryBlock (64, true));
  15734. // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
  15735. // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
  15736. juce::MemoryBlock slots;
  15737. const auto paramId = [&] (int i) {
  15738. const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
  15739. return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
  15740. };
  15741. const bool reorder = plugin->getParameters().size() >= 3;
  15742. if (reorder)
  15743. {
  15744. for (auto v : { 2u, paramId (2), paramId (0) })
  15745. slots.append (&v, 4);
  15746. report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
  15747. }
  15748. if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
  15749. for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
  15750. if (auto* child = xml->getChildByName (tag))
  15751. {
  15752. juce::MemoryBlock data;
  15753. data.fromBase64Encoding (child->getAllSubText());
  15754. record (id, data);
  15755. report << tag << "_bytes=" << (int) data.getSize() << "\n";
  15756. }
  15757. if (reorder)
  15758. record (4, slots);
  15759. plugin.reset();
  15760. auto song = lynx::Song::makeDefault();
  15761. auto& f = song.channels[4].plugin.foreign;
  15762. f.format = lynx::ForeignPlugin::Format::vst3;
  15763. f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
  15764. f.state = flState;
  15765. {
  15766. std::vector<std::uint8_t> comp, ctrl;
  15767. report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
  15768. << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
  15769. }
  15770. for (int k = 0; k < 3; ++k)
  15771. {
  15772. lynx::Automation a;
  15773. a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
  15774. song.automations.push_back (a);
  15775. }
  15776. const auto adopted = host.adoptFlPlugins (song);
  15777. report << "adopted=" << adopted << "\n";
  15778. juce::String mapped;
  15779. for (const auto& a : song.automations)
  15780. if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
  15781. mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
  15782. report << "slot_positions=" << mapped << "\n";
  15783. const auto slotsOk = ! reorder || mapped == "2,0,1";
  15784. offline.setSong (song);
  15785. if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
  15786. {
  15787. const auto value = loaded->getInstance().getParameters()[0]->getValue();
  15788. report << "restored_value=" << value << "\n";
  15789. ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
  15790. }
  15791. }
  15792. }
  15793. }
  15794. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  15795. juce::File (reportPath).replaceWithText (report);
  15796. setApplicationReturnValue (ok ? 0 : 1);
  15797. quit();
  15798. }
  15799. void runDemoSongs (const juce::String& folderPath)
  15800. {
  15801. const juce::File folder (folderPath);
  15802. folder.createDirectory();
  15803. bool ok = true;
  15804. for (int d = 1; d < lynx::demos::count; ++d)
  15805. {
  15806. juce::String error;
  15807. ok = lynx::ProjectFile::save (lynx::demos::make (d), folder.getChildFile (lynx::demos::fileName (d)), error) && ok;
  15808. }
  15809. setApplicationReturnValue (ok ? 0 : 1);
  15810. quit();
  15811. }
  15812. // --perfgen (round perfgate190id): each synthetic project of the performance gate written as <folder>/<name>.lynx, its
  15813. // audio as 16-bit WAVs in <folder>/<name>/ (written once: the same code makes the same audio). The report gives, per
  15814. // project, the .lynx size, the time to write it (ProjectFile::save, which reads it back) and to read it
  15815. // (ProjectFile::load), the medians of 5, and a hash of its text.
  15816. void runPerfGen (const juce::String& folderPath, const juce::String& reportPath, const juce::String& only)
  15817. {
  15818. const juce::File folder (folderPath);
  15819. folder.createDirectory();
  15820. const auto wanted = juce::StringArray::fromTokens (only, ",", "");
  15821. juce::String report;
  15822. bool ok = true;
  15823. auto median = [] (std::vector<double> v) {
  15824. std::sort (v.begin(), v.end());
  15825. return v[v.size() / 2];
  15826. };
  15827. for (const auto& name : lynx::perfprojects::names())
  15828. {
  15829. if (! wanted.isEmpty() && ! wanted.contains (juce::String (name)))
  15830. continue;
  15831. lynx::Song song;
  15832. lynx::perfprojects::Samples samples;
  15833. const auto audioFolder = folder.getChildFile (juce::String (name));
  15834. lynx::perfprojects::make (name, song, samples, audioFolder.getFullPathName().toStdString());
  15835. for (const auto& [path, data] : samples)
  15836. {
  15837. const juce::File wav { juce::String (path) };
  15838. if (wav.existsAsFile())
  15839. continue;
  15840. wav.getParentDirectory().createDirectory();
  15841. const auto frames = (int) data->frames();
  15842. juce::AudioBuffer<float> audio (2, frames);
  15843. audio.copyFrom (0, 0, data->leftData(), frames);
  15844. audio.copyFrom (1, 0, data->rightData(), frames);
  15845. juce::WavAudioFormat format;
  15846. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  15847. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), data->sampleRate, 2, 16, {}, 0) : nullptr)
  15848. {
  15849. out.release();
  15850. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  15851. ok = writer->writeFromAudioSampleBuffer (audio, 0, frames) && ok;
  15852. }
  15853. else
  15854. ok = false;
  15855. }
  15856. const auto file = folder.getChildFile (juce::String (name) + ".lynx");
  15857. std::vector<double> saveMs, loadMs;
  15858. juce::String error;
  15859. bool loadedOk = true;
  15860. for (int rep = 0; rep < 5; ++rep)
  15861. {
  15862. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  15863. ok = lynx::ProjectFile::save (song, file, error) && ok;
  15864. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  15865. const auto loaded = lynx::ProjectFile::load (file, error);
  15866. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  15867. loadedOk = loadedOk && loaded.has_value() && loaded->channels.size() == song.channels.size()
  15868. && loaded->playlist.size() == song.playlist.size() && loaded->automations.size() == song.automations.size();
  15869. saveMs.push_back (t1 - t0);
  15870. loadMs.push_back (t2 - t1);
  15871. }
  15872. ok = ok && loadedOk;
  15873. const auto text = file.loadFileAsString();
  15874. std::uint64_t h = 1469598103934665603ull;
  15875. for (auto* c = text.toRawUTF8(); *c != 0; ++c)
  15876. h = (h ^ (std::uint8_t) *c) * 1099511628211ull;
  15877. report << name << ": channels=" << (int) song.channels.size() << " inserts=" << (int) song.mixer.size() - 1
  15878. << " clips=" << (int) song.playlist.size() << " automations=" << (int) song.automations.size()
  15879. << " wavs=" << (int) samples.size() << " lynx_kb=" << juce::String ((double) file.getSize() / 1024.0, 1)
  15880. << " save_ms=" << juce::String (median (saveMs), 2) << " load_ms=" << juce::String (median (loadMs), 2)
  15881. << " roundtrip=" << (loadedOk ? "OK" : "FAILED") << " text_hash=" << juce::String::toHexString ((juce::int64) h)
  15882. << (error.isNotEmpty() ? " error=" + error : juce::String()) << "\n";
  15883. }
  15884. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  15885. if (reportPath.isNotEmpty())
  15886. juce::File (reportPath).replaceWithText (report);
  15887. else
  15888. std::fputs (report.toRawUTF8(), stdout);
  15889. setApplicationReturnValue (ok ? 0 : 1);
  15890. quit();
  15891. }
  15892. void runShowcase (const juce::String& outputPath, int currentPattern)
  15893. {
  15894. const auto song = lynx::makeShowcaseSong (currentPattern);
  15895. juce::String error;
  15896. const auto ok = lynx::ProjectFile::save (song, juce::File (outputPath), error);
  15897. setApplicationReturnValue (ok ? 0 : 1);
  15898. quit();
  15899. }
  15900. // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
  15901. // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
  15902. // to check that LYNX keeps going (silence, without waiting longer than the timeout).
  15903. // --sandboxtest: plays an instrument (a note) or an effect (a 440 Hz tone through it); render() adds into l / r
  15904. struct TestVoice
  15905. {
  15906. explicit TestVoice (std::unique_ptr<juce::AudioPluginInstance> p)
  15907. {
  15908. if (p->acceptsMidi() && p->getTotalNumInputChannels() == 0)
  15909. instrument = std::make_unique<lynx::PluginInstrument> (std::move (p), 512);
  15910. else
  15911. effect = std::move (p);
  15912. }
  15913. void noteOn()
  15914. {
  15915. if (instrument != nullptr)
  15916. instrument->noteOn (60, 0.9f);
  15917. }
  15918. void render (float* l, float* r, int n, float gainLeft, float gainRight)
  15919. {
  15920. if (instrument != nullptr)
  15921. {
  15922. instrument->render (l, r, n, gainLeft, gainRight);
  15923. return;
  15924. }
  15925. const auto channels = juce::jmax (2, effect->getTotalNumInputChannels(), effect->getTotalNumOutputChannels());
  15926. juce::AudioBuffer<float> block (channels, 512);
  15927. juce::MidiBuffer midi;
  15928. for (int done = 0; done < n; done += 512)
  15929. {
  15930. const auto k = juce::jmin (512, n - done);
  15931. block.setSize (channels, k, false, false, true);
  15932. for (int i = 0; i < k; ++i)
  15933. {
  15934. const auto v = 0.25f * (float) std::sin (phase);
  15935. phase += 2.0 * juce::MathConstants<double>::pi * 440.0 / 48000.0;
  15936. for (int c = 0; c < channels; ++c)
  15937. block.setSample (c, i, v);
  15938. }
  15939. effect->processBlock (block, midi);
  15940. for (int i = 0; i < k; ++i)
  15941. {
  15942. l[done + i] += gainLeft * block.getSample (0, i);
  15943. r[done + i] += gainRight * block.getSample (1, i);
  15944. }
  15945. }
  15946. }
  15947. void release()
  15948. {
  15949. instrument.reset();
  15950. effect.reset();
  15951. }
  15952. std::unique_ptr<lynx::PluginInstrument> instrument;
  15953. std::unique_ptr<juce::AudioPluginInstance> effect;
  15954. double phase = 0.0;
  15955. };
  15956. void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
  15957. {
  15958. juce::String report;
  15959. bool ok = false;
  15960. lynx::setPluginSandboxAlerts (false);
  15961. const juce::File log (reportPath + ".log");
  15962. auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
  15963. log.deleteFile();
  15964. {
  15965. lynx::PluginHost host (false);
  15966. host.addPluginFile (juce::File (pluginPath));
  15967. const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
  15968. // the file's instrument, else its first effect (round 161: effects too, e.g. a Windows effect through yabridge)
  15969. const juce::PluginDescription* instrument = nullptr;
  15970. for (const auto& type : types)
  15971. if (type.isInstrument)
  15972. instrument = &type;
  15973. for (const auto& type : types)
  15974. if (instrument == nullptr && ! type.isInstrument)
  15975. instrument = &type;
  15976. step ("host");
  15977. juce::String error;
  15978. auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
  15979. report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
  15980. step ("created");
  15981. if (remote != nullptr)
  15982. {
  15983. auto& proxy = *remote;
  15984. TestVoice voice (std::move (remote));
  15985. std::vector<float> l (48000), r (48000);
  15986. auto peakOf = [&] {
  15987. float peak = 0.0f;
  15988. for (std::size_t k = 0; k < l.size(); ++k)
  15989. peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
  15990. return peak;
  15991. };
  15992. const auto start = juce::Time::getMillisecondCounterHiRes();
  15993. voice.noteOn();
  15994. voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  15995. const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
  15996. const auto peak = peakOf();
  15997. step ("played");
  15998. if (juce::JUCEApplication::getCommandLineParameters().contains ("--expect-crash"))
  15999. {
  16000. // a plugin that crashes while playing (round 161 test plugin): LYNX notices, mutes it and keeps running
  16001. const auto dead = lynx::isSandboxedPluginDead (proxy);
  16002. std::fill (l.begin(), l.end(), 0.0f);
  16003. std::fill (r.begin(), r.end(), 0.0f);
  16004. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  16005. report << "peak=" << peak << " render_1s_ms=" << renderMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
  16006. ok = dead && peak > 1e-4f && renderMs < 2000.0 && peakOf() == 0.0f;
  16007. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  16008. juce::File (reportPath).replaceWithText (report);
  16009. setApplicationReturnValue (ok ? 0 : 1);
  16010. quit();
  16011. return;
  16012. }
  16013. report << "plugin=" << proxy.getName() << (instrument->isInstrument ? " (instrument)" : " (effect)") << " parameters="
  16014. << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
  16015. if (juce::JUCEApplication::getCommandLineParameters().contains ("--editor") && proxy.hasEditor())
  16016. {
  16017. // the plugin's own window, opened by the child process (4 s on screen); the child must stay responsive
  16018. std::unique_ptr<juce::AudioProcessorEditor> editor (proxy.createEditorIfNeeded());
  16019. juce::Thread::sleep (4000);
  16020. juce::MemoryBlock state;
  16021. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  16022. proxy.getStateInformation (state);
  16023. report << "editor_shown=1 state_with_editor_ms=" << (juce::Time::getMillisecondCounterHiRes() - t0) << " dead=" << (lynx::isSandboxedPluginDead (proxy) ? 1 : 0) << "\n";
  16024. editor.reset();
  16025. }
  16026. // parameter -> state -> in-process plugin
  16027. bool stateOk = false;
  16028. if (! proxy.getParameters().isEmpty())
  16029. {
  16030. auto* p = proxy.getParameters()[0];
  16031. const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
  16032. p->setValue (target);
  16033. std::fill (l.begin(), l.end(), 0.0f);
  16034. voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
  16035. juce::MemoryBlock state;
  16036. proxy.getStateInformation (state);
  16037. if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  16038. {
  16039. local->setStateInformation (state.getData(), (int) state.getSize());
  16040. const auto back = local->getParameters()[0]->getValue();
  16041. // the same steps without the sandbox: some plugins quantise the value or keep it out of their state
  16042. auto control = target;
  16043. if (auto a = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  16044. {
  16045. a->enableAllBuses();
  16046. a->prepareToPlay (48000.0, 512);
  16047. a->getParameters()[0]->setValue (target);
  16048. juce::AudioBuffer<float> block (juce::jmax (2, a->getTotalNumInputChannels(), a->getTotalNumOutputChannels()), 512);
  16049. block.clear();
  16050. juce::MidiBuffer none;
  16051. a->processBlock (block, none);
  16052. juce::MemoryBlock direct;
  16053. a->getStateInformation (direct);
  16054. if (auto b = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  16055. {
  16056. b->setStateInformation (direct.getData(), (int) direct.getSize());
  16057. control = b->getParameters()[0]->getValue();
  16058. }
  16059. a->releaseResources();
  16060. }
  16061. report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << " in_process_control=" << control << "\n";
  16062. stateOk = std::abs (back - control) < 0.02f;
  16063. }
  16064. }
  16065. step ("state");
  16066. // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
  16067. lynx::hangSandboxedPluginForTest (proxy);
  16068. juce::Thread::sleep (200);
  16069. std::fill (l.begin(), l.end(), 1.0f);
  16070. std::fill (r.begin(), r.end(), 1.0f);
  16071. const auto hangStart = juce::Time::getMillisecondCounterHiRes();
  16072. voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
  16073. std::fill (l.begin(), l.end(), 0.0f);
  16074. std::fill (r.begin(), r.end(), 0.0f);
  16075. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  16076. const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
  16077. const auto dead = lynx::isSandboxedPluginDead (proxy);
  16078. const auto hangPeak = peakOf();
  16079. report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << hangPeak << "\n";
  16080. // crashed child (round 161): a second instance aborts; LYNX notices, mutes it and keeps running
  16081. bool crashOk = false;
  16082. if (auto second = lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error))
  16083. {
  16084. auto& proxy2 = *second;
  16085. TestVoice voice2 (std::move (second));
  16086. voice2.noteOn();
  16087. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  16088. lynx::crashSandboxedPluginForTest (proxy2);
  16089. const auto crashStart = juce::Time::getMillisecondCounterHiRes();
  16090. while (! lynx::isSandboxedPluginDead (proxy2) && juce::Time::getMillisecondCounterHiRes() - crashStart < 5000.0)
  16091. {
  16092. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  16093. juce::Thread::sleep (5);
  16094. }
  16095. const auto crashMs = juce::Time::getMillisecondCounterHiRes() - crashStart;
  16096. std::fill (l.begin(), l.end(), 0.0f);
  16097. std::fill (r.begin(), r.end(), 0.0f);
  16098. voice2.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  16099. const auto crashDead = lynx::isSandboxedPluginDead (proxy2);
  16100. report << "crash_ms=" << crashMs << " crash_dead=" << (crashDead ? 1 : 0) << " crash_peak_after=" << peakOf() << "\n";
  16101. crashOk = crashDead && crashMs < 3000.0;
  16102. // issue #159: freeing the crashed plugin doesn't wait on its pipe (JUCE waited up to 10 s there for
  16103. // the gone child, on the message thread when the rack freed it); its teardown ends on its own
  16104. const auto freeStart = juce::Time::getMillisecondCounterHiRes();
  16105. voice2.release();
  16106. const auto freeMs = juce::Time::getMillisecondCounterHiRes() - freeStart;
  16107. const auto endedAll = lynx::finishSandboxTeardowns (15000);
  16108. report << "crashed_free_ms=" << freeMs << " teardown_done=" << (endedAll ? 1 : 0) << "\n";
  16109. crashOk = crashOk && freeMs < 250.0 && endedAll;
  16110. }
  16111. step ("crash");
  16112. ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && hangPeak == 0.0f && crashOk;
  16113. }
  16114. }
  16115. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  16116. juce::File (reportPath).replaceWithText (report);
  16117. setApplicationReturnValue (ok ? 0 : 1);
  16118. quit();
  16119. }
  16120. // --timertest (round 174f): a view's polling timer follows the view and its parents, and survives a minimised window
  16121. void runTimerTest (const juce::File& report)
  16122. {
  16123. struct Ticks final : juce::Timer
  16124. {
  16125. void timerCallback() override {}
  16126. } timer;
  16127. juce::Component top, parent, view;
  16128. parent.addChildComponent (view);
  16129. top.addChildComponent (parent);
  16130. top.setSize (320, 200);
  16131. lynx::ui::TimerWhileShowing watch (view, timer, 30);
  16132. juce::String text;
  16133. auto failures = 0;
  16134. auto expect = [&] (const char* step, bool running) {
  16135. const auto ok = timer.isTimerRunning() == running;
  16136. failures += ok ? 0 : 1;
  16137. text << step << ": timer " << (timer.isTimerRunning() ? "running" : "stopped") << (ok ? "" : " FAIL") << "\n";
  16138. };
  16139. expect ("never shown", false);
  16140. view.setVisible (true);
  16141. parent.setVisible (true);
  16142. expect ("view and parent visible, not on the desktop", false);
  16143. top.addToDesktop (juce::ComponentPeer::windowHasTitleBar);
  16144. top.setVisible (true);
  16145. expect ("window shown", true);
  16146. parent.setVisible (false);
  16147. expect ("parent hidden", false);
  16148. parent.setVisible (true);
  16149. expect ("parent shown", true);
  16150. view.setVisible (false);
  16151. expect ("view hidden", false);
  16152. top.getPeer()->setMinimised (true);
  16153. view.setVisible (true);
  16154. expect ("view shown while minimised", true);
  16155. top.getPeer()->setMinimised (false);
  16156. expect ("window restored", true);
  16157. top.setVisible (false);
  16158. expect ("window hidden", false);
  16159. top.setVisible (true);
  16160. expect ("window shown again", true);
  16161. top.removeFromDesktop();
  16162. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  16163. report.replaceWithText (text);
  16164. setApplicationReturnValue (failures == 0 ? 0 : 1);
  16165. quit();
  16166. }
  16167. // --cachetest (round 174f): PlaylistComponent::cacheSelfTest on the project, the Playlist off screen at 1466 x 930
  16168. void runCacheTest (const juce::File& project, const juce::File& report)
  16169. {
  16170. engine = std::make_unique<lynx::AudioEngine>();
  16171. juce::String error;
  16172. auto ok = false;
  16173. // (round 190nq: a Live set, FL Studio Mobile project or DAWproject takes the same import, issue #193's set)
  16174. if (project.hasFileExtension ("flp;als;flm;dawproject"))
  16175. ok = engine->importFlpFile (project, error);
  16176. else if (auto song = lynx::ProjectFile::load (project, error))
  16177. {
  16178. engine->setSong (std::move (*song));
  16179. ok = true;
  16180. }
  16181. juce::String text = "project: " + project.getFullPathName() + "\n";
  16182. if (ok)
  16183. {
  16184. text << "video tracks: " << (int) engine->getSong().videoTracks.size() << "\n";
  16185. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  16186. playlist->setBounds (0, 0, 1466, 930);
  16187. playlist->setVisible (true);
  16188. text << playlist->cacheSelfTest ([] { lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000); }, report.getParentDirectory());
  16189. }
  16190. else
  16191. text << "result=ERROR " << error << "\n";
  16192. report.replaceWithText (text);
  16193. setApplicationReturnValue (ok && text.contains ("result=OK") ? 0 : 1);
  16194. quit();
  16195. }
  16196. // --picturetest (round 190bm): ui/PictureCheck.h on the Playlist and the Mixer, at a window's usual size, at a 4K
  16197. // screen's, and wider than a GPU bitmap can be (16384 px)
  16198. void runPictureTest (const juce::File& report, const juce::File& project)
  16199. {
  16200. engine = std::make_unique<lynx::AudioEngine>();
  16201. juce::String error, text;
  16202. if (project != juce::File())
  16203. {
  16204. auto ok = false;
  16205. if (project.hasFileExtension ("flp"))
  16206. ok = engine->importFlpFile (project, error);
  16207. else if (auto song = lynx::ProjectFile::load (project, error))
  16208. {
  16209. engine->setSong (std::move (*song));
  16210. ok = true;
  16211. }
  16212. text << "project: " << project.getFullPathName() << (ok ? "" : " (not loaded: " + error + ")") << "\n";
  16213. }
  16214. #if JUCE_WINDOWS
  16215. text << "native image: " << juce::NativeImageType().create (juce::Image::RGB, 8, 8, true)->createType()->getTypeID()
  16216. << " (software = " << juce::SoftwareImageType().getTypeID() << ")\n";
  16217. #endif
  16218. auto failures = 0;
  16219. struct Size
  16220. {
  16221. int width, height;
  16222. std::vector<float> scales;
  16223. };
  16224. const auto folder = report.getParentDirectory();
  16225. for (const auto& size : { Size { 1466, 930, { 1.0f, 1.5f, 2.0f, 3.0f } }, Size { 3840, 2040, { 1.0f, 2.0f } }, Size { 17000, 700, { 1.0f } } })
  16226. {
  16227. const auto label = [&size] (const char* name) { return juce::String (name) + " " + juce::String (size.width) + " x " + juce::String (size.height); };
  16228. {
  16229. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  16230. playlist->setBounds (0, 0, size.width, size.height);
  16231. playlist->setVisible (true);
  16232. {
  16233. juce::Image warm (juce::Image::RGB, 64, 64, true); // (one paint asks for the waveforms, then they are waited for)
  16234. juce::Graphics g (warm);
  16235. playlist->paintEntireComponent (g, true);
  16236. }
  16237. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  16238. text << lynx::ui::picturecheck::run (*playlist, label ("Playlist"), size.scales, failures, folder);
  16239. }
  16240. {
  16241. auto mixer = std::make_unique<lynx::MixerComponent> (*engine);
  16242. mixer->setBounds (0, 0, size.width, juce::jmin (size.height, 700));
  16243. mixer->setVisible (true);
  16244. text << lynx::ui::picturecheck::run (*mixer, label ("Mixer"), size.scales, failures, folder);
  16245. }
  16246. }
  16247. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  16248. report.replaceWithText (text);
  16249. setApplicationReturnValue (failures == 0 ? 0 : 1);
  16250. quit();
  16251. }
  16252. // --uiperf (round 161): opens the project in the normal window, plays it, and drives the heavy UI cases of round 151
  16253. // through the window's own event path — the default layout, the Mixer maximised (meters while playing, then
  16254. // scrolled), the Playlist maximised (scroll down, scroll sideways, zoom in and out) and the Channel rack scrolled.
  16255. // Every frame is painted right after its event (ComponentPeer::performAnyPendingRepaintsNow) and timed; the report
  16256. // has, per case, the time to show it and the frames' mean / p95 / max, how many took longer than 16 ms, and the
  16257. // process CPU. The same on every OS, so Linux (X11, XWayland) and Windows numbers can be put side by side.
  16258. void runUiPerf (const juce::File& project, const juce::File& report)
  16259. {
  16260. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  16261. lynx::crashguard::startMainProfiler (profile.toStdString()); // (stopped in shutdown)
  16262. startupOptions = lynx::StartupOptions::load();
  16263. engine = std::make_unique<lynx::AudioEngine>();
  16264. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  16265. crashEngine = engine.get();
  16266. createMainWindow();
  16267. mainWindow->reveal();
  16268. // LYNX_UIPERF_SIZE=WxH, LYNX_UIPERF_SCALE=<percent> (round 179a): a large window, a HiDPI desktop's scale
  16269. if (const auto scale = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SCALE", {}).getIntValue(); scale > 0)
  16270. juce::Desktop::getInstance().setGlobalScaleFactor ((float) scale / 100.0f);
  16271. if (const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SIZE", {}), "x", ""); size.size() == 2)
  16272. mainWindow->setBounds (0, 0, size[0].getIntValue(), size[1].getIntValue());
  16273. juce::String error;
  16274. auto ok = false;
  16275. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  16276. if (project.hasFileExtension ("flp;als;flm;band;blx")) // (round 190gr: a Live set, its Session clips in the grid)
  16277. ok = engine->importFlpFile (project, error);
  16278. else if (auto song = lynx::ProjectFile::load (project, error))
  16279. {
  16280. engine->setSong (std::move (*song));
  16281. ok = true;
  16282. }
  16283. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  16284. if (! ok)
  16285. {
  16286. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  16287. setApplicationReturnValue (1);
  16288. quit();
  16289. return;
  16290. }
  16291. // LYNX_UIPERF_STANDIN=1 (round 190qe): no audio device here (Xvfb under WSL): the self-tests' stand-in device plays the
  16292. // song, so the "playing" steps move (the playhead of UX-A10's check above all)
  16293. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_STANDIN", {}) == "1" && engine->getDeviceManager().getCurrentAudioDevice() == nullptr)
  16294. if (const auto e = engine->openStandInDevice (48000.0, 512); e.isNotEmpty())
  16295. std::fprintf (stderr, "uiperf: stand-in device: %s\n", e.toRawUTF8());
  16296. // LYNX_UIPERF_MUTE=1: the Master fader down (the meters of the inserts still move): a run on a desktop someone uses
  16297. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_MUTE", {}) == "1")
  16298. engine->editSong ([] (lynx::Song& s) { if (! s.mixer.empty()) s.mixer[0].volume = 0.0f; }, false);
  16299. struct Step
  16300. {
  16301. juce::String name;
  16302. std::function<void()> setup;
  16303. std::function<void (int)> action; // per frame; none: the step watches the window for `frames` ms
  16304. int frames;
  16305. std::function<juce::String()> finish = {}; // round 173f: after the step, its own lines for the report
  16306. };
  16307. struct UiPerf final : juce::Timer
  16308. {
  16309. LynxApplication& app;
  16310. juce::File report;
  16311. juce::String text;
  16312. std::vector<Step> steps;
  16313. std::size_t step = 0;
  16314. int frame = -1;
  16315. std::vector<double> times, rendered; // whole frames (event + paint + blit, when this timer paints) / the window's paints
  16316. std::vector<double> frames; // round 173f: the time of every frame the window painted (ui/FrameProbe.h)
  16317. double paintedPixels = 0.0; // round 190ge: the dirty area of those frames, summed (overdraw / repaint storms)
  16318. double setupMs = 0.0, wallStart = 0.0;
  16319. double cpuStart = 0.0; // process CPU seconds (std::clock is wall time on Windows)
  16320. bool threadsWanted = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_THREADS", {}) == "1";
  16321. std::vector<lynx::ThreadCpu> threadsStart;
  16322. double messageCpuStart = 0.0; // the message thread's CPU seconds
  16323. // round 190jx: LYNX_UIPERF_PEER_PID=<pid> (Linux): another process's CPU over each step too (the X server, which
  16324. // draws the overlay's marks there)
  16325. int peerPid = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_PEER_PID", "0").getIntValue();
  16326. double peerCpuStart = 0.0;
  16327. static double peerCpuSeconds (int pid)
  16328. {
  16329. if (pid <= 0)
  16330. return 0.0;
  16331. const auto stat = juce::File ("/proc/" + juce::String (pid) + "/stat").loadFileAsString();
  16332. const auto fields = juce::StringArray::fromTokens (stat.fromLastOccurrenceOf (")", false, false), " ", "");
  16333. // (after the name: state is field 0, utime 11, stime 12, in clock ticks)
  16334. return fields.size() > 12 ? (fields[11].getDoubleValue() + fields[12].getDoubleValue()) / 100.0 : 0.0;
  16335. }
  16336. int presentsStart = 0; // round 190jy: Direct2D presents of every LYNX window (Windows)
  16337. double audioLoadSum = 0.0; // the device's CPU use (AudioDeviceManager::getCpuUsage), summed per tick
  16338. int audioLoadTicks = 0;
  16339. // round 190kb: exact CPU cycles, the worker pool's waiting, the callbacks' deadlines, the Direct2D presents
  16340. std::uint64_t cyclesStart = 0;
  16341. lynx::WorkerPool::Stats poolStart;
  16342. lynx::RtStats::Snapshot rtStart; // (presentsStart: 190jy's, above)
  16343. std::map<std::string, std::pair<long long, long long>> tickersStart; // round 190kr
  16344. int coveredStart = 0;
  16345. // round 190os: LYNX_UIPERF_STALLS=<folder>, each step's wall-clock thread samples and frame times there
  16346. // (crashguard::startStallSampler; perf190os/s/stalls.py)
  16347. juce::String stallsFolder = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_STALLS", {});
  16348. UiPerf (LynxApplication& a, juce::File r) : app (a), report (std::move (r))
  16349. {
  16350. lynx::WorkerPool::nameCurrentThread ("LYNX message thread"); // (round 190kb: the threads' lines)
  16351. }
  16352. juce::ComponentPeer* peer() const { return app.mainWindow != nullptr ? app.mainWindow->getPeer() : nullptr; }
  16353. double paintNow() const
  16354. {
  16355. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  16356. if (auto* p = peer())
  16357. p->performAnyPendingRepaintsNow();
  16358. return juce::Time::getMillisecondCounterHiRes() - t0;
  16359. }
  16360. void timerCallback() override
  16361. {
  16362. if (step >= steps.size())
  16363. {
  16364. stopTimer();
  16365. finish();
  16366. return;
  16367. }
  16368. auto& s = steps[step];
  16369. if (frame < 0)
  16370. {
  16371. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  16372. if (s.setup)
  16373. s.setup();
  16374. paintNow();
  16375. setupMs = juce::Time::getMillisecondCounterHiRes() - t0;
  16376. times.clear();
  16377. rendered.clear();
  16378. frames.clear();
  16379. paintedPixels = 0.0;
  16380. wallStart = juce::Time::getMillisecondCounterHiRes();
  16381. cpuStart = lynx::processCpuSeconds();
  16382. messageCpuStart = lynx::threadCpuSeconds();
  16383. peerCpuStart = peerCpuSeconds (peerPid);
  16384. // round 190os: LYNX_UIPERF_UIPRIO="<priority>[,m]" — the UI's helper threads (Direct2D's swap chain
  16385. // waiters, the vblank and timer threads; with ",m" the message thread too) at that Windows thread
  16386. // priority, for the stall A/B
  16387. if (const auto prio = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_UIPRIO", {}); prio.isNotEmpty())
  16388. text << " (UI threads at priority " << prio.getIntValue() << ": "
  16389. << lynx::setThreadPriorities ({ "swap chain", "VBlank", "Timer" }, prio.endsWith (",m"), prio.getIntValue()) << " set)\n";
  16390. // LYNX_UIPERF_DRVPRIO=<priority>: the graphics driver's own threads in this process (NVIDIA, AMD, Intel)
  16391. if (const auto prio = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DRVPRIO", {}); prio.isNotEmpty())
  16392. text << " (driver threads at priority " << prio.getIntValue() << ": "
  16393. << lynx::setThreadPriorities ({ "module:nvwgf2um", "module:amdxx", "module:atidxx", "module:igd10", "module:igd12" }, false, prio.getIntValue()) << " set)\n";
  16394. if (stallsFolder.isNotEmpty())
  16395. lynx::crashguard::startStallSampler ({ "swap chain", "VBlank", "Timer" }, 2000, &app.engine->getOverloadGuard().stateTag());
  16396. presentsStart = uiPerfPresents();
  16397. if (threadsWanted) // round 190ih: LYNX_UIPERF_THREADS=1, the CPU of every thread over the step
  16398. threadsStart = lynx::threadCpuList();
  16399. lynx::grossBeatPaintStats (true);
  16400. cyclesStart = lynx::processCpuCycles();
  16401. tickersStart = lynx::ui::FrameTicker::perOwner();
  16402. coveredStart = lynx::nativechild::coveredSkips().load();
  16403. if (const auto* pool = app.engine->getWorkerPool())
  16404. poolStart = pool->stats();
  16405. rtStart = app.engine->getRtStats().snapshot();
  16406. audioLoadSum = 0.0;
  16407. audioLoadTicks = 0;
  16408. frame = 0;
  16409. return;
  16410. }
  16411. audioLoadSum += app.engine->getDeviceManager().getCpuUsage();
  16412. ++audioLoadTicks;
  16413. if (s.action)
  16414. s.action (frame);
  16415. if (const auto ms = paintNow(); ms > 0.25) // (nothing to paint: not a frame)
  16416. times.push_back (ms);
  16417. ++frame;
  16418. if (s.action ? frame < s.frames : juce::Time::getMillisecondCounterHiRes() - wallStart < (double) s.frames)
  16419. return;
  16420. const auto wall = juce::Time::getMillisecondCounterHiRes() - wallStart;
  16421. const auto cpu = 1000.0 * (lynx::processCpuSeconds() - cpuStart);
  16422. const auto messageCpu = 1000.0 * (lynx::threadCpuSeconds() - messageCpuStart);
  16423. text << s.name << ": show " << juce::String (setupMs, 1) << " ms\n"
  16424. << " painted frames: " << stats (rendered) << "\n"
  16425. << " timed here (event + paint + blit): " << stats (times)
  16426. << "\n window frames (probe): " << lynx::ui::FrameStats::of (frames, wall).describe()
  16427. << ", painted " << juce::String (wall > 0.0 ? paintedPixels / wall / 1000.0 : 0.0, 2) << " Mpx/s"
  16428. << "\n CPU " << juce::String (wall > 0.0 ? 100.0 * cpu / wall : 0.0, 0) << "% (process, " << juce::String (wall / 1000.0, 1) << " s), message thread "
  16429. << juce::String (wall > 0.0 ? 100.0 * messageCpu / wall : 0.0, 1) << "%, audio device "
  16430. << juce::String (audioLoadTicks > 0 ? 100.0 * audioLoadSum / audioLoadTicks : 0.0, 1) << "%\n";
  16431. if (peerPid > 0 && wall > 0.0)
  16432. text << " peer process " << peerPid << " CPU " << juce::String (100.0 * 1000.0 * (peerCpuSeconds (peerPid) - peerCpuStart) / wall, 1) << "%\n";
  16433. // round 190jy: every LYNX window's Direct2D presents (the main window's and each native child's) and how
  16434. // the docked LYNX editors were drawn
  16435. {
  16436. int native = 0, inMain = 0, hidden = 0;
  16437. for (auto* w : lynx::dockedEditorWindows())
  16438. if (w != nullptr)
  16439. (! w->isVisible() ? hidden : lynx::isEditorInMainWindow (*w) ? inMain : native) += 1;
  16440. text << " presents " << juce::String (wall > 0.0 ? 1000.0 * (uiPerfPresents() - presentsStart) / wall : 0.0, 1)
  16441. << "/s; docked editors: " << native << " own windows, " << inMain << " in the main window, " << hidden << " hidden\n";
  16442. }
  16443. const auto cycleRate = lynx::cpuCyclesPerSecond();
  16444. if (cycleRate > 0.0 && wall > 0.0)
  16445. text << " CPU cycles " << juce::String (100.0 * (double) (lynx::processCpuCycles() - cyclesStart) / cycleRate / (wall / 1000.0), 1)
  16446. << "% (process, exact); presents " << juce::String (1000.0 * (uiPerfPresents() - presentsStart) / wall, 1) << "/s\n";
  16447. if (const auto* pool = app.engine->getWorkerPool(); pool != nullptr && wall > 0.0)
  16448. {
  16449. // round 190kb: per second of the step (time in ms/s = tenths of a percent of one core)
  16450. const auto p = pool->stats();
  16451. const auto& a = poolStart;
  16452. const auto perS = [wall] (std::uint64_t v) { return juce::String (1000.0 * (double) v / wall, 0); };
  16453. const auto msS = [wall] (std::uint64_t ns) { return juce::String ((double) ns / 1.0e6 * 1000.0 / wall, 2); };
  16454. text << " pool: rounds " << perS (p.rounds - a.rounds) << "/s; workers work " << msS (p.workNs - a.workNs)
  16455. << " ms/s, spin " << msS (p.spinNs - a.spinNs) << " ms/s (" << perS (p.spins - a.spins) << "/s: found "
  16456. << perS (p.spinFound - a.spinFound) << ", parked " << perS (p.spinParked - a.spinParked) << ", timed out "
  16457. << perS (p.spinTimedOut - a.spinTimedOut) << "), sleeps " << perS (p.sleeps - a.sleeps) << "/s (early "
  16458. << perS (p.earlyWakes - a.earlyWakes) << "); waits " << msS (p.waitNs - a.waitNs) << " ms/s (" << perS (p.waits - a.waits)
  16459. << "/s, yields " << perS (p.waitYields - a.waitYields) << ", sleeps " << perS (p.waitSleeps - a.waitSleeps) << " = " << msS (p.waitSleepNs - a.waitSleepNs) << " ms/s"
  16460. << "); caller wait " << msS (p.callerWaitNs - a.callerWaitNs) << " ms/s (sleeps " << perS (p.callerSleeps - a.callerSleeps) << "/s)\n";
  16461. }
  16462. {
  16463. const auto r = app.engine->getRtStats().snapshot();
  16464. text << " callbacks " << juce::String ((juce::int64) (r.callbacks - rtStart.callbacks)) << ", over the deadline "
  16465. << juce::String ((juce::int64) (r.overBudget - rtStart.overBudget)) << ", 80-100 % " << juce::String ((juce::int64) (r.nearBudget - rtStart.nearBudget))
  16466. << ", late " << juce::String ((juce::int64) (r.lateCalls - rtStart.lateCalls)) << "\n";
  16467. // round 190ok (P24): Settings › Audio › "Safe overloads" (core/OverloadGuard.h), since the start
  16468. const auto& guard = app.engine->getOverloadGuard();
  16469. text << " safe overloads " << (guard.isEnabled() ? "on" : "off") << ": engaged " << (juce::int64) guard.timesEngaged()
  16470. << " times" << (guard.engaged() ? " (now)" : "") << ", yielded " << juce::String (guard.yieldedMs(), 0) << " ms"
  16471. // round 190px: the render-ahead thread's catch-up paced while the UI starved
  16472. << ", render-ahead paced " << (juce::int64) guard.timesPaced() << " times (" << juce::String (guard.pacedMs(), 0) << " ms)";
  16473. // round 190os: the last release in this step — why, and how long after the callbacks kept their
  16474. // deadline again
  16475. if (const auto at = guard.lastReleaseAtMs(); at >= wallStart && guard.lastReleaseReason() != lynx::OverloadGuard::notReleased)
  16476. {
  16477. const char* why[] { "", "the transport stopped", "the load dropped", "a probe passed" };
  16478. text << "; let go " << juce::String (at - wallStart, 0) << " ms into the step (" << why[juce::jlimit (0, 3, guard.lastReleaseReason())]
  16479. << ", " << juce::String (guard.lastReleaseLagMs(), 0) << " ms after the callbacks kept their deadline)";
  16480. }
  16481. text << "\n";
  16482. }
  16483. if (threadsWanted && wall > 0.0)
  16484. {
  16485. // (round 190kb: and each thread's exact cycles in brackets, as % of one core; sorted by them where known)
  16486. std::vector<std::pair<double, juce::String>> rows;
  16487. for (const auto& t : lynx::threadCpuList())
  16488. {
  16489. auto before = 0.0;
  16490. std::uint64_t cyclesBefore = 0;
  16491. for (const auto& b : threadsStart)
  16492. if (b.id == t.id)
  16493. before = b.seconds, cyclesBefore = b.cycles;
  16494. const auto used = t.seconds - before;
  16495. const auto exact = cycleRate > 0.0 ? 100.0 * (double) (t.cycles - cyclesBefore) / cycleRate / (wall / 1000.0) : -1.0;
  16496. if (used > 0.0005 || exact > 0.05)
  16497. rows.push_back ({ exact >= 0.0 ? exact : 100.0 * 1000.0 * used / wall,
  16498. juce::String (t.id) + " " + (t.name.empty() ? juce::String ("(unnamed)") : juce::String (t.name)) + " "
  16499. + juce::String (100.0 * 1000.0 * used / wall, 1) + "%" + (exact >= 0.0 ? " [" + juce::String (exact, 1) + "%]" : juce::String()) });
  16500. }
  16501. std::sort (rows.begin(), rows.end(), [] (const auto& a, const auto& b) { return a.first > b.first; });
  16502. text << " threads:";
  16503. for (std::size_t k = 0; k < rows.size() && k < 16; ++k)
  16504. text << " " << rows[k].second << ";";
  16505. text << "\n";
  16506. }
  16507. if (const auto gb = lynx::grossBeatPaintStats (false); gb.isNotEmpty())
  16508. text << " " << gb << "\n";
  16509. // round 190kr: LYNX_UIPERF_TICKERS=1, the live views' frame steps per second (run / moved) and the steps
  16510. // left out because the view's docked panel was covered
  16511. if (lynx::ui::FrameTicker::perOwnerWanted() && wall > 0.0)
  16512. {
  16513. text << " tickers:";
  16514. for (const auto& [name, counts] : lynx::ui::FrameTicker::perOwner())
  16515. {
  16516. const auto before = tickersStart.count (name) != 0 ? tickersStart.at (name) : std::pair<long long, long long> {};
  16517. if (counts.first != before.first)
  16518. text << " " << juce::String (name).fromLastOccurrenceOf ("::", false, false).retainCharacters ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_")
  16519. << " " << juce::String (1000.0 * (double) (counts.first - before.first) / wall, 0) << "/" << juce::String (1000.0 * (double) (counts.second - before.second) / wall, 0);
  16520. }
  16521. text << "; covered skips " << juce::String (1000.0 * (double) (lynx::nativechild::coveredSkips().load() - coveredStart) / wall, 0) << "/s\n";
  16522. }
  16523. if (stallsFolder.isNotEmpty())
  16524. {
  16525. juce::File (stallsFolder).createDirectory();
  16526. lynx::crashguard::stopStallSampler (juce::File (stallsFolder).getChildFile ("stall-" + juce::String ((int) step) + ".txt").getFullPathName().toStdString());
  16527. juce::String list;
  16528. for (const auto t : frames)
  16529. list << juce::String (t, 3) << "\n";
  16530. juce::File (stallsFolder).getChildFile ("frames-" + juce::String ((int) step) + ".txt").replaceWithText (list);
  16531. text << " stall samples: " << stallsFolder << " (step " << (int) step << ")\n";
  16532. }
  16533. if (s.finish)
  16534. text << s.finish();
  16535. juce::File (report).replaceWithText (text);
  16536. ++step;
  16537. frame = -1;
  16538. }
  16539. static juce::String stats (std::vector<double> sorted)
  16540. {
  16541. std::sort (sorted.begin(), sorted.end());
  16542. const auto at = [&sorted] (double q) { return sorted.empty() ? 0.0 : sorted[(std::size_t) juce::jlimit (0, (int) sorted.size() - 1, (int) (q * (double) sorted.size()))]; };
  16543. double sum = 0.0;
  16544. int over = 0;
  16545. for (auto t : sorted)
  16546. {
  16547. sum += t;
  16548. over += t > 16.0 ? 1 : 0;
  16549. }
  16550. return juce::String ((int) sorted.size()) + ", mean " + juce::String (sorted.empty() ? 0.0 : sum / (double) sorted.size(), 1)
  16551. + " ms, p95 " + juce::String (at (0.95), 1) + " ms, max " + juce::String (sorted.empty() ? 0.0 : sorted.back(), 1)
  16552. + " ms, >16 ms " + juce::String (over);
  16553. }
  16554. void finish()
  16555. {
  16556. // the cost of asking where the mouse is (X11: a round trip to the display server)
  16557. const auto q0 = juce::Time::getMillisecondCounterHiRes();
  16558. for (int i = 0; i < 100; ++i)
  16559. juce::ignoreUnused (juce::Desktop::getInstance().getMainMouseSource().getScreenPosition());
  16560. text << "mouse position query: " << juce::String ((juce::Time::getMillisecondCounterHiRes() - q0) / 100.0, 3) << " ms\n";
  16561. app.mainWindow->onFrame = nullptr;
  16562. app.mainWindow->watchFrames ({});
  16563. app.engine->stop();
  16564. text << "result=OK\n";
  16565. report.replaceWithText (text);
  16566. app.setApplicationReturnValue (0);
  16567. app.quit();
  16568. }
  16569. };
  16570. auto* ui = &mainWindow->getContent();
  16571. auto wheelAt = [this] (juce::Component& target, float dx, float dy, juce::ModifierKeys mods) {
  16572. auto* peer = mainWindow->getPeer();
  16573. if (peer == nullptr || ! target.isShowing())
  16574. return;
  16575. juce::ModifierKeys::currentModifiers = mods;
  16576. const auto local = peer->globalToLocal (target.localPointToGlobal (target.getLocalBounds().getCentre()).toFloat());
  16577. juce::MouseWheelDetails wheel { dx, dy, false, false, false };
  16578. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  16579. juce::ModifierKeys::currentModifiers = {};
  16580. };
  16581. auto run = std::make_unique<UiPerf> (*this, report);
  16582. mainWindow->onFrame = [r = run.get()] (double ms) { if (r->frame >= 0) r->rendered.push_back (ms); };
  16583. // round 173f: every frame the window paints; a fader drag's moves count as shown when a frame covers the fader
  16584. auto drag = std::make_shared<UiPerfDrag>();
  16585. mainWindow->watchFrames ([r = run.get(), drag] (double now, juce::Rectangle<int> area) {
  16586. if (r->frame >= 0)
  16587. {
  16588. r->frames.push_back (now);
  16589. r->paintedPixels += (double) area.getWidth() * (double) area.getHeight();
  16590. }
  16591. drag->framePainted (now, area);
  16592. });
  16593. run->text << "project: " << project.getFullPathName() << "\n"
  16594. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  16595. << juce::SystemStats::getCpuModel() << ", window " << mainWindow->getWidth() << "x" << mainWindow->getHeight()
  16596. << ", scale " << juce::String (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
  16597. ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale : 1.0, 2)
  16598. << ", audio device " << (engine->getDeviceManager().getCurrentAudioDevice() != nullptr ? engine->getDeviceManager().getCurrentAudioDevice()->getName() : juce::String ("none")) << "\n"
  16599. << "load " << juce::String (loadMs / 1000.0, 2) << " s\n";
  16600. const auto none = juce::ModifierKeys();
  16601. // discussion #10 (round 173f): the reporter's screen — the Channel Rack and the Mixer open, the pattern playing —
  16602. // watched as it is, then insert 3's fader dragged up and down with the mouse (125 moves a second through the
  16603. // window's own mouse path, the frames painted as the window paints them)
  16604. const auto dragTrack = engine->getSong().mixer.size() > 3 ? 3 : 1;
  16605. run->steps.push_back ({ "rack + mixer, pattern playing", [this, ui] {
  16606. ui->showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  16607. engine->getTransport().songMode = false;
  16608. engine->rewind();
  16609. engine->play();
  16610. }, {}, 4000 });
  16611. run->steps.push_back ({ "fader drag by mouse, rack + mixer, pattern playing", [this, ui, drag, dragTrack] {
  16612. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  16613. const auto rail = strips.faderRailForSnapshot (dragTrack);
  16614. drag->start (*mainWindow, strips, rail, engine.get(), dragTrack);
  16615. }, {}, 3000, [drag] { return drag->stop(); } });
  16616. run->steps.push_back ({ "song stopped during the drag", {}, {}, 500, [drag] { return drag->release(); } });
  16617. run->steps.push_back ({ "after the drag (released)", {}, {}, 600, [drag] { return drag->released(); } });
  16618. run->steps.push_back ({ "desktop, playing", [this, ui] { ui->showDesktopForSnapshot (false); engine->rewind(); engine->play(); }, {}, 3000 });
  16619. run->steps.push_back ({ "mixer maximised, playing", [ui] { ui->selectTabForSnapshot (3); }, {}, 3000 });
  16620. // round 177a: only the meters move, so the strips' picture must stay valid, also with a folded group's tab and VCA
  16621. // strips on screen (their levels are drawn over the picture, like the inserts' meters)
  16622. run->steps.push_back ({ "mixer meters over the picture, playing", [this, ui] {
  16623. ui->selectTabForSnapshot (3);
  16624. engine->getTransport().songMode = false;
  16625. engine->rewind();
  16626. engine->play();
  16627. ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  16628. }, {}, 6000, [this, ui, report] {
  16629. const auto [spoiled, refills] = ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  16630. if (juce::FileOutputStream out (report.withFileExtension ("png")); out.openedOk())
  16631. {
  16632. out.setPosition (0);
  16633. out.truncate();
  16634. juce::PNGImageFormat().writeImageToStream (mainWindow->createComponentSnapshot (mainWindow->getLocalBounds()), out);
  16635. }
  16636. return juce::String (" mixer picture: spoiled ") + juce::String (spoiled) + " times, drawn again " + juce::String (refills) + " times\n";
  16637. } });
  16638. // (round 190my: the wheel goes to a strip's blank body near the Mixer's centre — since 293333ae6's Current strip the
  16639. // centre itself can be a control, which the wheel would turn instead of scrolling; trace 190my: the strips then
  16640. // move from x -56 to -325 in a 1113 px view. Strips that fit their view can't scroll: the step uses Extra large
  16641. // then, e.g. at a wide window.)
  16642. auto scrollLayout = std::make_shared<std::optional<lynx::mixerlayout::Layout>>();
  16643. auto scrollTrace = std::make_shared<juce::String>();
  16644. run->steps.push_back ({ "mixer scroll",
  16645. [ui, scrollLayout, scrollTrace] {
  16646. scrollTrace->clear();
  16647. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  16648. const auto* holder = strips.getParentComponent();
  16649. if (holder != nullptr && strips.getWidth() <= holder->getWidth() + 200)
  16650. {
  16651. *scrollLayout = lynx::MixerStrips::layout;
  16652. strips.setLayout (lynx::mixerlayout::Layout::extraLarge);
  16653. }
  16654. },
  16655. [this, ui, scrollTrace] (int f) {
  16656. auto& mixer = ui->getMixerForSnapshot();
  16657. auto& strips = mixer.getStripsForSnapshot();
  16658. auto* peer = mainWindow->getPeer();
  16659. if (peer == nullptr || ! strips.isShowing())
  16660. return;
  16661. const auto centre = strips.getLocalPoint (&mixer, mixer.getLocalBounds().getCentre());
  16662. const auto at = strips.wheelScrollPointForPerf (centre, strips.getParentComponent() != nullptr
  16663. ? strips.getLocalArea (strips.getParentComponent(), strips.getParentComponent()->getLocalBounds())
  16664. : strips.getLocalBounds());
  16665. const auto local = peer->globalToLocal (strips.localPointToGlobal (at).toFloat());
  16666. juce::ModifierKeys::currentModifiers = {};
  16667. juce::MouseWheelDetails wheel { 0.0f, f < 30 ? -0.25f : 0.25f, false, false, false };
  16668. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  16669. if (f == 0 || f == 29)
  16670. {
  16671. auto* under = peer->getComponent().getComponentAt (local.roundToInt());
  16672. const auto* holder = strips.getParentComponent();
  16673. *scrollTrace << " mixer scroll frame " << f << ": wheel at " << at.toString() << " (strips), under it "
  16674. << (under == &strips ? juce::String ("the strips") : under != nullptr ? juce::String (typeid (*under).name()) : juce::String ("nothing"))
  16675. << ", view " << (holder != nullptr ? holder->getBounds().toString() : juce::String()) << ", strips at x " << strips.getX() << "\n";
  16676. }
  16677. }, 60,
  16678. [ui, scrollLayout, scrollTrace] {
  16679. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  16680. const auto width = strips.getWidth();
  16681. juce::String used = scrollLayout->has_value() ? "Extra large (the strips fit the view in their layout)" : "the project's layout";
  16682. if (scrollLayout->has_value())
  16683. strips.setLayout (**scrollLayout);
  16684. scrollLayout->reset();
  16685. return juce::String (" mixer scroll: strips ") + juce::String (width) + " px, " + used + "\n" + *scrollTrace;
  16686. } });
  16687. // a fader dragged while the song plays (round 171c, discussion #10): 4 mouse moves per frame on insert 1's fader,
  16688. // through the old path (a whole snapshot per move) and through editLevels
  16689. auto faderMove = [this] (bool levels, int f) {
  16690. for (int k = 0; k < 4; ++k)
  16691. {
  16692. const auto v = 0.5f + 0.3f * std::sin ((float) (f * 4 + k) * 0.05f);
  16693. const auto edit = [v] (lynx::Song& s) { if (s.mixer.size() > 1) s.mixer[1].volume = v; };
  16694. if (levels)
  16695. engine->editLevels (edit, false); // (no undo step: in a real drag only the press saves one)
  16696. else
  16697. engine->editSong (edit, false);
  16698. }
  16699. };
  16700. run->steps.push_back ({ "mixer fader drag, playing, rebuild per move (before 171c)", {}, [faderMove] (int f) { faderMove (false, f); }, 60 });
  16701. run->steps.push_back ({ "mixer fader drag, playing, live levels (171c)", {}, [faderMove, this] (int f) { faderMove (true, f); if (f == 59) engine->flushLevels(); }, 60 });
  16702. // F8's Plugin picker (round 171c): opening it (the "show" time = building it + its first paint), its pictures
  16703. // loading while it stays open, pointing at the tiles, then closing it
  16704. run->steps.push_back ({ "plugin picker open (F8)", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 2500 });
  16705. run->steps.push_back ({ "plugin picker, pointing at tiles", {}, [ui] (int f) {
  16706. // (round 175b: the picker is its own window)
  16707. if (auto* picker = ui->pluginPickerForSnapshot(); picker != nullptr && picker->getPeer() != nullptr)
  16708. {
  16709. const auto p = picker->localPointToGlobal (juce::Point<int> (60 + (f * 37) % juce::jmax (1, picker->getWidth() - 120),
  16710. 90 + (f * 53) % juce::jmax (1, picker->getHeight() - 200)));
  16711. const auto local = picker->getPeer()->globalToLocal (p.toFloat());
  16712. picker->getPeer()->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, {}, 0.0f, 0.0f,
  16713. juce::Time::currentTimeMillis());
  16714. }
  16715. }, 60 });
  16716. run->steps.push_back ({ "plugin picker close", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 300 });
  16717. run->steps.push_back ({ "playlist maximised, playing", [ui] { ui->selectTabForSnapshot (2); }, {}, 3000 });
  16718. run->steps.push_back ({ "playlist scroll down/up", [this] { engine->stop(); },
  16719. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
  16720. run->steps.push_back ({ "playlist scroll sideways", {},
  16721. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
  16722. // round 174f: Ctrl+wheel zoom, a notch every third frame (~20 a second), three in then three out, as dupmon drives it
  16723. run->steps.push_back ({ "playlist zoom (Ctrl+wheel)", {},
  16724. [wheelAt, ui] (int f) {
  16725. if (f % 3 == 0)
  16726. wheelAt (ui->getPlaylistForSnapshot(), 0.0f, (f / 9) % 2 == 0 ? 0.15f : -0.15f, juce::ModifierKeys (juce::ModifierKeys::ctrlModifier));
  16727. }, 120 });
  16728. run->steps.push_back ({ "playlist after the zoom (settles)", {}, {}, 500 });
  16729. // round 190qe (TOP-NEXT R1): "edgescroll" — a clip held 20 px past the Playlist's right edge for 2 s: the view runs on
  16730. // the view's frames at FL's speed (Pattern layout: ≈ 223 px/s), so the window's frames a second are the display's rate
  16731. // (compare "playlist maximised, playing"); the move is undone after. "UX-A10" — the overview strip's window dragged
  16732. // sideways for 5 s while the song plays: the playhead drawn must move every frame (no stall, then jump, as FL's)
  16733. {
  16734. struct FeelPerf
  16735. {
  16736. double startScroll = 0.0, startMs = 0.0, ppt = 1.0;
  16737. juce::Point<int> press, held;
  16738. std::vector<double> playheads;
  16739. int stalls = 0, longestStall = 0, run = 0;
  16740. };
  16741. auto feel = std::make_shared<FeelPerf>();
  16742. auto inject = [this] (juce::Component& target, juce::Point<int> p, bool down) {
  16743. auto* peer = mainWindow->getPeer();
  16744. if (peer == nullptr)
  16745. return;
  16746. const auto mods = down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys();
  16747. juce::ModifierKeys::currentModifiers = mods;
  16748. const auto local = peer->globalToLocal (target.localPointToGlobal (p).toFloat());
  16749. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, mods, juce::MouseInputSource::defaultPressure,
  16750. juce::MouseInputSource::defaultOrientation, juce::Time::currentTimeMillis());
  16751. };
  16752. run->steps.push_back ({ "playlist edgescroll: a clip held 20 px past the right edge (2 s)", [this, ui, feel, inject] {
  16753. engine->stop();
  16754. ui->selectTabForSnapshot (2);
  16755. auto& pl = ui->getPlaylistForSnapshot();
  16756. const auto grid = pl.gridAreaForSnapshot();
  16757. // the first clip at least 24 px wide fully in view
  16758. const auto& list = engine->getSong().playlist;
  16759. for (int i = 0; i < (int) list.size(); ++i)
  16760. if (const auto b = pl.clipBoundsForSnapshot (i); b.getWidth() >= 24 && grid.contains (b) && b.getHeight() >= 12)
  16761. {
  16762. feel->press = { b.getX() + 12, b.getBottom() - 4 };
  16763. break;
  16764. }
  16765. feel->held = { grid.getRight() - 1 + 20, feel->press.y };
  16766. feel->startScroll = pl.viewNowForTests().scroll;
  16767. feel->ppt = pl.viewNowForTests().pixelsPerUnit;
  16768. inject (pl, feel->press, false);
  16769. inject (pl, feel->press, true);
  16770. inject (pl, { (feel->press.x + feel->held.x) / 2, feel->press.y }, true);
  16771. inject (pl, feel->held, true);
  16772. feel->startMs = juce::Time::getMillisecondCounterHiRes();
  16773. }, {}, 2000, [this, ui, feel, inject] {
  16774. auto& pl = ui->getPlaylistForSnapshot();
  16775. const auto ms = juce::Time::getMillisecondCounterHiRes() - feel->startMs;
  16776. const auto moved = (pl.viewNowForTests().scroll - feel->startScroll) * feel->ppt;
  16777. inject (pl, feel->held, false);
  16778. juce::ModifierKeys::currentModifiers = {};
  16779. engine->undo();
  16780. return " edge scroll: " + juce::String (moved, 0) + " px in " + juce::String (ms / 1000.0, 2) + " s = "
  16781. + juce::String (ms > 0.0 ? 1000.0 * moved / ms : 0.0, 0) + " px/s (FL's law 20 px out: 223 px/s; press at "
  16782. + feel->press.toString() + ")\n";
  16783. } });
  16784. run->steps.push_back ({ "playlist overview drag while playing (UX-A10, 5 s)", [this, ui, feel, inject] {
  16785. ui->selectTabForSnapshot (2);
  16786. auto& pl = ui->getPlaylistForSnapshot();
  16787. pl.setViewForSnapshot (64.0, 0, 0);
  16788. engine->getTransport().songMode = true;
  16789. engine->rewind();
  16790. engine->play();
  16791. auto& strip = pl.overviewForSnapshot();
  16792. const auto w = strip.windowAreaForSnapshot();
  16793. feel->press = pl.getLocalPoint (&strip, juce::Point<int> ((int) w.getCentreX(), (int) w.getCentreY()));
  16794. feel->playheads.clear();
  16795. feel->stalls = feel->longestStall = feel->run = 0;
  16796. inject (pl, feel->press, false);
  16797. inject (pl, feel->press, true);
  16798. },
  16799. [ui, feel, inject] (int f) {
  16800. auto& pl = ui->getPlaylistForSnapshot();
  16801. // 2 px a frame to the right for 2.5 s, then back
  16802. const auto dx = f < 150 ? 2 * f : 2 * (300 - f);
  16803. inject (pl, feel->press.translated (dx, 0), true);
  16804. const auto now = pl.playheadTickForSnapshot();
  16805. if (! feel->playheads.empty() && now == feel->playheads.back())
  16806. {
  16807. feel->longestStall = juce::jmax (feel->longestStall, ++feel->run);
  16808. ++feel->stalls;
  16809. }
  16810. else
  16811. feel->run = 0;
  16812. feel->playheads.push_back (now);
  16813. }, 300, [this, ui, feel, inject] {
  16814. auto& pl = ui->getPlaylistForSnapshot();
  16815. inject (pl, feel->press, false);
  16816. juce::ModifierKeys::currentModifiers = {};
  16817. engine->stop();
  16818. const auto ok = feel->longestStall < 2;
  16819. return " UX-A10: " + juce::String ((int) feel->playheads.size()) + " frames, the playhead stood still on "
  16820. + juce::String (feel->stalls) + " (longest run " + juce::String (feel->longestStall) + " frames) "
  16821. + (ok ? "OK" : "STALLS") + "\n";
  16822. } });
  16823. }
  16824. run->steps.push_back ({ "whole window repainted", {}, [this] (int) { mainWindow->repaint(); }, 40 });
  16825. run->steps.push_back ({ "channel rack scroll", [ui] { ui->selectTabForSnapshot (0); },
  16826. [wheelAt, ui, none] (int f) { wheelAt (ui->getRackViewportForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  16827. // round 190ge: the other main views while the pattern plays, then every view with the transport stopped and
  16828. // nothing moving (an idle view should paint nothing: its frames and painted area are the repaint storms), then
  16829. // the Clip-launch grid playing
  16830. auto playPattern = [this] {
  16831. engine->getTransport().songMode = false;
  16832. engine->rewind();
  16833. engine->play();
  16834. };
  16835. run->steps.push_back ({ "piano roll maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (1); playPattern(); }, {}, 3000 });
  16836. // round 190jx: the moving playheads alone, for the overlay's A/B (LYNX_UIPERF_ONLY="overlay A/B", LYNX_OVERLAY=0|1):
  16837. // the Playlist with the song playing and the Piano roll with the pattern playing, LYNX_UIPERF_PLAY_MS each (10 s)
  16838. {
  16839. const auto playMs = juce::jmax (1000, juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_PLAY_MS", "10000").getIntValue());
  16840. run->steps.push_back ({ "overlay A/B: playlist maximised, song playing", [this, ui] {
  16841. ui->selectTabForSnapshot (2);
  16842. engine->getTransport().songMode = true;
  16843. engine->rewind();
  16844. engine->play();
  16845. }, {}, playMs });
  16846. // round 190ok (P24): LYNX_UIPERF_RECOVERY=1 — the song stopped after it, 3 s: the safe-overload guard lets go
  16847. // and the callbacks keep their deadline again (the report's "safe overloads" line: no "(now)")
  16848. // (round 190os: and when the guard let go after the stop was asked)
  16849. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_RECOVERY", "0") == "1")
  16850. {
  16851. auto stopAt = std::make_shared<double> (0.0);
  16852. run->steps.push_back ({ "overlay A/B: playlist maximised, stopped after the song (recovery)", [this, stopAt] {
  16853. *stopAt = juce::Time::getMillisecondCounterHiRes();
  16854. engine->stop();
  16855. }, {}, 3000, [this, stopAt] {
  16856. const auto& guard = engine->getOverloadGuard();
  16857. const auto at = guard.lastReleaseAtMs();
  16858. return at >= *stopAt && guard.lastReleaseReason() != lynx::OverloadGuard::notReleased
  16859. ? " safe overloads let go " + juce::String (at - *stopAt, 1) + " ms after the stop\n"
  16860. : juce::String (" safe overloads: not let go after the stop\n");
  16861. } });
  16862. }
  16863. // round 190os: LYNX_UIPERF_LOAD_ENDS=<ms> — the song played again, and that many ms in every note and every
  16864. // playlist clip removed while the transport keeps running: the notes stop, the tails die out and the overload ends while playing.
  16865. // The report's "safe overloads" line says when the guard let go after the callbacks kept their deadline.
  16866. if (const auto endsMs = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_LOAD_ENDS", "0").getIntValue(); endsMs > 0)
  16867. {
  16868. auto emptiedAt = std::make_shared<double> (0.0);
  16869. run->steps.push_back ({ "overlay A/B: playlist maximised, the load ends while playing", [this, ui, endsMs, emptiedAt] {
  16870. ui->selectTabForSnapshot (2);
  16871. engine->getTransport().songMode = true;
  16872. engine->rewind();
  16873. engine->play();
  16874. juce::Timer::callAfterDelay (endsMs, [this, emptiedAt] {
  16875. *emptiedAt = juce::Time::getMillisecondCounterHiRes();
  16876. engine->editSong ([] (lynx::Song& song) {
  16877. for (auto& pattern : song.patterns)
  16878. pattern.notes.clear();
  16879. song.playlist.clear(); // (its audio and automation clips too)
  16880. }, false);
  16881. });
  16882. }, {}, endsMs + 4000, [this, emptiedAt] {
  16883. const auto& guard = engine->getOverloadGuard();
  16884. const auto at = guard.lastReleaseAtMs();
  16885. const auto playing = engine->getTransport().playing.load();
  16886. engine->stop();
  16887. return " notes removed (still playing: " + juce::String (playing ? "yes" : "no") + "); safe overloads "
  16888. + (at >= *emptiedAt && *emptiedAt > 0.0 ? "let go " + juce::String (at - *emptiedAt, 0) + " ms after it, "
  16889. + juce::String (guard.lastReleaseLagMs(), 0) + " ms after the callbacks kept their deadline\n"
  16890. : juce::String ("not let go after it\n"));
  16891. } });
  16892. }
  16893. run->steps.push_back ({ "overlay A/B: piano roll maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (1); playPattern(); }, {}, playMs,
  16894. [this] { engine->stop(); return juce::String(); } });
  16895. }
  16896. run->steps.push_back ({ "channel rack maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (0); playPattern(); }, {}, 3000 });
  16897. const char* idleViews[] { "channel rack", "piano roll", "playlist", "mixer" };
  16898. for (int view = 0; view < 4; ++view)
  16899. run->steps.push_back ({ juce::String ("idle: ") + idleViews[view] + ", stopped", [this, ui, view] { engine->stop(); ui->selectTabForSnapshot (view); }, {}, 3000 });
  16900. run->steps.push_back ({ "idle: desktop, stopped", [this, ui] { engine->stop(); ui->showDesktopForSnapshot (false); }, {}, 3000 });
  16901. // round 190im (R1, DE-124): the automation editor window open over the Playlist, stopped and then playing (its
  16902. // timer only while it plays, its playhead columns only); closed after
  16903. {
  16904. int automation = -1;
  16905. for (const auto& c : engine->getSong().playlist)
  16906. if (c.kind == lynx::ClipKind::automation && c.automation >= 0 && automation < 0)
  16907. automation = c.automation;
  16908. if (automation >= 0)
  16909. {
  16910. run->steps.push_back ({ "automation editor open, stopped", [this, ui, automation] {
  16911. engine->stop();
  16912. ui->selectTabForSnapshot (2);
  16913. lynx::openAutomationEditor (*engine, automation);
  16914. }, {}, 3000 });
  16915. run->steps.push_back ({ "automation editor open, song playing", [this] {
  16916. engine->getTransport().songMode = true;
  16917. engine->rewind();
  16918. engine->play();
  16919. }, {}, 3000, [this] {
  16920. engine->stop();
  16921. auto& desktop = juce::Desktop::getInstance();
  16922. for (int i = desktop.getNumComponents(); --i >= 0;)
  16923. if (auto* w = dynamic_cast<juce::DocumentWindow*> (desktop.getComponent (i)); w != nullptr && w->getName().startsWith ("Automation - "))
  16924. w->closeButtonPressed();
  16925. return juce::String();
  16926. } });
  16927. }
  16928. }
  16929. run->steps.push_back ({ "clip grid, song playing", [this, ui] {
  16930. ui->selectTabForSnapshot (2);
  16931. ui->setClipLaunchWorkflow (true);
  16932. ui->setClipGridView (lynx::PlaylistArea::GridView::grid);
  16933. engine->getTransport().songMode = true;
  16934. engine->rewind();
  16935. engine->play();
  16936. }, {}, 3000 });
  16937. // round 190gr: the grid's clips launched (every scene that has clips, one after the other: the playing cells'
  16938. // progress bars move, the launches blink until their grid point)
  16939. run->steps.push_back ({ "clip grid, clips launched", [this] {
  16940. engine->getTransport().songMode = true;
  16941. if (const auto& grid = engine->getSong().clipGrid)
  16942. for (int scene = 0; scene < juce::jmin (8, (int) grid->scenes.size()); ++scene)
  16943. engine->launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, scene });
  16944. }, {}, 3000, [this] {
  16945. int playing = 0;
  16946. if (const auto* state = engine->launcherState())
  16947. for (const auto& t : state->tracks)
  16948. playing += t.playing.load() >= 0 ? 1 : 0;
  16949. engine->launcherCommand ({ lynx::launcher::Command::Type::stopAll });
  16950. return " tracks playing a clip: " + juce::String (playing) + "\n";
  16951. } });
  16952. run->steps.push_back ({ "idle: clip grid, stopped", [this] { engine->stop(); }, {}, 3000, [ui] { ui->setClipLaunchWorkflow (false); return juce::String(); } });
  16953. // round 190jn: the Clip-launch layout's Arrangement (Live's look: 19 px lanes, colour blocks, dark waveforms) playing,
  16954. // then idle
  16955. run->steps.push_back ({ "clip arrangement, song playing", [this, ui] {
  16956. ui->selectTabForSnapshot (2);
  16957. ui->setClipLaunchWorkflow (true);
  16958. ui->setClipGridView (lynx::PlaylistArea::GridView::song);
  16959. engine->getTransport().songMode = true;
  16960. engine->rewind();
  16961. engine->play();
  16962. }, {}, 3000 });
  16963. run->steps.push_back ({ "idle: clip arrangement, stopped", [this] { engine->stop(); }, {}, 3000, [ui] {
  16964. ui->setClipGridView (lynx::PlaylistArea::GridView::grid);
  16965. ui->setClipLaunchWorkflow (false);
  16966. return juce::String();
  16967. } });
  16968. // round 190ih: the plugin windows with live parts — Gross Beat (its locator), the Formula Controller (its monitor),
  16969. // the Envelope Controller (its meters and key line) — idle with the song stopped, then Gross Beat while it plays
  16970. // (CPU and frames; the windows are their own, so the main window's painted area stays the main window's)
  16971. run->steps.push_back ({ "idle: Gross Beat + Formula + Envelope controller windows, stopped", [this] {
  16972. engine->stop();
  16973. auto& song = engine->getSong();
  16974. int gbTrack = -1, gbSlot = -1;
  16975. for (int t = 0; t < (int) song.mixer.size() && gbTrack < 0; ++t)
  16976. for (int k = 0; k < (int) song.mixer[(std::size_t) t].effects.size(); ++k)
  16977. if (song.mixer[(std::size_t) t].effects[(std::size_t) k].kind == lynx::EffectKind::grossBeat)
  16978. {
  16979. gbTrack = t;
  16980. gbSlot = k;
  16981. break;
  16982. }
  16983. const auto last = (int) song.mixer.size() - 1;
  16984. const auto formulaSlot = last >= 1 ? (int) song.mixer[(std::size_t) last].effects.size() : -1;
  16985. engine->editSong ([last] (lynx::Song& s) {
  16986. if (last >= 1 && s.mixer[(std::size_t) last].effects.size() < (std::size_t) lynx::maxEffectSlots)
  16987. s.mixer[(std::size_t) last].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::formulaController));
  16988. lynx::ChannelDef env;
  16989. env.name = "Envelope Controller";
  16990. env.instrument = lynx::InstrumentKind::controller;
  16991. env.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  16992. s.channels.push_back (env);
  16993. }, false);
  16994. engine->dispatchPendingMessages();
  16995. // LYNX_UIPERF_WINDOWS: which of them (G Gross Beat, F Formula, E Envelope Controller; default all)
  16996. const auto which = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_WINDOWS", "GFE");
  16997. if (gbTrack >= 0 && which.containsChar ('G'))
  16998. lynx::NativeEffectWindows::open (*engine, gbTrack, gbSlot);
  16999. if (formulaSlot >= 0 && which.containsChar ('F'))
  17000. lynx::FormulaControllerWindows::open (*engine, last, formulaSlot);
  17001. if (which.containsChar ('E'))
  17002. lynx::openChannelSettings (*engine, (int) engine->getSong().channels.size() - 1);
  17003. }, {}, 3000 });
  17004. // round 190ih: LYNX_UIPERF_GBAB=n — n cycles over Gross Beat's live-display variants, playing, 2.5 s each, in one
  17005. // process (other load hits every variant alike): the names carry the LYNX_GB_DIAG mask
  17006. if (const auto cycles = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_GBAB", "0").getIntValue(); cycles > 0)
  17007. {
  17008. run->steps.push_back ({ "Gross Beat A/B start", [this] {
  17009. engine->getTransport().songMode = true;
  17010. engine->rewind();
  17011. engine->play();
  17012. }, {}, 1500 });
  17013. // (off, the default, 30 / s, off, 10 / s; LYNX_UIPERF_GBAB_MASKS="1,2,0" picks others, e.g. round 190iy's
  17014. // locator on the GPU overlay (0) against the repaint path (2))
  17015. std::vector<int> masks { 1, 0, 30 << 8, 1, 10 << 8 };
  17016. if (const auto list = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_GBAB_MASKS", {}); list.isNotEmpty())
  17017. {
  17018. masks.clear();
  17019. for (const auto& m : juce::StringArray::fromTokens (list, ",", {}))
  17020. masks.push_back (m.trim().getIntValue());
  17021. }
  17022. for (int c = 0; c < cycles; ++c)
  17023. for (const int mask : masks)
  17024. run->steps.push_back ({ "Gross Beat A/B mask " + juce::String (mask) + " cycle " + juce::String (c + 1),
  17025. [this, mask] {
  17026. lynx::setGrossBeatDiagnostics (mask);
  17027. if (! engine->getTransport().playing.load()) // (the song ended: again)
  17028. {
  17029. engine->rewind();
  17030. engine->play();
  17031. }
  17032. }, {}, 2500 });
  17033. }
  17034. // round 190jy (queue item 44): LYNX_UIPERF_DOCKAB=n — the docked LYNX editors with live displays, playing, each set
  17035. // hidden / a native child window / drawn by the main window, n cycles of 2.5 s steps in one process.
  17036. // LYNX_UIPERF_DOCKAB_SETS (default "G,L,M,GLM"): G Gross Beat, L Fruity Limiter, M Maximus (both on the master).
  17037. if (const auto cycles = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKAB", "0").getIntValue(); cycles > 0)
  17038. {
  17039. auto sets = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKAB_SETS", "G,L,M,GLM"), ",", {});
  17040. auto shown = std::make_shared<std::vector<juce::Component::SafePointer<juce::DocumentWindow>>>();
  17041. auto keepPlaying = [this] {
  17042. engine->getTransport().songMode = true;
  17043. if (! engine->getTransport().playing.load()) // (the song ended: again)
  17044. {
  17045. engine->rewind();
  17046. engine->play();
  17047. }
  17048. };
  17049. for (const auto& set : sets)
  17050. {
  17051. const auto name = set.trim();
  17052. run->steps.push_back ({ "dock A/B " + name + " open", [this, name, shown, keepPlaying] {
  17053. lynx::NativeEffectWindows::closeAll();
  17054. for (auto* w : lynx::dockedEditorWindows()) // (a channel's settings window of the set before)
  17055. if (w != nullptr)
  17056. w->closeButtonPressed();
  17057. shown->clear();
  17058. auto& song = engine->getSong();
  17059. auto openKind = [this] (lynx::EffectKind kind) {
  17060. auto& so = engine->getSong();
  17061. for (int t = 0; t < (int) so.mixer.size(); ++t)
  17062. for (int k = 0; k < (int) so.mixer[(std::size_t) t].effects.size(); ++k)
  17063. if (so.mixer[(std::size_t) t].effects[(std::size_t) k].kind == kind)
  17064. {
  17065. lynx::NativeEffectWindows::open (*engine, t, k);
  17066. return;
  17067. }
  17068. // (not in the project: on the master, after its effects)
  17069. if (so.mixer.empty() || so.mixer[0].effects.size() >= (std::size_t) lynx::maxEffectSlots)
  17070. return;
  17071. const auto slot = (int) so.mixer[0].effects.size();
  17072. engine->editSong ([kind] (lynx::Song& s2) { s2.mixer[0].effects.push_back (lynx::makeEffectSlot (kind)); }, false);
  17073. engine->dispatchPendingMessages();
  17074. lynx::NativeEffectWindows::open (*engine, 0, slot);
  17075. };
  17076. juce::ignoreUnused (song);
  17077. if (name.containsChar ('G'))
  17078. openKind (lynx::EffectKind::grossBeat);
  17079. if (name.containsChar ('L'))
  17080. openKind (lynx::EffectKind::fruityLimiter);
  17081. if (name.containsChar ('M'))
  17082. openKind (lynx::EffectKind::maximus);
  17083. // S: a Slicex channel (a 2 s tone in 4 regions) that plays the notes of the project's busiest
  17084. // channel, its settings window open (its deck's play line moves while it sounds)
  17085. if (name.containsChar ('S'))
  17086. {
  17087. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-uiperf-slicex.wav");
  17088. {
  17089. juce::AudioBuffer<float> tone (2, 96000);
  17090. for (int i = 0; i < tone.getNumSamples(); ++i)
  17091. tone.setSample (0, i, 0.3f * (float) std::sin (juce::MathConstants<double>::twoPi * (200.0 + 200.0 * (i / 24000)) * i / 48000.0));
  17092. tone.copyFrom (1, 0, tone, 0, 0, tone.getNumSamples());
  17093. wav.deleteFile();
  17094. if (auto out = std::unique_ptr<juce::OutputStream> (wav.createOutputStream()))
  17095. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), 48000.0, 2, 16, {}, 0)))
  17096. {
  17097. out.release();
  17098. writer->writeFromAudioSampleBuffer (tone, 0, tone.getNumSamples());
  17099. }
  17100. }
  17101. int busiest = -1;
  17102. {
  17103. std::map<int, int> count;
  17104. for (const auto& pat : engine->getSong().patterns)
  17105. for (const auto& n : pat.notes)
  17106. ++count[n.channel];
  17107. int best = 0;
  17108. for (const auto& [ch, n] : count)
  17109. if (n > best)
  17110. best = n, busiest = ch;
  17111. }
  17112. const auto index = (int) engine->getSong().channels.size();
  17113. engine->editSong ([&wav, busiest, index] (lynx::Song& s2) {
  17114. lynx::ChannelDef ch;
  17115. ch.name = "Slicex (uiperf)";
  17116. ch.instrument = lynx::InstrumentKind::slicex;
  17117. ch.samplePath = wav.getFullPathName().toStdString();
  17118. auto state = lynx::slicex::fresh();
  17119. lynx::slicex::setDeckFile (state, 0, ch.samplePath, 4);
  17120. lynx::slicex::setDeckBeats (state, 0, 0.0, 4.0);
  17121. ch.pluginState = lynx::slicex::write (state);
  17122. s2.channels.push_back (ch);
  17123. for (auto& pat : s2.patterns)
  17124. {
  17125. std::vector<lynx::Note> copies;
  17126. for (const auto& n : pat.notes)
  17127. if (n.channel == busiest)
  17128. {
  17129. auto c = n;
  17130. c.channel = index;
  17131. c.key = 60 + (int) (copies.size() % 4); // (the four slices in turn)
  17132. copies.push_back (c);
  17133. }
  17134. pat.notes.insert (pat.notes.end(), copies.begin(), copies.end());
  17135. pat.sortNotes();
  17136. }
  17137. }, false);
  17138. engine->dispatchPendingMessages();
  17139. lynx::openChannelSettings (*engine, index);
  17140. }
  17141. for (auto* w : lynx::dockedEditorWindows())
  17142. shown->emplace_back (w);
  17143. keepPlaying();
  17144. }, {}, 1500 });
  17145. static const char* variantNames[] = { "hidden", "own window", "main window" };
  17146. for (int c = 0; c < cycles; ++c)
  17147. for (int v = 0; v < 3; ++v)
  17148. run->steps.push_back ({ "dock A/B " + name + " " + variantNames[v] + " cycle " + juce::String (c + 1), [v, shown, keepPlaying] {
  17149. if (v > 0)
  17150. lynx::moveDockedEditors (v == 2);
  17151. for (auto& w : *shown)
  17152. if (w != nullptr && w->isVisible() != (v > 0))
  17153. w->setVisible (v > 0);
  17154. keepPlaying();
  17155. }, {}, 2500 });
  17156. }
  17157. run->steps.push_back ({ "dock A/B close", [this, shown] {
  17158. engine->stop();
  17159. shown->clear();
  17160. lynx::NativeEffectWindows::closeAll();
  17161. for (auto* w : lynx::dockedEditorWindows())
  17162. if (w != nullptr)
  17163. w->closeButtonPressed();
  17164. }, {}, 500 });
  17165. }
  17166. // round 190jy: LYNX_UIPERF_DOCKCHECK=1 — the checks of a docked editor drawn by the main window (ui/DockPaintCheck.h),
  17167. // on screen in this main window; LYNX_UIPERF_DOCKCHECK_SHOTS=<folder> keeps the two on-screen pictures compared
  17168. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKCHECK", {}) == "1")
  17169. {
  17170. auto check = std::make_shared<std::unique_ptr<lynx::dockpaint::Check>>();
  17171. auto lines = std::make_shared<juce::String>();
  17172. for (int i = 0; i < lynx::dockpaint::Check::count(); ++i)
  17173. run->steps.push_back ({ "dock check " + juce::String (i), [this, ui, check, lines, i] {
  17174. if (*check == nullptr)
  17175. *check = std::make_unique<lynx::dockpaint::Check> (*engine, *ui, *mainWindow,
  17176. juce::File (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKCHECK_SHOTS", {})));
  17177. *lines = (*check)->step (i);
  17178. }, {}, 700, [lines] { return *lines; } });
  17179. }
  17180. run->steps.push_back ({ "Gross Beat window, song playing", [this] {
  17181. engine->getTransport().songMode = true;
  17182. engine->rewind();
  17183. engine->play();
  17184. }, {}, 3000, [this] {
  17185. engine->stop();
  17186. lynx::NativeEffectWindows::closeAll();
  17187. lynx::FormulaControllerWindows::closeAll();
  17188. return juce::String();
  17189. } });
  17190. // round 190kb: LYNX_UIPERF_SPINAB=n — the worker pool's waiting policies (WorkerPool::Tuning) A/B inside one
  17191. // process while the song plays with live editor windows: per set (LYNX_UIPERF_SPINAB_SETS, default "G,GLM": G
  17192. // Gross Beat, L Fruity Limiter, M Maximus; on the master when the project has none), n cycles over every
  17193. // variant (LYNX_UIPERF_SPINAB_VARIANTS="name:spec;…", spec as LYNX_POOL) with the windows hidden and shown,
  17194. // 2.5 s steps, the order turning every cycle. Run with LYNX_UIPERF_THREADS=1 for the threads' lines.
  17195. if (const auto cycles = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SPINAB", "0").getIntValue(); cycles > 0)
  17196. {
  17197. auto sets = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SPINAB_SETS", "G,GLM"), ",", {});
  17198. struct Variant
  17199. {
  17200. juce::String name, spec;
  17201. };
  17202. std::vector<Variant> variants;
  17203. for (const auto& v : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable (
  17204. "LYNX_UIPERF_SPINAB_VARIANTS", "old:spin=60,adaptive=0,wait=0;new:spin=60,adaptive=1,dry=4,wait=1,waitspin=30"),
  17205. ";", {}))
  17206. if (v.containsChar (':'))
  17207. variants.push_back ({ v.upToFirstOccurrenceOf (":", false, false).trim(), v.fromFirstOccurrenceOf (":", false, false).trim() });
  17208. auto shown = std::make_shared<std::vector<juce::Component::SafePointer<juce::Component>>>();
  17209. // every step plays the same part of the song (LYNX_UIPERF_SPINAB_AT: a fraction of the song, default 0.4): the
  17210. // audio work differs from part to part far more than between the variants (a first run without this put the
  17211. // variants of one cycle in different parts and read the parts)
  17212. auto at = std::make_shared<double> (0.0);
  17213. const auto atFraction = juce::jlimit (0.0, 0.95, juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SPINAB_AT", "0.4").getDoubleValue());
  17214. auto keepPlaying = [this, at] {
  17215. engine->getTransport().songMode = true;
  17216. engine->seek (*at);
  17217. if (! engine->getTransport().playing.load())
  17218. engine->play();
  17219. };
  17220. for (const auto& set : sets)
  17221. {
  17222. const auto name = set.trim();
  17223. run->steps.push_back ({ "spin A/B " + name + " open", [this, name, shown, keepPlaying, at, atFraction] {
  17224. *at = atFraction * engine->getTransport().songEnd.load();
  17225. lynx::NativeEffectWindows::closeAll();
  17226. shown->clear();
  17227. std::vector<juce::Component*> before;
  17228. auto& desktop = juce::Desktop::getInstance();
  17229. for (int i = 0; i < desktop.getNumComponents(); ++i)
  17230. before.push_back (desktop.getComponent (i));
  17231. auto openKind = [this] (lynx::EffectKind kind) {
  17232. auto& so = engine->getSong();
  17233. for (int t = 0; t < (int) so.mixer.size(); ++t)
  17234. for (int k = 0; k < (int) so.mixer[(std::size_t) t].effects.size(); ++k)
  17235. if (so.mixer[(std::size_t) t].effects[(std::size_t) k].kind == kind)
  17236. {
  17237. lynx::NativeEffectWindows::open (*engine, t, k);
  17238. return;
  17239. }
  17240. // (not in the project: on the master, after its effects)
  17241. if (so.mixer.empty() || so.mixer[0].effects.size() >= (std::size_t) lynx::maxEffectSlots)
  17242. return;
  17243. const auto slot = (int) so.mixer[0].effects.size();
  17244. engine->editSong ([kind] (lynx::Song& s2) { s2.mixer[0].effects.push_back (lynx::makeEffectSlot (kind)); }, false);
  17245. engine->dispatchPendingMessages();
  17246. lynx::NativeEffectWindows::open (*engine, 0, slot);
  17247. };
  17248. if (name.containsChar ('G'))
  17249. openKind (lynx::EffectKind::grossBeat);
  17250. if (name.containsChar ('L'))
  17251. openKind (lynx::EffectKind::fruityLimiter);
  17252. if (name.containsChar ('M'))
  17253. openKind (lynx::EffectKind::maximus);
  17254. for (int i = 0; i < desktop.getNumComponents(); ++i)
  17255. if (auto* c = desktop.getComponent (i); std::find (before.begin(), before.end(), c) == before.end())
  17256. shown->emplace_back (c);
  17257. keepPlaying();
  17258. }, {}, 1500, [shown, at] { return " windows of the set: " + juce::String ((int) shown->size()) + ", every step from tick " + juce::String (*at, 0) + "\n"; } });
  17259. for (int c = 0; c < cycles; ++c)
  17260. for (int k = 0; k < (int) variants.size() * 2; ++k)
  17261. {
  17262. // (the variants in turn, starting one further each cycle; hidden / shown swapped every cycle)
  17263. const auto& v = variants[(std::size_t) ((k / 2 + c) % (int) variants.size())];
  17264. const auto visible = ((k % 2) == 1) != ((c % 2) == 1);
  17265. run->steps.push_back ({ "spin A/B " + name + " " + v.name + (visible ? " shown" : " hidden") + " cycle " + juce::String (c + 1),
  17266. [spec = v.spec, visible, shown, keepPlaying] {
  17267. lynx::WorkerPool::tuning().apply (spec.toRawUTF8());
  17268. for (auto& w : *shown)
  17269. if (w != nullptr && w->isVisible() != visible)
  17270. w->setVisible (visible);
  17271. keepPlaying();
  17272. }, {}, 2500 });
  17273. }
  17274. }
  17275. run->steps.push_back ({ "spin A/B close", [this, shown] {
  17276. engine->stop();
  17277. shown->clear();
  17278. lynx::NativeEffectWindows::closeAll();
  17279. lynx::WorkerPool::tuning().apply (juce::SystemStats::getEnvironmentVariable ("LYNX_POOL", "").toRawUTF8());
  17280. }, {}, 500 });
  17281. }
  17282. // round 190iv: the Simple layout (its toolbar) idle and while the song plays
  17283. run->steps.push_back ({ "idle: simple layout, stopped", [this, ui] {
  17284. engine->stop();
  17285. ui->setLayoutStyle (lynx::layoutstyle::Style::simple, false);
  17286. }, {}, 3000 });
  17287. run->steps.push_back ({ "simple layout, song playing", [this] {
  17288. engine->getTransport().songMode = true;
  17289. engine->rewind();
  17290. engine->play();
  17291. }, {}, 3000, [this, ui] {
  17292. engine->stop();
  17293. ui->setLayoutStyle (lynx::layoutstyle::Style::pattern, false);
  17294. return juce::String();
  17295. } });
  17296. // LYNX_UIPERF_ONLY=text: only the steps whose name has that text
  17297. if (const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_ONLY", {}); only.isNotEmpty())
  17298. run->steps.erase (std::remove_if (run->steps.begin(), run->steps.end(), [&only] (const auto& s) { return ! juce::String (s.name).contains (only); }), run->steps.end());
  17299. // let the window draw the project first
  17300. perf = std::move (run);
  17301. juce::Timer::callAfterDelay (1500, [this] { if (perf != nullptr) perf->startTimer (16); });
  17302. }
  17303. // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
  17304. // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
  17305. // --rtstress --backuptest N (round 177d): while the project plays, a device's MIDI clock (10/s) and active sensing
  17306. // (3/s) arrive, and the project counts as changed. N > 0 also forces a backup every N seconds on top of the timed ones.
  17307. // The report tells how many backups were written, when, and what the MIDI counters did.
  17308. struct BackupTest final : juce::Timer
  17309. {
  17310. lynx::AudioEngine* engine = nullptr;
  17311. lynx::MainComponent* ui = nullptr;
  17312. double everyMs = 0.0, startMs = 0.0, lastForcedMs = 0.0, longestCallMs = 0.0;
  17313. int ticks = 0, forced = 0;
  17314. std::uint64_t seenOver = 0, seenNear = 0;
  17315. juce::String misses; // each callback over (or near) its deadline: how long after the last forced backup
  17316. void timerCallback() override
  17317. {
  17318. engine->injectMidiInput (juce::MidiMessage (0xf8));
  17319. if (++ticks % 3 == 0)
  17320. engine->injectMidiInput (juce::MidiMessage (0xfe));
  17321. const auto now = juce::Time::getMillisecondCounterHiRes();
  17322. const auto s = engine->getRtStats().snapshot();
  17323. if (s.overBudget != seenOver || s.nearBudget != seenNear)
  17324. {
  17325. misses << " +" << juce::String ((now - lastForcedMs) / 1000.0, 1) << " s after the last forced backup (or the start): over +"
  17326. << (juce::int64) (s.overBudget - seenOver) << ", near +" << (juce::int64) (s.nearBudget - seenNear) << "\n";
  17327. seenOver = s.overBudget;
  17328. seenNear = s.nearBudget;
  17329. }
  17330. if (everyMs > 0.0 && now - lastForcedMs >= everyMs)
  17331. {
  17332. lastForcedMs = now;
  17333. ++forced;
  17334. ui->backupNowForTest();
  17335. longestCallMs = juce::jmax (longestCallMs, juce::Time::getMillisecondCounterHiRes() - now);
  17336. }
  17337. }
  17338. };
  17339. std::unique_ptr<BackupTest> backupTest;
  17340. void startBackupTest()
  17341. {
  17342. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  17343. const auto at = cli.indexOf ("--backuptest");
  17344. auto* ui = mainWindow != nullptr ? dynamic_cast<lynx::MainComponent*> (mainWindow->getContentComponent()) : nullptr;
  17345. if (at < 0 || ui == nullptr)
  17346. return;
  17347. backupTest = std::make_unique<BackupTest>();
  17348. backupTest->engine = engine.get();
  17349. backupTest->ui = ui;
  17350. backupTest->everyMs = cli[at + 1].getDoubleValue() * 1000.0;
  17351. backupTest->startMs = backupTest->lastForcedMs = juce::Time::getMillisecondCounterHiRes();
  17352. // (the project counts as changed, so a backup has something to write; the Master's fader is down, so a long run
  17353. // makes no sound: everything else is processed as usual)
  17354. engine->editSong ([] (lynx::Song& s) {
  17355. if (! s.mixer.empty())
  17356. s.mixer[0].volume = 0.0f;
  17357. });
  17358. backupTest->startTimer (100);
  17359. }
  17360. juce::String finishBackupTest()
  17361. {
  17362. if (backupTest == nullptr)
  17363. return {};
  17364. backupTest->stopTimer();
  17365. juce::String text;
  17366. const auto played = engine->getMidiPlayed();
  17367. text << " backup test: MIDI light count " << (int) engine->getMidiActivity() << ", played count " << (int) played << " (clock and active sensing only)\n";
  17368. text << " backup test: " << backupTest->forced << " forced, longest forced call on the message thread "
  17369. << juce::String (backupTest->longestCallMs, 1) << " ms\n";
  17370. if (backupTest->misses.isNotEmpty())
  17371. text << " backup test: callbacks over or near the deadline (seen within 100 ms):\n" << backupTest->misses;
  17372. auto files = lynx::autosaveFolder().findChildFiles (juce::File::findFiles, false, "*.lynx");
  17373. text << " backup test: " << files.size() << " file(s) in the backup folder:\n";
  17374. for (const auto& f : files)
  17375. text << " " << juce::String ((f.getLastModificationTime().toMilliseconds() - juce::Time::getCurrentTime().toMilliseconds()) / 1000) << " s before the end: "
  17376. << f.getFileName() << " (" << f.getSize() << " bytes)\n";
  17377. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 1));
  17378. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  17379. text << " backup test: after a played note, played count " << (int) engine->getMidiPlayed() << "\n";
  17380. backupTest.reset();
  17381. return text;
  17382. }
  17383. void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize,
  17384. const juce::String& deviceType, const juce::String& deviceName, const juce::String& recordTo = {})
  17385. {
  17386. startupOptions = lynx::StartupOptions::load();
  17387. engine = std::make_unique<lynx::AudioEngine>();
  17388. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  17389. crashEngine = engine.get();
  17390. // the user's saved device stays as it was: this run's choices are undone before quitting
  17391. savedDeviceState = engine->getDeviceManager().createStateXml();
  17392. auto& devices = engine->getDeviceManager();
  17393. const auto driverFile = addDriverFileDeviceType();
  17394. const auto type = deviceType.isEmpty() && driverFile ? juce::String (lynx::dllAsioTypeName) : deviceType;
  17395. if (type.isNotEmpty() && devices.getCurrentAudioDeviceType() != type)
  17396. devices.setCurrentAudioDeviceType (type, true);
  17397. if (bufferSize > 0 || deviceName.isNotEmpty())
  17398. {
  17399. auto setup = devices.getAudioDeviceSetup();
  17400. if (bufferSize > 0)
  17401. setup.bufferSize = bufferSize;
  17402. if (deviceName.isNotEmpty())
  17403. setup.outputDeviceName = deviceName;
  17404. const auto error = devices.setAudioDeviceSetup (setup, true);
  17405. if (error.isNotEmpty())
  17406. report.replaceWithText ("device error: " + error + "\n");
  17407. }
  17408. createMainWindow();
  17409. if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
  17410. mainWindow->reveal();
  17411. juce::String error;
  17412. auto ok = false;
  17413. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  17414. if (project.hasFileExtension ("flp"))
  17415. ok = engine->importFlpFile (project, error);
  17416. else if (auto song = lynx::ProjectFile::load (project, error))
  17417. {
  17418. engine->setSong (std::move (*song));
  17419. ok = true;
  17420. }
  17421. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  17422. if (! ok)
  17423. {
  17424. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  17425. restoreSavedDeviceState();
  17426. setApplicationReturnValue (1);
  17427. quit();
  17428. return;
  17429. }
  17430. if (recordTo.isNotEmpty())
  17431. engine->setAudioRecordingArmed (true); // opens the input of the driver
  17432. // let the window draw the project, then play from the start with fresh statistics
  17433. juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs, recordTo] {
  17434. if (engine == nullptr)
  17435. return;
  17436. engine->stop();
  17437. engine->rewind();
  17438. engine->getRtStats().reset();
  17439. engine->takeUiPulse();
  17440. if (recordTo.isNotEmpty())
  17441. engine->setRecording (true);
  17442. // --log folder: the audio logger records what the Master plays during the run (realtime vs export checks)
  17443. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  17444. if (const auto at = cli.indexOf ("--log"); at >= 0 && at + 1 < cli.size())
  17445. engine->getAudioLogger().start (juce::File (cli[at + 1].unquoted()), engine->getDeviceManager().getCurrentAudioDevice() != nullptr
  17446. ? engine->getDeviceManager().getCurrentAudioDevice()->getCurrentSampleRate() : 44100.0);
  17447. engine->play();
  17448. startBackupTest();
  17449. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
  17450. if (engine == nullptr)
  17451. return;
  17452. const auto backupReport = finishBackupTest();
  17453. engine->stop();
  17454. juce::String recording;
  17455. if (engine->getAudioLogger().isLogging())
  17456. {
  17457. recording << " logged: " << engine->getAudioLogger().currentFile().getFullPathName() << "\n";
  17458. engine->getAudioLogger().stop();
  17459. }
  17460. if (recordTo.isNotEmpty())
  17461. recording = finishStressTake (juce::File (recordTo), seconds);
  17462. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  17463. const auto s = engine->getRtStats().snapshot();
  17464. juce::String text;
  17465. text << "project: " << project.getFullPathName() << "\n"
  17466. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  17467. << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
  17468. << juce::SystemStats::getCpuModel() << "\n"
  17469. << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
  17470. << engine->describeRealtime();
  17471. const auto pulse = engine->takeUiPulse();
  17472. text << " UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
  17473. << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
  17474. text << " load histogram (share of the deadline: callbacks):";
  17475. for (std::size_t b = 0; b < s.histogram.size(); ++b)
  17476. if (s.histogram[b] > 0)
  17477. text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
  17478. text << "\n";
  17479. text << recording << backupReport;
  17480. // --settingsshot file.png (round 161): Options > Audio settings of this run's device, as a picture
  17481. if (const auto at = cli.indexOf ("--settingsshot"); at >= 0 && at + 1 < cli.size())
  17482. {
  17483. auto page = lynx::makeSettingsPanel (*engine, lynx::SettingsPage::audio);
  17484. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  17485. {
  17486. juce::Graphics g (image);
  17487. g.fillAll (lynx::theme::panel);
  17488. page->paintEntireComponent (g, false);
  17489. }
  17490. const juce::File shot (cli[at + 1].unquoted());
  17491. shot.deleteFile();
  17492. if (auto out = shot.createOutputStream())
  17493. juce::PNGImageFormat().writeImageToStream (image, *out);
  17494. }
  17495. text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
  17496. report.replaceWithText (text);
  17497. restoreSavedDeviceState();
  17498. setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
  17499. quit();
  17500. });
  17501. });
  17502. }
  17503. // --bendrectest (round 167a): see the command line above
  17504. void runBendRecordTest (const juce::File& report, bool songMode)
  17505. {
  17506. engine = std::make_unique<lynx::AudioEngine>();
  17507. auto text = std::make_shared<juce::String>();
  17508. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  17509. auto finish = [this] (int code) {
  17510. setApplicationReturnValue (code);
  17511. quit();
  17512. };
  17513. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  17514. if (device == nullptr)
  17515. {
  17516. step ("result=ERROR no audio device");
  17517. finish (1);
  17518. return;
  17519. }
  17520. step ("device=" + device->getTypeName() + " | " + device->getName() + " | mode " + (songMode ? "song" : "pattern"));
  17521. auto song = lynx::Song::makeDefault();
  17522. song.bpm = 120.0;
  17523. song.mode = songMode ? lynx::PlayMode::song : lynx::PlayMode::pattern;
  17524. engine->setSong (std::move (song));
  17525. auto o = engine->getRecordOptions();
  17526. o.mode = lynx::RecordMode::overdub;
  17527. o.recordNotes = true;
  17528. o.recordAutomation = true;
  17529. o.countInBars = 0;
  17530. o.waitForInput = false;
  17531. o.quantiseAutomation = false;
  17532. o.punchLoopRegion = false;
  17533. o.preRollBars = o.postRollBars = 0;
  17534. engine->setRecordOptions (o);
  17535. engine->stop();
  17536. engine->rewind();
  17537. engine->setRecording (true);
  17538. engine->startPlayback();
  17539. // 2 s of wheel at ~100 messages a second: 0 → +1 (0.5 s), +1 → −1 (1 s), −1 → 0 (0.5 s)
  17540. auto sent = std::make_shared<std::vector<std::pair<double, float>>>();
  17541. auto t0 = std::make_shared<double> (juce::Time::getMillisecondCounterHiRes());
  17542. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 100));
  17543. auto tick = std::make_shared<std::function<void()>>();
  17544. *tick = [this, sent, t0, tick, step, finish, songMode] {
  17545. if (engine == nullptr)
  17546. return;
  17547. const auto ms = juce::Time::getMillisecondCounterHiRes() - *t0;
  17548. if (ms < 2000.0)
  17549. {
  17550. const auto x = ms / 1000.0;
  17551. const auto v = (float) (x < 0.5 ? x * 2.0 : x < 1.5 ? 1.0 - (x - 0.5) * 2.0 : -1.0 + (x - 1.5) * 2.0);
  17552. const auto wheel = juce::jlimit (0, 16383, 8192 + juce::roundToInt (v * 8191.0f));
  17553. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, wheel));
  17554. sent->push_back ({ ms, (float) (wheel - 8192) / 8192.0f });
  17555. juce::Timer::callAfterDelay (10, *tick);
  17556. return;
  17557. }
  17558. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, 8192));
  17559. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  17560. juce::Timer::callAfterDelay (400, [this, sent, step, finish, songMode] {
  17561. if (engine == nullptr)
  17562. return;
  17563. engine->stop();
  17564. juce::Timer::callAfterDelay (600, [this, sent, step, finish, songMode] {
  17565. if (engine == nullptr)
  17566. return;
  17567. engine->setRecording (false);
  17568. const auto& s = engine->getSong();
  17569. // the channel's pitch bend (MIDI channel 1), recorded as a lane or a clip
  17570. std::vector<std::pair<std::int64_t, float>> got;
  17571. juce::String where = "nothing";
  17572. for (const auto& a : s.automations)
  17573. if (a.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (a.target.param))
  17574. {
  17575. where = "automation clip \"" + juce::String (a.name) + "\"";
  17576. for (const auto& pt : a.points)
  17577. got.push_back ({ pt.tick, pt.value });
  17578. }
  17579. for (const auto& p : s.patterns)
  17580. for (const auto& lane : p.events)
  17581. if (lane.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (lane.target.param))
  17582. {
  17583. where = "pattern \"" + juce::String (p.name) + "\" event lane";
  17584. for (const auto& e : lane.events)
  17585. got.push_back ({ e.tick, e.value });
  17586. }
  17587. int notes = 0;
  17588. for (const auto& p : s.patterns)
  17589. notes += (int) p.notes.size();
  17590. float lo = 1.0f, hi = 0.0f;
  17591. for (const auto& [t, v] : got)
  17592. lo = std::min (lo, v), hi = std::max (hi, v);
  17593. // ticks: in order, spread over the ~2 s sweep (8 beats of 96 ticks at 120 bpm ≈ 4 beats)
  17594. const auto span = got.empty() ? 0 : got.back().first - got.front().first;
  17595. const auto sorted = std::is_sorted (got.begin(), got.end(), [] (const auto& a, const auto& b) { return a.first < b.first; });
  17596. step ("sent=" + juce::String ((int) sent->size()) + " wheel messages over 2 s");
  17597. step ("recorded=" + juce::String ((int) got.size()) + " points in " + where + ", value " + juce::String (lo, 3) + " .. "
  17598. + juce::String (hi, 3) + " (0.5 = centre), ticks " + juce::String (span) + " apart, " + (sorted ? "in order" : "OUT OF ORDER")
  17599. + ", notes " + juce::String (notes));
  17600. if (! got.empty())
  17601. step ("last=" + juce::String (got.back().second, 3));
  17602. // song mode: a clip over the take, ending back at the centre. Pattern mode: the take loops the 1-bar pattern
  17603. // (4.6 beats of take), so the lane spans the bar and the last wheel message (the centre) lands inside it
  17604. const auto centred = std::any_of (got.begin(), got.end(), [] (const auto& p) { return std::abs (p.second - 0.5f) < 0.02f; });
  17605. const auto ok = got.size() >= 20 && hi > 0.97f && lo < 0.03f && sorted && notes >= 1
  17606. && (songMode ? span > lynx::ppq * 3 && span < lynx::ppq * 6 && std::abs (got.back().second - 0.5f) < 0.02f
  17607. : span > lynx::ppq * 2 && span <= lynx::ppq * 4 && centred);
  17608. step (ok ? "result=OK" : "result=FAILED");
  17609. finish (ok ? 0 : 1);
  17610. });
  17611. });
  17612. };
  17613. juce::Timer::callAfterDelay (300, *tick);
  17614. }
  17615. // --countinrectest (round 170d): see the command line above.
  17616. void runCountInRecordTest (const juce::File& report)
  17617. {
  17618. engine = std::make_unique<lynx::AudioEngine>();
  17619. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  17620. struct StandIn final : juce::AudioIODevice
  17621. {
  17622. StandIn() : juce::AudioIODevice ("countin", "test") {}
  17623. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  17624. juce::StringArray getInputChannelNames() override { return {}; }
  17625. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  17626. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  17627. int getDefaultBufferSize() override { return 512; }
  17628. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  17629. void close() override {}
  17630. bool isOpen() override { return true; }
  17631. void start (juce::AudioIODeviceCallback*) override {}
  17632. void stop() override {}
  17633. bool isPlaying() override { return true; }
  17634. juce::String getLastError() override { return {}; }
  17635. int getCurrentBufferSizeSamples() override { return 512; }
  17636. double getCurrentSampleRate() override { return 48000.0; }
  17637. int getCurrentBitDepth() override { return 32; }
  17638. juce::BigInteger getActiveOutputChannels() const override
  17639. {
  17640. juce::BigInteger b;
  17641. b.setRange (0, 2, true);
  17642. return b;
  17643. }
  17644. juce::BigInteger getActiveInputChannels() const override { return {}; }
  17645. int getOutputLatencyInSamples() override { return 256; }
  17646. int getInputLatencyInSamples() override { return 0; }
  17647. };
  17648. auto device = std::make_shared<StandIn>();
  17649. auto text = std::make_shared<juce::String>();
  17650. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  17651. auto finish = [this] (int code) {
  17652. setApplicationReturnValue (code);
  17653. quit();
  17654. };
  17655. constexpr std::int64_t bar = 4 * lynx::ppq; // 120 BPM, 4/4
  17656. lynx::Song song; // (as --cliplooptest: one synth channel on insert 1, an empty pattern)
  17657. song.bpm = 120.0;
  17658. song.mixer = lynx::Song::defaultMixer (2);
  17659. song.channels.resize (1);
  17660. song.channels[0].mixerTrack = 1;
  17661. song.patterns.emplace_back();
  17662. song.mode = lynx::PlayMode::song;
  17663. song.currentPattern = 0;
  17664. engine->setSong (song);
  17665. engine->getTransport().metronome.store (true);
  17666. auto o = engine->getRecordOptions();
  17667. o.mode = lynx::RecordMode::overdub;
  17668. o.countInBars = 1;
  17669. o.catchWindow = lynx::ppq / 4;
  17670. o.compensateOutput = true;
  17671. o.recordNotes = true;
  17672. o.recordAudio = false;
  17673. o.recordAutomation = false;
  17674. o.waitForInput = false;
  17675. o.quantise = 0;
  17676. o.placeSongClip = true;
  17677. o.recordingMarkers = false;
  17678. o.punchLoopRegion = false;
  17679. o.preRollBars = o.postRollBars = 0;
  17680. engine->setRecordOptions (o);
  17681. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  17682. step ("stand-in device: 48 kHz, blocks of 512, output latency 256 samples; Song mode, 120 BPM, take from bar 3, count-in 1 bar");
  17683. // an event heard at output sample `heard` (counted from the first block after Play), sent as MIDI input
  17684. struct Event
  17685. {
  17686. std::int64_t heard;
  17687. juce::MidiMessage message;
  17688. };
  17689. struct Pass
  17690. {
  17691. std::vector<float> out;
  17692. std::vector<Event> events;
  17693. std::int64_t playingAt = -1; // the first sample of the block the song started in
  17694. int block = 0, blocks = 0;
  17695. std::function<void()> done;
  17696. };
  17697. constexpr int n = 512;
  17698. constexpr double rate = 48000.0;
  17699. // one pass: the take recorded from bar 3, `blocks` blocks driven by hand, 8 at a time between the engine's timer
  17700. // ticks (the take is committed there); then stopped and its results left to the timer
  17701. auto runPass = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  17702. *runPass = [this] (std::shared_ptr<Pass> pass) {
  17703. auto& cb = engine->deviceCallback();
  17704. std::vector<float> l (n), r (n);
  17705. float* outs[] = { l.data(), r.data() };
  17706. juce::AudioIODeviceCallbackContext context;
  17707. if (pass->block == 0)
  17708. {
  17709. engine->stop();
  17710. engine->seek ((double) (2 * bar));
  17711. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context); // (the seek, stopped)
  17712. engine->setRecording (true);
  17713. engine->startPlayback(); // the count-in starts
  17714. }
  17715. for (int k = 0; k < 8 && pass->block < pass->blocks; ++k, ++pass->block)
  17716. {
  17717. // the events heard in this block: stamped the way the engine's clock maps time to heard samples
  17718. const auto blockStart = (std::int64_t) pass->block * n;
  17719. const auto clock = engine->liveClock();
  17720. const auto compMs = 1000.0 * (n + 256) / rate;
  17721. for (auto& e : pass->events)
  17722. if (e.heard >= blockStart && e.heard < blockStart + n)
  17723. {
  17724. auto m = e.message;
  17725. m.setTimeStamp ((clock.timeMs + compMs + (double) (e.heard - blockStart) * 1000.0 / rate) * 0.001);
  17726. engine->injectMidiInput (m);
  17727. }
  17728. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context);
  17729. pass->out.insert (pass->out.end(), l.begin(), l.end());
  17730. if (pass->playingAt < 0 && engine->getTransport().playing.load())
  17731. pass->playingAt = blockStart;
  17732. }
  17733. };
  17734. // (the recursion through the message loop; written out so each step lets the engine's timer run)
  17735. auto drive = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  17736. // (round 190rf: the step holds itself weakly, the timer's call strongly: a strong self-capture never freed the passes'
  17737. // takes, ~4 MB, LeakSanitizer in the sanitizer sweep)
  17738. *drive = [this, runPass, weakDrive = std::weak_ptr (drive), device] (std::shared_ptr<Pass> pass) { // (the stand-in lives while the passes run)
  17739. if (engine == nullptr)
  17740. return;
  17741. (*runPass) (pass);
  17742. if (pass->block < pass->blocks)
  17743. {
  17744. if (auto self = weakDrive.lock())
  17745. juce::Timer::callAfterDelay (40, [pass, self] { (*self) (pass); });
  17746. return;
  17747. }
  17748. engine->stop();
  17749. juce::Timer::callAfterDelay (300, [this, pass] {
  17750. if (engine == nullptr)
  17751. return;
  17752. engine->setRecording (false);
  17753. juce::Timer::callAfterDelay (200, [pass] { pass->done(); });
  17754. });
  17755. };
  17756. auto onsets = [] (const std::vector<float>& out) {
  17757. std::vector<std::int64_t> at;
  17758. std::int64_t last = -100000;
  17759. for (std::size_t i = 0; i < out.size(); ++i)
  17760. if (std::abs (out[i]) > 0.02f && (std::int64_t) i - last > 4000)
  17761. {
  17762. at.push_back ((std::int64_t) i);
  17763. last = (std::int64_t) i;
  17764. }
  17765. else if (std::abs (out[i]) > 0.02f)
  17766. last = (std::int64_t) i;
  17767. return at;
  17768. };
  17769. // the graph is (re)built on the message thread: start once it has settled
  17770. juce::Timer::callAfterDelay (1500, [this, step, finish, drive, onsets] {
  17771. if (engine == nullptr)
  17772. return;
  17773. auto first = std::make_shared<Pass>();
  17774. first->blocks = (int) (rate * 18.0 / n); // count-in + 8 bars
  17775. first->done = [this, weakFirst = std::weak_ptr (first), step, finish, drive, onsets] { // (round 190rf: not itself)
  17776. const auto first = weakFirst.lock();
  17777. if (first == nullptr)
  17778. return;
  17779. const auto clicks = onsets (first->out);
  17780. juce::String list;
  17781. for (std::size_t i = 0; i < std::min<std::size_t> (clicks.size(), 8); ++i)
  17782. list << clicks[i] << " ";
  17783. step ("pass 1: clicks heard at samples " + list + "…, the song started in the block at " + juce::String (first->playingAt));
  17784. // the bar-3 downbeat: the click at the block the song started in
  17785. std::int64_t down = -1;
  17786. for (auto c : clicks)
  17787. if (std::abs (c - first->playingAt) < n)
  17788. down = c;
  17789. if (down < 0 || engine->getSong().patterns[0].notes.size() != 0)
  17790. {
  17791. step ("result=FAILED no downbeat click found (or notes recorded without input)");
  17792. finish (1);
  17793. return;
  17794. }
  17795. const auto ms = [down] (double t) { return down + (std::int64_t) std::llround (t * rate / 1000.0); };
  17796. auto second = std::make_shared<Pass>();
  17797. second->blocks = first->blocks;
  17798. auto add = [&second] (std::int64_t at, int key, bool on) {
  17799. second->events.push_back ({ at, on ? juce::MidiMessage::noteOn (1, key, (juce::uint8) 100) : juce::MidiMessage::noteOff (1, key) });
  17800. };
  17801. for (int key : { 60, 64, 67 }) // the chord, 15 ms early, held half a second
  17802. {
  17803. add (ms (-15.0), key, true);
  17804. add (ms (500.0), key, false);
  17805. }
  17806. add (ms (-1500.0), 62, true); // beat 2 of the count-in bar (bar 2)
  17807. add (ms (-1250.0), 62, false);
  17808. add (ms (503.0), 77, true); // 3 ms after beat 2
  17809. add (ms (603.0), 77, false);
  17810. for (int b = 1; b <= 6; ++b) // a note a bar ("it stopped after two bars")
  17811. {
  17812. add (ms (b * 2000.0), 70 + b, true);
  17813. add (ms (b * 2000.0 + 250.0), 70 + b, false);
  17814. }
  17815. second->done = [this, step, finish] {
  17816. const auto& s = engine->getSong();
  17817. const auto& p = s.patterns[0];
  17818. const lynx::Clip* clip = nullptr;
  17819. for (const auto& c : s.playlist)
  17820. if (c.kind == lynx::ClipKind::pattern && c.pattern == 0)
  17821. clip = &c;
  17822. const auto origin = clip != nullptr ? clip->start - clip->offset : -1;
  17823. step ("pass 2: " + juce::String ((int) p.notes.size()) + " notes recorded, clip at " + juce::String (clip != nullptr ? clip->start : -1));
  17824. auto ok = clip != nullptr && origin == bar && p.notes.size() == 11;
  17825. // where each one was heard (song ticks): 0.5 ms = ~1 tick
  17826. const std::vector<std::pair<int, double>> want = { { 60, 2.0 * bar }, { 64, 2.0 * bar }, { 67, 2.0 * bar },
  17827. { 62, 2.0 * bar - 3 * lynx::ppq }, { 77, 2.0 * bar + lynx::ppq + 3.0 * 1.92 },
  17828. { 71, 3.0 * bar }, { 72, 4.0 * bar }, { 73, 5.0 * bar },
  17829. { 74, 6.0 * bar }, { 75, 7.0 * bar }, { 76, 8.0 * bar } };
  17830. for (const auto& [key, tick] : want)
  17831. {
  17832. const lynx::Note* found = nullptr;
  17833. for (const auto& note : p.notes)
  17834. if (note.key == key)
  17835. found = &note;
  17836. const auto at = found != nullptr ? (double) (origin + found->start) : -1.0;
  17837. const auto good = found != nullptr && std::abs (at - tick) <= 2.0;
  17838. ok = ok && good;
  17839. step ("key " + juce::String (key) + ": heard at tick " + juce::String (tick, 2) + ", recorded at " + juce::String (at, 0)
  17840. + (good ? " ok" : " WRONG"));
  17841. }
  17842. const auto* chord = [&p] () -> const lynx::Note* {
  17843. for (const auto& note : p.notes)
  17844. if (note.key == 60)
  17845. return &note;
  17846. return nullptr;
  17847. }();
  17848. if (chord != nullptr)
  17849. step ("chord length " + juce::String (chord->length) + " ticks (caught 15 ms early, released 500 ms after bar 3: 960)");
  17850. step (ok ? "result=OK" : "result=FAILED");
  17851. finish (ok ? 0 : 1);
  17852. };
  17853. (*drive) (second);
  17854. };
  17855. (*drive) (first);
  17856. });
  17857. }
  17858. // --cliplooptest (round 167q): see the command line above.
  17859. // --slicexedittest (round 190aj): see the command line above
  17860. void runDirectWaveEditTest (const juce::String& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
  17861. {
  17862. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17863. juce::StringArray lines;
  17864. {
  17865. lynx::AudioEngine offline (false);
  17866. lynx::MainComponent ui (offline, false);
  17867. ui.setSize (1280, 720);
  17868. if (project == "new")
  17869. {
  17870. if (auto c = lynx::natives::makeChannel (lynx::InstrumentKind::directwave, {}))
  17871. offline.editSong ([c] (lynx::Song& s) { s.channels.push_back (*c); });
  17872. }
  17873. else
  17874. ui.openFile (juce::File (project));
  17875. offline.dispatchPendingMessages();
  17876. int channel = -1;
  17877. for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
  17878. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::directwave)
  17879. channel = c;
  17880. if (channel < 0)
  17881. lines.add ("no DirectWave channel in " + project);
  17882. else
  17883. {
  17884. auto panel = lynx::makeChannelSettingsPanel (offline, channel);
  17885. juce::Component frame;
  17886. frame.setSize (panel->getWidth(), panel->getHeight());
  17887. frame.setOpaque (true);
  17888. frame.addAndMakeVisible (*panel);
  17889. panel->setTopLeftPosition (0, 0);
  17890. offline.dispatchPendingMessages();
  17891. juce::StringArray commands;
  17892. script.readLines (commands);
  17893. for (const auto& raw : commands)
  17894. {
  17895. const auto command = raw.trim();
  17896. if (command.isEmpty() || command.startsWith ("#"))
  17897. {
  17898. lines.add (command);
  17899. continue;
  17900. }
  17901. if (command.startsWith ("shot "))
  17902. {
  17903. frame.setSize (panel->getWidth(), panel->getHeight());
  17904. // (round 190jd: at the shot scale, --shot-scale / LYNX_SHOT_SCALE, with its suffix; scale 1 = the same pixels)
  17905. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  17906. const auto file = lynx::shot::file (juce::File (prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png"));
  17907. file.deleteFile();
  17908. juce::PNGImageFormat png;
  17909. if (auto out = file.createOutputStream())
  17910. png.writeImageToStream (image, *out);
  17911. lines.add (command + " -> " + file.getFileName());
  17912. continue;
  17913. }
  17914. if (command.startsWith ("savestate "))
  17915. {
  17916. const auto& st = offline.getSong().channels[(std::size_t) channel].pluginState;
  17917. juce::File (command.fromFirstOccurrenceOf (" ", false, false).trim()).replaceWithData (st.data(), st.size());
  17918. lines.add (command + " -> " + juce::String ((int) st.size()) + " bytes");
  17919. continue;
  17920. }
  17921. const auto result = lynx::directWaveEditorTest (*panel, command);
  17922. offline.dispatchPendingMessages();
  17923. lines.add (command + " -> " + result);
  17924. }
  17925. }
  17926. }
  17927. report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
  17928. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  17929. quit();
  17930. }
  17931. void runSlicexEditTest (const juce::File& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
  17932. {
  17933. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17934. juce::StringArray lines;
  17935. {
  17936. lynx::AudioEngine offline (false);
  17937. lynx::MainComponent ui (offline, false);
  17938. ui.setSize (1280, 720);
  17939. ui.openFile (project);
  17940. offline.dispatchPendingMessages();
  17941. int channel = -1;
  17942. for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
  17943. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  17944. channel = c;
  17945. if (channel < 0)
  17946. lines.add ("no Slicex channel in " + project.getFullPathName());
  17947. else
  17948. {
  17949. auto panel = lynx::makeChannelSettingsPanel (offline, channel);
  17950. juce::Component frame;
  17951. frame.setSize (panel->getWidth(), panel->getHeight());
  17952. frame.setOpaque (true);
  17953. frame.addAndMakeVisible (*panel);
  17954. panel->setTopLeftPosition (0, 0);
  17955. offline.dispatchPendingMessages();
  17956. juce::StringArray commands;
  17957. script.readLines (commands);
  17958. for (const auto& raw : commands)
  17959. {
  17960. const auto command = raw.trim();
  17961. if (command.isEmpty() || command.startsWith ("#"))
  17962. {
  17963. lines.add (command);
  17964. continue;
  17965. }
  17966. if (command.startsWith ("shot "))
  17967. {
  17968. frame.setSize (panel->getWidth(), panel->getHeight()); // (round 190hg: the display modes resize the editor)
  17969. // (round 190jd: at the shot scale, --shot-scale / LYNX_SHOT_SCALE, with its suffix; scale 1 = the same pixels)
  17970. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  17971. const auto file = lynx::shot::file (juce::File (prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png"));
  17972. file.deleteFile();
  17973. juce::PNGImageFormat png;
  17974. if (auto out = file.createOutputStream())
  17975. png.writeImageToStream (image, *out);
  17976. lines.add (command + " -> " + file.getFileName());
  17977. continue;
  17978. }
  17979. if (command.startsWith ("menushot ")) // round 190jd: the deck's Snap menu as a picture
  17980. {
  17981. const auto file = prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png";
  17982. saveMenus (juce::StringArray { "Slicex deck: Snap" }, std::vector<juce::PopupMenu> { lynx::slicexSnapMenuForSnapshot (*panel) }, file);
  17983. lines.add (command + " -> " + juce::File (file).getFileName());
  17984. continue;
  17985. }
  17986. const auto result = lynx::slicexEditorTest (*panel, command);
  17987. offline.dispatchPendingMessages();
  17988. lines.add (command + " -> " + result);
  17989. }
  17990. }
  17991. }
  17992. report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
  17993. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  17994. quit();
  17995. }
  17996. // --slicexkeytest (round 190ac): see the command line above
  17997. void runSlicexKeyTest (const juce::File& report)
  17998. {
  17999. engine = std::make_unique<lynx::AudioEngine>();
  18000. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  18001. struct StandIn final : juce::AudioIODevice
  18002. {
  18003. StandIn() : juce::AudioIODevice ("slicexkey", "test") {}
  18004. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  18005. juce::StringArray getInputChannelNames() override { return {}; }
  18006. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  18007. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  18008. int getDefaultBufferSize() override { return 512; }
  18009. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  18010. void close() override {}
  18011. bool isOpen() override { return true; }
  18012. void start (juce::AudioIODeviceCallback*) override {}
  18013. void stop() override {}
  18014. bool isPlaying() override { return true; }
  18015. juce::String getLastError() override { return {}; }
  18016. int getCurrentBufferSizeSamples() override { return 512; }
  18017. double getCurrentSampleRate() override { return 48000.0; }
  18018. int getCurrentBitDepth() override { return 32; }
  18019. juce::BigInteger getActiveOutputChannels() const override
  18020. {
  18021. juce::BigInteger b;
  18022. b.setRange (0, 2, true);
  18023. return b;
  18024. }
  18025. juce::BigInteger getActiveInputChannels() const override { return {}; }
  18026. int getOutputLatencyInSamples() override { return 0; }
  18027. int getInputLatencyInSamples() override { return 0; }
  18028. };
  18029. auto device = std::make_shared<StandIn>();
  18030. auto text = std::make_shared<juce::String>();
  18031. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  18032. // the deck's sample: 1 s at 48 kHz, four regions (cue points) of 0.25 s, each a steady tone of its own (200 Hz
  18033. // × region number), so the region a key played can be read from the output
  18034. constexpr int rate = 48000, regionFrames = rate / 4;
  18035. const auto wavFile = report.getSiblingFile ("slicexkey-deck.wav");
  18036. {
  18037. juce::MemoryOutputStream w;
  18038. auto chunk = [&w] (const char* id, const juce::MemoryBlock& body) {
  18039. w.write (id, 4);
  18040. w.writeInt ((int) body.getSize());
  18041. w.write (body.getData(), body.getSize());
  18042. };
  18043. juce::MemoryOutputStream fmt, data, cue;
  18044. fmt.writeShort (1);
  18045. fmt.writeShort (1);
  18046. fmt.writeInt (rate);
  18047. fmt.writeInt (rate * 2);
  18048. fmt.writeShort (2);
  18049. fmt.writeShort (16);
  18050. for (int i = 0; i < 4 * regionFrames; ++i)
  18051. data.writeShort ((short) std::lround (12000.0 * std::sin (juce::MathConstants<double>::twoPi * 200.0 * (double) (i / regionFrames + 1) * (double) i / rate)));
  18052. cue.writeInt (4);
  18053. for (int k = 0; k < 4; ++k)
  18054. {
  18055. cue.writeInt (k + 1);
  18056. cue.writeInt (k * regionFrames);
  18057. cue.write ("data", 4);
  18058. cue.writeInt (0);
  18059. cue.writeInt (0);
  18060. cue.writeInt (k * regionFrames);
  18061. }
  18062. juce::MemoryOutputStream riff;
  18063. riff.write ("WAVE", 4);
  18064. w.reset();
  18065. chunk ("fmt ", fmt.getMemoryBlock());
  18066. chunk ("data", data.getMemoryBlock());
  18067. chunk ("cue ", cue.getMemoryBlock());
  18068. riff.write (w.getData(), w.getDataSize());
  18069. juce::MemoryOutputStream file;
  18070. file.write ("RIFF", 4);
  18071. file.writeInt ((int) riff.getDataSize());
  18072. file.write (riff.getData(), riff.getDataSize());
  18073. wavFile.replaceWithData (file.getData(), file.getDataSize());
  18074. }
  18075. lynx::Song song;
  18076. song.bpm = 120.0;
  18077. song.mixer = lynx::Song::defaultMixer (2);
  18078. song.channels.resize (1);
  18079. auto& channel = song.channels[0];
  18080. channel.instrument = lynx::InstrumentKind::slicex;
  18081. channel.mixerTrack = 1;
  18082. channel.samplePath = wavFile.getFullPathName().toStdString();
  18083. {
  18084. auto state = lynx::slicex::fresh();
  18085. lynx::slicex::setDeckFile (state, 0, channel.samplePath, 4);
  18086. lynx::slicex::setDeckBeats (state, 0, 0.0, 2.0);
  18087. channel.pluginState = lynx::slicex::write (state);
  18088. }
  18089. song.patterns.emplace_back();
  18090. engine->setSong (song);
  18091. auto& callback = engine->deviceCallback();
  18092. callback.audioDeviceAboutToStart (device.get());
  18093. step ("song=one Slicex channel, deck A = 4 regions of 0.25 s (200 / 400 / 600 / 800 Hz), 48 kHz, blocks of 512; keys as the editor's keyboard sends them");
  18094. juce::Timer::callAfterDelay (2000, [this, device, step] {
  18095. if (engine == nullptr)
  18096. return;
  18097. auto& cb = engine->deviceCallback();
  18098. auto pump = [&cb] (int blocks) {
  18099. std::vector<float> l (512), r (512), out;
  18100. float* outs[] = { l.data(), r.data() };
  18101. juce::AudioIODeviceCallbackContext context;
  18102. for (int k = 0; k < blocks; ++k)
  18103. {
  18104. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  18105. out.insert (out.end(), l.begin(), l.end());
  18106. }
  18107. return out;
  18108. };
  18109. auto rms = [] (const std::vector<float>& x, int from, int count) {
  18110. double sum = 0.0;
  18111. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  18112. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  18113. return std::sqrt (sum / juce::jmax (1, count));
  18114. };
  18115. // the tone's frequency from its rising zero crossings over a stretch
  18116. auto hertz = [] (const std::vector<float>& x, int from, int count) {
  18117. int crossings = 0, first = -1, last = -1;
  18118. for (int i = from + 1; i < from + count && i < (int) x.size(); ++i)
  18119. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  18120. {
  18121. first = first < 0 ? i : first;
  18122. last = i;
  18123. ++crossings;
  18124. }
  18125. return crossings > 1 ? 48000.0 * (double) (crossings - 1) / (double) (last - first) : 0.0;
  18126. };
  18127. bool ok = true;
  18128. auto check = [&ok, step] (bool good, const juce::String& what) {
  18129. ok = ok && good;
  18130. step ((good ? "ok " : "FAIL ") + what);
  18131. };
  18132. const auto idle = pump (20);
  18133. engine->getMeters().takePeak (1, 0);
  18134. check (rms (idle, 0, (int) idle.size()) < 1.0e-6, "idle: rms " + juce::String (rms (idle, 0, (int) idle.size()), 9));
  18135. // 4 regions map to keys 60…63 (FL's automatic map); the editor's click: velocity 100 / 128
  18136. engine->sendLiveNote (0, 60, 0.78125f, true);
  18137. const auto first = pump (16); // 8192 frames = 171 ms, inside region 1 (250 ms)
  18138. const auto meter = engine->getMeters().takePeak (1, 0);
  18139. check (rms (first, 1024, 6000) > 0.01, "key 60 down: rms " + juce::String (rms (first, 1024, 6000), 6) + ", " + juce::String (hertz (first, 1024, 6000), 1) + " Hz");
  18140. check (std::abs (hertz (first, 1024, 6000) - 200.0) < 4.0, "key 60 plays region 1 (200 Hz)");
  18141. check (meter > 0.01f, "mixer track 1 meter peak " + juce::String (meter, 6));
  18142. engine->sendLiveNote (0, 60, 0.0f, false);
  18143. const auto tail = pump (60);
  18144. check (rms (tail, (int) tail.size() - 4096, 4096) < 1.0e-5, "key 60 up: the end is silent, rms " + juce::String (rms (tail, (int) tail.size() - 4096, 4096), 9));
  18145. engine->sendLiveNote (0, 62, 0.78125f, true);
  18146. const auto third = pump (16);
  18147. check (rms (third, 1024, 6000) > 0.01 && std::abs (hertz (third, 1024, 6000) - 600.0) < 8.0,
  18148. "key 62 plays region 3 (600 Hz): rms " + juce::String (rms (third, 1024, 6000), 6) + ", " + juce::String (hertz (third, 1024, 6000), 1) + " Hz");
  18149. engine->sendLiveNote (0, 62, 0.0f, false);
  18150. engine->sendLiveNote (0, 72, 0.78125f, true); // a key without a region
  18151. const auto none = pump (60);
  18152. check (rms (none, (int) none.size() - 4096, 4096) < 1.0e-5, "key 72 (no region): silent, rms " + juce::String (rms (none, (int) none.size() - 4096, 4096), 9));
  18153. engine->sendLiveNote (0, 72, 0.0f, false);
  18154. step (ok ? "result=OK" : "result=FAILED");
  18155. setApplicationReturnValue (ok ? 0 : 1);
  18156. quit();
  18157. });
  18158. }
  18159. // --renderaheadtest (round 190gq): see the command line above
  18160. void runRenderAheadTest (const juce::File& report, const juce::StringArray& projects, int block, double seconds)
  18161. {
  18162. struct StandIn final : juce::AudioIODevice
  18163. {
  18164. explicit StandIn (int b) : juce::AudioIODevice ("renderahead", "test"), block (b) {}
  18165. const int block;
  18166. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  18167. juce::StringArray getInputChannelNames() override { return {}; }
  18168. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  18169. juce::Array<int> getAvailableBufferSizes() override { return { block }; }
  18170. int getDefaultBufferSize() override { return block; }
  18171. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  18172. void close() override {}
  18173. bool isOpen() override { return true; }
  18174. void start (juce::AudioIODeviceCallback*) override {}
  18175. void stop() override {}
  18176. bool isPlaying() override { return true; }
  18177. juce::String getLastError() override { return {}; }
  18178. int getCurrentBufferSizeSamples() override { return block; }
  18179. double getCurrentSampleRate() override { return 48000.0; }
  18180. int getCurrentBitDepth() override { return 32; }
  18181. juce::BigInteger getActiveOutputChannels() const override
  18182. {
  18183. juce::BigInteger b;
  18184. b.setRange (0, 2, true);
  18185. return b;
  18186. }
  18187. juce::BigInteger getActiveInputChannels() const override { return {}; }
  18188. int getOutputLatencyInSamples() override { return 0; }
  18189. int getInputLatencyInSamples() override { return 0; }
  18190. };
  18191. struct Scenario
  18192. {
  18193. juce::String name;
  18194. juce::File file; // a project, or none: the showcase song
  18195. int mode = 0; // 0 Song mode from the start, 1 a loop region, 2 Pattern mode
  18196. };
  18197. auto scenarios = std::make_shared<std::vector<Scenario>>();
  18198. scenarios->push_back ({ "showcase, Song mode", {}, 0 });
  18199. scenarios->push_back ({ "showcase, a loop region wrapping mid-block", {}, 1 });
  18200. scenarios->push_back ({ "showcase, Pattern mode", {}, 2 });
  18201. for (const auto& p : projects)
  18202. scenarios->push_back ({ juce::File (p).getFileName(), juce::File (p), 0 });
  18203. auto text = std::make_shared<juce::String>();
  18204. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  18205. step ("render-ahead test: blocks of " + juce::String (block) + " at 48 kHz, " + juce::String (seconds, 1) + " s per run");
  18206. auto outputs = std::make_shared<std::vector<std::vector<float>>>();
  18207. auto ok = std::make_shared<bool> (true);
  18208. auto run = std::make_shared<std::function<void (std::size_t, int)>>();
  18209. // (round 190rf, LeakSanitizer: the step holds itself weakly, what is pending holds it: a strong self-capture kept the
  18210. // last engine's outputs for good)
  18211. *run = [this, scenarios, step, outputs, ok, weakRun = std::weak_ptr (run), block, seconds, report] (std::size_t index, int pass) {
  18212. const auto run = weakRun.lock();
  18213. if (run == nullptr)
  18214. return;
  18215. if (index >= scenarios->size())
  18216. {
  18217. lynx::renderAheadOption().store (true);
  18218. step (juce::String ("result=") + (*ok ? "OK" : "FAIL"));
  18219. setApplicationReturnValue (*ok ? 0 : 1);
  18220. engine.reset();
  18221. quit();
  18222. return;
  18223. }
  18224. const auto& sc = (*scenarios)[index];
  18225. lynx::renderAheadOption().store (pass == 1);
  18226. engine = std::make_unique<lynx::AudioEngine>();
  18227. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  18228. engine->setRenderAheadAlways (true); // (the showcase song is light: the app would leave it real-time)
  18229. juce::String error;
  18230. auto loaded = true;
  18231. if (sc.file == juce::File())
  18232. {
  18233. auto song = lynx::makeShowcaseSong (0);
  18234. if (sc.mode == 1)
  18235. {
  18236. song.loopStart = 4 * lynx::ppq * song.beatsPerBar + 37; // (not on a block boundary)
  18237. song.loopEnd = 6 * lynx::ppq * song.beatsPerBar + 211;
  18238. song.loopOff = false;
  18239. }
  18240. if (sc.mode == 2)
  18241. song.mode = lynx::PlayMode::pattern;
  18242. engine->setSong (std::move (song));
  18243. }
  18244. else if (sc.file.hasFileExtension ("flp"))
  18245. loaded = engine->importFlpFile (sc.file, error);
  18246. else if (auto song = lynx::ProjectFile::load (sc.file, error))
  18247. engine->setSong (std::move (*song));
  18248. else
  18249. loaded = false;
  18250. if (! loaded)
  18251. {
  18252. step ("FAIL " + sc.name + ": " + error);
  18253. *ok = false;
  18254. (*run) (index + 1, 0);
  18255. return;
  18256. }
  18257. auto device = std::make_shared<StandIn> (block);
  18258. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  18259. // the graph is (re)built on the message thread: the run starts once it has settled
  18260. juce::Timer::callAfterDelay (1500, [this, scenarios, step, outputs, ok, run, block, seconds, index, pass, device] {
  18261. if (engine == nullptr)
  18262. return;
  18263. const auto& sc = (*scenarios)[index];
  18264. auto& cb = engine->deviceCallback();
  18265. std::vector<float> l ((std::size_t) block), r ((std::size_t) block), out;
  18266. float* outs[] = { l.data(), r.data() };
  18267. juce::AudioIODeviceCallbackContext context;
  18268. engine->stop();
  18269. engine->seek (0.0);
  18270. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context); // (the seek, stopped)
  18271. engine->play();
  18272. const auto blocks = (int) (seconds * 48000.0 / block);
  18273. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  18274. for (int k = 0; k < blocks; ++k)
  18275. {
  18276. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
  18277. out.insert (out.end(), l.begin(), l.end());
  18278. out.insert (out.end(), r.begin(), r.end());
  18279. // (about the device's pace at the start of each second, so the render-ahead thread gets ahead)
  18280. if (k % (48000 / block) < 48000 / block / 2)
  18281. std::this_thread::sleep_for (std::chrono::microseconds ((int) (block * 1.0e6 / 48000.0 * 0.6)));
  18282. }
  18283. const auto ms = juce::Time::getMillisecondCounterHiRes() - t0;
  18284. engine->stop();
  18285. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
  18286. const auto* st = engine->renderAheadStats();
  18287. auto n = [] (const std::atomic<std::uint64_t>& v) { return (juce::int64) v.load(); };
  18288. juce::String line = sc.name + (pass == 1 ? ", render ahead on: " : ", render ahead off: ") + juce::String (ms / 1000.0, 1) + " s";
  18289. if (st != nullptr && pass == 1)
  18290. line << "; blocks " << n (st->blocks) << ", from the ring " << n (st->fromRing) << ", waited " << n (st->waited) << ", in the callback "
  18291. << n (st->inline_) << ", dropped " << n (st->flushes) << ", drained " << n (st->drains) << ", started " << n (st->engagements)
  18292. << ", boundary mismatches " << n (st->splitMismatches) << "; ahead " << st->aheadChannels.load() << " channels / "
  18293. << st->aheadTracks.load() << " inserts, boundary " << st->boundary.load() << ", window " << st->window.load();
  18294. step (" " + line);
  18295. if (pass == 0)
  18296. {
  18297. outputs->assign (1, std::move (out));
  18298. (*run) (index, 1);
  18299. return;
  18300. }
  18301. const auto& off = outputs->front();
  18302. std::size_t first = off.size() == out.size() ? off.size() : 0;
  18303. for (std::size_t s = 0; s < std::min (off.size(), out.size()); ++s)
  18304. if (std::memcmp (&off[s], &out[s], sizeof (float)) != 0)
  18305. {
  18306. first = s;
  18307. break;
  18308. }
  18309. const auto same = off.size() == out.size() && first == off.size();
  18310. const auto clean = st != nullptr && st->flushes.load() == 0 && st->splitMismatches.load() == 0 && st->engagements.load() >= 1
  18311. && st->fromRing.load() > st->blocks.load() / 4;
  18312. *ok = *ok && same && clean;
  18313. step (juce::String (same && clean ? "ok " : "FAIL ") + sc.name + ": " + (same ? "bit-identical" : "differs from sample " + juce::String ((juce::int64) first / 2 % block) + " of block " + juce::String ((juce::int64) first / 2 / block))
  18314. + (clean ? "" : ", render-ahead counters off (see above)"));
  18315. (*run) (index + 1, 0);
  18316. });
  18317. };
  18318. (*run) (0, 0);
  18319. }
  18320. void runClipLoopTest (const juce::File& report, const juce::File& wavFile)
  18321. {
  18322. engine = std::make_unique<lynx::AudioEngine>();
  18323. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  18324. struct StandIn final : juce::AudioIODevice
  18325. {
  18326. StandIn() : juce::AudioIODevice ("cliploop", "test") {}
  18327. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  18328. juce::StringArray getInputChannelNames() override { return {}; }
  18329. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  18330. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  18331. int getDefaultBufferSize() override { return 512; }
  18332. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  18333. void close() override {}
  18334. bool isOpen() override { return true; }
  18335. void start (juce::AudioIODeviceCallback*) override {}
  18336. void stop() override {}
  18337. bool isPlaying() override { return true; }
  18338. juce::String getLastError() override { return {}; }
  18339. int getCurrentBufferSizeSamples() override { return 512; }
  18340. double getCurrentSampleRate() override { return 48000.0; }
  18341. int getCurrentBitDepth() override { return 32; }
  18342. juce::BigInteger getActiveOutputChannels() const override
  18343. {
  18344. juce::BigInteger b;
  18345. b.setRange (0, 2, true);
  18346. return b;
  18347. }
  18348. juce::BigInteger getActiveInputChannels() const override { return {}; }
  18349. int getOutputLatencyInSamples() override { return 0; }
  18350. int getInputLatencyInSamples() override { return 0; }
  18351. };
  18352. auto device = std::make_shared<StandIn>();
  18353. auto text = std::make_shared<juce::String>();
  18354. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  18355. constexpr int bar = 96000, beat = bar / 4; // 120 BPM, 48 kHz
  18356. const auto ppq = (double) lynx::ppq;
  18357. lynx::Song song;
  18358. song.bpm = 120.0;
  18359. song.mixer = lynx::Song::defaultMixer (2);
  18360. song.channels.resize (1); // the synth of a new channel: deterministic
  18361. song.channels[0].mixerTrack = 1;
  18362. auto& pattern = song.patterns.emplace_back(); // 1 bar: C5 on beat 0, C6 on beat 2
  18363. for (auto [b, key] : { std::pair { 0, 60 }, std::pair { 2, 72 } })
  18364. {
  18365. lynx::Note n;
  18366. n.start = b * lynx::ppq;
  18367. n.length = lynx::ppq / 4;
  18368. n.key = key;
  18369. pattern.notes.push_back (n);
  18370. }
  18371. lynx::Clip clip;
  18372. clip.pattern = 0;
  18373. clip.length = 16 * lynx::ppq; // stretched to 4 bars
  18374. song.playlist.push_back (clip);
  18375. song.mode = lynx::PlayMode::song;
  18376. {
  18377. // the Windows GUI check's project: the same song with a 1-bar clip, to stretch with the mouse
  18378. auto gui = song;
  18379. gui.playlist[0].length = 4 * lynx::ppq;
  18380. juce::String error;
  18381. lynx::ProjectFile::save (gui, report.getSiblingFile ("cliploop-gui.lynx"), error);
  18382. }
  18383. engine->setSong (song);
  18384. auto& callback = engine->deviceCallback();
  18385. callback.audioDeviceAboutToStart (device.get());
  18386. step ("song=1-bar synth pattern, clip stretched to 4 bars, 120 BPM, 48 kHz, blocks of 512");
  18387. // the graph is (re)built on the message thread: the scenarios run once it has settled
  18388. juce::Timer::callAfterDelay (1500, [this, device, step, wavFile, ppq] {
  18389. if (engine == nullptr)
  18390. return;
  18391. auto& cb = engine->deviceCallback();
  18392. // plays `samples` from tick `from` through the device callback; `between` runs after each block (block index)
  18393. auto play = [this, &cb] (double from, int samples, const std::function<void (int)>& between = {}) {
  18394. engine->stop();
  18395. engine->seek (from);
  18396. std::vector<float> l (512), r (512), out;
  18397. float* outs[] = { l.data(), r.data() };
  18398. juce::AudioIODeviceCallbackContext context;
  18399. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context); // (the seek, stopped)
  18400. engine->play();
  18401. for (int k = 0; (int) out.size() < samples; ++k)
  18402. {
  18403. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  18404. out.insert (out.end(), l.begin(), l.end());
  18405. if (between)
  18406. between (k);
  18407. }
  18408. engine->stop();
  18409. for (int k = 0; k < 400; ++k) // the tails of the scenario die out
  18410. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  18411. out.resize ((std::size_t) samples);
  18412. return out;
  18413. };
  18414. auto rms = [] (const std::vector<float>& x, int from, int count) {
  18415. double sum = 0.0;
  18416. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  18417. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  18418. return std::sqrt (sum / juce::jmax (1, count));
  18419. };
  18420. auto diff = [] (const std::vector<float>& a, int aFrom, const std::vector<float>& b, int bFrom, int count) {
  18421. double m = 0.0;
  18422. for (int i = 0; i < count && aFrom + i < (int) a.size() && bFrom + i < (int) b.size(); ++i)
  18423. m = juce::jmax (m, (double) std::abs (a[(std::size_t) (aFrom + i)] - b[(std::size_t) (bFrom + i)]));
  18424. return m;
  18425. };
  18426. auto num = [] (double v) { return juce::String (v, 6); };
  18427. bool ok = true;
  18428. auto check = [&ok, step] (bool good, const juce::String& what) {
  18429. ok = ok && good;
  18430. step ((good ? "ok " : "FAIL ") + what);
  18431. };
  18432. lynx::setStretchedClipsLoop (true);
  18433. const auto a = play (0.0, 4 * bar);
  18434. const auto bar1 = rms (a, 0, bar);
  18435. check (bar1 > 0.01, "play from the start: bar 1 RMS " + num (bar1));
  18436. for (int k = 1; k < 4; ++k)
  18437. {
  18438. const auto rk = rms (a, k * bar, bar), d = diff (a, k * bar, a, 0, bar);
  18439. check (std::abs (rk / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  18440. "bar " + juce::String (k + 1) + " RMS " + num (rk) + " (x" + num (rk / bar1) + " of bar 1), max |bar - bar 1| " + juce::String (d, 9));
  18441. }
  18442. {
  18443. const auto x = play (10 * ppq, bar + bar / 2);
  18444. const auto d = juce::jmax (diff (x, 0, a, 2 * beat, bar / 2), diff (x, bar / 2, a, 0, bar));
  18445. check (rms (x, 0, bar / 2) > 0.01 && d < 1.0e-4,
  18446. "start inside a repeat (bar 3, beat 3): RMS " + num (rms (x, 0, (int) x.size())) + ", max diff vs bar 1 " + juce::String (d, 9));
  18447. }
  18448. {
  18449. // a seek while playing, after 6.99 beats, to bar 4 beat 3 (a ruler click)
  18450. const auto jumpBlock = 7 * beat / 512 - 1;
  18451. const auto x = play (0.0, 2 * bar, [this, jumpBlock, ppq] (int k) {
  18452. if (k == jumpBlock)
  18453. engine->seek (14 * ppq);
  18454. });
  18455. // (the best of 0-2 samples late: anything but 0 fails)
  18456. const auto at = (jumpBlock + 1) * 512;
  18457. int lag = 0;
  18458. auto d = 1.0e9;
  18459. for (int l = 0; l <= 2; ++l)
  18460. if (const auto dl = diff (x, at + l, a, 2 * beat, beat - 2); dl < d)
  18461. d = dl, lag = l;
  18462. d = lag == 0 ? d : 1.0;
  18463. const auto ratio = rms (x, at, beat) / rms (a, 2 * beat, beat);
  18464. check (std::abs (ratio - 1.0) < 1.0e-3 && d < 1.0e-4,
  18465. "jump mid-clip to bar 4 beat 3: RMS " + num (rms (x, at, beat)) + " (x" + num (ratio) + " of bar 1 beat 3), max diff "
  18466. + juce::String (d, 9) + " (" + juce::String (lag) + " sample(s) late)");
  18467. }
  18468. {
  18469. engine->editSong ([ppq] (lynx::Song& s) {
  18470. s.loopStart = (std::int64_t) (4 * ppq);
  18471. s.loopEnd = (std::int64_t) (12 * ppq);
  18472. }, false);
  18473. const auto x = play (0.0, 7 * bar);
  18474. double d = 0.0;
  18475. juce::String lags;
  18476. for (int k = 1; k < 7; ++k) // (the best of 0-2 samples late after a wrap, as after a jump)
  18477. {
  18478. auto best = 1.0e9;
  18479. int lag = 0;
  18480. for (int l = 0; l <= 2; ++l)
  18481. if (const auto dl = diff (x, k * bar + l, a, 0, bar - 2); dl < best)
  18482. best = dl, lag = l;
  18483. d = juce::jmax (d, lag == 0 ? best : 1.0); // a sample gained at a wrap fails (round 167q loopwrap)
  18484. lags << (k > 1 ? "," : "") << lag;
  18485. }
  18486. const auto r = rms (x, bar, 6 * bar);
  18487. check (std::abs (r / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  18488. "loop region bars 2-3, played 3 times: RMS " + num (r) + " (x" + num (r / bar1) + "), max diff of each bar vs bar 1 " + juce::String (d, 9)
  18489. + " (samples late, bars 2-7: " + lags + ")");
  18490. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  18491. }
  18492. {
  18493. // 100 wraps of a 1-bar loop region (bar 2): every pass on its sample, none gained (round 167q loopwrap: each
  18494. // wrap used to play one sample more)
  18495. engine->editSong ([ppq] (lynx::Song& s) {
  18496. s.loopStart = (std::int64_t) (4 * ppq);
  18497. s.loopEnd = (std::int64_t) (8 * ppq);
  18498. }, false);
  18499. const auto x = play (0.0, 101 * bar);
  18500. double d = 0.0;
  18501. int worst = 0;
  18502. for (int k = 1; k <= 100; ++k)
  18503. if (const auto dk = diff (x, k * bar, a, 0, bar); dk > d)
  18504. d = dk, worst = k + 1;
  18505. check (d < 1.0e-4, "loop region bar 2, 100 wraps: max diff of every pass vs bar 1 " + juce::String (d, 9)
  18506. + (d < 1.0e-4 ? juce::String() : " (worst: bar " + juce::String (worst) + ")"));
  18507. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  18508. }
  18509. lynx::setStretchedClipsLoop (false);
  18510. {
  18511. const auto x = play (0.0, 4 * bar);
  18512. const auto r = juce::jmax (rms (x, bar, bar), juce::jmax (rms (x, 2 * bar, bar), rms (x, 3 * bar, bar)));
  18513. check (diff (x, 0, a, 0, bar) < 1.0e-4 && r < 1.0e-5, "option off (FL): bar 1 the same, bars 2-4 RMS at most " + juce::String (r, 9));
  18514. }
  18515. lynx::setStretchedClipsLoop (true);
  18516. cb.audioDeviceStopped();
  18517. // the export: a WAV of the 4 bars, read back from the file
  18518. if (wavFile != juce::File())
  18519. {
  18520. for (const auto loops : { true, false })
  18521. {
  18522. lynx::setStretchedClipsLoop (loops);
  18523. const auto file = loops ? wavFile : wavFile.getSiblingFile (wavFile.getFileNameWithoutExtension() + "-off.wav");
  18524. file.deleteFile();
  18525. {
  18526. juce::WavAudioFormat wav;
  18527. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (file.createOutputStream().release(), 48000.0, 2, 32, {}, 0));
  18528. engine->stop();
  18529. engine->seek (0.0);
  18530. lynx::AudioEngine::RenderOptions o;
  18531. o.seconds = 8.0;
  18532. o.sampleRate = 48000.0;
  18533. o.output = writer.get();
  18534. engine->renderOffline (o);
  18535. }
  18536. juce::WavAudioFormat wav;
  18537. std::unique_ptr<juce::AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
  18538. std::vector<float> x;
  18539. if (reader != nullptr)
  18540. {
  18541. juce::AudioBuffer<float> buffer (2, (int) reader->lengthInSamples);
  18542. reader->read (&buffer, 0, (int) reader->lengthInSamples, 0, true, true);
  18543. x.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + buffer.getNumSamples());
  18544. }
  18545. const auto b1 = rms (x, 0, bar);
  18546. juce::String line = juce::String (loops ? "export" : "export, option off") + " (" + file.getFileName() + ", " + juce::String ((int) x.size()) + " samples): bar 1 RMS " + num (b1);
  18547. bool good = x.size() >= (std::size_t) 4 * bar && b1 > 0.01;
  18548. for (int k = 1; k < 4; ++k)
  18549. {
  18550. const auto rk = rms (x, k * bar, bar);
  18551. line << ", bar " << (k + 1) << " " << num (rk);
  18552. good = good && (loops ? std::abs (rk / b1 - 1.0) < 1.0e-3 && diff (x, k * bar, x, 0, bar) < 1.0e-4 : rk < 1.0e-5);
  18553. }
  18554. if (loops)
  18555. line << ", max |bar - bar 1| " << juce::String (juce::jmax (diff (x, bar, x, 0, bar), juce::jmax (diff (x, 2 * bar, x, 0, bar), diff (x, 3 * bar, x, 0, bar))), 9);
  18556. check (good, line);
  18557. }
  18558. lynx::setStretchedClipsLoop (true);
  18559. }
  18560. step (ok ? "result=OK" : "result=FAILED");
  18561. setApplicationReturnValue (ok ? 0 : 1);
  18562. quit();
  18563. });
  18564. }
  18565. // --rectest (round 163): see the command line above. Writes report lines step by step (a driver that ends the
  18566. // process leaves what was done).
  18567. void runRecordTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  18568. const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
  18569. {
  18570. engine = std::make_unique<lynx::AudioEngine>();
  18571. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  18572. savedDeviceState = engine->getDeviceManager().createStateXml();
  18573. auto text = std::make_shared<juce::String>();
  18574. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  18575. auto finish = [this, step] (int code) {
  18576. restoreSavedDeviceState();
  18577. setApplicationReturnValue (code);
  18578. quit();
  18579. };
  18580. auto& devices = engine->getDeviceManager();
  18581. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  18582. devices.setCurrentAudioDeviceType (deviceType, true);
  18583. {
  18584. auto setup = devices.getAudioDeviceSetup();
  18585. if (deviceName.isNotEmpty())
  18586. setup.outputDeviceName = deviceName;
  18587. if (bufferSize > 0)
  18588. setup.bufferSize = bufferSize;
  18589. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  18590. step ("device_error=" + error);
  18591. }
  18592. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  18593. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  18594. // takes go next to the report, not into the user's recordings folder
  18595. engine->setRecordingTarget (report.getSiblingFile (report.getFileNameWithoutExtension() + "-takes"), {});
  18596. auto* device = devices.getCurrentAudioDevice();
  18597. if (device == nullptr || engine->getInputChannelNames().empty())
  18598. {
  18599. step ("result=ERROR no device / no input");
  18600. finish (1);
  18601. return;
  18602. }
  18603. const auto rate = device->getCurrentSampleRate();
  18604. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples())
  18605. + " | driver latency in " + juce::String (device->getInputLatencyInSamples()) + " out " + juce::String (device->getOutputLatencyInSamples()));
  18606. // a click (the ping's pulse) on every beat at 120 bpm: beat k at sample k * rate / 2
  18607. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  18608. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  18609. {
  18610. lynx::takes::WavTakeWriter w;
  18611. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  18612. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  18613. std::vector<float> block (4096);
  18614. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  18615. {
  18616. std::fill (block.begin(), block.end(), 0.0f);
  18617. for (int k = 0; k < (int) block.size(); ++k)
  18618. {
  18619. const auto f = at + k;
  18620. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  18621. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  18622. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  18623. if (rel >= 0 && rel < 5)
  18624. block[(std::size_t) k] = 0.5f * shape[rel];
  18625. }
  18626. const float* d[] { block.data() };
  18627. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  18628. }
  18629. w.close();
  18630. }
  18631. lynx::Song song = lynx::Song::makeDefault();
  18632. song.bpm = 120.0;
  18633. song.mode = lynx::PlayMode::song;
  18634. song.playlist.clear();
  18635. lynx::ChannelDef c;
  18636. c.name = "Clicks";
  18637. c.instrument = lynx::InstrumentKind::audioClip;
  18638. c.samplePath = clickFile.getFullPathName().toStdString();
  18639. c.mixerTrack = 0;
  18640. c.volume = 1.0f;
  18641. song.channels.push_back (c);
  18642. lynx::Clip clip;
  18643. clip.kind = lynx::ClipKind::audio;
  18644. clip.channel = (int) song.channels.size() - 1;
  18645. clip.track = 0;
  18646. clip.start = 0;
  18647. clip.length = (std::int64_t) beats * lynx::ppq;
  18648. song.playlist.push_back (clip);
  18649. if (mode == 1) // loop recording, bars 2-4
  18650. {
  18651. song.loopStart = 4 * lynx::ppq;
  18652. song.loopEnd = 16 * lynx::ppq;
  18653. }
  18654. else if (mode == 2) // punch in/out, bars 3-4
  18655. {
  18656. song.loopStart = 8 * lynx::ppq;
  18657. song.loopEnd = 16 * lynx::ppq;
  18658. }
  18659. if (song.mixer.size() > 1)
  18660. {
  18661. song.mixer[1].name = "Loop In";
  18662. song.mixer[1].monitor = lynx::InputMonitor::off; // (the loopback must not hear itself)
  18663. }
  18664. engine->setSong (std::move (song));
  18665. engine->setInsertInput (1, 0, false);
  18666. juce::ignoreUnused (pdcSamples);
  18667. // 1) the ping
  18668. if (const auto error = engine->startLatencyPing(); error.isNotEmpty())
  18669. step ("ping_error=" + error);
  18670. juce::Timer::callAfterDelay (3500, [this, step, finish, seconds, rate, report, mode] {
  18671. if (engine == nullptr)
  18672. return;
  18673. if (engine->isPinging())
  18674. engine->cancelLatencyPing();
  18675. const auto r = engine->finishLatencyPing();
  18676. step ("ping=" + juce::String (r.ok ? "ok" : "FAILED " + juce::String (r.problem)) + " samples " + juce::String (r.samples) + " spread " + juce::String (r.spread)
  18677. + " found " + juce::String (r.found) + "/" + juce::String (r.sent) + " peak " + juce::String (juce::Decibels::gainToDecibels (r.peak, -150.0f), 1) + " dB");
  18678. const auto l = engine->currentLatency();
  18679. step ("compensation=" + juce::String (l.total()) + " (round trip " + juce::String (l.roundTrip()) + ", manual " + juce::String (l.manual) + ", pdc " + juce::String (l.pdc) + ")");
  18680. // 2) record
  18681. engine->setInsertArmed (1, true);
  18682. auto o = engine->getRecordOptions();
  18683. o.recordAudio = true;
  18684. o.countInBars = 0;
  18685. o.waitForInput = false;
  18686. o.punchLoopRegion = mode == 2;
  18687. o.preRollBars = mode == 2 ? 1 : 0;
  18688. o.postRollBars = mode == 2 ? 1 : 0;
  18689. // (round 177c: LYNX_RECTEST_BLEND_OFF=1: Blend off; LYNX_RECTEST_LAST_PASS=1: "only the last pass plays")
  18690. o.mode = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_BLEND_OFF", {}) == "1" ? lynx::RecordMode::replace
  18691. : lynx::RecordMode::overdub;
  18692. o.lastLoopPassPlays = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_LAST_PASS", {}) == "1";
  18693. engine->setRecordOptions (o);
  18694. engine->stop();
  18695. engine->rewind();
  18696. engine->setRecording (true);
  18697. juce::Timer::callAfterDelay (300, [this, step, finish, seconds, rate, report, mode] {
  18698. if (engine == nullptr)
  18699. return;
  18700. engine->startPlayback(); // (as the Play button: pre-roll / punch)
  18701. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, step, finish, seconds, rate, report, mode] {
  18702. if (engine == nullptr)
  18703. return;
  18704. if (mode == 2)
  18705. step (juce::String ("stopped_by_post_roll=") + (engine->getTransport().playing.load() ? "no" : "yes"));
  18706. engine->stop();
  18707. juce::Timer::callAfterDelay (500, [this, step, finish, seconds, rate, report, mode] {
  18708. if (engine == nullptr)
  18709. return;
  18710. engine->setRecording (false);
  18711. const auto& s = engine->getSong();
  18712. const auto tps = 120.0 * lynx::ppq / (60.0 * rate);
  18713. int take = -1;
  18714. for (int ch = 0; ch < (int) s.channels.size(); ++ch)
  18715. if (s.channels[(std::size_t) ch].instrument == lynx::InstrumentKind::audioClip && s.channels[(std::size_t) ch].name != "Clicks")
  18716. take = ch;
  18717. if (take < 0)
  18718. {
  18719. step ("result=ERROR no take (" + engine->getLastRecordingError() + ")");
  18720. finish (1);
  18721. return;
  18722. }
  18723. std::vector<std::vector<float>> audio;
  18724. double takeRate = 0.0;
  18725. const auto& path = s.channels[(std::size_t) take].samplePath;
  18726. lynx::takes::readWav (path, audio, &takeRate);
  18727. const auto frames = audio.empty() ? (juce::int64) 0 : (juce::int64) audio[0].size();
  18728. step ("take=" + juce::String::fromUTF8 (path.c_str()) + " frames " + juce::String (frames) + " (" + juce::String ((double) frames / rate, 3)
  18729. + " s of " + juce::String (seconds, 1) + " s played) lost " + juce::String (engine->getLostRecordingFrames()));
  18730. // the clicks in the file (peaks above -12 dBFS, one per 1/8 s at most)
  18731. std::vector<juce::int64> peaks;
  18732. if (! audio.empty())
  18733. for (juce::int64 f = 1; f + 1 < frames; ++f)
  18734. {
  18735. const auto x = std::abs (audio[0][(std::size_t) f]);
  18736. if (x > 0.25f && x >= std::abs (audio[0][(std::size_t) f - 1]) && x > std::abs (audio[0][(std::size_t) f + 1])
  18737. && (peaks.empty() || f - peaks.back() > (juce::int64) (rate / 8)))
  18738. peaks.push_back (f);
  18739. }
  18740. // every clip of the take: each click inside it against the nearest beat
  18741. int clips = 0, checked = 0, muted = 0;
  18742. double worst = 0.0, sum = 0.0;
  18743. for (const auto& c : s.playlist)
  18744. {
  18745. if (c.kind != lynx::ClipKind::audio || c.channel != take)
  18746. continue;
  18747. ++clips;
  18748. muted += c.muted ? 1 : 0;
  18749. const auto skip = ((double) c.offset + (double) c.offsetFraction) / tps; // file samples before the clip start
  18750. for (const auto f : peaks)
  18751. {
  18752. const auto intoClip = (double) f - skip;
  18753. if (intoClip < 0.0 || intoClip * tps >= (double) c.length)
  18754. continue;
  18755. const auto songTick = (double) c.start + intoClip * tps - 2.0 * tps; // (the pulse's peak is its 3rd sample)
  18756. const auto beat = std::round (songTick / lynx::ppq) * lynx::ppq;
  18757. const auto error = (songTick - beat) / tps;
  18758. worst = std::max (worst, std::abs (error));
  18759. sum += error;
  18760. ++checked;
  18761. }
  18762. step ("clip track " + juce::String (c.track) + " start " + juce::String ((juce::int64) c.start) + " length " + juce::String ((juce::int64) c.length)
  18763. + " offset " + juce::String ((juce::int64) c.offset) + juce::String (c.offsetFraction >= 0.0f ? "+" : "") + juce::String (c.offsetFraction, 4)
  18764. + (c.muted ? " (muted lane)" : ""));
  18765. }
  18766. step ("clicks_in_file=" + juce::String ((int) peaks.size()) + " checked=" + juce::String (checked) + " clips=" + juce::String (clips)
  18767. + " muted_lanes=" + juce::String (muted));
  18768. step ("placement_error_samples=max " + juce::String (worst, 3) + " mean " + juce::String (checked > 0 ? sum / checked : 0.0, 3));
  18769. auto ok = checked > 0 && worst <= 1.0 && engine->getLostRecordingFrames() == 0;
  18770. if (mode == 2) // one clip, exactly the punch range, its 8 beats
  18771. {
  18772. const auto& sp = engine->getSong();
  18773. bool exact = false;
  18774. for (const auto& c : sp.playlist)
  18775. if (c.kind == lynx::ClipKind::audio && c.channel == take)
  18776. exact = c.start == sp.loopStart && c.start + c.length == sp.loopEnd;
  18777. step (juce::String ("punch_clip_matches_range=") + (exact ? "yes" : "no"));
  18778. ok = ok && clips == 1 && exact && checked == 8;
  18779. }
  18780. report.getSiblingFile (report.getFileNameWithoutExtension() + "-project.lynx").replaceWithText (lynx::ProjectFile::toJson (engine->getSong()));
  18781. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  18782. finish (ok ? 0 : 1);
  18783. });
  18784. });
  18785. });
  18786. });
  18787. }
  18788. // --hwinserttest (round 164d): see the command line above.
  18789. void runHwInsertTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  18790. const juce::String& inputName, int bufferSize, bool inPatcher = false, juce::File bounceFile = {})
  18791. {
  18792. engine = std::make_unique<lynx::AudioEngine>();
  18793. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  18794. savedDeviceState = engine->getDeviceManager().createStateXml();
  18795. auto text = std::make_shared<juce::String>();
  18796. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  18797. auto finish = [this] (int code) {
  18798. if (engine != nullptr)
  18799. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  18800. restoreSavedDeviceState();
  18801. setApplicationReturnValue (code);
  18802. quit();
  18803. };
  18804. auto& devices = engine->getDeviceManager();
  18805. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  18806. devices.setCurrentAudioDeviceType (deviceType, true);
  18807. {
  18808. auto setup = devices.getAudioDeviceSetup();
  18809. if (deviceName.isNotEmpty())
  18810. setup.outputDeviceName = deviceName;
  18811. if (bufferSize > 0)
  18812. setup.bufferSize = bufferSize;
  18813. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  18814. step ("device_error=" + error);
  18815. }
  18816. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  18817. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  18818. auto* device = devices.getCurrentAudioDevice();
  18819. if (device == nullptr || engine->getInputChannelNames().empty())
  18820. {
  18821. step ("result=ERROR no device / no input");
  18822. finish (1);
  18823. return;
  18824. }
  18825. const auto rate = device->getCurrentSampleRate();
  18826. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples()));
  18827. // the click track: the ping's pulse on every beat at 120 bpm
  18828. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  18829. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  18830. {
  18831. lynx::takes::WavTakeWriter w;
  18832. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  18833. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  18834. std::vector<float> block (4096);
  18835. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  18836. {
  18837. std::fill (block.begin(), block.end(), 0.0f);
  18838. for (int k = 0; k < (int) block.size(); ++k)
  18839. {
  18840. const auto f = at + k;
  18841. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  18842. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  18843. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  18844. if (rel >= 0 && rel < 5)
  18845. block[(std::size_t) k] = 0.5f * shape[rel];
  18846. }
  18847. const float* d[] { block.data() };
  18848. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  18849. }
  18850. w.close();
  18851. }
  18852. lynx::Song song = lynx::Song::makeDefault();
  18853. song.bpm = 120.0;
  18854. song.mode = lynx::PlayMode::song;
  18855. song.playlist.clear();
  18856. song.channels.clear();
  18857. for (int k = 0; k < 2; ++k)
  18858. {
  18859. lynx::ChannelDef c;
  18860. c.name = k == 0 ? "Wet" : "Dry";
  18861. c.instrument = lynx::InstrumentKind::audioClip;
  18862. c.samplePath = clickFile.getFullPathName().toStdString();
  18863. c.mixerTrack = k + 1;
  18864. c.volume = 1.0f;
  18865. song.channels.push_back (c);
  18866. lynx::Clip clip;
  18867. clip.kind = lynx::ClipKind::audio;
  18868. clip.channel = k;
  18869. clip.track = k;
  18870. clip.start = 0;
  18871. clip.length = (std::int64_t) beats * lynx::ppq;
  18872. song.playlist.push_back (clip);
  18873. }
  18874. song.mixer[0].outputChannel = lynx::outputNone; // (the cable carries the send only)
  18875. for (auto& fx : song.mixer[0].effects) // (no Master effects: the default limiter's PDC would hide nothing, but keep it plain)
  18876. fx.enabled = false;
  18877. song.mixer[1].pan = -1.0f;
  18878. song.mixer[2].pan = 1.0f;
  18879. auto hw = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  18880. hw.params[lynx::hwinsert::output] = lynx::hwinsert::channelValue (0);
  18881. hw.params[lynx::hwinsert::input] = lynx::hwinsert::channelValue (0);
  18882. hw.params[lynx::hwinsert::inputStereo] = 1.0f;
  18883. song.mixer[1].effects.clear();
  18884. lynx::AudioEngine::HardwareInsertRef ref { false, 1, 0, {} };
  18885. if (inPatcher) // (round 165c) From LYNX -> Hardware Insert -> To LYNX
  18886. {
  18887. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  18888. lynx::PatchNode node;
  18889. node.effect = hw;
  18890. slot.patcher.nodes = { node };
  18891. lynx::PatchWire in, out;
  18892. in.from = lynx::patchFromHost;
  18893. in.to = 0;
  18894. out.from = 0;
  18895. out.to = lynx::patchToHost;
  18896. slot.patcher.wires = { in, out };
  18897. song.mixer[1].effects.push_back (slot);
  18898. ref.nodes = { 0 };
  18899. }
  18900. else
  18901. song.mixer[1].effects.push_back (hw);
  18902. engine->setSong (std::move (song));
  18903. step (juce::String ("insert=") + (inPatcher ? "inside a Patcher on Insert 1" : "Insert 1 slot 1"));
  18904. const auto meter = [this, ref] (int output) {
  18905. const auto fx = engine->runningHardwareInsert (ref);
  18906. return fx != nullptr ? fx->controlOutput (output) : 0.0f;
  18907. };
  18908. // 1) the insert's ping (as its Ping button: a momentary value flipped)
  18909. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  18910. if (engine == nullptr)
  18911. return;
  18912. engine->pingHardwareInserts ({ ref });
  18913. juce::Timer::callAfterDelay (3500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  18914. if (engine == nullptr)
  18915. return;
  18916. // (round 165c) the engine makes a ping's result the slot's round trip with the device setup it belongs to; the
  18917. // new round trip rebuilds the insert (its latency), so the result is read from the slot
  18918. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  18919. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  18920. const auto setup = slot != nullptr ? lynx::hwinsert::measuredSetup (*slot) : std::string();
  18921. const auto state = meter (lynx::hwinsert::pingState);
  18922. const auto ok = samples > 0 && setup == engine->currentSetupKey();
  18923. step ("ping_round_trip=" + juce::String (samples) + " measured_setup=" + juce::String (setup) + (ok ? " (ok)" : " (FAILED)")
  18924. + " live_ping_state=" + juce::String (state, 3) + " status_flags=" + juce::String (juce::roundToInt (meter (lynx::hwinsert::status) * 16.0f)));
  18925. if (! ok)
  18926. {
  18927. step ("result=FAILED ping");
  18928. finish (1);
  18929. return;
  18930. }
  18931. // a stale setup is noticed: another setup key on the slot gives the notice, the real one none
  18932. step ("stale_now=" + juce::String ((int) engine->staleHardwareInserts().size()));
  18933. // 2) play, capturing the Master
  18934. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, samples, ref, inPatcher, bounceFile] {
  18935. if (engine == nullptr)
  18936. return;
  18937. step ("pdc_total=" + juce::String (engine->getLatencySamples()) + " (expected " + juce::String (samples) + ")");
  18938. // saved in the project: the slot comes back the same (routing, round trip), and its latency with it — also an
  18939. // odd round trip (12345 samples: the project keeps it to the sample)
  18940. if (! inPatcher)
  18941. {
  18942. auto odd = engine->getSong();
  18943. odd.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (12345);
  18944. juce::String error;
  18945. auto same = true;
  18946. for (const auto* song : { &engine->getSong(), (const lynx::Song*) &odd })
  18947. {
  18948. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (song == &odd ? "-odd.lynx" : ".lynx"));
  18949. const auto saved = lynx::ProjectFile::save (*song, file, error);
  18950. const auto loaded = saved ? lynx::ProjectFile::load (file, error) : std::nullopt;
  18951. same = same && loaded && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  18952. && loaded->mixer[1].effects[0].kind == lynx::EffectKind::hardwareInsert
  18953. && loaded->mixer[1].effects[0].params == song->mixer[1].effects[0].params
  18954. && lynx::makeEffect (loaded->mixer[1].effects[0])->latencySamples() == (song == &odd ? 12345 : samples);
  18955. }
  18956. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + ".lynx");
  18957. step (juce::String ("project_round_trip=") + (same ? "same" : "DIFFERENT " + error) + " (" + file.getFileName() + ")");
  18958. if (! same)
  18959. {
  18960. step ("result=FAILED project");
  18961. finish (1);
  18962. return;
  18963. }
  18964. }
  18965. auto left = std::make_shared<std::vector<float>>(), right = std::make_shared<std::vector<float>>();
  18966. engine->stop();
  18967. engine->rewind();
  18968. engine->getMeters().capture.setSource (0);
  18969. engine->play();
  18970. auto pulls = std::make_shared<int> ((int) (seconds * 5.0));
  18971. auto pull = std::make_shared<std::function<void()>>();
  18972. *pull = [this, report, step, finish, seconds, rate, samples, left, right, pulls, pull, ref, inPatcher, bounceFile] {
  18973. if (engine == nullptr)
  18974. return;
  18975. engine->getMeters().capture.pull (*left, *right);
  18976. if (*pulls == 10) // the insert's editor while it plays (next to the report)
  18977. for (const auto scale : { 1.0f, 1.5f })
  18978. {
  18979. auto editor = inPatcher ? lynx::makeNodeEffectEditor (
  18980. *engine, [ref] (lynx::Song& s) { return lynx::AudioEngine::locateHardwareInsert (s, ref); },
  18981. [this, ref] { return engine->runningHardwareInsert (ref); }, "Insert 1 (Patcher)", scale)
  18982. : lynx::makeNativeEffectEditor (*engine, 1, 0, scale, 0);
  18983. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  18984. {
  18985. juce::Graphics g (image);
  18986. g.fillAll (lynx::theme::panel);
  18987. editor->paintEntireComponent (g, false);
  18988. }
  18989. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (scale > 1.0f ? "-editor150.png" : "-editor.png"));
  18990. file.deleteFile();
  18991. juce::PNGImageFormat png;
  18992. if (auto stream = file.createOutputStream())
  18993. png.writeImageToStream (image, *stream);
  18994. }
  18995. if (--*pulls > 0)
  18996. {
  18997. juce::Timer::callAfterDelay (200, *pull);
  18998. return;
  18999. }
  19000. engine->stop();
  19001. const auto dropped = engine->getMeters().capture.droppedFrames();
  19002. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  19003. // the clicks of each side (peaks above -12 dBFS, one per 1/8 s at most)
  19004. auto peaksOf = [rate] (const std::vector<float>& x) {
  19005. std::vector<juce::int64> peaks;
  19006. for (std::size_t f = 1; f + 1 < x.size(); ++f)
  19007. if (std::abs (x[f]) > 0.25f && std::abs (x[f]) >= std::abs (x[f - 1]) && std::abs (x[f]) > std::abs (x[f + 1])
  19008. && (peaks.empty() || (juce::int64) f - peaks.back() > (juce::int64) (rate / 8)))
  19009. peaks.push_back ((juce::int64) f);
  19010. return peaks;
  19011. };
  19012. const auto wet = peaksOf (*left), dry = peaksOf (*right);
  19013. int pairs = 0;
  19014. juce::int64 worst = 0;
  19015. double gainSum = 0.0, residual = 0.0, energy = 0.0;
  19016. for (const auto w : wet)
  19017. {
  19018. auto best = std::min_element (dry.begin(), dry.end(), [w] (juce::int64 a, juce::int64 b) { return std::abs (a - w) < std::abs (b - w); });
  19019. if (best == dry.end() || std::abs (*best - w) > (juce::int64) (rate / 8))
  19020. continue;
  19021. ++pairs;
  19022. worst = std::max (worst, std::abs (*best - w));
  19023. gainSum += (*left)[(std::size_t) w] / (*right)[(std::size_t) *best];
  19024. }
  19025. const auto gain = pairs > 0 ? gainSum / pairs : 1.0;
  19026. // dry clicks with no wet click beside them (a dropout of the cable / device), listed
  19027. juce::String unmatched;
  19028. for (const auto d : dry)
  19029. if (std::none_of (wet.begin(), wet.end(), [d, rate] (juce::int64 w) { return std::abs (w - d) <= (juce::int64) (rate / 8); }))
  19030. unmatched << " " << (juce::int64) d << " (" << juce::String ((*left)[(std::size_t) d], 3) << ")";
  19031. if (unmatched.isNotEmpty())
  19032. step ("dry_clicks_without_wet=" + unmatched);
  19033. // the null test: left − gain · right around each click (both sides aligned → only the cable's colour remains)
  19034. for (const auto w : wet)
  19035. for (juce::int64 f = std::max<juce::int64> (0, w - 16); f < std::min<juce::int64> ((juce::int64) left->size(), w + 16); ++f)
  19036. {
  19037. const auto d = (double) (*left)[(std::size_t) f] - gain * (double) (*right)[(std::size_t) f];
  19038. residual += d * d;
  19039. energy += (double) (*left)[(std::size_t) f] * (*left)[(std::size_t) f];
  19040. }
  19041. const auto nullDb = energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, residual / energy)) : 0.0;
  19042. step ("captured=" + juce::String ((int) left->size()) + " frames dropped=" + juce::String (dropped) + " wet_clicks=" + juce::String ((int) wet.size())
  19043. + " dry_clicks=" + juce::String ((int) dry.size()) + " pairs=" + juce::String (pairs));
  19044. step ("alignment_error_samples=max " + juce::String ((int) worst) + " cable_gain=" + juce::String (gain, 4) + " null_residual_db=" + juce::String (nullDb, 1));
  19045. auto* dev = engine->getDeviceManager().getCurrentAudioDevice();
  19046. const auto xruns = dev != nullptr ? dev->getXRunCount() : -1;
  19047. step ("device_xruns=" + juce::String (xruns) + " (a dropout loses what was on the cable then: its clicks are excused)");
  19048. const auto excused = xruns > 0 ? 2 * xruns : 0;
  19049. const auto ok = pairs >= (int) (seconds * 2.0) - 2 - excused && worst == 0 && dropped == 0 && engine->getLatencySamples() == samples;
  19050. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  19051. // (round 165c) then the re-ping notice after a buffer size change
  19052. auto then = [this, ref, step, finish] (int code) {
  19053. if (code != 0)
  19054. finish (code);
  19055. else
  19056. runRepingCheck (ref, step, finish);
  19057. };
  19058. if (! ok)
  19059. {
  19060. finish (1);
  19061. return;
  19062. }
  19063. if (bounceFile == juce::File())
  19064. then (0);
  19065. else
  19066. runBounceCheck (bounceFile, step, then);
  19067. };
  19068. juce::Timer::callAfterDelay (200, *pull);
  19069. });
  19070. });
  19071. });
  19072. }
  19073. // --hwinserttest --bounce (round 165c): Export › "Render through the hardware in real time" of the test song next to
  19074. // the offline export of the same song. Through the loopback cable (gain 1) the return is the send delayed by the
  19075. // pinged round trip, so the real-time file must equal the offline one (which passes the dry signal at that delay)
  19076. // to float rounding, with the wet clicks (left) on the dry clicks' samples (right).
  19077. // --hwinserttest (round 165c): the buffer size changes (another round trip on the device): the engine notices the
  19078. // insert measured for the old setup (the app's "Ping now?" prompt), "Ping now" measures it again for the new one
  19079. void runRepingCheck (lynx::AudioEngine::HardwareInsertRef ref, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  19080. {
  19081. auto& devices = engine->getDeviceManager();
  19082. auto setup = devices.getAudioDeviceSetup();
  19083. const auto before = setup.bufferSize;
  19084. setup.bufferSize = before == 512 ? 256 : 512;
  19085. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  19086. step ("reping_device_error=" + error);
  19087. engine->takeHardwareInsertNotice(); // (whatever was pending before the change)
  19088. juce::Timer::callAfterDelay (1500, [this, ref, step, finish, before] {
  19089. if (engine == nullptr)
  19090. return;
  19091. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  19092. const auto block = device != nullptr ? device->getCurrentBufferSizeSamples() : 0;
  19093. const auto notice = engine->takeHardwareInsertNotice();
  19094. step ("reping_buffer=" + juce::String (before) + "->" + juce::String (block) + " notice=" + juce::String ((int) notice.size())
  19095. + " stale=" + juce::String ((int) engine->staleHardwareInserts().size()));
  19096. if (notice.size() != 1 || ! (notice[0] == ref))
  19097. {
  19098. step ("result_reping=FAILED (no notice)");
  19099. finish (1);
  19100. return;
  19101. }
  19102. engine->pingHardwareInserts (notice); // ("Ping now")
  19103. juce::Timer::callAfterDelay (3500, [this, ref, step, finish, block] {
  19104. if (engine == nullptr)
  19105. return;
  19106. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  19107. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  19108. const auto stale = (int) engine->staleHardwareInserts().size();
  19109. step ("reping_round_trip=" + juce::String (samples) + " pdc_total=" + juce::String (engine->getLatencySamples()) + " stale=" + juce::String (stale));
  19110. const auto ok = stale == 0 && samples > 0 && engine->getLatencySamples() == samples;
  19111. step (juce::String ("result_reping=") + (ok ? "OK" : "FAILED") + " (device block " + juce::String (block) + ")");
  19112. finish (ok ? 0 : 1);
  19113. });
  19114. });
  19115. }
  19116. void runBounceCheck (const juce::File& bounceFile, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  19117. {
  19118. // the Export window as the user sees it with the real-time option ticked (next to the report)
  19119. lynx::showExportDialog (*engine, bounceFile.getParentDirectory(), "bounce", 0);
  19120. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  19121. if (auto* w = juce::TopLevelWindow::getTopLevelWindow (k))
  19122. {
  19123. std::function<juce::ToggleButton* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ToggleButton* {
  19124. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Render through the hardware in real time"))
  19125. return t;
  19126. for (auto* child : c.getChildren())
  19127. if (auto* t = find (*child))
  19128. return t;
  19129. return nullptr;
  19130. };
  19131. if (auto* toggle = find (*w))
  19132. {
  19133. step (juce::String ("export_option_visible=") + (toggle->isVisible() ? "yes" : "NO"));
  19134. toggle->setToggleState (true, juce::sendNotificationSync); // (calls its onClick, as a click)
  19135. auto* c = dynamic_cast<juce::DocumentWindow*> (w) != nullptr ? static_cast<juce::DocumentWindow*> (w)->getContentComponent() : w;
  19136. if (c != nullptr)
  19137. {
  19138. const auto file = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-export.png");
  19139. file.deleteFile();
  19140. juce::FileOutputStream out (file);
  19141. juce::PNGImageFormat png;
  19142. if (out.openedOk())
  19143. png.writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  19144. }
  19145. delete w;
  19146. break;
  19147. }
  19148. }
  19149. lynx::exportopts::Options o;
  19150. o.format = lynx::exportopts::Format::wav;
  19151. o.wavBits = 32;
  19152. o.dither = lynx::exportopts::DitherMode::none;
  19153. o.tail = lynx::exportopts::TailMode::cut;
  19154. o.range = lynx::exportopts::Range::song;
  19155. o.trimPdc = true;
  19156. o.hqAllPlugins = false;
  19157. o.pluginWarmUp = false;
  19158. const auto offlineFile = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-offline.wav");
  19159. auto realtimeJob = std::make_shared<lynx::ExportJob> (*engine, o, bounceFile);
  19160. o.sampleRate = engine->getTransport().sampleRate.load();
  19161. auto offlineJob = std::make_shared<lynx::ExportJob> (engine->getSong(), o, offlineFile);
  19162. struct Shared
  19163. {
  19164. std::atomic<int> done { 0 };
  19165. bool okRealtime = false, okOffline = false;
  19166. juce::String errorRealtime, errorOffline;
  19167. double lastProgress = 0.0;
  19168. double started = juce::Time::getMillisecondCounterHiRes();
  19169. };
  19170. auto shared = std::make_shared<Shared>();
  19171. // (the jobs stay owned by the message thread's poll below: they are destroyed there)
  19172. juce::Thread::launch ([rt = realtimeJob.get(), off = offlineJob.get(), shared] {
  19173. shared->okRealtime = rt->run ([shared] (double p) { shared->lastProgress = p; return true; }, shared->errorRealtime);
  19174. shared->okOffline = off->run ({}, shared->errorOffline);
  19175. shared->done.store (1);
  19176. });
  19177. auto poll = std::make_shared<std::function<void()>>();
  19178. *poll = [this, poll, shared, realtimeJob, offlineJob, bounceFile, offlineFile, step, finish] {
  19179. if (shared->done.load() == 0)
  19180. {
  19181. juce::Timer::callAfterDelay (100, *poll);
  19182. return;
  19183. }
  19184. const auto seconds = (juce::Time::getMillisecondCounterHiRes() - shared->started) / 1000.0;
  19185. step ("bounce_realtime=" + juce::String (shared->okRealtime ? "ok" : "FAILED " + shared->errorRealtime) + " offline="
  19186. + juce::String (shared->okOffline ? "ok" : "FAILED " + shared->errorOffline) + " took=" + juce::String (seconds, 1) + " s (music "
  19187. + juce::String (realtimeJob->getMusicSeconds(), 1) + " s)" + (realtimeJob->getNotice().isNotEmpty() ? " notice=" + realtimeJob->getNotice() : juce::String()));
  19188. juce::AudioFormatManager formats;
  19189. formats.registerBasicFormats();
  19190. std::unique_ptr<juce::AudioFormatReader> a (formats.createReaderFor (bounceFile)), b (formats.createReaderFor (offlineFile));
  19191. if (! shared->okRealtime || ! shared->okOffline || a == nullptr || b == nullptr)
  19192. {
  19193. step ("result=FAILED bounce");
  19194. finish (1);
  19195. return;
  19196. }
  19197. const auto frames = (int) std::min (a->lengthInSamples, b->lengthInSamples);
  19198. juce::AudioBuffer<float> x (2, frames), y (2, frames);
  19199. a->read (&x, 0, frames, 0, true, true);
  19200. b->read (&y, 0, frames, 0, true, true);
  19201. double residual = 0.0, energy = 0.0, wetDry = 0.0;
  19202. for (int ch = 0; ch < 2; ++ch)
  19203. for (int i = 0; i < frames; ++i)
  19204. {
  19205. const double d = x.getSample (ch, i) - y.getSample (ch, i);
  19206. residual += d * d;
  19207. energy += (double) y.getSample (ch, i) * y.getSample (ch, i);
  19208. }
  19209. for (int i = 0; i < frames; ++i) // the wet side against the dry side of the real-time file
  19210. wetDry += std::pow ((double) x.getSample (0, i) - x.getSample (1, i), 2.0);
  19211. const auto db = [energy] (double r) { return energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, r / energy)) : 0.0; };
  19212. step ("bounce_frames=" + juce::String ((juce::int64) a->lengthInSamples) + " offline_frames=" + juce::String ((juce::int64) b->lengthInSamples)
  19213. + " rate=" + juce::String (a->sampleRate) + " bounce_vs_offline_db=" + juce::String (db (residual), 1)
  19214. + " wet_vs_dry_db=" + juce::String (db (2.0 * wetDry), 1) + " peak=" + juce::String (realtimeJob->getPeak(), 3));
  19215. const auto ok = std::abs (a->lengthInSamples - b->lengthInSamples) <= 1 && db (residual) < -100.0 && realtimeJob->getPeak() > 0.1f;
  19216. step (juce::String ("result_bounce=") + (ok ? "OK" : "FAILED"));
  19217. finish (ok ? 0 : 1);
  19218. };
  19219. juce::Timer::callAfterDelay (100, *poll);
  19220. }
  19221. // --rtstress --record: stops recording (the take becomes a clip of the song, as in the app), moves the take's WAV to
  19222. // `target` and describes it: length against the time played, channels, peak, the latencies the driver reported.
  19223. juce::String finishStressTake (const juce::File& target, double seconds)
  19224. {
  19225. juce::String text;
  19226. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  19227. text << " recording: input " << (device != nullptr ? device->getActiveInputChannels().countNumberOfSetBits() : 0) << " channel(s)";
  19228. if (device != nullptr)
  19229. text << ", input latency " << device->getInputLatencyInSamples() << " + output latency " << device->getOutputLatencyInSamples() << " samples";
  19230. engine->setRecording (false); // closes the take: a clip of the song
  19231. juce::File take;
  19232. for (const auto& c : engine->getSong().channels)
  19233. if (c.instrument == lynx::InstrumentKind::audioClip)
  19234. take = juce::File (juce::String::fromUTF8 (c.samplePath.c_str()));
  19235. if (! take.existsAsFile())
  19236. return text + "\n recording: no take (" + engine->getLastRecordingError() + ")\n";
  19237. target.deleteFile();
  19238. if (! take.moveFileTo (target))
  19239. take.copyFileTo (target);
  19240. juce::AudioFormatManager formats;
  19241. formats.registerBasicFormats();
  19242. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (target)); reader != nullptr)
  19243. {
  19244. juce::AudioBuffer<float> audio ((int) reader->numChannels, (int) reader->lengthInSamples);
  19245. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, true);
  19246. const auto peak = audio.getMagnitude (0, audio.getNumSamples());
  19247. const auto length = (double) reader->lengthInSamples / reader->sampleRate;
  19248. text << "\n recording: take " << juce::String (length, 3) << " s of " << juce::String (seconds, 0) << " s played, "
  19249. << (int) reader->numChannels << " ch @ " << (int) reader->sampleRate << " Hz, peak "
  19250. << juce::String (juce::Decibels::gainToDecibels (peak, -150.0f), 1) << " dBFS -> " << target.getFullPathName() << "\n";
  19251. }
  19252. else
  19253. text << "\n recording: take unreadable (" << target.getFullPathName() << ")\n";
  19254. return text;
  19255. }
  19256. // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
  19257. // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
  19258. void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
  19259. {
  19260. lynx::AudioEngine offline (false);
  19261. const juce::File input (inputPath);
  19262. juce::String error, report;
  19263. bool ok = false;
  19264. if (input.hasFileExtension ("flp;als;flm;songtmpl;band;blx;mod;xm;s3m;it")) // (round 190ic: a GarageBand .band folder too; 190nw: a module)
  19265. ok = offline.importFlpFile (input, error);
  19266. else if (auto song = lynx::ProjectFile::load (input, error))
  19267. {
  19268. offline.setSong (std::move (*song));
  19269. ok = true;
  19270. }
  19271. int samplers = 0, samplersLoaded = 0;
  19272. if (ok)
  19273. {
  19274. for (const auto& c : offline.getSong().channels)
  19275. if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
  19276. {
  19277. ++samplers;
  19278. samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
  19279. }
  19280. const juce::File output (outputPath);
  19281. output.deleteFile();
  19282. juce::WavAudioFormat wav;
  19283. std::unique_ptr<juce::AudioFormatWriter> writer (
  19284. wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
  19285. if (writer == nullptr)
  19286. {
  19287. ok = false;
  19288. error = lynx::utf8 ("could not create ") + outputPath;
  19289. }
  19290. else
  19291. {
  19292. const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
  19293. report << "peak=" << peak << "\n";
  19294. ok = peak > 0.001f;
  19295. }
  19296. }
  19297. report << "samples=" << samplersLoaded << "/" << samplers << "\n"
  19298. << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  19299. juce::File (outputPath + ".txt").replaceWithText (report);
  19300. setApplicationReturnValue (ok ? 0 : 1);
  19301. quit();
  19302. }
  19303. // LYNX.exe --export-flp project.(lynx|flp|als) output.(flp|zip) [--substitute] (round 171e): File › Export › FL Studio
  19304. // project without the window (option A unless --substitute; the renders next to a .flp in "<name> audio"); the
  19305. // report goes to output.txt
  19306. void runAlsExport (const juce::String& inputPath, const juce::String& folderPath, bool live11, bool reference)
  19307. {
  19308. juce::String error;
  19309. juce::StringArray notes;
  19310. juce::File als;
  19311. {
  19312. lynx::AudioEngine loader (false);
  19313. const juce::File input (inputPath);
  19314. bool ok = false;
  19315. // --scan: the targeted plugin scan an open runs first (child processes), so the set's plugins load
  19316. if (juce::JUCEApplication::getCommandLineParameterArray().contains ("--scan") && input.hasFileExtension ("flp;als;flm;songtmpl"))
  19317. {
  19318. juce::MemoryBlock data;
  19319. if (input.loadFileAsData (data))
  19320. {
  19321. const std::vector<std::uint8_t> bytes (static_cast<const std::uint8_t*> (data.getData()),
  19322. static_cast<const std::uint8_t*> (data.getData()) + data.getSize());
  19323. try
  19324. {
  19325. const auto uses = input.hasFileExtension ("als") ? lynx::alsForeignPlugins (bytes)
  19326. : lynx::flpForeignPlugins (flp::parseProject ({ bytes.data(), bytes.size() }));
  19327. loader.getPluginHost().scanFiles (loader.getPluginHost().filesToScanFor (uses), {});
  19328. }
  19329. catch (const std::exception&)
  19330. {
  19331. }
  19332. }
  19333. }
  19334. if (input.hasFileExtension ("flp;als;flm;songtmpl;band;blx;mod;xm;s3m;it"))
  19335. ok = loader.importFlpFile (input, error);
  19336. else if (auto song = lynx::ProjectFile::load (input, error))
  19337. {
  19338. loader.setSong (std::move (*song));
  19339. ok = true;
  19340. }
  19341. if (ok)
  19342. {
  19343. loader.capturePluginStates();
  19344. const juce::File folder (folderPath);
  19345. folder.createDirectory();
  19346. als = lynx::writeAlsProject (loader.getSong(), &loader.getPluginHost(), live11 ? lynx::AlsVersion::live11 : lynx::AlsVersion::live12, ! reference, folder,
  19347. input.getFileNameWithoutExtension(), notes, error);
  19348. }
  19349. }
  19350. juce::String report;
  19351. report << (als != juce::File() ? "ok " + als.getFullPathName() : "error=" + error) << "\n" << notes.joinIntoString ("\n") << "\n";
  19352. juce::File (folderPath).getChildFile ("export-als.txt").replaceWithText (report);
  19353. setApplicationReturnValue (als != juce::File() ? 0 : 1);
  19354. quit();
  19355. }
  19356. // --versionsshot <prefix> (round 190ap): everything the round adds, offscreen (no window on the desktop):
  19357. // -versions.png / -versions-unsaved.png the Versions panel (a project with versions, backups and labels; a new one)
  19358. // -menu-file.png / -menu-file-pluginsoff.png the File menu, and as it is while the plugins are off
  19359. // -pluginsoff-window.png / -pluginsoff-mixer.png a project opened without its third-party plugins (the tags)
  19360. // -pluginsoff-panel.png / -pluginsoff-panel-one.png the list, all off, then after "Switch on" for one
  19361. // -export-default.png / -export.png the Export window as it opens, and with the additions in use
  19362. bool runLinkShot (const juce::String& prefix)
  19363. {
  19364. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19365. juce::StringArray report;
  19366. bool allOk = true;
  19367. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  19368. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  19369. allOk = allOk && ok;
  19370. };
  19371. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  19372. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  19373. };
  19374. using lynx::AutomationTarget;
  19375. using lynx::AutomationTargetKind;
  19376. using lynx::MidiLink;
  19377. lynx::AudioEngine engine (false);
  19378. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 },
  19379. insert { AutomationTargetKind::mixerVolume, 1 };
  19380. // ---- the window as it opens on a control with no link (FL's defaults)
  19381. {
  19382. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  19383. shoot (*panel, "remote-default");
  19384. check ("default_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  19385. // Auto detect: the controller that sends next fills the fields
  19386. engine.injectControllerForTest (74, 2, 100, 5);
  19387. lynx::remoteControlPanelPoll (*panel);
  19388. check ("auto_detect", lynx::remoteControlPanelState (*panel).startsWith ("5|3|74|"), lynx::remoteControlPanelState (*panel));
  19389. // a formula preset, smoothing; Accept writes the link
  19390. lynx::remoteControlPanelSetController (*panel, -1, 1, 7);
  19391. lynx::remoteControlPanelSetFormula (*panel, "Tension(Input,10)");
  19392. lynx::remoteControlPanelSetSmoothing (*panel, true, 469);
  19393. shoot (*panel, "remote-formula-smoothing");
  19394. lynx::remoteControlPanelPress (*panel, 2);
  19395. const auto& links = engine.getSong().midiLinks;
  19396. check ("accept_writes_link", links.size() == 1 && links[0].cc == 7 && links[0].channel == 0 && links[0].port == -1
  19397. && links[0].formula == "Tension(Input,10)" && links[0].smooth && links[0].target == volume);
  19398. }
  19399. // ---- a broken formula: the message, the red text
  19400. {
  19401. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  19402. lynx::remoteControlPanelSetFormula (*panel, "Min(Input*2,");
  19403. shoot (*panel, "remote-formula-error");
  19404. check ("formula_error_shown", ! lynx::remoteControlPanelState (*panel).contains ("Compiled ok."), lynx::remoteControlPanelState (*panel));
  19405. }
  19406. // ---- the engine: formula, port, conflicts, omni
  19407. {
  19408. engine.editSong ([&] (lynx::Song& s) {
  19409. s.midiLinks.clear();
  19410. MidiLink inverted { 20, 0, volume };
  19411. inverted.formula = "1-Input";
  19412. MidiLink ported { 21, 0, pan };
  19413. ported.port = 3;
  19414. s.midiLinks = { inverted, ported };
  19415. });
  19416. engine.injectControllerForTest (20, 0, 127);
  19417. check ("formula_inverts", std::abs (engine.currentTargetValue (volume)) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  19418. engine.injectControllerForTest (20, 0, 0);
  19419. check ("formula_inverts_back", std::abs (engine.currentTargetValue (volume) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  19420. const auto panBefore = engine.currentTargetValue (pan);
  19421. engine.injectControllerForTest (21, 0, 127); // no port: not this link's device
  19422. check ("port_must_match", std::abs (engine.currentTargetValue (pan) - panBefore) < 0.001f);
  19423. engine.injectControllerForTest (21, 0, 127, 3);
  19424. check ("port_matches", std::abs (engine.currentTargetValue (pan) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (pan)));
  19425. // the window on a control whose controller another control uses: Remove conflicts in red; Accept removes it
  19426. auto panel = lynx::makeRemoteControlPanel (engine, { insert }, false);
  19427. lynx::remoteControlPanelSetController (*panel, -1, 1, 20);
  19428. shoot (*panel, "remote-conflict");
  19429. check ("conflict_counted", lynx::remoteControlPanelState (*panel).contains ("|1|"), lynx::remoteControlPanelState (*panel));
  19430. lynx::remoteControlPanelPress (*panel, 2);
  19431. const auto& links = engine.getSong().midiLinks;
  19432. check ("conflict_removed", links.size() == 2
  19433. && std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; })
  19434. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == insert && l.cc == 20; }));
  19435. engine.undo();
  19436. check ("accept_is_one_undo_step", engine.getSong().midiLinks.size() == 2 && engine.getSong().midiLinks[0].target == volume);
  19437. }
  19438. // ---- an existing link opened again: "Link 1" / "New link"
  19439. {
  19440. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  19441. shoot (*panel, "remote-existing-link");
  19442. check ("existing_link_loaded", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|20|1-Input|"), lynx::remoteControlPanelState (*panel));
  19443. // Reset, then Accept: a link without a controller is removed
  19444. lynx::remoteControlPanelPress (*panel, 0);
  19445. check ("reset_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  19446. lynx::remoteControlPanelPress (*panel, 2);
  19447. const auto& links = engine.getSong().midiLinks;
  19448. check ("reset_accept_unlinks", std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; }));
  19449. }
  19450. // ---- several controls ("Link to controllers..."): Accept and Skip step through them
  19451. {
  19452. auto panel = lynx::makeRemoteControlPanel (engine, { volume, pan, insert }, false, [] {});
  19453. shoot (*panel, "remote-multilink");
  19454. const auto parameter = [&panel] { return juce::StringArray::fromTokens (lynx::remoteControlPanelState (*panel), "|", "")[6]; };
  19455. const auto first = parameter();
  19456. check ("multilink_caption_and_skip", first.startsWith ("1/3") && first.contains (lynx::tr ("Channel volume"))
  19457. && lynx::remoteControlPanelState (*panel).contains ("S|omni"),
  19458. lynx::remoteControlPanelState (*panel));
  19459. lynx::remoteControlPanelSetController (*panel, -1, 1, 30);
  19460. lynx::remoteControlPanelPress (*panel, 2); // Accept: volume linked, on to pan
  19461. const auto second = parameter();
  19462. lynx::remoteControlPanelPress (*panel, 1); // Skip: pan untouched, on to the insert
  19463. const auto third = parameter();
  19464. const auto beforeLast = lynx::remoteControlPanelFinished (*panel);
  19465. lynx::remoteControlPanelPress (*panel, 1); // Skip on the last one: done
  19466. const auto closed = ! beforeLast && lynx::remoteControlPanelFinished (*panel);
  19467. const auto& links = engine.getSong().midiLinks;
  19468. check ("multilink_steps", first != second && second != third && closed
  19469. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume && l.cc == 30; }),
  19470. first + " > " + second + " > " + third);
  19471. }
  19472. // ---- Global link settings
  19473. {
  19474. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  19475. shoot (*panel, "global-default");
  19476. lynx::remoteControlPanelSetController (*panel, 2, 1, 11);
  19477. lynx::remoteControlPanelSetFormula (*panel, "Input*0.5");
  19478. lynx::remoteControlPanelPress (*panel, 2);
  19479. const auto global = engine.globalLinkOf (volume);
  19480. check ("global_link_written", global && global->cc == 11 && global->port == 2 && global->formula == "Input*0.5");
  19481. const auto text = engine.getMidiPrefs().toText();
  19482. const auto back = lynx::prefs::MidiPrefs::fromText (text);
  19483. check ("global_link_settings_round_trip", back.globalLinks == engine.getMidiPrefs().globalLinks && text.find ("linkset=2|0|469|Input*0.5") != std::string::npos);
  19484. auto again = lynx::makeRemoteControlPanel (engine, { volume }, true);
  19485. shoot (*again, "global-existing-link");
  19486. engine.setGlobalLink (volume, std::nullopt);
  19487. check ("global_link_removed", ! engine.globalLinkOf (volume));
  19488. }
  19489. // ---- the project file: links with settings come back; a project of an older version loads the same
  19490. {
  19491. lynx::Song song = engine.getSong();
  19492. MidiLink plain { 7, -1, volume };
  19493. MidiLink rich { 74, 2, pan };
  19494. rich.port = 4;
  19495. rich.formula = "Min(Input*1.1,0.5)+Max(Input*1.1,0.6)-0.6";
  19496. rich.smooth = true;
  19497. rich.smoothing = -300;
  19498. rich.omni = true;
  19499. song.midiLinks = { plain, rich };
  19500. juce::String error;
  19501. const auto json = lynx::ProjectFile::toJson (song);
  19502. const auto back = lynx::ProjectFile::fromJson (json, error);
  19503. check ("project_round_trip", back && back->midiLinks == song.midiLinks, error);
  19504. // without settings the file holds only the list older versions wrote
  19505. song.midiLinks = { plain };
  19506. const auto plainJson = lynx::ProjectFile::toJson (song);
  19507. check ("plain_links_write_the_old_form", ! plainJson.contains ("midiLinkSettings") && plainJson.contains ("midiLinks"));
  19508. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  19509. check ("old_project_loads_the_same", plainBack && plainBack->midiLinks.size() == 1 && plainBack->midiLinks[0] == plain
  19510. && ! plainBack->midiLinks[0].hasSettings());
  19511. // what an older version does with a new file: it reads "midiLinks" alone, so the links stay (plain)
  19512. auto parsed = juce::JSON::parse (json);
  19513. if (auto* o = parsed.getDynamicObject())
  19514. o->removeProperty ("midiLinkSettings");
  19515. const auto stripped = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  19516. check ("older_version_keeps_the_links", stripped && stripped->midiLinks.size() == 2 && stripped->midiLinks[1].cc == 74
  19517. && ! stripped->midiLinks[1].hasSettings());
  19518. }
  19519. // ---- round 190cs: FL's live answers (live check 190cq) and the note / button link modes
  19520. {
  19521. const auto state = [] (juce::Component& p) { return lynx::remoteControlPanelState (p); };
  19522. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  19523. // the layout FL shows: no assignment list without a link, no Skip outside Multilink, no internal
  19524. // controller group without a controller in the project; the parameter caption in FL's words
  19525. auto fresh = lynx::makeRemoteControlPanel (engine, { volume }, false);
  19526. shoot (*fresh, "cs-remote-default");
  19527. check ("cs_layout_without_link", state (*fresh).contains ("|" + lynx::tr ("Channel volume") + "|") && state (*fresh).contains ("|shown=POC|"), state (*fresh));
  19528. // Omni: enabled on a mixer track's volume (FL: "Insert 1 - Volume"), greyed on the tempo
  19529. auto onInsert = lynx::makeRemoteControlPanel (engine, { insert }, false);
  19530. auto onTempo = lynx::makeRemoteControlPanel (engine, { AutomationTarget { AutomationTargetKind::tempo, 0 } }, false);
  19531. shoot (*onInsert, "cs-remote-omni-insert");
  19532. check ("cs_omni_mixer_track", state (*onInsert).contains ("|omni=on|") && state (*onTempo).contains ("|omni=off|"),
  19533. state (*onInsert) + " / " + state (*onTempo));
  19534. // the formula compiles on Enter only; FL's messages and colours
  19535. lynx::remoteControlPanelSetFormula (*fresh, "1-Input^2", false);
  19536. check ("cs_no_compile_while_typing", state (*fresh).contains ("|" + lynx::tr ("(default 1:1 mapping)") + "|"), state (*fresh));
  19537. lynx::remoteControlPanelSetFormula (*fresh, "-Input^2");
  19538. shoot (*fresh, "cs-remote-compiled");
  19539. check ("cs_compiled_on_enter", state (*fresh).contains ("|" + lynx::tr ("Compiled ok.") + "|"), state (*fresh));
  19540. const std::pair<const char*, const char*> errors[] { { "Input*", "Syntax error: function or operand" },
  19541. { "foo(Input)", "Invalid identifier: foo" },
  19542. { "Sin(Input", "Unequal brackets" },
  19543. { "Input 2", "input two space limited" } };
  19544. for (const auto& [text, expected] : errors)
  19545. {
  19546. lynx::remoteControlPanelSetFormula (*fresh, text);
  19547. check ("cs_fl_error_text", state (*fresh).contains (expected), state (*fresh));
  19548. }
  19549. lynx::remoteControlPanelSetFormula (*fresh, "foo(Input)");
  19550. shoot (*fresh, "cs-remote-error");
  19551. // Accept with that formula: the link is made, the formula is not kept (FL reopens it as "Input")
  19552. lynx::remoteControlPanelSetController (*fresh, -1, 1, 7);
  19553. lynx::remoteControlPanelPress (*fresh, 2);
  19554. check ("cs_bad_formula_accept_is_input", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == 7
  19555. && engine.getSong().midiLinks[0].formula.empty());
  19556. auto reopened = lynx::makeRemoteControlPanel (engine, { volume }, false);
  19557. shoot (*reopened, "cs-remote-reopened");
  19558. check ("cs_reopened_shows_input_and_link_list", state (*reopened).startsWith ("-1|1|7|Input|" + lynx::tr ("(default 1:1 mapping)") + "|")
  19559. && state (*reopened).contains ("|shown=PAOC|"),
  19560. state (*reopened));
  19561. // the internal controller group appears with a controller in the project, with "Record automation"
  19562. engine.editSong ([] (lynx::Song& s) {
  19563. lynx::EffectSlot peak;
  19564. peak.kind = lynx::EffectKind::peakController;
  19565. s.mixer[0].effects.push_back (peak);
  19566. });
  19567. auto withController = lynx::makeRemoteControlPanel (engine, { volume }, false);
  19568. lynx::remoteControlPanelSetInternal (*withController, 1, true);
  19569. shoot (*withController, "cs-remote-internal");
  19570. check ("cs_internal_group_shown", state (*withController).contains ("|shown=PAIOC|") && state (*withController).startsWith ("-1|1|-1|"),
  19571. state (*withController));
  19572. lynx::remoteControlPanelPress (*withController, 2);
  19573. const auto& autos = engine.getSong().automations;
  19574. check ("cs_record_automation_kept", std::any_of (autos.begin(), autos.end(), [&] (const lynx::Automation& a) {
  19575. return a.isLive() && a.target == volume && a.recordLive;
  19576. }));
  19577. engine.editSong ([] (lynx::Song& s) {
  19578. s.mixer[0].effects.pop_back();
  19579. s.automations.clear();
  19580. s.midiLinks.clear();
  19581. });
  19582. // the global window: no parameter list, Omni, Remove conflicts or Skip; Mode is there
  19583. auto globalPanel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  19584. shoot (*globalPanel, "cs-global-default");
  19585. check ("cs_global_layout", state (*globalPanel).contains ("|shown=|"), state (*globalPanel));
  19586. // a key link in each Mode: note 60 = FL's controller number 256 + 60
  19587. const auto key = lynx::linkNoteBase + 60;
  19588. auto modePanel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  19589. lynx::remoteControlPanelSetController (*modePanel, -1, 1, key);
  19590. lynx::remoteControlPanelSetMode (*modePanel, 2);
  19591. shoot (*modePanel, "cs-remote-note-latch");
  19592. lynx::remoteControlPanelPress (*modePanel, 2);
  19593. check ("cs_note_link_written", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == key
  19594. && engine.getSong().midiLinks[0].mode == 2);
  19595. const auto play = [&engine, key, volume] (int velocity) {
  19596. engine.injectControllerForTest (key, 0, velocity);
  19597. return engine.currentTargetValue (volume);
  19598. };
  19599. const auto setMode = [&engine] (int mode) {
  19600. engine.editSong ([mode] (lynx::Song& s) { s.midiLinks[0].mode = mode; });
  19601. engine.editSong ([] (lynx::Song& s) { s.setTargetValue ({ AutomationTargetKind::channelVolume, 0 }, 0.25f); });
  19602. };
  19603. setMode (2); // Latch: press switches, release does nothing
  19604. const auto l1 = play (100), l1off = play (0), l2 = play (90), l2off = play (0);
  19605. check ("cs_mode_latch", std::abs (l1 - 1.0f) < 1e-4f && std::abs (l1off - 1.0f) < 1e-4f && l2 < 1e-4f && l2off < 1e-4f,
  19606. juce::String (l1) + " " + juce::String (l1off) + " " + juce::String (l2) + " " + juce::String (l2off));
  19607. setMode (1); // Hold: the velocity while held, back to 0 on release
  19608. const auto h1 = play (100), h1off = play (0);
  19609. check ("cs_mode_hold", std::abs (h1 - 100.0f / 127.0f) < 1e-4f && h1off < 1e-4f, juce::String (h1) + " " + juce::String (h1off));
  19610. setMode (0); // Default: as Hold for a key
  19611. const auto d1 = play (64), d1off = play (0);
  19612. check ("cs_mode_default", std::abs (d1 - 64.0f / 127.0f) < 1e-4f && d1off < 1e-4f, juce::String (d1) + " " + juce::String (d1off));
  19613. setMode (3); // Inc: each press adds 1/128
  19614. const auto i1 = play (100), i1off = play (0), i2 = play (20);
  19615. check ("cs_mode_inc", std::abs (i1 - (0.25f + 1.0f / 128.0f)) < 1e-4f && std::abs (i1off - i1) < 1e-6f
  19616. && std::abs (i2 - (0.25f + 2.0f / 128.0f)) < 1e-4f,
  19617. juce::String (i1) + " " + juce::String (i2));
  19618. setMode (4); // Stay: the velocity, kept after the release
  19619. const auto s1 = play (100), s1off = play (0);
  19620. check ("cs_mode_stay", std::abs (s1 - 100.0f / 127.0f) < 1e-4f && std::abs (s1off - s1) < 1e-6f, juce::String (s1) + " " + juce::String (s1off));
  19621. // the project file keeps the key link and its mode; an older reader skips it
  19622. lynx::Song song = engine.getSong();
  19623. song.midiLinks[0].mode = 2;
  19624. MidiLink cc7 { 7, 0, pan };
  19625. cc7.mode = 4;
  19626. song.midiLinks.insert (song.midiLinks.begin(), cc7);
  19627. juce::String error;
  19628. const auto json = lynx::ProjectFile::toJson (song);
  19629. const auto back = lynx::ProjectFile::fromJson (json, error);
  19630. check ("cs_note_link_round_trip", back && back->midiLinks == song.midiLinks && json.contains ("midiNoteLinks"), error);
  19631. auto parsed = juce::JSON::parse (json);
  19632. if (auto* o = parsed.getDynamicObject())
  19633. {
  19634. o->removeProperty ("midiNoteLinks");
  19635. o->removeProperty ("midiLinkSettings");
  19636. }
  19637. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  19638. check ("cs_older_reader_keeps_cc_links_only", older && older->midiLinks.size() == 1 && older->midiLinks[0].cc == 7);
  19639. // "Record automation" of an internal-controller link, saved only when on
  19640. lynx::Automation live;
  19641. live.target = volume;
  19642. live.source.track = 0;
  19643. live.recordLive = true;
  19644. song.automations = { live };
  19645. const auto withLive = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  19646. live.recordLive = false;
  19647. song.automations = { live };
  19648. check ("cs_record_automation_round_trip", withLive && withLive->automations.size() == 1 && withLive->automations[0].recordLive
  19649. && ! lynx::ProjectFile::toJson (song).contains ("recordLive"));
  19650. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  19651. }
  19652. // ---- menus: the control menu, the formula presets, the controller list, the Multilink items
  19653. {
  19654. juce::PopupMenu control;
  19655. lynx::addAutomationItem (control, engine, volume, true);
  19656. engine.setMultilink (true);
  19657. engine.noteTweaked (volume);
  19658. engine.noteTweaked (pan);
  19659. juce::PopupMenu multilink;
  19660. lynx::addMultilinkControlsItems (multilink, engine);
  19661. check ("multilink_queue", engine.multilinkTargets().size() == 2);
  19662. engine.setMultilink (false);
  19663. saveMenus (juce::StringArray { "Control menu", "Formula presets", "Multilink" },
  19664. std::vector<juce::PopupMenu> { control, lynx::remoteControlFormulaMenu ([] (const juce::String&) {}), multilink },
  19665. prefix + "-menus.png");
  19666. saveMenus (juce::StringArray { "Ctrl menu" }, std::vector<juce::PopupMenu> { lynx::remoteControlControllerMenu ([] (int) {}) },
  19667. prefix + "-ctrl-menu.png");
  19668. // the Mode list as its box pops it up (round 190cs)
  19669. juce::PopupMenu modes;
  19670. for (const char* m : { "Default", "Hold", "Latch", "Inc", "Stay" })
  19671. modes.addItem (lynx::tr (m), true, juce::String (m) == "Default", [] {});
  19672. saveMenus (juce::StringArray { "Mode" }, std::vector<juce::PopupMenu> { modes }, prefix + "-mode-menu.png");
  19673. }
  19674. // ---- Settings > MIDI: the input's Port box, the link list with a link's settings
  19675. {
  19676. engine.editSong ([&] (lynx::Song& s) {
  19677. MidiLink l { 74, 2, pan };
  19678. l.port = 4;
  19679. l.formula = "1-Input";
  19680. l.smooth = true;
  19681. s.midiLinks = { MidiLink { 7, 0, volume }, l };
  19682. });
  19683. auto page = lynx::makeMidiPage (engine, {}, false);
  19684. page->setSize (760, 900);
  19685. shoot (*page, "settings-midi");
  19686. }
  19687. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  19688. return allOk;
  19689. }
  19690. // A stand-in hosted plugin for the shot route: three parameters, its state = their values
  19691. struct FlCtlShotPlugin final : juce::AudioPluginInstance
  19692. {
  19693. FlCtlShotPlugin()
  19694. {
  19695. for (const char* n : { "Cutoff", "Resonance", "Drive" })
  19696. addHostedParameter (std::make_unique<juce::AudioParameterFloat> (juce::ParameterID (n, 1), n, 0.0f, 1.0f, 0.5f));
  19697. }
  19698. const juce::String getName() const override { return "Shot plugin"; }
  19699. void prepareToPlay (double, int) override {}
  19700. void releaseResources() override {}
  19701. void processBlock (juce::AudioBuffer<float>&, juce::MidiBuffer&) override {}
  19702. double getTailLengthSeconds() const override { return 0.0; }
  19703. bool acceptsMidi() const override { return false; }
  19704. bool producesMidi() const override { return false; }
  19705. juce::AudioProcessorEditor* createEditor() override { return nullptr; }
  19706. bool hasEditor() const override { return false; }
  19707. int getNumPrograms() override { return 1; }
  19708. int getCurrentProgram() override { return 0; }
  19709. void setCurrentProgram (int) override {}
  19710. const juce::String getProgramName (int) override { return {}; }
  19711. void changeProgramName (int, const juce::String&) override {}
  19712. void getStateInformation (juce::MemoryBlock& b) override
  19713. {
  19714. for (auto* p : getParameters())
  19715. {
  19716. const float v = static_cast<juce::AudioParameterFloat*> (p)->get();
  19717. b.append (&v, sizeof (float));
  19718. }
  19719. }
  19720. void setStateInformation (const void* data, int size) override
  19721. {
  19722. const auto& list = getParameters();
  19723. for (int i = 0; i < list.size() && (i + 1) * (int) sizeof (float) <= size; ++i)
  19724. *static_cast<juce::AudioParameterFloat*> (list[i]) = static_cast<const float*> (data)[i];
  19725. }
  19726. void fillInPluginDescription (juce::PluginDescription& d) const override
  19727. {
  19728. d.name = getName();
  19729. d.pluginFormatName = "Shot";
  19730. d.fileOrIdentifier = "shot";
  19731. }
  19732. };
  19733. static juce::File writeShotSample (const juce::File& file, double hz)
  19734. {
  19735. juce::AudioBuffer<float> buffer (1, 22050);
  19736. for (int i = 0; i < buffer.getNumSamples(); ++i)
  19737. buffer.setSample (0, i, (float) (std::sin (juce::MathConstants<double>::twoPi * hz * i / 44100.0) * std::exp (-i / 6000.0)));
  19738. file.deleteFile();
  19739. juce::WavAudioFormat wav;
  19740. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  19741. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  19742. return file;
  19743. }
  19744. static bool clickMenuItem (const juce::PopupMenu& menu, const juce::String& text)
  19745. {
  19746. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  19747. if (it.getItem().text == text && it.getItem().isEnabled && it.getItem().action != nullptr)
  19748. {
  19749. it.getItem().action();
  19750. return true;
  19751. }
  19752. return false;
  19753. }
  19754. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen — the page as FL's shot (dock188a) shows it,
  19755. // the legacy effects, a small window, a zoomed waveform — and its laws turned as a user would; prefix-checks.txt
  19756. bool runSamplerPageShot (const juce::String& prefix)
  19757. {
  19758. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19759. juce::StringArray report;
  19760. bool allOk = true;
  19761. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  19762. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  19763. allOk = allOk && ok;
  19764. };
  19765. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  19766. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  19767. };
  19768. lynx::AudioEngine engine (false);
  19769. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("sampler-samples");
  19770. folder.createDirectory();
  19771. // an 808-like kick, 1 s (FL's shot: "Basic 808 Kick.wav")
  19772. const auto kick = folder.getChildFile ("Basic 808 Kick.wav");
  19773. {
  19774. juce::AudioBuffer<float> buffer (1, 44100);
  19775. double phase = 0.0;
  19776. for (int i = 0; i < buffer.getNumSamples(); ++i)
  19777. {
  19778. const auto t = i / 44100.0;
  19779. phase += juce::MathConstants<double>::twoPi * (48.0 + 90.0 * std::exp (-t * 30.0)) / 44100.0;
  19780. buffer.setSample (0, i, (float) (0.9 * std::sin (phase) * std::exp (-t * 3.2)));
  19781. }
  19782. kick.deleteFile();
  19783. juce::WavAudioFormat wav;
  19784. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (kick.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  19785. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  19786. }
  19787. engine.editSong ([&] (lynx::Song& s) {
  19788. if (s.channels.empty())
  19789. s.channels.resize (1);
  19790. lynx::audioclips::loadSampleInto (s.channels[0], kick.getFullPathName().toStdString(), "808 Kick");
  19791. // FL's shot: Resample and Load regions on, Use loop points on, declicking "Out only (no bleeding)"
  19792. s.channels[0].sampler.resampleOnLoad = true;
  19793. });
  19794. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  19795. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  19796. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  19797. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  19798. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  19799. shoot (*frame, "sampler-page");
  19800. report.add ("page size " + juce::String (frame->getWidth()) + "x" + juce::String (frame->getHeight()));
  19801. // ---- the laws, turned on the page
  19802. auto& f = *frame;
  19803. lynx::samplerPageTurn (f, "pingPong", 1.0);
  19804. check ("ping_pong", sampler().precompute.pingPong);
  19805. lynx::samplerPageTurn (f, "pingPong", 0.0);
  19806. lynx::samplerPageTurn (f, "loopStart", 5000.0);
  19807. check ("loop_start", sampler().loopStart == 5000 && sampler().loopEnd == 5001, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  19808. lynx::samplerPageTurn (f, "loopEnd", 15000.0);
  19809. check ("loop_end", sampler().loopStart == 5000 && sampler().loopEnd == 15000);
  19810. lynx::samplerPageTurn (f, "loopStart", 20000.0, true); // Shift: the loop moves
  19811. check ("loop_shift_moves", sampler().loopStart == 20000 && sampler().loopEnd == 30000, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  19812. check ("keep_on_disk_greyed_with_loop", lynx::samplerPageQuery (f, "keepOnDisk") == "0");
  19813. lynx::samplerPageTurn (f, "useLoops", 0.0);
  19814. check ("keep_on_disk_back", lynx::samplerPageQuery (f, "keepOnDisk") == "1" && ! sampler().useLoopPoints);
  19815. check ("not_cut_yet", ! lynx::channelCutsItself (engine.getSong().channels[0]));
  19816. lynx::samplerPageTurn (f, "useLoops", 1.0);
  19817. check ("use_loops_cuts_itself", sampler().useLoopPoints && lynx::channelCutsItself (engine.getSong().channels[0]));
  19818. engine.editSong ([] (lynx::Song& s) {
  19819. lynx::setChannelCutsItself (s.channels[0], 0, false);
  19820. s.channels[0].sampler.useLoopPoints = false;
  19821. });
  19822. lynx::samplerPageTurn (f, "crossfade", 300.0); // (Use loop points off: the crossfade switches it on)
  19823. check ("crossfade_switches_loops_on", sampler().precompute.crossfade == 300 && sampler().useLoopPoints);
  19824. lynx::samplerPageTurn (f, "crossfade", 0.0);
  19825. lynx::samplerPageTurn (f, "pitch", 300.0); // (Resample: FL switches to Auto)
  19826. check ("pitch_resample_to_auto", sampler().keepPitch && sampler().flStretchMode == 5 && sampler().flStretchPitch == 300
  19827. && lynx::samplerPageQuery (f, "mode") == lynx::tr ("General"),
  19828. lynx::samplerPageQuery (f, "mode") + " " + juce::String (sampler().pitch));
  19829. lynx::samplerPageTurn (f, "pitch", 0.0);
  19830. lynx::samplerPageTurn (f, "mode", 1.0); // Resample
  19831. check ("mode_resample", ! sampler().keepPitch && std::abs (sampler().pitch) < 1.0e-4f);
  19832. lynx::samplerPageTurn (f, "time", 4.0);
  19833. lynx::samplerPageTurn (f, "mul", 10000.0);
  19834. check ("time_mul", std::abs (sampler().stretchBeats - 8.0f) < 1.0e-3f && sampler().stretchMul == 10000, juce::String (sampler().stretchBeats));
  19835. lynx::samplerPageTurn (f, "mul", 0.0);
  19836. lynx::samplerPageTurn (f, "time", 0.0);
  19837. lynx::samplerPageTurn (f, "length", 0.5);
  19838. lynx::samplerPageTurn (f, "smpStart", 0.5);
  19839. check ("smp_start_keeps_length", std::abs (sampler().regionStart - 0.5f) < 1.0e-3f && std::abs (sampler().regionEnd - 0.75f) < 1.0e-3f,
  19840. juce::String (sampler().regionStart) + "-" + juce::String (sampler().regionEnd));
  19841. lynx::samplerPageTurn (f, "smpStart", 0.0);
  19842. lynx::samplerPageTurn (f, "length", 1.0);
  19843. lynx::samplerPageTurn (f, "declick", 4.0);
  19844. check ("declick_mode", sampler().declickMode == 4);
  19845. lynx::samplerPageTurn (f, "declick", 0.0);
  19846. // ---- the .lynx keeps what the page set
  19847. {
  19848. lynx::samplerPageTurn (f, "mul", -5000.0);
  19849. lynx::samplerPageTurn (f, "keepOnDisk", 1.0);
  19850. juce::String error;
  19851. const auto json = lynx::ProjectFile::toJson (engine.getSong(), false);
  19852. const auto back = lynx::ProjectFile::fromJson (json, error);
  19853. check ("lynx_round_trip", back.has_value() && back->channels[0].sampler == engine.getSong().channels[0].sampler, error);
  19854. lynx::samplerPageTurn (f, "mul", 0.0);
  19855. lynx::samplerPageTurn (f, "keepOnDisk", 0.0);
  19856. }
  19857. // ---- shots: FL's state again (loop points from the file: none), the legacy panel, a zoom, a small window
  19858. engine.editSong ([] (lynx::Song& s) {
  19859. auto& ch = s.channels[0];
  19860. ch.sampler.loopStart = ch.sampler.loopEnd = -1;
  19861. ch.sampler.useLoopPoints = true;
  19862. ch.sampler.precompute = {};
  19863. });
  19864. lynx::samplerPageTurn (f, "show", 0.0); // (no control: the page shows the channel again)
  19865. frame->createComponentSnapshot (frame->getLocalBounds());
  19866. shoot (*frame, "sampler-page-fl-state");
  19867. lynx::samplerPageTurn (f, "legacy", 1.0);
  19868. check ("legacy_panel", lynx::samplerPageQuery (f, "legacy") == "1");
  19869. shoot (*frame, "sampler-page-legacy");
  19870. lynx::samplerPageTurn (f, "legacy", 0.0);
  19871. lynx::samplerPageTurn (f, "zoom", 0.25);
  19872. check ("zoom_scroll", lynx::samplerPageQuery (f, "scroll") == "0.250", lynx::samplerPageQuery (f, "scroll"));
  19873. shoot (*frame, "sampler-page-zoom");
  19874. lynx::samplerPageTurn (f, "zoom", 1.0);
  19875. frame->setSize (520, 470);
  19876. frame->createComponentSnapshot (frame->getLocalBounds());
  19877. shoot (*frame, "sampler-page-small");
  19878. report.add (juce::String ("result=") + (allOk ? "OK" : "FAIL"));
  19879. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  19880. return allOk;
  19881. }
  19882. bool runFlCtlShot (const juce::String& prefix)
  19883. {
  19884. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19885. juce::StringArray report;
  19886. bool allOk = true;
  19887. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  19888. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  19889. allOk = allOk && ok;
  19890. };
  19891. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  19892. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  19893. };
  19894. using lynx::AutomationTarget;
  19895. using lynx::AutomationTargetKind;
  19896. lynx::AudioEngine engine (false);
  19897. engine.editSong ([] (lynx::Song& s) {
  19898. if (s.channels.size() < 3)
  19899. s.channels.resize (3);
  19900. if (s.patterns.empty())
  19901. s.patterns.resize (1);
  19902. s.currentPattern = 0;
  19903. });
  19904. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 };
  19905. // ---- FL's multilink menu: on with two queued controls, off with the last tweaked parameters
  19906. {
  19907. engine.setMultilink (true);
  19908. engine.noteTweaked (volume);
  19909. engine.noteTweaked (pan);
  19910. auto on = lynx::multilinkButtonMenu (engine);
  19911. juce::PopupMenu::MenuItemIterator first (on);
  19912. first.next();
  19913. check ("ml_caption_on", first.getItem().isSectionHeader && first.getItem().text == lynx::tr ("{0} parameters selected", { "2" }), first.getItem().text);
  19914. // Init pattern: the values at the pattern's start; ends multilink
  19915. const auto v0 = engine.currentTargetValue (volume);
  19916. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initPattern, engine.multilinkTargets(), 0);
  19917. const auto& lanes = engine.getSong().patterns[0].events;
  19918. check ("ml_init_pattern", lanes.size() == 2 && ! lanes[0].events.empty() && lanes[0].events[0].tick == 0
  19919. && std::abs (lanes[0].events[0].value - v0) < 1.0e-6f && ! engine.isMultilinkOn());
  19920. // Randomize keeps multilink on; Humanize moves at most an eighth
  19921. engine.setMultilink (true);
  19922. engine.noteTweaked (volume);
  19923. engine.noteTweaked (pan);
  19924. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::randomize, engine.multilinkTargets(), 1234);
  19925. check ("ml_randomize_keeps_queue", engine.isMultilinkOn() && engine.multilinkTargets().size() == 2);
  19926. const auto before = engine.currentTargetValue (volume);
  19927. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::humanize, engine.multilinkTargets(), 99);
  19928. check ("ml_humanize_small", std::abs (engine.currentTargetValue (volume) - before) <= 0.1251f && engine.isMultilinkOn(),
  19929. juce::String (before) + " -> " + juce::String (engine.currentTargetValue (volume)));
  19930. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initSong, engine.multilinkTargets(), 0);
  19931. check ("ml_init_song", engine.getSong().findInitialValue (volume) >= 0 && ! engine.isMultilinkOn());
  19932. // off: the last two tweaked parameters, no Cancel
  19933. auto off = lynx::multilinkButtonMenu (engine);
  19934. bool hasCancel = false;
  19935. for (juce::PopupMenu::MenuItemIterator it (off); it.next();)
  19936. hasCancel = hasCancel || it.getItem().text == lynx::tr ("Cancel");
  19937. juce::PopupMenu::MenuItemIterator offFirst (off);
  19938. offFirst.next();
  19939. check ("ml_off_caption", offFirst.getItem().text == lynx::tr ("Last 2 tweaked parameters") && ! hasCancel, offFirst.getItem().text);
  19940. // LYNX's own one-step items stay, after FL's items below a line (greyed while multilink is off)
  19941. juce::String last;
  19942. bool lineBefore = false, prevLine = false;
  19943. for (juce::PopupMenu::MenuItemIterator it (on); it.next();)
  19944. {
  19945. if (it.getItem().text == lynx::tr ("Link to controller"))
  19946. lineBefore = prevLine;
  19947. prevLine = it.getItem().isSeparator;
  19948. last = it.getItem().text;
  19949. }
  19950. check ("ml_lynx_items_after_fl", lineBefore && last == lynx::tr ("Override global links"), last);
  19951. saveMenus (juce::StringArray { "Multilink on (2 queued)", "Multilink off" }, std::vector<juce::PopupMenu> { on, off },
  19952. prefix + "-multilink-menu.png");
  19953. }
  19954. // ---- the plugin menu's spare state and Parameters > Link all parameters...
  19955. {
  19956. FlCtlShotPlugin plugin;
  19957. juce::PopupMenu menu;
  19958. lynx::addPluginWrapperItems (menu, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  19959. saveMenus (juce::StringArray { "Plugin menu: spare state and parameters" }, std::vector<juce::PopupMenu> { menu }, prefix + "-plugin-menu.png");
  19960. const auto targets = lynx::allPluginParameterTargets (plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  19961. check ("link_all_parameters", targets.size() == 3 && targets[2].param == 2 && targets[2].index == 1);
  19962. auto* cutoff = static_cast<juce::AudioParameterFloat*> (plugin.getParameters()[0]);
  19963. *cutoff = 0.2f;
  19964. check ("spare_store", clickMenuItem (menu, lynx::tr ("Store in spare state")));
  19965. *cutoff = 0.9f;
  19966. juce::PopupMenu again;
  19967. lynx::addPluginWrapperItems (again, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  19968. check ("spare_flip", clickMenuItem (again, lynx::tr ("Flip with spare state")) && std::abs (cutoff->get() - 0.2f) < 1.0e-6f, juce::String (cutoff->get()));
  19969. check ("spare_flip_back", clickMenuItem (again, lynx::tr ("Flip with spare state")) && std::abs (cutoff->get() - 0.9f) < 1.0e-6f, juce::String (cutoff->get()));
  19970. lynx::sparestate::shared().forget (&plugin);
  19971. }
  19972. // ---- the sampler's File row: Load (history menu, wheel), Locate, Remove
  19973. {
  19974. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flctl-samples");
  19975. folder.createDirectory();
  19976. const auto a = writeShotSample (folder.getChildFile ("Kick 1.wav"), 60.0), b = writeShotSample (folder.getChildFile ("Snare 2.wav"), 200.0),
  19977. c = writeShotSample (folder.getChildFile ("Hat 3.wav"), 900.0);
  19978. lynx::samplehistory::list().clear();
  19979. engine.editSong ([&] (lynx::Song& s) {
  19980. for (const auto& f : { c, b, a }) // (each load goes into the history, newest first)
  19981. lynx::audioclips::loadSampleInto (s.channels[1], f.getFullPathName().toStdString(), f.getFileNameWithoutExtension().toStdString());
  19982. });
  19983. check ("history_order", lynx::samplehistory::list().size() == 3 && lynx::samplehistory::list().front() == a.getFullPathName().toStdString());
  19984. juce::File located;
  19985. lynx::locateInBrowserHandler() = [&located] (const juce::File& f) { located = f; };
  19986. auto frame = lynx::makeChannelFrame (engine, 1, 0);
  19987. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 820);
  19988. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  19989. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  19990. shoot (*frame, "sampler-file-row");
  19991. const auto history = lynx::samplerHistoryMenu (*frame);
  19992. check ("history_menu", history.has_value() && history->getNumItems() == 4); // (caption + three samples)
  19993. if (history)
  19994. saveMenus (juce::StringArray { "Load: Sample history" }, std::vector<juce::PopupMenu> { *history }, prefix + "-sample-history.png");
  19995. lynx::samplerFileRowPress (*frame, 0); // wheel down: the next (older) sample
  19996. check ("wheel_down", engine.getSong().channels[1].samplePath == b.getFullPathName().toStdString(), juce::String (engine.getSong().channels[1].samplePath));
  19997. lynx::samplerFileRowPress (*frame, 1); // wheel up: back
  19998. check ("wheel_up", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  19999. lynx::samplerFileRowPress (*frame, 2);
  20000. check ("locate", located == a, located.getFullPathName());
  20001. lynx::samplerFileRowPress (*frame, 3);
  20002. check ("remove", engine.getSong().channels[1].samplePath.empty());
  20003. engine.undo();
  20004. check ("remove_undo", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  20005. lynx::locateInBrowserHandler() = nullptr;
  20006. }
  20007. // ---- a sampler running FL's voice: FL's Envelope / instrument page with the tensions, the predelay and presets
  20008. {
  20009. engine.editSong ([] (lynx::Song& s) {
  20010. auto& ch = s.channels[2];
  20011. ch.instrument = lynx::InstrumentKind::sampler;
  20012. ch.name = "FL sampler";
  20013. const auto snap = lynx::flvp::defaultSnapshot();
  20014. ch.sampler.flChannel.assign (90, 0);
  20015. std::memcpy (ch.sampler.flChannel.data(), snap.data(), 85 * 4);
  20016. std::memcpy (&ch.sampler.flChannel[85], snap.data() + 0x15c, 4);
  20017. std::memcpy (&ch.sampler.flChannel[86], snap.data() + 0x160, 4);
  20018. std::memcpy (&ch.sampler.flChannel[87], snap.data() + 0x168, 4);
  20019. ch.sampler.flChannel[88] = 96;
  20020. ch.sampler.flChannel[89] = 0;
  20021. auto& vol = ch.sampler.flChannel; // the volume envelope on, bent
  20022. vol[17 + 1] = -1;
  20023. vol[17 + 2] = 4000; // predelay
  20024. vol[17 + 14] = -70; // attack tension
  20025. vol[17 + 15] = 60; // decay tension
  20026. vol[17 + 16] = -40; // release tension
  20027. });
  20028. auto frame = lynx::makeChannelFrame (engine, 2, 1);
  20029. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 560);
  20030. shoot (*frame, "sampler-fl-envelope");
  20031. check ("fl_page_shown", lynx::flVoicePresetsMenu (*frame).has_value());
  20032. lynx::flVoicePresetFolder().deleteRecursively();
  20033. check ("preset_save", lynx::flVoiceSavePreset (*frame, "Bent volume")
  20034. && lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV").getSize() == 68);
  20035. if (const auto menu = lynx::flVoicePresetsMenu (*frame))
  20036. saveMenus (juce::StringArray { "Channel envelope presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-envelope-presets.png");
  20037. // the preset into the pitch target: its record becomes the saved one
  20038. lynx::showFlVoiceTarget (*frame, lynx::flvoice::pitch);
  20039. const auto loaded = lynx::flVoiceLoadPreset (*frame, lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV"));
  20040. const auto& fl = engine.getSong().channels[2].sampler.flChannel;
  20041. check ("preset_load", loaded && fl.size() == 90 && fl[68 + 2] == 4000 && fl[68 + 14] == -70 && fl[68 + 16] == -40 && fl[88] == 96);
  20042. engine.undo();
  20043. check ("preset_load_undo", engine.getSong().channels[2].sampler.flChannel[68 + 14] != -70);
  20044. }
  20045. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  20046. return allOk;
  20047. }
  20048. // --flplshot (round 190dx): see the dispatch above
  20049. bool runHdrShot190ft (const juce::String& prefix)
  20050. {
  20051. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20052. juce::StringArray report;
  20053. bool allOk = true;
  20054. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  20055. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  20056. allOk = allOk && ok;
  20057. };
  20058. const auto list = [] (const std::vector<int>& v) {
  20059. juce::StringArray out;
  20060. for (auto i : v)
  20061. out.add (juce::String (i));
  20062. return out.joinIntoString (",");
  20063. };
  20064. lynx::AudioEngine engine (false);
  20065. lynx::MainComponent ui (engine, false);
  20066. ui.setSize (1600, 900);
  20067. {
  20068. auto song = lynx::Song::makeDefault();
  20069. song.playlist.clear();
  20070. for (int t = 0; t < 6; ++t)
  20071. {
  20072. if ((int) song.playlistTracks.size() <= t)
  20073. song.playlistTracks.resize ((std::size_t) t + 1);
  20074. song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
  20075. for (int k = 0; k < 2; ++k)
  20076. {
  20077. lynx::Clip c;
  20078. c.kind = lynx::ClipKind::pattern;
  20079. c.pattern = 0;
  20080. c.track = t;
  20081. c.start = (std::int64_t) (k * 4 + t % 3) * lynx::ppq;
  20082. c.length = 2 * lynx::ppq;
  20083. song.playlist.push_back (c);
  20084. }
  20085. }
  20086. if (song.mixer.size() < 4)
  20087. song.mixer.resize (4);
  20088. song.playlistTracks[2].mode = lynx::PlaylistTrackMode::audio; // an audio track linked to mixer track 3
  20089. song.playlistTracks[2].mixerTrack = 3;
  20090. song.playlistTracks[2].name = "Vox";
  20091. engine.setSong (std::move (song));
  20092. }
  20093. engine.dispatchPendingMessages();
  20094. ui.selectTabForSnapshot (2);
  20095. engine.dispatchPendingMessages();
  20096. auto& pl = ui.getPlaylistForSnapshot();
  20097. pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
  20098. auto source = juce::Desktop::getInstance().getMainMouseSource();
  20099. const auto now = juce::Time::getCurrentTime();
  20100. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  20101. const int ctrl = juce::ModifierKeys::commandModifier; // (FL's Ctrl: Cmd on a Mac)
  20102. const int shift = juce::ModifierKeys::shiftModifier;
  20103. const int alt = juce::ModifierKeys::altModifier;
  20104. const auto event = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  20105. return juce::MouseEvent (source, p.toFloat(), mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &c, &c, now, down.toFloat(), now, clicks, dragged);
  20106. };
  20107. // a press (and release) at p with the modifiers; `to`: a drag there before the release
  20108. const auto press = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}, int clicks = 1) {
  20109. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  20110. c.mouseMove (event (c, p, mods, p, 1, false));
  20111. c.mouseDown (event (c, p, down, p, clicks, false));
  20112. if (to)
  20113. c.mouseDrag (event (c, *to, down, p, clicks, true));
  20114. c.mouseUp (event (c, to ? *to : p, mods, p, clicks, to.has_value()));
  20115. };
  20116. const auto headerPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getY() + juce::jmin (10, r.getHeight() / 3)); };
  20117. const auto bandPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getBottom() - 2); };
  20118. const auto clipsOn = [&] (const std::vector<int>& tracks) {
  20119. std::vector<int> out;
  20120. const auto& song = engine.getSong();
  20121. for (int i = 0; i < (int) song.playlist.size(); ++i)
  20122. if (std::find (tracks.begin(), tracks.end(), song.playlist[(std::size_t) i].track) != tracks.end())
  20123. out.push_back (i);
  20124. return out;
  20125. };
  20126. const auto sortedClips = [&] { auto v = pl.getSelectedClips(); std::sort (v.begin(), v.end()); return v; };
  20127. const auto headerShot = [&] (const juce::String& name, int rows) {
  20128. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  20129. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 760), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  20130. };
  20131. // ---- 1. selection (AUTracksPanelMouseDown / FUN_012e83e0)
  20132. press (pl, headerPoint (1), {});
  20133. check ("click_selects_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
  20134. pl.selectClipsForSnapshot ({});
  20135. // LYNX extra (issue #163): Ctrl+click adds / removes one track, its clips follow
  20136. press (pl, headerPoint (3), ctrl);
  20137. check ("ctrl_click_adds_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3 } && sortedClips() == clipsOn ({ 3 }),
  20138. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  20139. press (pl, headerPoint (5), ctrl);
  20140. press (pl, headerPoint (1), ctrl);
  20141. check ("ctrl_click_removes_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 3, 5 } && sortedClips() == clipsOn ({ 3, 5 }),
  20142. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  20143. // FL's own toggle: Ctrl+Shift+click (its clips are added)
  20144. press (pl, headerPoint (1), ctrl | shift);
  20145. check ("ctrl_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
  20146. check ("ctrl_shift_click_adds_clips", sortedClips() == clipsOn ({ 1, 3, 5 }), list (sortedClips()));
  20147. press (pl, headerPoint (3), ctrl | shift);
  20148. check ("ctrl_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 5 }, list (pl.selectedTracksForSnapshot()));
  20149. press (pl, headerPoint (3), ctrl | shift);
  20150. check ("ctrl_shift_click_adds_again", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
  20151. pl.selectClipsForSnapshot ({});
  20152. headerShot ("-ctrl-multiselect.png", 6);
  20153. press (pl, headerPoint (0), ctrl, headerPoint (2));
  20154. check ("ctrl_drag_range_with_clips", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2 } && sortedClips() == clipsOn ({ 0, 1, 2 }),
  20155. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  20156. press (pl, headerPoint (1), shift); // LYNX's own Shift+click range (from the last clicked track, 0)
  20157. check ("lynx_shift_range_kept", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
  20158. {
  20159. int linked = -1;
  20160. auto old = pl.onLinkedMixerTrack;
  20161. pl.onLinkedMixerTrack = [&linked] (int insert) { linked = insert; };
  20162. press (pl, headerPoint (2), {});
  20163. check ("audio_track_click_links_mixer_track", linked == 3, juce::String (linked));
  20164. pl.onLinkedMixerTrack = old;
  20165. }
  20166. // ---- 2. the resize band (FUN_00ea93a0, AUTracksPanelMouseMove)
  20167. const auto heightOf = [&] (int t) { return pl.trackRowForSnapshot (t).getHeight(); };
  20168. const auto& tracks = [&]() -> const std::vector<lynx::PlaylistTrack>& { return engine.getSong().playlistTracks; };
  20169. press (pl, headerPoint (4), {}); // (track 4 alone selected)
  20170. {
  20171. const auto start = bandPoint (4);
  20172. press (pl, start, {}, start + juce::Point<int> (0, 41));
  20173. check ("drag_resizes", tracks()[4].height == 88 && heightOf (4) == 88, juce::String (tracks()[4].height) + " / " + juce::String (heightOf (4))); // (190gw: from FL's 48 px row)
  20174. headerShot ("-resized.png", 6);
  20175. const auto again = bandPoint (4);
  20176. press (pl, again, {}, again + juce::Point<int> (0, -100)); // (above the row's top, but less than 32 px)
  20177. check ("drag_stops_at_16", heightOf (4) == 16, juce::String (heightOf (4)));
  20178. press (pl, bandPoint (4), alt);
  20179. check ("alt_click_resets", tracks()[4].height == 0 && tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (heightOf (4)));
  20180. press (pl, bandPoint (4), {}, {}, 2); // the second press of a double click
  20181. check ("double_click_locks_small", tracks()[4].lockedHeight == 1 && heightOf (4) == 16, juce::String (tracks()[4].lockedHeight));
  20182. press (pl, bandPoint (4), {});
  20183. check ("click_on_locked_band_unlocks", tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (tracks()[4].lockedHeight));
  20184. const auto top = pl.trackRowForSnapshot (4).getY();
  20185. const auto b = bandPoint (4);
  20186. press (pl, b, {}, juce::Point<int> (b.x, top - 40));
  20187. check ("drag_past_the_top_groups", tracks()[4].grouped && tracks()[4].height == 0, juce::String ((int) tracks()[4].grouped));
  20188. const auto b2 = bandPoint (4);
  20189. press (pl, b2, {}, juce::Point<int> (b2.x, pl.trackRowForSnapshot (4).getY() - 40));
  20190. check ("again_ungroups", ! tracks()[4].grouped, juce::String ((int) tracks()[4].grouped));
  20191. }
  20192. {
  20193. // every selected track: the same height, from the first one's top to the mouse
  20194. press (pl, headerPoint (1), {});
  20195. press (pl, headerPoint (2), ctrl | shift);
  20196. press (pl, headerPoint (3), ctrl | shift);
  20197. const auto top = pl.trackRowForSnapshot (1).getY();
  20198. const auto b = bandPoint (2);
  20199. press (pl, b, {}, juce::Point<int> (b.x, top + 2 * 50));
  20200. check ("selected_tracks_share_the_height", tracks()[1].height == 50 && tracks()[2].height == 50 && tracks()[3].height == 50,
  20201. juce::String (tracks()[1].height) + "," + juce::String (tracks()[2].height) + "," + juce::String (tracks()[3].height));
  20202. headerShot ("-selected-resized.png", 6);
  20203. }
  20204. // ---- 3. saved: .lynx round trip and the .flp size factor
  20205. {
  20206. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[5].height = 300; s.playlistTracks[0].lockedHeight = 60; });
  20207. const auto json = lynx::ProjectFile::toJson (engine.getSong());
  20208. juce::String error;
  20209. const auto back = lynx::ProjectFile::fromJson (json, error);
  20210. check ("lynx_round_trip", back && back->playlistTracks.size() > 5 && back->playlistTracks[5].height == 300 && back->playlistTracks[1].height == 50
  20211. && back->playlistTracks[0].lockedHeight == 60, error);
  20212. lynx::flpexport::Options options;
  20213. lynx::flpexport::Report flpReport;
  20214. const auto project = flp::parseProject (lynx::flpexport::exportFlp (engine.getSong(), options, flpReport));
  20215. float size5 = -1.0f, size1 = -1.0f;
  20216. for (const auto& arrangement : project.arrangements)
  20217. for (const auto& t : arrangement.tracks)
  20218. {
  20219. if (t.index == 5) size5 = t.heightScale;
  20220. if (t.index == 1) size1 = t.heightScale;
  20221. }
  20222. check ("flp_size_factor", std::abs (size5 - lynx::polish::flSizeForHeight (300, 48)) < 1.0e-4f && std::abs (size1 - lynx::polish::flSizeForHeight (50, 48)) < 1.0e-4f,
  20223. juce::String (size5) + " " + juce::String (size1));
  20224. }
  20225. // ---- 4. the mixer strips (round 170b's FL rules): Ctrl+click alone, Ctrl+Shift+click adds / removes
  20226. {
  20227. ui.selectTabForSnapshot (3);
  20228. engine.editSong ([] (lynx::Song& s) { if (s.mixer.size() < 9) s.mixer.resize (9); });
  20229. engine.dispatchPendingMessages();
  20230. auto& mixer = ui.getMixerForSnapshot();
  20231. mixer.setSize (1400, 640);
  20232. auto& strips = mixer.getStripsForSnapshot();
  20233. strips.setSize (juce::jmax (strips.getWidth(), 1300), juce::jmax (strips.getHeight(), 560));
  20234. const auto at = [&] (int t) { return juce::Point<int> (strips.stripLeft (t) + 8, strips.getHeight() / 2 + 40); };
  20235. press (strips, at (2), {});
  20236. check ("mixer_click_alone", strips.getSelection() == std::vector<int> { 2 }, list (strips.getSelection()));
  20237. // LYNX extra (issue #163): Ctrl+click adds / removes one insert
  20238. press (strips, at (4), ctrl);
  20239. press (strips, at (6), ctrl);
  20240. check ("mixer_ctrl_click_adds_lynx", strips.getSelection() == std::vector<int> { 2, 4, 6 }, list (strips.getSelection()));
  20241. press (strips, at (4), ctrl);
  20242. check ("mixer_ctrl_click_removes_lynx", strips.getSelection() == std::vector<int> { 2, 6 }, list (strips.getSelection()));
  20243. // FL: Ctrl+Shift+click adds / removes too
  20244. press (strips, at (5), ctrl | shift);
  20245. check ("mixer_ctrl_shift_click_adds", strips.getSelection() == std::vector<int> { 2, 5, 6 }, list (strips.getSelection()));
  20246. savePng (mixer.createComponentSnapshot ({ 0, 0, juce::jmin (mixer.getWidth(), 900), mixer.getHeight() }), prefix + "-mixer-ctrl-multiselect.png");
  20247. // FL: Ctrl+drag across the strips = the range from the press, alone
  20248. press (strips, at (3), ctrl, at (4));
  20249. check ("mixer_ctrl_drag_range", strips.getSelection() == std::vector<int> { 3, 4 }, list (strips.getSelection()));
  20250. }
  20251. // ---- 5. round 190gw (live check 190gu B1): FL's default row, the left lock strip, the right selection strip
  20252. {
  20253. ui.selectTabForSnapshot (2);
  20254. auto song = lynx::Song::makeDefault();
  20255. song.playlist.clear();
  20256. song.playlistTracks.assign (6, {});
  20257. for (int t = 0; t < 6; ++t)
  20258. song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
  20259. engine.setSong (std::move (song));
  20260. engine.dispatchPendingMessages();
  20261. pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
  20262. check ("gw_default_row_48", heightOf (0) == 48 && heightOf (5) == 48, juce::String (heightOf (0)));
  20263. const auto rowMid = [&] (int t) { const auto r = pl.trackRowForSnapshot (t); return r.getY() + r.getHeight() / 2 - 4; };
  20264. const auto stripX = pl.headerWidthForSnapshot() - 4;
  20265. // the left strip (x < 10): the row flips to the smallest size and back; nothing selects
  20266. press (pl, { 2, rowMid (2) }, {});
  20267. check ("gw_left_strip_smallest", heightOf (2) == 16 && tracks()[2].lockedHeight == 1, juce::String (heightOf (2)));
  20268. press (pl, { 2, rowMid (2) }, {});
  20269. check ("gw_left_strip_back", heightOf (2) == 48 && tracks()[2].lockedHeight == -1, juce::String (heightOf (2)));
  20270. // the right strip: click = alone, Shift+click toggles, right-click toggles with no menu
  20271. press (pl, { stripX, rowMid (0) }, {});
  20272. check ("gw_strip_click_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 0 }, list (pl.selectedTracksForSnapshot()));
  20273. press (pl, { stripX, rowMid (1) }, shift);
  20274. check ("gw_strip_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
  20275. headerShot ("-gw-strip-two-selected.png", 6);
  20276. press (pl, { stripX, rowMid (0) }, shift);
  20277. check ("gw_strip_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
  20278. {
  20279. const juce::Point<int> p { stripX, rowMid (4) };
  20280. const juce::ModifierKeys right (juce::ModifierKeys::rightButtonModifier);
  20281. pl.mouseDown (event (pl, p, right, p, 1, false));
  20282. pl.mouseUp (event (pl, p, {}, p, 1, false));
  20283. }
  20284. check ("gw_strip_right_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 4 }, list (pl.selectedTracksForSnapshot()));
  20285. // a drag down the strip: the tracks crossed join (FUN_012e8740)
  20286. press (pl, { stripX, rowMid (0) }, {}, juce::Point<int> (stripX, rowMid (4)));
  20287. check ("gw_strip_drag_range", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2, 3, 4 }, list (pl.selectedTracksForSnapshot()));
  20288. headerShot ("-gw-strip-range.png", 6);
  20289. // a double click: the track alone <-> every track
  20290. press (pl, { stripX, rowMid (2) }, {});
  20291. press (pl, { stripX, rowMid (2) }, {}, {}, 2);
  20292. check ("gw_strip_double_click_all", (int) pl.selectedTracksForSnapshot().size() == pl.numTracksForSnapshot(), list (pl.selectedTracksForSnapshot()));
  20293. press (pl, { stripX, rowMid (1) }, {});
  20294. // .lynx: the new default row is saved; a project from before (no key) keeps LYNX's old 38 px row
  20295. juce::String error;
  20296. const auto json = lynx::ProjectFile::toJson (engine.getSong());
  20297. const auto back = lynx::ProjectFile::fromJson (json, error);
  20298. check ("gw_lynx_row_saved", back && back->playlistRowHeight == 48, error);
  20299. auto parsed = juce::JSON::parse (json);
  20300. if (auto* o = parsed.getDynamicObject())
  20301. o->removeProperty ("playlistRowHeight");
  20302. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  20303. check ("gw_old_lynx_keeps_38", old && old->playlistRowHeight == 38, error);
  20304. engine.setSong (*old);
  20305. engine.dispatchPendingMessages();
  20306. check ("gw_old_lynx_rows_38", heightOf (0) == 38, juce::String (heightOf (0)));
  20307. // an automation clip with two target links (Crossfade with) comes back with its links and formulas
  20308. auto linked = lynx::Song::makeDefault();
  20309. linked.channels.resize (2);
  20310. lynx::Automation a;
  20311. a.links = { { { lynx::AutomationTargetKind::channelAdjust, 0, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeOutFormula },
  20312. { { lynx::AutomationTargetKind::channelAdjust, 1, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeInFormula } };
  20313. a.target = a.links[0].target;
  20314. a.points = { { 0, 1.0f, 0.0f }, { 384, 0.0f, 0.0f } };
  20315. linked.automations.push_back (a);
  20316. const auto linkedBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (linked), error);
  20317. check ("gw_lynx_links_round_trip", linkedBack && linkedBack->automations.size() == linked.automations.size()
  20318. && linkedBack->automations.back().links == a.links && linkedBack->automations.back().target == a.target, error);
  20319. // Sampler › Open in new Fruity Slicer / Slicex channel: named after the sample, " #n" when taken
  20320. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190gw").getChildFile ("Basic 808 Clap.wav");
  20321. wav.getParentDirectory().createDirectory();
  20322. {
  20323. juce::AudioBuffer<float> b (1, 4410);
  20324. for (int i = 0; i < b.getNumSamples(); ++i)
  20325. b.setSample (0, i, 0.5f * std::sin ((float) i * 0.2f) * (1.0f - (float) i / (float) b.getNumSamples()));
  20326. wav.deleteFile();
  20327. juce::WavAudioFormat format;
  20328. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream());
  20329. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  20330. {
  20331. out.release();
  20332. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  20333. writer->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  20334. }
  20335. }
  20336. engine.editSong ([] (lynx::Song& s) {
  20337. s.channels.resize (1);
  20338. s.channels[0] = {};
  20339. s.channels[0].name = "Basic 808 Clap";
  20340. });
  20341. engine.dispatchPendingMessages();
  20342. if (lynx::openInNewChannelHandler())
  20343. {
  20344. lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::fruityslicer);
  20345. lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::slicex);
  20346. }
  20347. engine.dispatchPendingMessages();
  20348. const auto& ch = engine.getSong().channels;
  20349. check ("gw_open_in_new_named_after_sample", ch.size() >= 3 && ch[1].name == "Basic 808 Clap #2" && ch[2].name == "Basic 808 Clap #3"
  20350. && ch[1].instrument == lynx::InstrumentKind::fruityslicer && ch[2].instrument == lynx::InstrumentKind::slicex,
  20351. ch.size() >= 3 ? juce::String::fromUTF8 (ch[1].name.c_str()) + " | " + juce::String::fromUTF8 (ch[2].name.c_str()) : juce::String ((int) ch.size()));
  20352. wav.getParentDirectory().deleteRecursively();
  20353. // the mixer's two boxes (live check 190gu B4): "Insert multiple..." asks "Number of tracks to add" (1),
  20354. // "Add multiple..." "Enter the number of mixer tracks to add" (10)
  20355. for (const auto adding : { false, true })
  20356. {
  20357. auto box = lynx::MixerStrips::makeInsertMultipleBox (adding);
  20358. const auto text = box->getTextEditorContents ("count");
  20359. check (adding ? "gw_add_multiple_box" : "gw_insert_multiple_box", text == (adding ? "10" : "1"), text);
  20360. if (box->getWidth() > 0 && box->getHeight() > 0)
  20361. savePng (box->createComponentSnapshot (box->getLocalBounds()), prefix + (adding ? "-gw-add-multiple-box.png" : "-gw-insert-multiple-box.png"));
  20362. }
  20363. }
  20364. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  20365. return allOk;
  20366. }
  20367. #include "FoldersShot190jf.inc" // round 190jf (slice B17)
  20368. // --userfixshot190ib (round 190ib): see the dispatch above
  20369. bool runUserFixShot190ib (const juce::String& prefix)
  20370. {
  20371. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20372. juce::StringArray report;
  20373. bool allOk = true;
  20374. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  20375. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  20376. allOk = allOk && ok;
  20377. };
  20378. lynx::AudioEngine engine (false);
  20379. lynx::MainComponent ui (engine, false);
  20380. ui.setSize (1600, 900);
  20381. engine.dispatchPendingMessages();
  20382. // ---- #182: a real JUCE popup menu inside a host component, keys sent to its window as the keyboard would
  20383. juce::Component host;
  20384. host.setSize (560, 900);
  20385. const auto typeInto = [&host] (const juce::String& text) {
  20386. auto* menuWindow = host.getNumChildComponents() > 0 ? host.getChildComponent (host.getNumChildComponents() - 1) : nullptr;
  20387. for (auto c : text)
  20388. if (menuWindow != nullptr)
  20389. menuWindow->keyPressed (juce::KeyPress ((int) juce::CharacterFunctions::toLowerCase (c), 0, c));
  20390. return menuWindow != nullptr;
  20391. };
  20392. const auto shotMenu = [&host, &prefix] (const juce::String& name) {
  20393. savePng (host.createComponentSnapshot (host.getLocalBounds()), prefix + name);
  20394. };
  20395. {
  20396. auto& pl = ui.getPlaylistForSnapshot();
  20397. pl.editMenu().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
  20398. check ("menu_shown", host.getNumChildComponents() > 0, juce::String (host.getNumChildComponents()));
  20399. shotMenu ("-menu-0.png");
  20400. typeInto ("d");
  20401. shotMenu ("-menu-d.png"); // the first item starting with D
  20402. typeInto ("d");
  20403. shotMenu ("-menu-dd.png"); // D again: the next one
  20404. juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100); // (a pause: a new prefix)
  20405. typeInto ("drop a");
  20406. shotMenu ("-menu-drop-a.png"); // "Drop audio on track headers"
  20407. juce::PopupMenu::dismissAllActiveMenus();
  20408. }
  20409. {
  20410. auto& pr = ui.getPianoRollForSnapshot();
  20411. pr.moreMenuForSnapshot().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
  20412. juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100);
  20413. typeInto ("preview");
  20414. shotMenu ("-pianoroll-preview.png"); // #183's item, reached by typing its name
  20415. juce::PopupMenu::dismissAllActiveMenus();
  20416. check ("preview_while_playing_off_by_default", ! lynx::PianoRollComponent::previewWhilePlaying);
  20417. }
  20418. // ---- #181: Ctrl+, (Cmd+, on macOS) through the main window's key handling opens Settings, again closes it
  20419. const auto ctrlComma = juce::KeyPress (',', juce::ModifierKeys::commandModifier, ',');
  20420. check ("settings_closed_first", lynx::shownSettingsPage() < 0);
  20421. ui.keyPressed (ctrlComma);
  20422. check ("ctrl_comma_opens_settings", lynx::shownSettingsPage() == (int) lynx::SettingsPage::general, juce::String (lynx::shownSettingsPage()));
  20423. ui.keyPressed (ctrlComma);
  20424. check ("ctrl_comma_again_closes_it", lynx::shownSettingsPage() < 0, juce::String (lynx::shownSettingsPage()));
  20425. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  20426. return allOk;
  20427. }
  20428. // --issuesshot190ht (round 190ht): see the dispatch above
  20429. bool runIssuesShot190ht (const juce::String& prefix)
  20430. {
  20431. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20432. juce::StringArray report;
  20433. bool allOk = true;
  20434. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  20435. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  20436. allOk = allOk && ok;
  20437. };
  20438. using namespace lynx;
  20439. AudioEngine engine (false);
  20440. MainComponent ui (engine, false);
  20441. ui.setSize (1600, 900);
  20442. const auto bar = (std::int64_t) 4 * ppq;
  20443. {
  20444. // Kick (1 bar), Bass (2 bars, a long note across its second bar), Lead (1 bar), Pad (1 bar): blocks in rows
  20445. auto song = Song::makeDefault();
  20446. song.playlist.clear();
  20447. song.patterns.clear();
  20448. const auto pattern = [&song] (const char* name, std::uint32_t colour, int channel, std::int64_t length) {
  20449. auto& p = song.patterns.emplace_back();
  20450. p.name = name;
  20451. p.colour = colour;
  20452. for (int step : { 0, 4, 8, 12 })
  20453. p.toggleStep (channel, step);
  20454. p.lengthTicks = length;
  20455. return (int) song.patterns.size() - 1;
  20456. };
  20457. pattern ("Kick", 0xFFD85A3C, 0, bar);
  20458. const auto bass = pattern ("Bass", 0xFF3C8DD8, 1, 0);
  20459. Note longNote;
  20460. longNote.channel = 1;
  20461. longNote.start = 6 * ppq;
  20462. longNote.length = 2 * ppq;
  20463. song.patterns[(std::size_t) bass].notes.push_back (longNote);
  20464. song.patterns[(std::size_t) bass].sortNotes();
  20465. pattern ("Lead", 0xFF8A5CD8, 2, bar);
  20466. pattern ("Pad", 0xFF5CB85C, 3, bar);
  20467. song.patternBlocksOn = true;
  20468. for (int b = 0; b < 8; ++b)
  20469. patternblocks::place (song, 0, b * bar);
  20470. patternblocks::place (song, 1, 0);
  20471. patternblocks::place (song, 1, 4 * bar);
  20472. for (int b = 2; b < 6; ++b)
  20473. patternblocks::place (song, 2, b * bar);
  20474. patternblocks::place (song, 3, 0);
  20475. engine.setSong (std::move (song));
  20476. }
  20477. engine.dispatchPendingMessages();
  20478. ui.selectTabForSnapshot (2);
  20479. engine.dispatchPendingMessages();
  20480. auto& pl = ui.getPlaylistForSnapshot();
  20481. pl.setSize (juce::jmax (pl.getWidth(), 1000), juce::jmax (pl.getHeight(), 640));
  20482. pl.setViewForSnapshot (90.0, 0, 0); // (bar 1 at the left edge)
  20483. pl.setBlocksHeight (6 + 5 * 18 + 6);
  20484. engine.dispatchPendingMessages();
  20485. const auto& song = [&]() -> const Song& { return engine.getSong(); };
  20486. auto* blocks = pl.getBlocksViewForSnapshot();
  20487. check ("blocks_view", blocks != nullptr && blocks->isVisible());
  20488. if (blocks == nullptr)
  20489. {
  20490. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=FAIL\n");
  20491. return false;
  20492. }
  20493. const auto shotBlocks = [&] (const juce::String& name) {
  20494. engine.dispatchPendingMessages();
  20495. const auto area = blocks->getBoundsInParent().withWidth (juce::jmin (pl.getWidth(), 900)).expanded (0, 2).getIntersection (pl.getLocalBounds());
  20496. savePng (pl.createComponentSnapshot (area), prefix + name);
  20497. };
  20498. auto source = juce::Desktop::getInstance().getMainMouseSource();
  20499. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
  20500. juce::Point<float> pressedAt;
  20501. const auto bEvent = [&] (int row, std::int64_t tick, juce::ModifierKeys mods, int clicks = 1) {
  20502. const auto at = blocks->pointForSnapshot (row, tick).toFloat();
  20503. const auto now = juce::Time::getCurrentTime();
  20504. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, clicks, at != pressedAt);
  20505. };
  20506. const auto bPress = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  20507. pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
  20508. blocks->mouseDown (bEvent (row, tick, mods));
  20509. };
  20510. const auto bDrag = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (bEvent (row, tick, mods)); };
  20511. const auto bRelease = [&] (int row, std::int64_t tick, juce::ModifierKeys mods = {}) {
  20512. blocks->mouseUp (bEvent (row, tick, mods));
  20513. engine.dispatchPendingMessages();
  20514. };
  20515. const auto blockOf = [&] (int row, std::int64_t start) -> const PatternBlock* {
  20516. const auto i = patternblocks::indexOf (song(), { row, start });
  20517. return i < 0 ? nullptr : &song().blocks[(std::size_t) i];
  20518. };
  20519. const auto mutedAt = [&] (int row, std::int64_t start) { const auto* x = blockOf (row, start); return x != nullptr && x->muted; };
  20520. const auto playingAt = [&] (int row, std::int64_t start) { const auto* x = blockOf (row, start); return x != nullptr && ! x->muted; };
  20521. const auto mutedCount = [&] {
  20522. int n = 0;
  20523. for (const auto& b : song().blocks)
  20524. n += b.muted ? 1 : 0;
  20525. return n;
  20526. };
  20527. shotBlocks ("-blocks-before.png");
  20528. // ---- #127 Mute: a click mutes the block, a drag down across rows mutes the blocks it crosses (any row)
  20529. pl.setToolForSnapshot (EditTool::mute);
  20530. bPress (0, 2 * bar + 40, left);
  20531. bRelease (0, 2 * bar + 40);
  20532. check ("mute_click", blockOf (0, 2 * bar) != nullptr && mutedAt (0, 2 * bar) && mutedCount() == 1);
  20533. bPress (0, 4 * bar + 40, left);
  20534. bDrag (1, 4 * bar + 60, left);
  20535. bDrag (2, 4 * bar + 80, left);
  20536. bRelease (2, 4 * bar + 80);
  20537. check ("mute_drag_across_rows", mutedAt (0, 4 * bar) && blockOf (1, 4 * bar) != nullptr && mutedAt (1, 4 * bar)
  20538. && mutedAt (2, 4 * bar) && playingAt (3, 0) && mutedCount() == 4,
  20539. juce::String (mutedCount()));
  20540. shotBlocks ("-blocks-mute.png");
  20541. // a sweep that starts on a muted block unmutes
  20542. bPress (0, 2 * bar + 40, left);
  20543. bDrag (0, 3 * bar + 40, left);
  20544. bRelease (0, 3 * bar + 40);
  20545. check ("mute_sweep_from_muted_unmutes", playingAt (0, 2 * bar) && playingAt (0, 3 * bar) && mutedCount() == 3,
  20546. juce::String (mutedCount()));
  20547. // the right button erases, as with every tool but Select / Slice / Zoom
  20548. bPress (3, 40, right);
  20549. bRelease (3, 40);
  20550. check ("mute_right_click_erases", blockOf (3, 0) == nullptr);
  20551. engine.undo();
  20552. engine.dispatchPendingMessages();
  20553. check ("undo_erase", blockOf (3, 0) != nullptr);
  20554. // the muted blocks play nothing: their clips in the playback copy are muted
  20555. {
  20556. auto copy = song();
  20557. patternblocks::expandSong (copy);
  20558. int mutedClips = 0;
  20559. for (const auto& c : copy.playlist)
  20560. mutedClips += c.muted ? 1 : 0;
  20561. check ("muted_blocks_play_muted_clips", mutedClips == 3, juce::String (mutedClips));
  20562. juce::String error;
  20563. const auto back = ProjectFile::fromJson (ProjectFile::toJson (song()), error);
  20564. check ("muted_blocks_saved", back && back->blocks == song().blocks, error);
  20565. }
  20566. // ---- #127 Select: a box over rows 0-2, bars 5-6 selects every block it meets; Pencil moves them together
  20567. pl.setToolForSnapshot (EditTool::lasso);
  20568. bPress (0, 4 * bar + 40, left);
  20569. bDrag (2, 5 * bar + 40, left);
  20570. shotBlocks ("-blocks-select-box.png");
  20571. bRelease (2, 5 * bar + 40);
  20572. const auto selection = blocks->selectionForSnapshot();
  20573. check ("select_box_any_row", selection.size() == 5 && patternblocks::contains (selection, { 0, 4 * bar }) && patternblocks::contains (selection, { 1, 4 * bar })
  20574. && patternblocks::contains (selection, { 2, 5 * bar }),
  20575. juce::String ((int) selection.size()));
  20576. pl.setToolForSnapshot (EditTool::pencil);
  20577. // (Kick's bars 7 and 8 are in the way of a 2-bar move: move the group by 1 bar after clearing them)
  20578. engine.editSong ([bar] (Song& s) { patternblocks::eraseRange (s, 0, 6 * bar, 8 * bar); });
  20579. engine.dispatchPendingMessages();
  20580. bPress (1, 4 * bar + 40, left);
  20581. bDrag (1, 6 * bar + 40, left);
  20582. bRelease (1, 6 * bar + 40);
  20583. check ("pencil_moves_the_selection", blockOf (1, 6 * bar) != nullptr && blockOf (0, 6 * bar) != nullptr && blockOf (0, 7 * bar) != nullptr
  20584. && blockOf (2, 6 * bar) != nullptr && blockOf (2, 7 * bar) != nullptr && blockOf (1, 4 * bar) == nullptr
  20585. && blocks->selectionForSnapshot().size() == 5);
  20586. shotBlocks ("-blocks-select-moved.png");
  20587. // a press on a block outside the selection moves that block alone and drops the selection
  20588. bPress (3, 40, left);
  20589. bDrag (3, bar + 40, left);
  20590. bRelease (3, bar + 40);
  20591. check ("pencil_unselected_block_alone", blockOf (3, bar) != nullptr && blockOf (0, 6 * bar) != nullptr && blocks->selectionForSnapshot().empty());
  20592. // the right button selects too (FL 10: either button)
  20593. pl.setToolForSnapshot (EditTool::lasso);
  20594. bPress (3, bar + 40, right);
  20595. bRelease (3, bar + 40);
  20596. check ("select_click_right_button", blocks->selectionForSnapshot().size() == 1 && blockOf (3, bar) != nullptr);
  20597. // ---- #127 Slice: a click on Bass's first block at bar 2 beat 4 cuts the pattern; a new pattern takes the rest
  20598. pl.setToolForSnapshot (EditTool::knife);
  20599. const auto patternsBefore = song().patterns.size();
  20600. const juce::ModifierKeys freeLeft (juce::ModifierKeys::leftButtonModifier | juce::ModifierKeys::altModifier); // (Alt: no snap)
  20601. bPress (1, bar + 3 * ppq, freeLeft);
  20602. bDrag (2, bar + 3 * ppq, freeLeft); // (a vertical drag: the row under the mouse when released is cut)
  20603. bRelease (1, bar + 3 * ppq);
  20604. check ("slice_adds_a_pattern", song().patterns.size() == patternsBefore + 1 && song().patterns[2].name == "Bass #2",
  20605. juce::String ((int) song().patterns.size()));
  20606. check ("slice_trims_the_long_note", song().patterns[1].notes.back().start == 6 * ppq && song().patterns[1].notes.back().length >= ppq
  20607. && song().patterns[1].notes.back().length < ppq + ppq / 4 && song().patterns[2].notes.empty(),
  20608. juce::String (song().patterns[1].notes.back().length));
  20609. check ("slice_new_blocks_where_bass_ends", blockOf (2, 2 * bar) != nullptr && blockOf (2, 8 * bar) != nullptr);
  20610. shotBlocks ("-blocks-slice.png");
  20611. engine.undo();
  20612. engine.dispatchPendingMessages();
  20613. check ("undo_slice", song().patterns.size() == patternsBefore && song().patterns[2].name == "Lead");
  20614. // ---- #127 Zoom: a drag zooms to the range, a click goes back
  20615. pl.setToolForSnapshot (EditTool::zoom);
  20616. const auto zoomBefore = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  20617. bPress (0, 2 * bar, left);
  20618. bDrag (0, 4 * bar, left);
  20619. bRelease (0, 4 * bar);
  20620. const auto zoomed = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  20621. check ("zoom_drag_zooms_in", zoomed > zoomBefore * 1.5, juce::String (zoomed) + " vs " + juce::String (zoomBefore));
  20622. pressedAt = blocks->pointForSnapshot (0, 3 * bar).toFloat();
  20623. blocks->mouseDown (bEvent (0, 3 * bar, right));
  20624. blocks->mouseUp (bEvent (0, 3 * bar, {}));
  20625. const auto back = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  20626. check ("zoom_click_goes_back", std::abs (back - zoomBefore) < 0.5, juce::String (back));
  20627. // hints name each tool's gesture
  20628. pl.setToolForSnapshot (EditTool::mute);
  20629. check ("hint_mute", blocks->hintAt (blocks->pointForSnapshot (0, 40)).text.contains ("mutes"));
  20630. pl.setToolForSnapshot (EditTool::pencil);
  20631. // ---- #154: linked tracks, then the insert effects list on their headers
  20632. engine.editSong ([bar] (Song& s) {
  20633. s.patternBlocksOn = false;
  20634. s.blocks.clear();
  20635. s.playlist.clear();
  20636. ChannelDef vox;
  20637. vox.name = "Lead vocal";
  20638. vox.instrument = InstrumentKind::audioClip;
  20639. vox.samplePath = "/shots/Lead vocal.wav";
  20640. vox.mixerTrack = 12;
  20641. s.channels.push_back (vox);
  20642. const auto voxChannel = (int) s.channels.size() - 1;
  20643. s.mixer[12].name = "Vox chain";
  20644. for (auto k : { EffectKind::parametricEq, EffectKind::compressor, EffectKind::delay, EffectKind::reverb })
  20645. s.mixer[12].effects.push_back (makeEffectSlot (k));
  20646. s.mixer[12].effects[2].enabled = false;
  20647. s.channels[0].mixerTrack = 3;
  20648. s.mixer[3].name = "Kick";
  20649. s.mixer[3].effects.push_back (makeEffectSlot (EffectKind::compressor));
  20650. const auto clip = [&s, bar] (int track, ClipKind kind, int source, int at, int bars) {
  20651. Clip c;
  20652. c.kind = kind;
  20653. c.track = track;
  20654. c.start = at * bar;
  20655. c.length = bars * bar;
  20656. (kind == ClipKind::pattern ? c.pattern : c.channel) = source;
  20657. s.playlist.push_back (c);
  20658. };
  20659. clip (0, ClipKind::pattern, 0, 0, 4);
  20660. clip (1, ClipKind::audio, voxChannel, 0, 8);
  20661. s.playlistTracks.resize (4);
  20662. s.playlistTracks[1].height = 70;
  20663. });
  20664. engine.dispatchPendingMessages();
  20665. // (rollup 0.1.30: since round 190ib, switching the link on asks first when it moves inserts or routes channels;
  20666. // this run accepts, as the user clicking "Link")
  20667. PlaylistComponent::answerLinkConfirmation = [] (const autolink::Report&) { return true; };
  20668. // (round 190qk: the inserts column is on by default now; this route starts with it off, as before, and puts it back)
  20669. const auto insertsWere = std::exchange (PlaylistComponent::showTrackInserts, false);
  20670. pl.runAction ("playlist.linkTracks");
  20671. PlaylistComponent::answerLinkConfirmation = nullptr;
  20672. engine.dispatchPendingMessages();
  20673. // (rollup 0.1.30: round 190ib links Playlist track N to insert N, moving the inserts there: the Vox chain and
  20674. // the Kick follow their tracks, so the checks read the inserts the tracks are linked to)
  20675. const auto vox = song().playlistTracks.size() > 1 ? song().playlistTracks[1].mixerTrack : -1;
  20676. const auto kick = song().playlistTracks.size() > 0 ? song().playlistTracks[0].mixerTrack : -1;
  20677. check ("linked", song().linkTracksToMixer && vox > 0 && song().mixer[(std::size_t) vox].name == "Vox chain" && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth,
  20678. juce::String (pl.headerWidthForSnapshot()));
  20679. check ("inserts_off", ! PlaylistComponent::showTrackInserts && pl.insertsListForSnapshot (1).isEmpty());
  20680. const auto shotRows = [&] (const juce::String& name, int rows) {
  20681. engine.dispatchPendingMessages();
  20682. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  20683. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 820), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  20684. };
  20685. shotRows ("-inserts-off.png", 3);
  20686. pl.runAction ("playlist.trackInserts");
  20687. engine.dispatchPendingMessages();
  20688. check ("inserts_on_widens_linked_headers", PlaylistComponent::showTrackInserts
  20689. && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth + PlaylistComponent::insertsColumnWidth,
  20690. juce::String (pl.headerWidthForSnapshot()));
  20691. const auto list = [&] (int t) { return pl.insertsListForSnapshot (t); };
  20692. check ("list_on_linked_tracks_only", ! list (0).isEmpty() && ! list (1).isEmpty() && list (2).isEmpty(),
  20693. list (0).toString() + " / " + list (1).toString());
  20694. shotRows ("-inserts-on.png", 3);
  20695. // a row's hint names the effect
  20696. const auto rowPoint = [&] (int t, int row, bool dot) {
  20697. const auto r = list (t);
  20698. return juce::Point<int> (dot ? r.getX() + 5 : r.getX() + 40, r.getY() + row * 13 + 6);
  20699. };
  20700. const auto hintOf = [&] (juce::Point<int> p) { return pl.hintAt (p); };
  20701. check ("hint_names_the_effect", hintOf (rowPoint (1, 1, false)).value == quickpick::slotName (engine, song().mixer[(std::size_t) vox].effects[1]),
  20702. hintOf (rowPoint (1, 1, false)).value);
  20703. check ("hint_add_row", hintOf (rowPoint (0, 1, false)).text.contains ("add an effect"));
  20704. const auto now = juce::Time::getCurrentTime();
  20705. const int ctrl = juce::ModifierKeys::commandModifier;
  20706. const auto event = [&] (juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  20707. return juce::MouseEvent (source, p.toFloat(), mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &pl, &pl, now, down.toFloat(), now, clicks, dragged);
  20708. };
  20709. const auto press = [&] (juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}) {
  20710. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  20711. pl.mouseMove (event (p, mods, p, 1, false));
  20712. pl.mouseDown (event (p, down, p, 1, false));
  20713. if (to)
  20714. {
  20715. pl.mouseDrag (event ((p + *to) / 2, down, p, 1, true));
  20716. pl.mouseDrag (event (*to, down, p, 1, true));
  20717. }
  20718. pl.mouseUp (event (to ? *to : p, mods, p, 1, to.has_value()));
  20719. engine.dispatchPendingMessages();
  20720. };
  20721. const auto kinds = [&] (int insert) {
  20722. juce::StringArray k;
  20723. for (const auto& fx : song().mixer[(std::size_t) insert].effects)
  20724. k.add (juce::String ((int) fx.kind) + (fx.enabled ? "" : "-"));
  20725. return k.joinIntoString (",");
  20726. };
  20727. const auto eq = juce::String ((int) EffectKind::parametricEq), comp = juce::String ((int) EffectKind::compressor),
  20728. delay = juce::String ((int) EffectKind::delay), verb = juce::String ((int) EffectKind::reverb);
  20729. // the dot bypasses / un-bypasses, as the Mixer slot's LED (one undo step each)
  20730. press (rowPoint (1, 0, true), {});
  20731. check ("dot_bypasses", ! song().mixer[(std::size_t) vox].effects[0].enabled);
  20732. press (rowPoint (1, 2, true), {});
  20733. check ("dot_switches_on", song().mixer[(std::size_t) vox].effects[2].enabled);
  20734. engine.undo();
  20735. engine.dispatchPendingMessages();
  20736. check ("undo_dot", ! song().mixer[(std::size_t) vox].effects[2].enabled && ! song().mixer[(std::size_t) vox].effects[0].enabled);
  20737. press (rowPoint (1, 0, true), {});
  20738. shotRows ("-inserts-bypass.png", 3);
  20739. // drag the reverb (row 4) above the EQ: the chain order changes, as the Device View's drag
  20740. const auto before = kinds (vox);
  20741. press (rowPoint (1, 3, false), {}, rowPoint (1, 0, false) - juce::Point<int> (0, 4));
  20742. check ("drag_reorders", kinds (vox) == verb + "," + eq + "," + comp + "," + delay + "-", before + " -> " + kinds (vox));
  20743. // Ctrl + drag copies (the compressor, under the delay)
  20744. press (rowPoint (1, 2, false), juce::ModifierKeys (ctrl), rowPoint (1, 4, false) - juce::Point<int> (0, 4));
  20745. check ("ctrl_drag_copies", kinds (vox) == verb + "," + eq + "," + comp + "," + delay + "-," + comp, kinds (vox));
  20746. // onto another linked track's list: it moves to that insert (the Kick's)
  20747. press (rowPoint (1, 1, false), {}, rowPoint (0, 0, false));
  20748. check ("drag_to_another_track_moves", kinds (kick) == comp + "," + eq && kinds (vox) == verb + "," + comp + "," + delay + "-," + comp,
  20749. kinds (kick) + " | " + kinds (vox));
  20750. // the wheel scrolls a list longer than its track (Kick's 4 effects + "add" in a 3-row header)
  20751. engine.editSong ([kick] (Song& s) {
  20752. s.mixer[(std::size_t) kick].effects.push_back (makeEffectSlot (EffectKind::delay));
  20753. s.mixer[(std::size_t) kick].effects.push_back (makeEffectSlot (EffectKind::reverb));
  20754. });
  20755. engine.dispatchPendingMessages();
  20756. const auto firstName = hintOf (rowPoint (0, 0, false)).value;
  20757. const auto rowsShown = list (0).getHeight() / 13;
  20758. pl.mouseWheelMove (event (rowPoint (0, 0, false), {}, rowPoint (0, 0, false), 0, false), juce::MouseWheelDetails { 0.0f, -0.5f, false, false, false });
  20759. const auto afterWheel = hintOf (rowPoint (0, 0, false));
  20760. check ("wheel_scrolls_a_long_list", rowsShown < 5 && afterWheel.value != firstName
  20761. && afterWheel.value == quickpick::slotName (engine, song().mixer[(std::size_t) kick].effects[1]),
  20762. juce::String (rowsShown) + " rows, " + firstName + " -> " + afterWheel.value);
  20763. shotRows ("-inserts-edited.png", 3);
  20764. // a view option: not saved with the project
  20765. check ("option_not_in_project", ! ProjectFile::toJson (song()).contains ("trackInserts"));
  20766. // off again: the linked headers' own width
  20767. pl.runAction ("playlist.trackInserts");
  20768. engine.dispatchPendingMessages();
  20769. check ("inserts_off_again", ! PlaylistComponent::showTrackInserts && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth);
  20770. PlaylistComponent::showTrackInserts = insertsWere;
  20771. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  20772. return allOk;
  20773. }
  20774. #include "WorkflowShot190iu.inc" // round 190iu
  20775. #include "PlaylistShot190jq.inc" // round 190jq
  20776. #include "IssuesShot190jz.inc" // round 190jz
  20777. #include "IssuesShot190lw.inc" // round 190lw
  20778. #include "IssuesShot190mq.inc" // round 190mq
  20779. #include "Focus218Shot190ng.inc" // round 190ng (issue #218)
  20780. #include "Mixer221Shot190ng.inc" // round 190ng (issue #221)
  20781. #include "MixerQolShot190qh.inc" // round 190qh (research190qa R5, Mixer QoL)
  20782. #include "Slots260Shot190qf.inc" // round 190qf (PR #260)
  20783. #include "IssuesShot190ng.inc" // round 190ng (issues #215, #217, #219, #220, #222)
  20784. #include "TrackClipsShot190ne.inc" // round 190ne
  20785. #include "TrackStatesShot190op.inc" // round 190op
  20786. #include "AutoModesShot190pa.inc" // round 190pa
  20787. #include "Tracks190peShot.inc" // round 190pe
  20788. #include "HeaderGearShot248.inc" // rollup 0.1.31 step 7 (PRs #248 / #256)
  20789. #include "PerTabShot259.inc" // round 190pw (PR #259)
  20790. #include "HotfixUi190qp.inc" // hotfix 0.1.31.1 (round 190qp)
  20791. #include "TrackerShot190nw.inc" // round 190nw
  20792. #include "IssuesShot190nq.inc" // round 190nq (issues #193, #225-#230)
  20793. #include "Research190onShot.inc" // round 190on (research190oe P2, P8, P10)
  20794. #include "IssuesShot190ns.inc" // round 190ns (issues #231-#235)
  20795. #include "Rollup031S3Shot.inc" // rollup 0.1.31 step 3 (round 190ny)
  20796. #include "Tabs2Test190nz.inc" // round 190nz (issue #232 stage 2)
  20797. #include "IssuesShot190od.inc" // round 190od (issues #236-#242)
  20798. #include "Design190ojShot.inc" // round 190oj (design review of every view)
  20799. #include "Design190ooShot.inc" // round 190oo (design review 2: the owner's options and the round's fixes)
  20800. #include "Extras190qkShot.inc" // round 190qk (the LYNX extras on by default)
  20801. #include "IssuesShot190oq.inc" // round 190oq (issues #243-#252)
  20802. #include "IssuesShot190qb.inc" // round 190qb (follow-ups of issues #206, #215)
  20803. #include "Picker190qiShot.inc" // round 190qi (TOP-NEXT R6): picker and Browser quality of life
  20804. #include "PickerPaintBench190qi.inc" // round 190qi: the plugin lists' and the Browser's paint gate
  20805. #include "IssuesShot190qo.inc" // round 190qo (issues #239, #215, #251, #270)
  20806. #include "RackAuto190owShot.inc" // round 190ow (PAT-7 rest, DE-123: the automation clip rows at work)
  20807. #include "DetailsShot190kn.inc" // round 190kn
  20808. #include "SmartTipShot190ok.inc" // round 190ok (D1)
  20809. #include "SimpleDuckShot190ot.inc" // round 190ot (research190oe P5)
  20810. #include "Discord190quShot.inc" // round 190qu (Discord #general 11-24)
  20811. #include "Repeats190pmShot.inc" // round 190pm (research190oe P19, P23)
  20812. #include "DetailsShot190ld.inc" // round 190ld
  20813. #include "DetailsShot190lr.inc" // round 190lr
  20814. #include "DetailsShot190lx.inc" // round 190lx
  20815. #include "DetailsShot190mf.inc" // round 190mf
  20816. #include "DetailsShot190mk.inc" // round 190mk
  20817. #include "DetailsShot190mp.inc" // round 190mp
  20818. #include "HWheel254Test.inc" // round 190ou: issue #254, the horizontal wheel
  20819. #include "Feel190qeTest.inc" // round 190qe (TOP-NEXT R1): edge scroll, view stack, glide, keep labels
  20820. #include "MultiEditor255Test.inc" // round 190ou: issue #255, several plugin editors in use
  20821. #include "Issue258Test.inc" // round 190pv: issue #258, a cloned channel's own automation
  20822. #include "Hotfix190qpTest.inc" // round 190qp: imported automation heard and shown (issue #253)
  20823. #include "Hotfix190qpWf.inc" // round 190qp: 0.1.31.1 hotfix (track clips open their notes; Export... with folders in the name)
  20824. #include "Issue282Check.inc" // round 190qs: issue #282, FL's trial mark and the Patcher generator in Export to FL Studio
  20825. #include "ToolbarShot190qg.inc" // round 190qg: the toolbar never hides anything silently (walk, pictures)
  20826. #include "Issues190qrCheck.inc" // round 190qr: issues #274-#281 (markers, rack meter, zoom, extras)
  20827. #include "Qa190rbCheck.inc" // round 190rb: the 0.1.32 quality round's crash / memory fixes, checked
  20828. #include "DetailsShot190mr.inc" // round 190mr
  20829. #include "DetailsShot190mv.inc" // round 190mv
  20830. #include "DetailsShot190my.inc" // round 190my
  20831. #include "DetailsShot190oa.inc" // round 190oa
  20832. #include "RackShot190nc.inc" // round 190nc
  20833. #include "OnboardShot190np.inc" // round 190np
  20834. #include "Demo190pgCheck.inc" // round 190pg
  20835. #include "Demo190plCheck.inc" // round 190pl
  20836. #include "AutoLinks190ovCheck.inc" // round 190ov (FL automation clips linked to several controls)
  20837. // --trackautoshot190gz (round 190gz): see the dispatch above
  20838. bool runTrackAutoShot190gz (const juce::String& prefix)
  20839. {
  20840. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20841. juce::StringArray report;
  20842. bool allOk = true;
  20843. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  20844. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  20845. allOk = allOk && ok;
  20846. };
  20847. lynx::AudioEngine engine (false);
  20848. lynx::MainComponent ui (engine, false);
  20849. ui.setSize (1600, 900);
  20850. {
  20851. // a small song in FL's shape: Kick and Synth patterns, a drum loop, a vocal on its prepared insert, a mixed beat
  20852. using namespace lynx;
  20853. auto song = Song::makeDefault();
  20854. song.playlist.clear();
  20855. song.patterns.clear();
  20856. for (auto& c : song.channels)
  20857. c.mixerTrack = 0; // (FL's new channels play on the Master)
  20858. song.channels[4].mixerTrack = 9; // the Synth on a bus the user made
  20859. song.mixer[9].name = "Synth bus";
  20860. const auto audio = [&song] (const char* name, int mixer) {
  20861. ChannelDef c;
  20862. c.name = name;
  20863. c.instrument = InstrumentKind::audioClip;
  20864. c.samplePath = std::string ("/shots/") + name + ".wav";
  20865. c.mixerTrack = mixer;
  20866. song.channels.push_back (c);
  20867. return (int) song.channels.size() - 1;
  20868. };
  20869. const auto loop = audio ("Drum loop", 0);
  20870. const auto vox = audio ("Lead vocal", 12);
  20871. song.mixer[12].name = "Vox chain";
  20872. song.mixer[12].colour = 0xFF3C8DD8;
  20873. song.mixer[12].effects.push_back (makeEffectSlot (EffectKind::parametricEq));
  20874. const auto pattern = [&song] (const char* name, std::vector<int> channels, std::uint32_t colour) {
  20875. auto& p = song.patterns.emplace_back();
  20876. p.name = name;
  20877. p.colour = colour;
  20878. for (const auto c : channels)
  20879. for (int step : { 0, 4, 8, 12 })
  20880. p.toggleStep (c, step);
  20881. return (int) song.patterns.size() - 1;
  20882. };
  20883. const auto kick = pattern ("Kick", { 0 }, 0xFFD85A3C);
  20884. const auto lead = pattern ("Lead", { 4 }, 0xFF8A5CD8);
  20885. const auto beat = pattern ("Beat", { 1, 2, 3 }, 0xFF5CB85C);
  20886. const auto clip = [&song] (int track, ClipKind kind, int source, int bar, int bars) {
  20887. Clip c;
  20888. c.kind = kind;
  20889. c.track = track;
  20890. c.start = (std::int64_t) bar * 4 * ppq;
  20891. c.length = (std::int64_t) bars * 4 * ppq;
  20892. (kind == ClipKind::pattern ? c.pattern : c.channel) = source;
  20893. song.playlist.push_back (c);
  20894. };
  20895. for (int bar = 0; bar < 8; bar += 2)
  20896. {
  20897. clip (0, ClipKind::pattern, kick, bar, 2);
  20898. clip (2, ClipKind::pattern, beat, bar, 2);
  20899. }
  20900. clip (1, ClipKind::audio, loop, 0, 8);
  20901. clip (3, ClipKind::pattern, lead, 2, 4);
  20902. clip (4, ClipKind::audio, vox, 4, 4);
  20903. clip (6, ClipKind::pattern, kick, 4, 2); // (round 190ib: Track 7 only repeats Track 1's Kick)
  20904. song.playlistTracks.resize (8);
  20905. engine.setSong (std::move (song));
  20906. }
  20907. engine.dispatchPendingMessages();
  20908. ui.selectTabForSnapshot (2);
  20909. engine.dispatchPendingMessages();
  20910. auto& pl = ui.getPlaylistForSnapshot();
  20911. pl.setSize (juce::jmax (pl.getWidth(), 1000), juce::jmax (pl.getHeight(), 640));
  20912. pl.setViewForSnapshot (120.0, 1, 0);
  20913. const auto shotRows = [&] (const juce::String& name, int rows) {
  20914. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  20915. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 820), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  20916. };
  20917. const auto& song = [&]() -> const lynx::Song& { return engine.getSong(); };
  20918. const auto mode = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mode : lynx::PlaylistTrackMode::unassigned; };
  20919. const auto mixerOf = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mixerTrack : -1; };
  20920. // ---- 1. FL's default: tracks and inserts apart, FL's narrow headers
  20921. check ("off_by_default", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow(),
  20922. juce::String (pl.headerWidthForSnapshot()));
  20923. shotRows ("-off.png", 7);
  20924. // ---- 2. the switch (Playlist › Edit, Track mode, Settings › Project): it lists what it changes and asks (round
  20925. // 190ib: inserts move, channels are routed), then it is one undo step
  20926. lynx::autolink::Report plan;
  20927. bool asked = false;
  20928. lynx::PlaylistComponent::answerLinkConfirmation = [&] (const lynx::autolink::Report& r) {
  20929. plan = r;
  20930. asked = true;
  20931. return true;
  20932. };
  20933. {
  20934. const auto text = lynx::PlaylistComponent::describeLinkPlan (song(), lynx::autolink::planOn (song()));
  20935. juce::AlertWindow box (lynx::tr ("Link Playlist tracks to mixer tracks"), text, juce::MessageBoxIconType::QuestionIcon);
  20936. box.addButton (lynx::tr ("Link"), 1);
  20937. box.addButton (lynx::tr ("Cancel"), 0);
  20938. box.sendLookAndFeelChange();
  20939. savePng (lynx::shot::snapshot (box), prefix + "-confirm.png");
  20940. }
  20941. pl.runAction ("playlist.linkTracks");
  20942. engine.dispatchPendingMessages();
  20943. const auto moved = [&plan] (int from, int to) {
  20944. return std::any_of (plan.changes.begin(), plan.changes.end(), [=] (const lynx::autolink::Change& c) {
  20945. return c.kind == lynx::autolink::Change::Kind::moveInsert && c.from == from && c.to == to;
  20946. });
  20947. };
  20948. check ("asked_first_with_the_moves", asked && moved (9, 4) && moved (12, 5) && plan.repeats.size() == 1 && ! plan.changesSound(),
  20949. juce::String ((int) plan.changes.size()));
  20950. check ("switch_on", song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth,
  20951. juce::String (pl.headerWidthForSnapshot()));
  20952. check ("kick_instrument_track_insert_1", mode (0) == lynx::PlaylistTrackMode::instrument && mixerOf (0) == 1 && song().channels[0].mixerTrack == 1,
  20953. juce::String (mixerOf (0)));
  20954. check ("loop_audio_track_insert_2", mode (1) == lynx::PlaylistTrackMode::audio && mixerOf (1) == 2 && song().mixer[2].name == "Drum loop",
  20955. juce::String (mixerOf (1)));
  20956. // (round 190ib: Track N = insert N for every track with content of its own)
  20957. check ("beat_track_insert_3", mode (2) == lynx::PlaylistTrackMode::audio && mixerOf (2) == 3 && song().channels[1].mixerTrack == 3
  20958. && song().channels[2].mixerTrack == 3 && song().channels[3].mixerTrack == 3,
  20959. juce::String (mixerOf (2)));
  20960. check ("synth_bus_moves_to_insert_4", mode (3) == lynx::PlaylistTrackMode::instrument && song().channels[4].mixerTrack == 4
  20961. && song().mixer[4].name == "Synth bus" && song().playlistTracks[3].name == "Synth bus",
  20962. juce::String (song().channels[4].mixerTrack));
  20963. check ("vocal_chain_moves_to_insert_5", mode (4) == lynx::PlaylistTrackMode::audio && mixerOf (4) == 5 && song().mixer[5].effects.size() == 1
  20964. && song().mixer[5].name == "Vox chain",
  20965. juce::String (mixerOf (4)));
  20966. check ("empty_and_repeat_tracks_stay", mode (5) == lynx::PlaylistTrackMode::unassigned && mode (6) == lynx::PlaylistTrackMode::unassigned
  20967. && lynx::autolink::repeatedTracks (song())[6] == 0);
  20968. shotRows ("-on.png", 7);
  20969. // one undo step: Undo brings FL's tracks back, Redo the links
  20970. engine.undo();
  20971. engine.dispatchPendingMessages();
  20972. check ("undo_switch_on", ! song().linkTracksToMixer && mode (0) == lynx::PlaylistTrackMode::unassigned && mode (1) == lynx::PlaylistTrackMode::unassigned
  20973. && song().channels[0].mixerTrack == 0 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow());
  20974. engine.redo();
  20975. engine.dispatchPendingMessages();
  20976. check ("redo_switch_on", song().linkTracksToMixer && mixerOf (1) == 2 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth);
  20977. auto source = juce::Desktop::getInstance().getMainMouseSource();
  20978. const auto now = juce::Time::getCurrentTime();
  20979. const int ctrl = juce::ModifierKeys::commandModifier;
  20980. const auto event = [&] (juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  20981. return juce::MouseEvent (source, p.toFloat(), mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &pl, &pl, now, down.toFloat(), now, clicks, dragged);
  20982. };
  20983. const auto press = [&] (juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}) {
  20984. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  20985. pl.mouseMove (event (p, mods, p, 1, false));
  20986. pl.mouseDown (event (p, down, p, 1, false));
  20987. if (to)
  20988. pl.mouseDrag (event (*to, down, p, 1, true));
  20989. pl.mouseUp (event (to ? *to : p, mods, p, 1, to.has_value()));
  20990. engine.flushLevels();
  20991. engine.dispatchPendingMessages();
  20992. };
  20993. const auto doubleClick = [&] (juce::Point<int> p) {
  20994. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  20995. pl.mouseDown (event (p, down, p, 2, false));
  20996. pl.mouseDoubleClick (event (p, down, p, 2, false));
  20997. pl.mouseUp (event (p, {}, p, 2, false));
  20998. engine.flushLevels();
  20999. engine.dispatchPendingMessages();
  21000. };
  21001. // the controls are found where they are drawn: M right of the plate, S left of it, the volume bar and the pan knob
  21002. // under them (the same geometry the header paints with)
  21003. const auto row = [&] (int t) { return pl.trackRowForSnapshot (t); };
  21004. const int w = pl.headerWidthForSnapshot();
  21005. const auto mAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 13 - 9, r.getY() + 11); }; // (meter column 9 px)
  21006. const auto sAt = [&] (int t) { return mAt (t) - juce::Point<int> (20, 0); };
  21007. const auto volumeAt = [&] (int t, float fraction) {
  21008. const auto r = row (t);
  21009. const auto left = 8, width = w - 9 - 2 - 32;
  21010. return juce::Point<int> (left + juce::roundToInt (fraction * (float) width), r.getY() + 26);
  21011. };
  21012. const auto panAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 9 - 6 - 7, r.getY() + 26); };
  21013. const auto& insert2 = [&]() -> const lynx::MixerTrack& { return song().mixer[2]; };
  21014. // ---- 3. the linked headers' controls act on the track's mixer track
  21015. press (mAt (1), {});
  21016. check ("m_mutes_the_insert", insert2().muted, juce::String ((int) insert2().muted));
  21017. press (mAt (1), {});
  21018. check ("m_again_unmutes", ! insert2().muted);
  21019. press (sAt (1), {});
  21020. check ("s_solos_the_insert", insert2().solo);
  21021. press (sAt (1), {});
  21022. press (volumeAt (1, 0.25f), {});
  21023. check ("volume_click_sets_the_level", std::abs (insert2().volume - 0.25f) < 0.03f, juce::String (insert2().volume, 3));
  21024. press (volumeAt (1, 0.25f), {}, volumeAt (1, 0.5f));
  21025. check ("volume_drag", std::abs (insert2().volume - 0.5f) < 0.03f, juce::String (insert2().volume, 3));
  21026. doubleClick (volumeAt (1, 0.5f));
  21027. check ("volume_double_click_0_db", insert2().volume == lynx::unityFader, juce::String (insert2().volume, 3));
  21028. press (panAt (1), {}, panAt (1) - juce::Point<int> (0, 40));
  21029. check ("pan_drag_up", std::abs (insert2().pan - 0.5f) < 0.02f, juce::String (insert2().pan, 3));
  21030. shotRows ("-controls.png", 7);
  21031. doubleClick (panAt (1));
  21032. check ("pan_double_click_centre", insert2().pan == 0.0f, juce::String (insert2().pan, 3));
  21033. // an instrument track's header acts on its channel's insert (Synth: insert 4 since round 190ib)
  21034. press (volumeAt (3, 0.4f), {});
  21035. check ("instrument_track_volume_on_its_insert", std::abs (song().mixer[4].volume - 0.4f) < 0.03f, juce::String (song().mixer[4].volume, 3));
  21036. engine.editSong ([] (lynx::Song& s) { s.mixer[4].volume = lynx::unityFader; });
  21037. // FL's track mute and solo stay on the Playlist track: Ctrl+click on M solos it, a muted track lights M and the
  21038. // first click unmutes it
  21039. press (mAt (1), ctrl);
  21040. check ("ctrl_m_solos_the_playlist_track", song().isTrackMuted (0) && ! song().isTrackMuted (1) && ! insert2().solo);
  21041. press (mAt (1), ctrl);
  21042. engine.editSong ([] (lynx::Song& s) {
  21043. for (auto& t : s.playlistTracks)
  21044. t.muted = false;
  21045. s.playlistTracks[1].muted = true;
  21046. });
  21047. press (mAt (1), {});
  21048. check ("m_unmutes_a_muted_playlist_track_first", ! song().isTrackMuted (1) && ! insert2().muted);
  21049. // a track that only repeats another keeps FL's LED (Track 7, Track 1's Kick): a click mutes the Playlist track
  21050. press (juce::Point<int> (w - 9 - 11, row (6).getCentreY()), {});
  21051. check ("unlinked_led_is_fl", song().isTrackMuted (6));
  21052. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[6].muted = false; });
  21053. // round 190ib: a linked track and its insert keep one name, whichever is renamed
  21054. engine.editSong ([] (lynx::Song& s) { s.mixer[3].name = "Drums"; });
  21055. check ("insert_rename_renames_the_track", song().playlistTracks[2].name == "Drums");
  21056. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[2].name = "Beat"; });
  21057. check ("track_rename_renames_the_insert", song().mixer[3].name == "Beat");
  21058. // ---- 4. new content follows: a sample on empty Track 6 makes it an audio track (insert 6)
  21059. engine.editSong ([] (lynx::Song& s) {
  21060. lynx::ChannelDef c;
  21061. c.name = "Guitar";
  21062. c.instrument = lynx::InstrumentKind::audioClip;
  21063. c.samplePath = "/shots/Guitar.wav";
  21064. s.channels.push_back (c);
  21065. lynx::Clip clip;
  21066. clip.kind = lynx::ClipKind::audio;
  21067. clip.channel = (int) s.channels.size() - 1;
  21068. clip.track = 5;
  21069. clip.start = 4 * 4 * lynx::ppq;
  21070. clip.length = 4 * 4 * lynx::ppq;
  21071. s.playlist.push_back (clip);
  21072. });
  21073. check ("new_sample_links_its_track", mode (5) == lynx::PlaylistTrackMode::audio && mixerOf (5) == 6 && song().channels.back().mixerTrack == 6,
  21074. juce::String (mixerOf (5)));
  21075. engine.undo();
  21076. check ("undo_takes_the_clip_and_the_link", mode (5) == lynx::PlaylistTrackMode::unassigned && song().channels.back().name != "Guitar");
  21077. // ---- 5. row heights (round 190ft): short rows keep M / S; from 34 px the volume and pan; tall rows the input
  21078. const auto heights = [&] (std::vector<std::pair<int, int>> rows) {
  21079. engine.editSong ([rows] (lynx::Song& s) {
  21080. for (const auto& [t, h] : rows)
  21081. s.playlistTracks[(std::size_t) t].height = h;
  21082. });
  21083. engine.dispatchPendingMessages();
  21084. };
  21085. heights ({ { 0, 16 }, { 1, 24 }, { 4, 80 } });
  21086. shotRows ("-heights.png", 7);
  21087. {
  21088. const auto r = row (1);
  21089. const auto before = insert2().volume;
  21090. press (juce::Point<int> (20, r.getY() + 12), {}); // (no volume bar on a 24 px row: the press selects)
  21091. check ("short_row_has_no_volume_bar", insert2().volume == before && pl.selectedTracksForSnapshot() == std::vector<int> { 1 });
  21092. press (juce::Point<int> (w - 22, r.getY() + 12), {});
  21093. check ("short_row_m_still_works", insert2().muted);
  21094. press (juce::Point<int> (w - 22, r.getY() + 12), {});
  21095. }
  21096. heights ({ { 0, 0 }, { 1, 0 }, { 4, 0 } });
  21097. // ---- 6. saved: .lynx keeps the switch; the links themselves are FL track modes
  21098. {
  21099. juce::String error;
  21100. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song()), error);
  21101. check ("lynx_round_trip", back && back->linkTracksToMixer && back->playlistTracks.size() > 4 && back->playlistTracks[1].mixerTrack == 2
  21102. && back->playlistTracks[0].mode == lynx::PlaylistTrackMode::instrument, error);
  21103. auto plain = song();
  21104. plain.linkTracksToMixer = false;
  21105. const auto json = lynx::ProjectFile::toJson (plain);
  21106. check ("off_not_saved", ! json.contains ("linkTracksToMixer"));
  21107. }
  21108. // ---- 7. off: FL's headers again (the links stay)
  21109. lynx::PlaylistComponent::answerLinkConfirmation = nullptr;
  21110. pl.runAction ("playlist.linkTracks");
  21111. engine.dispatchPendingMessages();
  21112. check ("switch_off_fl_headers", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow()
  21113. && mode (1) == lynx::PlaylistTrackMode::audio);
  21114. shotRows ("-off-after.png", 7);
  21115. // ---- 8. Settings › Project's switches
  21116. {
  21117. auto panel = lynx::makeSettingsPanel (engine, lynx::SettingsPage::project);
  21118. panel->setSize (760, 720);
  21119. savePng (lynx::shot::snapshot (*panel), prefix + "-settings-project.png");
  21120. }
  21121. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  21122. return allOk;
  21123. }
  21124. bool runFlPlShot (const juce::String& prefix)
  21125. {
  21126. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21127. juce::StringArray report;
  21128. bool allOk = true;
  21129. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  21130. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  21131. allOk = allOk && ok;
  21132. };
  21133. const auto plain = [] (juce::String t) {
  21134. // (without the shortcut column and the mnemonic: the mark, or the " (K)" a translation without the letter gets)
  21135. t = t.upToFirstOccurrenceOf ("\t", false, false);
  21136. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  21137. t = t.substring (0, at);
  21138. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  21139. };
  21140. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  21141. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21142. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  21143. return it.getItem().subMenu.get();
  21144. return nullptr;
  21145. };
  21146. const auto texts = [&plain] (const juce::PopupMenu& menu, int count) {
  21147. juce::StringArray out;
  21148. for (juce::PopupMenu::MenuItemIterator it (menu); it.next() && out.size() < count;)
  21149. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  21150. return out;
  21151. };
  21152. const auto modelTexts = [] (const std::vector<lynx::fltrackmenus::Entry>& model) {
  21153. juce::StringArray out;
  21154. for (const auto& e : model)
  21155. if (e.kind != lynx::fltrackmenus::Entry::Kind::list)
  21156. out.add (e.kind == lynx::fltrackmenus::Entry::Kind::separator ? juce::String ("-")
  21157. : e.kind == lynx::fltrackmenus::Entry::Kind::caption ? "[" + lynx::tr (e.text) + "]"
  21158. : lynx::tr (e.text));
  21159. return out;
  21160. };
  21161. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  21162. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21163. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  21164. {
  21165. it.getItem().action();
  21166. return true;
  21167. }
  21168. return false;
  21169. };
  21170. lynx::AudioEngine engine (false);
  21171. lynx::MainComponent ui (engine, false);
  21172. ui.setSize (1600, 900);
  21173. int vox = -1;
  21174. {
  21175. auto song = lynx::Song::makeDefault();
  21176. song.channels.push_back ({});
  21177. song.channels.back().name = "Vox";
  21178. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  21179. song.channels.back().volume = 0.6f;
  21180. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  21181. vox = (int) song.channels.size() - 1;
  21182. lynx::Clip c;
  21183. c.kind = lynx::ClipKind::audio;
  21184. c.channel = vox;
  21185. c.track = 3;
  21186. c.start = 4 * lynx::ppq;
  21187. c.length = 2 * lynx::ppq;
  21188. song.playlist.push_back (c);
  21189. engine.setSong (std::move (song));
  21190. }
  21191. engine.dispatchPendingMessages();
  21192. auto& playlist = ui.getPlaylistForSnapshot();
  21193. // ---- 1. the audio clip menu: Preview first, Automate › Panning / Volume
  21194. {
  21195. const auto menu = playlist.getClipMenuForSnapshot (0);
  21196. juce::PopupMenu::MenuItemIterator it (menu);
  21197. it.next(); // (the "Audio clip" title band)
  21198. it.next();
  21199. check ("clip_menu_preview_first", plain (it.getItem().text) == lynx::tr ("Preview"), it.getItem().text);
  21200. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  21201. check ("clip_menu_automate", automate != nullptr && texts (*automate, 9) == modelTexts (lynx::fltrackmenus::automate()),
  21202. automate != nullptr ? texts (*automate, 9).joinIntoString ("|") : juce::String ("missing"));
  21203. saveMenus (juce::StringArray { "Audio clip menu", "Automate" }, std::vector<juce::PopupMenu> { menu, automate != nullptr ? *automate : juce::PopupMenu() },
  21204. prefix + "-clip-menu.png");
  21205. const auto before = engine.getSong().automations.size();
  21206. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  21207. const auto& song = engine.getSong();
  21208. // (round 190dz: the Levels adjustment's volume multiplier, neutral = 0.5 of its 0…200 % travel)
  21209. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  21210. && song.automations.back().target.param == lynx::leveladjust::volume
  21211. && song.automations.back().target.index == vox && song.automations.back().points.size() == 2
  21212. && song.automations.back().points[1].tick == 2 * lynx::ppq && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  21213. const auto* clip = ok ? &song.playlist.back() : nullptr;
  21214. check ("automate_volume_clip", ok && clip->kind == lynx::ClipKind::automation && clip->track == 3 && clip->start == 4 * lynx::ppq
  21215. && clip->length == 2 * lynx::ppq,
  21216. ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  21217. engine.undo();
  21218. check ("automate_undo", engine.getSong().automations.size() == before);
  21219. // Preview: the clip's own audio (FL plays it through its channel); LYNX renders it for the preview output
  21220. const auto rendered = engine.renderClipAudio (0);
  21221. check ("preview_renders_the_clip", ! rendered.left.empty(), juce::String ((int) rendered.left.size()) + " frames");
  21222. }
  21223. // ---- 2. the Playlist's "+": its menu, a right click's audio track, the corner
  21224. {
  21225. const auto menu = playlist.getAddTrackMenuForSnapshot();
  21226. check ("add_menu_head", texts (menu, 5) == modelTexts (lynx::fltrackmenus::addTrack()), texts (menu, 5).joinIntoString ("|"));
  21227. saveMenus (juce::StringArray { "Playlist +" }, std::vector<juce::PopupMenu> { menu }, prefix + "-add-track-menu.png");
  21228. ui.selectTabForSnapshot (2);
  21229. engine.dispatchPendingMessages();
  21230. auto* button = playlist.getAddTrackButtonForSnapshot();
  21231. check ("add_button_in_corner", button != nullptr && button->isVisible() && button->getX() == 7 && button->getWidth() == 21 && button->getHeight() == 18
  21232. && button->getBottom() <= lynx::PlaylistComponent::headerHeight);
  21233. savePng (playlist.createComponentSnapshot (juce::Rectangle<int> (0, 0, juce::jmin (560, playlist.getWidth()), juce::jmin (260, playlist.getHeight()))),
  21234. prefix + "-playlist-corner.png");
  21235. const auto track = playlist.addAudioTrackNow();
  21236. const auto& song = engine.getSong();
  21237. check ("add_audio_track", track == 0 && song.playlistTracks.size() > 0 && song.playlistTracks[0].mode == lynx::PlaylistTrackMode::audio
  21238. && song.playlistTracks[0].mixerTrack > 0,
  21239. juce::String (track));
  21240. engine.undo();
  21241. }
  21242. // ---- 3. Track mode › Instrument track ›
  21243. {
  21244. const auto menu = playlist.getTrackMenuForSnapshot (5);
  21245. const auto* modes = findSub (menu, lynx::tr ("Track mode"));
  21246. const auto* instrument = modes != nullptr ? findSub (*modes, lynx::tr ("Instrument track")) : nullptr;
  21247. check ("instrument_track_head", instrument != nullptr && texts (*instrument, 4) == modelTexts (lynx::fltrackmenus::instrumentTrack()),
  21248. instrument != nullptr ? texts (*instrument, 4).joinIntoString ("|") : juce::String ("missing"));
  21249. const auto* existing = instrument != nullptr ? findSub (*instrument, lynx::tr ("Use existing channel")) : nullptr;
  21250. check ("use_existing_lists_generators", existing != nullptr && existing->getNumItems() == 5, existing != nullptr ? juce::String (existing->getNumItems()) : juce::String());
  21251. std::vector<juce::PopupMenu> menus { modes != nullptr ? *modes : juce::PopupMenu(), instrument != nullptr ? *instrument : juce::PopupMenu(),
  21252. existing != nullptr ? *existing : juce::PopupMenu() };
  21253. saveMenus (juce::StringArray { "Track mode", "Instrument track", "Use existing channel" }, menus, prefix + "-instrument-track-menu.png");
  21254. lynx::ChannelDef synth;
  21255. synth.name = "Lead";
  21256. synth.instrument = lynx::InstrumentKind::synth;
  21257. const auto channels = engine.getSong().channels.size();
  21258. int made = -1;
  21259. engine.editSong ([&] (lynx::Song& s) { made = lynx::trackmodes::addInstrumentTrack (s, synth, 5); });
  21260. check ("instrument_track_new_channel", made == (int) channels && engine.getSong().playlistTracks.size() > 5
  21261. && engine.getSong().playlistTracks[5].channel == made);
  21262. engine.undo();
  21263. }
  21264. // ---- 4. the Channel rack menu: Assign to new instrument track / Unassign
  21265. {
  21266. auto& rack = ui.getRackForSnapshot();
  21267. const auto menu = rack.getChannelMenuForSnapshot (1);
  21268. saveMenus (juce::StringArray { "Channel menu" }, std::vector<juce::PopupMenu> { menu }, prefix + "-channel-menu.png");
  21269. check ("assign_runs", click (menu, lynx::tr ("Assign to new instrument track")));
  21270. const auto tracks = lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1);
  21271. check ("assign_first_free_track", tracks == std::vector<int> { 0 }, juce::String (tracks.empty() ? -1 : tracks.front()));
  21272. const auto again = rack.getChannelMenuForSnapshot (1);
  21273. check ("unassign_offered", click (again, lynx::tr ("Unassign from instrument track")) && lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1).empty());
  21274. bool greyed = false;
  21275. const auto voxMenu = rack.getChannelMenuForSnapshot (vox);
  21276. for (juce::PopupMenu::MenuItemIterator it (voxMenu); it.next();)
  21277. if (plain (it.getItem().text) == plain (lynx::tr ("Assign to new instrument track")))
  21278. greyed = ! it.getItem().isEnabled;
  21279. check ("assign_greyed_for_audio_clip_channel", greyed);
  21280. }
  21281. // ---- 5. Tools › One-click audio recording
  21282. std::fprintf (stderr, "flplshot: tools\n");
  21283. {
  21284. const auto names = ui.getMenuNamesForSnapshot();
  21285. const auto tools = ui.getMenuForSnapshot (names.indexOf (lynx::tr ("Tools")));
  21286. const auto* oneClick = findSub (tools, lynx::tr ("One-click audio recording"));
  21287. check ("one_click_submenu", oneClick != nullptr && texts (*oneClick, 3) == modelTexts (lynx::fltrackmenus::oneClickRecording()),
  21288. oneClick != nullptr ? texts (*oneClick, 3).joinIntoString ("|") : juce::String ("missing"));
  21289. saveMenus (juce::StringArray { "Tools", "One-click audio recording" }, std::vector<juce::PopupMenu> { tools, oneClick != nullptr ? *oneClick : juce::PopupMenu() },
  21290. prefix + "-tools-one-click.png");
  21291. const auto plan = lynx::oneclick::plan (engine.getSong(), {}, 2, lynx::oneclick::Into::playlist);
  21292. check ("one_click_plan", plan.insert == 2 && plan.armInsert && plan.askInput && plan.songMode);
  21293. }
  21294. // ---- 6. Mixer › Disk recording › Latency compensation
  21295. {
  21296. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  21297. const auto menu = strips.buildMenu (1);
  21298. const auto* disk = findSub (menu, lynx::tr ("Disk recording"));
  21299. int after = -1, at = -1, i = 0;
  21300. bool ticked = false;
  21301. if (disk != nullptr)
  21302. for (juce::PopupMenu::MenuItemIterator it (*disk); it.next(); ++i)
  21303. {
  21304. if (plain (it.getItem().text) == plain (lynx::tr ("Auto-create audio clip (the rendered files go on the Playlist)")))
  21305. after = i;
  21306. if (plain (it.getItem().text) == plain (lynx::tr ("Latency compensation")))
  21307. {
  21308. at = i;
  21309. ticked = it.getItem().isTicked;
  21310. }
  21311. }
  21312. check ("latency_comp_item", disk != nullptr && after >= 0 && at == after + 1 && ticked && engine.getRecordOptions().latencyCompensation,
  21313. juce::String (after) + " " + juce::String (at));
  21314. saveMenus (juce::StringArray { "Disk recording" }, std::vector<juce::PopupMenu> { disk != nullptr ? *disk : juce::PopupMenu() },
  21315. prefix + "-disk-recording.png");
  21316. check ("latency_comp_toggles", disk != nullptr && click (*disk, lynx::tr ("Latency compensation")) && ! engine.getRecordOptions().latencyCompensation);
  21317. }
  21318. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  21319. return allOk;
  21320. }
  21321. // --flclipshot (round 190dz): see the dispatch above
  21322. // a menu as JUCE lays it out with explicit column breaks (PopupMenu::addColumnBreak): the columns side by side on
  21323. // one menu background; custom items (the title band) are painted by their own component
  21324. static juce::Image columnMenuImage (const juce::PopupMenu& menu)
  21325. {
  21326. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  21327. const auto border = lf.getPopupMenuBorderSize();
  21328. struct Row
  21329. {
  21330. const juce::PopupMenu::Item* item;
  21331. int height;
  21332. };
  21333. std::vector<std::vector<Row>> columns (1);
  21334. std::vector<int> widths (1, 160);
  21335. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21336. {
  21337. const auto& item = it.getItem();
  21338. int w = 0, h = 0;
  21339. if (item.customComponent != nullptr)
  21340. item.customComponent->getIdealSize (w, h);
  21341. else
  21342. {
  21343. lf.getIdealPopupMenuItemSize (item.text.upToFirstOccurrenceOf ("\t", false, false), item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  21344. if (item.isSectionHeader)
  21345. h += h / 2; // as JUCE does
  21346. if (item.text.containsChar ('\t'))
  21347. w += 90;
  21348. }
  21349. columns.back().push_back ({ &item, h });
  21350. widths.back() = juce::jmax (widths.back(), w + 10);
  21351. if (item.shouldBreakAfter)
  21352. {
  21353. columns.emplace_back();
  21354. widths.push_back (160);
  21355. }
  21356. }
  21357. int width = 0, height = 0;
  21358. for (std::size_t c = 0; c < columns.size(); ++c)
  21359. {
  21360. width += widths[c];
  21361. int h = 2 * border;
  21362. for (const auto& row : columns[c])
  21363. h += row.height;
  21364. height = juce::jmax (height, h);
  21365. }
  21366. auto image = lynx::shot::canvas (width, height);
  21367. juce::Graphics g (image);
  21368. lynx::shot::logical (g);
  21369. lf.drawPopupMenuBackground (g, width, height);
  21370. int x = 0;
  21371. for (std::size_t c = 0; c < columns.size(); ++c)
  21372. {
  21373. int y = border;
  21374. for (const auto& row : columns[c])
  21375. {
  21376. const auto& item = *row.item;
  21377. const juce::Rectangle<int> r (x, y, widths[c], row.height);
  21378. if (item.customComponent != nullptr)
  21379. {
  21380. juce::Graphics::ScopedSaveState state (g);
  21381. g.setOrigin (r.getPosition());
  21382. item.customComponent->setSize (r.getWidth(), r.getHeight());
  21383. item.customComponent->paintEntireComponent (g, false);
  21384. }
  21385. else if (item.isSectionHeader)
  21386. lf.drawPopupMenuSectionHeader (g, r, item.text);
  21387. else
  21388. {
  21389. juce::Graphics::ScopedSaveState state (g);
  21390. g.setOrigin (r.getPosition());
  21391. lf.drawPopupMenuItem (g, r.withPosition (0, 0), item.isSeparator, item.isEnabled, false, item.isTicked, item.subMenu != nullptr,
  21392. item.text.upToFirstOccurrenceOf ("\t", false, false), item.text.fromFirstOccurrenceOf ("\t", false, false),
  21393. item.image.get(), nullptr);
  21394. }
  21395. y += row.height;
  21396. }
  21397. x += widths[c];
  21398. if (c + 1 < columns.size()) // (JUCE's column separator)
  21399. {
  21400. g.setColour (lf.findColour (juce::PopupMenu::textColourId).withAlpha (0.15f));
  21401. g.fillRect (x - 1, border, 1, height - 2 * border);
  21402. }
  21403. }
  21404. return image;
  21405. }
  21406. // --genpresetshot (round 190fs): see the dispatch above
  21407. bool runGenPresetShot (const juce::String& prefix)
  21408. {
  21409. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21410. juce::StringArray report;
  21411. bool allOk = true;
  21412. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  21413. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  21414. allOk = allOk && ok;
  21415. };
  21416. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  21417. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  21418. };
  21419. const auto plain = [] (juce::String t) { return t.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&"); };
  21420. const auto texts = [&plain] (const juce::PopupMenu& menu) {
  21421. juce::StringArray out;
  21422. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21423. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  21424. return out;
  21425. };
  21426. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  21427. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21428. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  21429. {
  21430. it.getItem().action();
  21431. return true;
  21432. }
  21433. return false;
  21434. };
  21435. const auto sameSound = [] (const lynx::ChannelDef& a, const lynx::ChannelDef& b) { return lynx::genpresets::sameSound (a, b); };
  21436. lynx::AudioEngine engine (false);
  21437. const auto& fl = lynx::flStudioAccess();
  21438. auto dx = lynx::natives::makeChannel (lynx::InstrumentKind::dx10, fl);
  21439. auto osc = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, fl);
  21440. check ("channels_made", dx.has_value() && osc.has_value());
  21441. if (! dx || ! osc)
  21442. {
  21443. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  21444. return false;
  21445. }
  21446. engine.editSong ([&] (lynx::Song& s) {
  21447. s.channels.clear();
  21448. s.channels.push_back (*dx);
  21449. s.channels.back().mixerTrack = 1;
  21450. s.channels.push_back (*osc);
  21451. s.channels.back().mixerTrack = 2;
  21452. lynx::ChannelDef synth;
  21453. synth.instrument = lynx::InstrumentKind::synth;
  21454. synth.name = "Synth";
  21455. synth.mixerTrack = 3;
  21456. s.channels.push_back (synth);
  21457. });
  21458. const auto channel = [&engine] (int i) { return engine.getSong().channels[(std::size_t) i]; };
  21459. // ---- 1. Fruity DX10: the preset box before and after "Save preset..."
  21460. {
  21461. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  21462. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  21463. auto menu = lynx::channelPresetMenu (*frame);
  21464. check ("dx10_menu", menu.has_value());
  21465. const auto before = menu ? texts (*menu) : juce::StringArray();
  21466. check ("dx10_menu_has_save", before.contains (lynx::tr ("Save preset...")) && before.contains (lynx::tr ("Show the presets folder"))
  21467. && ! before.contains ("[" + lynx::tr ("Your presets") + "]"), before.joinIntoString ("|"));
  21468. if (menu)
  21469. saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu-before.png");
  21470. // a sound of its own: the bank's 4th preset, then a knob moved (a sound no factory preset has)
  21471. const auto mine = [&] {
  21472. auto c = channel (0);
  21473. if (auto b = lynx::banks::withPreset (c, 3))
  21474. c = *b;
  21475. if (! c.pluginState.empty())
  21476. c.pluginState[c.pluginState.size() / 2] ^= 0x5a;
  21477. return c;
  21478. }();
  21479. engine.editSong ([&] (lynx::Song& s) { s.channels[0] = mine; });
  21480. check ("dx10_saved", lynx::channelPresetSave (*frame, "My FM Bell"));
  21481. const auto file = lynx::genpresetui::folderFor (lynx::InstrumentKind::dx10).getChildFile ("My FM Bell.lynxpreset");
  21482. check ("dx10_file", file.existsAsFile() && lynx::genpresetui::isPresetFile (file), file.getFullPathName());
  21483. check ("dx10_box_shows_it", lynx::channelPresetName (*frame) == "My FM Bell", lynx::channelPresetName (*frame));
  21484. menu = lynx::channelPresetMenu (*frame);
  21485. const auto after = menu ? texts (*menu) : juce::StringArray();
  21486. check ("dx10_menu_your_presets", after.contains ("[" + lynx::tr ("Your presets") + "]") && after.contains ("My FM Bell")
  21487. && after.contains (lynx::tr ("Delete preset \"{0}\"", { "My FM Bell" })), after.joinIntoString ("|"));
  21488. if (menu)
  21489. saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu.png");
  21490. shoot (*frame, "dx10-window");
  21491. // another sound, then the user's preset from the menu: the saved sound back, one undo step, project changed
  21492. if (auto other = lynx::banks::withPreset (channel (0), 0))
  21493. engine.editSong ([&] (lynx::Song& s) { s.channels[0] = *other; });
  21494. check ("dx10_other_sound", ! sameSound (channel (0), mine));
  21495. engine.markSaved();
  21496. menu = lynx::channelPresetMenu (*frame);
  21497. check ("dx10_load_click", menu.has_value() && click (*menu, "My FM Bell"));
  21498. check ("dx10_loaded_identical", sameSound (channel (0), mine) && channel (0).pluginState == mine.pluginState);
  21499. check ("dx10_loaded_name_and_insert", channel (0).name == "My FM Bell" && channel (0).mixerTrack == 1,
  21500. juce::String::fromUTF8 (channel (0).name.c_str()));
  21501. check ("dx10_project_changed", engine.isModified());
  21502. engine.undo();
  21503. check ("dx10_one_undo_step", ! sameSound (channel (0), mine));
  21504. engine.redo();
  21505. check ("dx10_redo", sameSound (channel (0), mine));
  21506. // the Browser: a new channel with the preset's generator, sound and name
  21507. juce::String error;
  21508. const auto count = engine.getSong().channels.size();
  21509. check ("browser_new_channel", lynx::genpresetui::addChannel (engine, file, error) && engine.getSong().channels.size() == count + 1, error);
  21510. const auto added = engine.getSong().channels.back();
  21511. check ("browser_channel_sound", added.instrument == lynx::InstrumentKind::dx10 && sameSound (added, mine) && added.name == "My FM Bell");
  21512. engine.undo();
  21513. check ("browser_channel_undo", engine.getSong().channels.size() == count);
  21514. }
  21515. // ---- 2. 3x Osc: save, the menu, delete
  21516. {
  21517. auto frame = lynx::makeChannelFrame (engine, 1, 0);
  21518. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  21519. check ("3xosc_saved", lynx::channelPresetSave (*frame, "Wide Saw Lead") && lynx::channelPresetSave (*frame, "Sub Bass"));
  21520. auto menu = lynx::channelPresetMenu (*frame);
  21521. const auto items = menu ? texts (*menu) : juce::StringArray();
  21522. check ("3xosc_menu", items.contains ("Wide Saw Lead") && items.contains ("Sub Bass") && items.contains (lynx::tr ("Save preset...")),
  21523. items.joinIntoString ("|"));
  21524. if (menu)
  21525. saveMenus (juce::StringArray { "3x Osc presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-3xosc-menu.png");
  21526. shoot (*frame, "3xosc-window");
  21527. check ("3xosc_delete", menu.has_value() && click (*menu, lynx::tr ("Delete preset \"{0}\"", { "Sub Bass" })));
  21528. check ("3xosc_deleted", lynx::genpresetui::userPresets (lynx::InstrumentKind::threeosc).size() == 1
  21529. && ! lynx::genpresetui::folderFor (lynx::InstrumentKind::threeosc).getChildFile ("Sub Bass.lynxpreset").exists());
  21530. menu = lynx::channelPresetMenu (*frame);
  21531. const auto left = menu ? texts (*menu) : juce::StringArray();
  21532. check ("3xosc_menu_after_delete", left.contains ("Wide Saw Lead") && ! left.contains ("Sub Bass"), left.joinIntoString ("|"));
  21533. }
  21534. // ---- 3. LYNX's synth: its "Presets..." box
  21535. {
  21536. engine.editSong ([] (lynx::Song& s) { s.channels[2].synth.cutoff = 777.0f; });
  21537. auto frame = lynx::makeChannelFrame (engine, 2, 0);
  21538. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  21539. check ("synth_saved", lynx::channelPresetSave (*frame, "Dark Pad"));
  21540. const auto menu = lynx::channelPresetMenu (*frame);
  21541. const auto items = menu ? texts (*menu) : juce::StringArray();
  21542. check ("synth_menu", items.contains ("Dark Pad") && items.contains (lynx::tr ("Save preset...")) && items.contains (lynx::tr ("Show the presets folder")),
  21543. items.joinIntoString ("|"));
  21544. if (menu)
  21545. saveMenus (juce::StringArray { "Synth presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-synth-menu.png");
  21546. const auto saved = lynx::genpresetui::read (lynx::genpresetui::folderFor (lynx::InstrumentKind::synth).getChildFile ("Dark Pad.lynxpreset"));
  21547. check ("synth_file", saved.has_value() && saved->sound.synth.cutoff == 777.0f);
  21548. }
  21549. // ---- 4. the name box (the hosted plugins' and the effects' "Save preset" box)
  21550. {
  21551. auto box = lynx::genpresetui::makeNameBox ("My FM Bell");
  21552. box->setSize (juce::jmax (360, box->getWidth()), juce::jmax (150, box->getHeight()));
  21553. shoot (*box, "save-name-box");
  21554. check ("name_box", box->getTextEditorContents ("name") == "My FM Bell");
  21555. }
  21556. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  21557. return allOk;
  21558. }
  21559. // --flfixshot (round 190ey): see the dispatch above
  21560. bool runFlFixShot (const juce::String& prefix)
  21561. {
  21562. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21563. juce::StringArray report;
  21564. bool allOk = true;
  21565. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  21566. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  21567. allOk = allOk && ok;
  21568. };
  21569. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  21570. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  21571. };
  21572. const auto plain = [] (juce::String t) {
  21573. t = t.upToFirstOccurrenceOf ("\t", false, false);
  21574. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  21575. t = t.substring (0, at);
  21576. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  21577. };
  21578. const auto texts = [&plain] (const juce::PopupMenu& menu) {
  21579. juce::StringArray out;
  21580. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21581. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  21582. return out;
  21583. };
  21584. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  21585. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21586. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  21587. return it.getItem().subMenu.get();
  21588. return nullptr;
  21589. };
  21590. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  21591. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21592. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  21593. {
  21594. it.getItem().action();
  21595. return true;
  21596. }
  21597. return false;
  21598. };
  21599. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flfix-samples");
  21600. folder.createDirectory();
  21601. const auto writeWav = [] (const juce::File& file, double rate, int frames, double hz) {
  21602. juce::AudioBuffer<float> buffer (1, frames);
  21603. for (int i = 0; i < frames; ++i)
  21604. buffer.setSample (0, i, (float) (0.8 * std::sin (juce::MathConstants<double>::twoPi * hz * i / rate) * std::exp (-i / (rate * 0.12))));
  21605. file.deleteFile();
  21606. juce::WavAudioFormat wav;
  21607. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), rate, 1, 16, {}, 0)))
  21608. out->writeFromAudioSampleBuffer (buffer, 0, frames);
  21609. return file;
  21610. };
  21611. // ---- 1. the Sampler page (SMP-1 / 4 / 5 / 7, CTL-4)
  21612. {
  21613. lynx::AudioEngine engine (false);
  21614. const auto clap = writeWav (folder.getChildFile ("Basic 808 Clap.wav"), 44100.0, 11600, 180.0);
  21615. const auto loop48 = writeWav (folder.getChildFile ("Loop 48k.wav"), 48000.0, 48000, 220.0);
  21616. engine.editSong ([&] (lynx::Song& s) {
  21617. if (s.channels.empty())
  21618. s.channels.resize (1);
  21619. lynx::audioclips::loadSampleInto (s.channels[0], clap.getFullPathName().toStdString(), "808 Clap");
  21620. });
  21621. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  21622. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  21623. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  21624. frame->createComponentSnapshot (frame->getLocalBounds());
  21625. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  21626. auto& f = *frame;
  21627. lynx::samplerPageTurn (f, "show", 0.0);
  21628. const auto rate = engine.getTransport().sampleRate.load();
  21629. check ("resample_greyed_at_project_rate", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 44100.0) < 0.5 ? "0" : "1"), juce::String (rate));
  21630. check ("load_regions_greyed_without_regions", lynx::samplerPageQuery (f, "loadRegions") == "0");
  21631. check ("load_markers_greyed_without_markers", lynx::samplerPageQuery (f, "loadMarkers") == "0");
  21632. check ("bit_depth_16", lynx::samplerPageQuery (f, "corner") == "16", lynx::samplerPageQuery (f, "corner"));
  21633. check ("wave_hint_summary", lynx::samplerPageQuery (f, "waveHint").startsWith ("44100Hz, 16Bit int mono, 0:263"), lynx::samplerPageQuery (f, "waveHint"));
  21634. shoot (f, "sampler-44k");
  21635. // SMP-5: MUL's text
  21636. lynx::samplerPageTurn (f, "mul", 800.0);
  21637. check ("mul_text", lynx::samplerPageQuery (f, "mulText") == "105.70%", lynx::samplerPageQuery (f, "mulText"));
  21638. lynx::samplerPageTurn (f, "mul", 0.0);
  21639. // SMP-4: CROSSFADE on a loopless sample: Use loop points on, the loop = the whole sample, the box reads 32
  21640. engine.editSong ([] (lynx::Song& s) { s.channels[0].sampler.useLoopPoints = false; });
  21641. lynx::samplerPageTurn (f, "crossfade", 120.0);
  21642. check ("crossfade_loops_whole_sample", sampler().useLoopPoints && sampler().loopStart == 0 && sampler().loopEnd == 11599,
  21643. juce::String (sampler().loopStart) + ".." + juce::String (sampler().loopEnd));
  21644. check ("bit_depth_32_precomputed", lynx::samplerPageQuery (f, "corner") == "32", lynx::samplerPageQuery (f, "corner"));
  21645. frame->createComponentSnapshot (frame->getLocalBounds());
  21646. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  21647. shoot (f, "sampler-crossfade-red-loop");
  21648. lynx::samplerPageTurn (f, "crossfade", 0.0);
  21649. // SMP-3: a loop set with END alone, drawn red (FL: 0..276)
  21650. engine.editSong ([] (lynx::Song& s) {
  21651. s.channels[0].sampler.loopStart = 0;
  21652. s.channels[0].sampler.loopEnd = 2400;
  21653. });
  21654. lynx::samplerPageTurn (f, "show", 0.0);
  21655. shoot (f, "sampler-end-loop-red");
  21656. // round 190gw (live check 190gu B3): the waveform menu's Spectrum view / Multichannel waveform view, on a stereo
  21657. // clap-like noise burst (left and right differ) with no loop, as FL's shot
  21658. {
  21659. const auto noisy = folder.getChildFile ("Noise Clap.wav");
  21660. juce::AudioBuffer<float> b (2, 44100);
  21661. juce::Random random (190);
  21662. for (int i = 0; i < b.getNumSamples(); ++i)
  21663. for (int c = 0; c < 2; ++c)
  21664. b.setSample (c, i, (float) ((random.nextFloat() * 2.0f - 1.0f) * 0.9 * std::exp (-i / (44100.0 * (c == 0 ? 0.10 : 0.18)))
  21665. * (i > 1500 * c ? 1.0 : 0.15)));
  21666. noisy.deleteFile();
  21667. juce::WavAudioFormat wav;
  21668. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (noisy.createOutputStream().release(), 44100.0, 2, 16, {}, 0)))
  21669. out->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  21670. const auto before = engine.getSong().channels[0];
  21671. engine.editSong ([&] (lynx::Song& s) {
  21672. s.channels[0].samplePath = noisy.getFullPathName().toStdString();
  21673. s.channels[0].sampler.loopStart = s.channels[0].sampler.loopEnd = -1;
  21674. s.channels[0].sampler.useLoopPoints = false;
  21675. });
  21676. lynx::samplerPageTurn (f, "show", 0.0);
  21677. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
  21678. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  21679. lynx::samplerpage::waveViews().spectrum = true;
  21680. lynx::samplerPageTurn (f, "show", 0.0);
  21681. shoot (f, "sampler-spectrum-view");
  21682. lynx::samplerpage::waveViews() = { false, true };
  21683. lynx::samplerPageTurn (f, "show", 0.0);
  21684. shoot (f, "sampler-multichannel-view");
  21685. lynx::samplerpage::waveViews() = {};
  21686. engine.editSong ([&before] (lynx::Song& s) { s.channels[0] = before; });
  21687. lynx::samplerPageTurn (f, "show", 0.0);
  21688. frame->createComponentSnapshot (frame->getLocalBounds());
  21689. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  21690. }
  21691. // SMP-7: the waveform menu
  21692. const auto waveMenu = lynx::samplerWaveMenu (f);
  21693. juce::StringArray expected { lynx::tr ("Reload"), lynx::tr ("Save as..."), lynx::tr ("Locate file"), lynx::tr ("Copy audio to clipboard"),
  21694. lynx::tr ("Paste audio from clipboard"), "-", lynx::tr ("Edit in audio editor"),
  21695. lynx::tr ("Edit in pitch corrector"), lynx::tr ("Edit in time warper"), "-", // (round 190gw)
  21696. lynx::tr ("Open in new sampler channel"), lynx::tr ("Open in new Fruity Granulizer channel"),
  21697. lynx::tr ("Open in new Fruity Slicer channel"), lynx::tr ("Open in new Slicex channel"), "-", // (round 190gk)
  21698. lynx::tr ("Detect tempo") };
  21699. if (lynx::fileProperties) // (round 190gk: Windows only)
  21700. expected.add (lynx::tr ("Get properties"));
  21701. expected.addArray (juce::StringArray { "-", lynx::tr ("Spectrum view"), lynx::tr ("Multichannel waveform view") }); // (round 190gw)
  21702. check ("wave_menu_items", waveMenu.has_value() && texts (*waveMenu) == expected, waveMenu.has_value() ? texts (*waveMenu).joinIntoString ("|") : juce::String ("none"));
  21703. if (waveMenu.has_value())
  21704. saveMenus (juce::StringArray { "Sampler waveform" }, std::vector<juce::PopupMenu> { *waveMenu }, prefix + "-wave-menu.png");
  21705. check ("copy_audio_to_clipboard", waveMenu.has_value() && click (*waveMenu, lynx::tr ("Copy audio to clipboard"))
  21706. && lynx::audioclipboard::editor().frames() == 11600);
  21707. // SMP-1: a 48 kHz sample in this project: Resample enabled
  21708. lynx::samplerPageTurn (f, "show", 0.0);
  21709. engine.editSong ([&] (lynx::Song& s) { s.channels[0].samplePath = loop48.getFullPathName().toStdString(); });
  21710. lynx::samplerPageTurn (f, "show", 0.0);
  21711. check ("resample_enabled_48k", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 48000.0) < 0.5 ? "0" : "1"), juce::String (rate));
  21712. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
  21713. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  21714. shoot (f, "sampler-48k");
  21715. // CTL-4: Remove sample renames the channel "Sampler"
  21716. lynx::samplerFileRowPress (f, 3);
  21717. check ("remove_sample_renames", engine.getSong().channels[0].name == "Sampler" && engine.getSong().channels[0].samplePath.empty(),
  21718. juce::String::fromUTF8 (engine.getSong().channels[0].name.c_str()));
  21719. lynx::samplerPageTurn (f, "show", 0.0);
  21720. check ("no_sample_content_greyed", lynx::samplerPageQuery (f, "keepOnDisk") == "0" && lynx::samplerPageQuery (f, "resample") == "0");
  21721. shoot (f, "sampler-removed");
  21722. }
  21723. // ---- 2. the Multilink button's menu with multilink off (CTL-1)
  21724. lynx::AudioEngine engine (false);
  21725. lynx::MainComponent ui (engine, false);
  21726. ui.setSize (1600, 900);
  21727. {
  21728. using lynx::AutomationTarget;
  21729. using lynx::AutomationTargetKind;
  21730. engine.editSong ([] (lynx::Song& s) {
  21731. if (s.channels.empty())
  21732. s.channels.resize (1);
  21733. s.channels[0].name = "808 Kick";
  21734. });
  21735. engine.setMultilink (false);
  21736. engine.noteTweaked ({ AutomationTargetKind::channelVolume, 0 });
  21737. engine.noteTweaked ({ AutomationTargetKind::channelPan, 0 });
  21738. const auto menu = ui.getMultilinkMenuForSnapshot();
  21739. juce::PopupMenu::MenuItemIterator first (menu);
  21740. first.next();
  21741. const auto caption = first.getItem().text;
  21742. bool columnBreak = false, lynxLines = false;
  21743. juce::String rightCaption;
  21744. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21745. {
  21746. if (columnBreak && rightCaption.isEmpty() && it.getItem().isSectionHeader)
  21747. rightCaption = it.getItem().text;
  21748. columnBreak = columnBreak || it.getItem().shouldBreakAfter;
  21749. lynxLines = lynxLines || it.getItem().text == lynx::tr ("Link to controller");
  21750. }
  21751. check ("ml_off_left_column_named", first.getItem().isSectionHeader && caption == lynx::describeAutomationTarget (engine, { AutomationTargetKind::channelPan, 0 }), caption);
  21752. check ("ml_off_two_columns", columnBreak && rightCaption == lynx::tr ("Last 2 tweaked parameters"), rightCaption);
  21753. check ("ml_off_no_lynx_greyed_lines", ! lynxLines);
  21754. savePng (columnMenuImage (menu), prefix + "-multilink-off-menu.png");
  21755. }
  21756. // ---- 3. the Playlist (PL-1 / 2 / 3 / 6 / 7 / 8)
  21757. auto& playlist = ui.getPlaylistForSnapshot();
  21758. {
  21759. auto song = lynx::Song::makeDefault();
  21760. lynx::ChannelDef bass;
  21761. bass.name = "Amount Too - Bass";
  21762. bass.instrument = lynx::InstrumentKind::audioClip;
  21763. bass.samplePath = writeWav (folder.getChildFile ("bass.wav"), 44100.0, 88200, 82.0).getFullPathName().toStdString();
  21764. bass.misc.levels.volume = 1.468f;
  21765. song.channels.push_back (bass);
  21766. lynx::Clip c;
  21767. c.kind = lynx::ClipKind::audio;
  21768. c.channel = (int) song.channels.size() - 1;
  21769. c.track = 3;
  21770. c.start = 4 * lynx::ppq;
  21771. c.length = 2 * lynx::ppq;
  21772. song.playlist.push_back (c);
  21773. engine.setSong (std::move (song));
  21774. }
  21775. engine.dispatchPendingMessages();
  21776. const auto clipIndex = (int) engine.getSong().playlist.size() - 1;
  21777. {
  21778. const auto menu = playlist.getClipMenuForSnapshot (clipIndex);
  21779. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  21780. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  21781. const auto& song = engine.getSong();
  21782. const auto made = (int) song.automations.size() - 1;
  21783. check ("automate_makes_current_clip", made >= 0 && playlist.brush.kind == lynx::ClipKind::automation && playlist.brush.index == made,
  21784. juce::String (playlist.brush.index));
  21785. // (PL-2: Levels VOL 147 %, FL's clip plays unity)
  21786. check ("automate_volume_unity", made >= 0 && song.automations.back().points[0].value == 0.5f
  21787. && lynx::lasttweak::valueText (song, song.automations.back().target, song.automations.back().points[0].value) == "100% 0.0dB 1.00");
  21788. const auto again = playlist.getClipMenuForSnapshot (clipIndex);
  21789. const auto* automate2 = findSub (again, lynx::tr ("Automate"));
  21790. check ("automate_second_is_2", automate2 != nullptr && click (*automate2, lynx::tr ("Volume"))
  21791. && juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()).endsWith (" #2"),
  21792. juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()));
  21793. // PL-7: Fade in / out curve
  21794. const auto* fadeIn = findSub (menu, lynx::tr ("Fade in curve"));
  21795. const auto* fadeOut = findSub (menu, lynx::tr ("Fade out curve"));
  21796. const juce::StringArray curve { lynx::tr ("Reset"), lynx::tr ("Normalize"), lynx::tr ("Normalize selection as a group"), lynx::tr ("Create crossfade"),
  21797. lynx::tr ("Manual"), "[" + lynx::tr ("Declicker") + "]", lynx::tr ("Automatic"), lynx::tr ("Disabled"), lynx::tr ("Enabled"),
  21798. "[" + lynx::tr ("Curve shape") + "]", lynx::tr ("Smooth curve"), lynx::tr ("Single curve") };
  21799. check ("fade_curve_submenus", fadeIn != nullptr && fadeOut != nullptr && texts (*fadeIn) == curve && texts (*fadeOut) == curve,
  21800. fadeIn != nullptr ? texts (*fadeIn).joinIntoString ("|") : juce::String ("missing"));
  21801. if (fadeOut != nullptr)
  21802. saveMenus (juce::StringArray { "Audio clip menu", "Fade out curve" }, std::vector<juce::PopupMenu> { menu, *fadeOut }, prefix + "-fade-curve-menu.png");
  21803. // PL-8: Detect tempo is one item now
  21804. bool detectItem = false;
  21805. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21806. if (plain (it.getItem().text) == plain (lynx::tr ("Detect tempo")))
  21807. detectItem = it.getItem().subMenu == nullptr && it.getItem().action != nullptr;
  21808. check ("detect_tempo_item", detectItem);
  21809. // PL-3: Preview through the channel; transport start ends it
  21810. check ("preview_through_channel", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  21811. engine.play();
  21812. check ("preview_stops_on_transport", ! engine.isClipPreviewing());
  21813. engine.stop();
  21814. check ("preview_again_then_stop", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  21815. engine.stop();
  21816. check ("preview_stops_on_stop", ! engine.isClipPreviewing());
  21817. }
  21818. // PL-8: the dialog
  21819. {
  21820. lynx::ui::TempoDetectionRequest r;
  21821. r.name = "Amount Too - Bass";
  21822. // (a drum-like loop at 117.5 BPM, 100 beats as in FL's dialog: clicks on every beat)
  21823. {
  21824. auto beats = std::make_shared<lynx::SampleData>();
  21825. beats->sampleRate = 44100.0;
  21826. const auto period = 44100.0 * 60.0 / 117.5;
  21827. beats->left.assign ((std::size_t) std::llround (period * 100.0), 0.0f);
  21828. for (int b = 0; b < 100; ++b)
  21829. for (int i = 0; i < 2000; ++i)
  21830. if (const auto at = (std::size_t) std::llround (b * period) + (std::size_t) i; at < beats->left.size())
  21831. beats->left[at] = (float) (0.9 * std::sin (i * 0.09) * std::exp (-i / 400.0));
  21832. r.sample = beats;
  21833. }
  21834. r.projectBpm = 100.0;
  21835. double applied = -1.0;
  21836. r.apply = [&applied] (double beats) { applied = beats; };
  21837. auto panel = lynx::ui::makeTempoDetectionPanel (r);
  21838. panel->setSize (panel->getWidth(), panel->getHeight());
  21839. shoot (*panel, "tempo-detection");
  21840. report.add ("tempo dialog title: " + lynx::ui::tempoDetectionTitle (r.name));
  21841. const auto project = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 3);
  21842. const auto seconds = (double) r.sample->frames() / r.sample->sampleRate; // (100 beats at 117.5 BPM)
  21843. check ("tempo_project_button", std::abs (applied - seconds * 100.0 / 60.0) < 1.0e-6, project + " -> " + juce::String (applied));
  21844. const auto none = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 2);
  21845. check ("tempo_no_tempo_button", applied == 0.0, none);
  21846. }
  21847. // ---- 4. issue #152's question (ISS152-1): FL's message with "Remember my choice"
  21848. {
  21849. auto box = lynx::makeFlMessageDialog ({ lynx::tr ("External input"),
  21850. lynx::tr ("You've selected an external input. Do you want to switch to |External input only| to avoid recording internal audio on this track?"),
  21851. { lynx::tr ("Yes"), lynx::tr ("No") }, true });
  21852. shoot (*box, "external-input-question");
  21853. bool listed = false;
  21854. for (const auto& m : lynx::messages::all())
  21855. listed = listed || juce::String (m.id) == "RecAutoSwitchExternalInput";
  21856. check ("external_input_in_manage_messages", listed);
  21857. }
  21858. // ---- 5. round 190gk: FL's Start in the render window; the Sampler's "Open in new Fruity Slicer / Slicex channel";
  21859. // a Gross Beat slot picked by MIDI becomes its parameter
  21860. {
  21861. lynx::AudioEngine engine (false);
  21862. auto panel = lynx::makeClipRenderPanel (engine);
  21863. panel->setSize (panel->getWidth() > 0 ? panel->getWidth() : 640, panel->getHeight() > 0 ? panel->getHeight() : 480);
  21864. juce::String button;
  21865. for (auto* c : panel->getChildren())
  21866. if (auto* b = dynamic_cast<juce::TextButton*> (c); b != nullptr && b->isVisible() && b->getTooltip() == lynx::tr ("Start rendering"))
  21867. button = b->getButtonText();
  21868. check ("render_button_start", button == lynx::trc ("@render button: Start") && button == "Start", button);
  21869. shoot (*panel, "fltails190gk-render-start");
  21870. const auto clap = writeWav (folder.getChildFile ("Slice me.wav"), 44100.0, 44100, 140.0);
  21871. engine.editSong ([] (lynx::Song& s) {
  21872. s.channels.resize (2);
  21873. s.channels[0] = {};
  21874. s.channels[0].instrument = lynx::InstrumentKind::fruityslicer;
  21875. s.channels[0].name = "Fruity Slicer";
  21876. s.channels[1] = {};
  21877. s.channels[1].instrument = lynx::InstrumentKind::slicex;
  21878. s.channels[1].name = "Slicex";
  21879. });
  21880. const auto locate = [] (int index) {
  21881. return [index] (lynx::Song& s) -> lynx::ChannelDef* { return index < (int) s.channels.size() ? &s.channels[(std::size_t) index] : nullptr; };
  21882. };
  21883. lynx::loadSampleWhenOpened (0, clap.getFullPathName());
  21884. auto slicer = lynx::makeFruitySlicerEditor (engine, locate (0), 0);
  21885. const auto& fs = engine.getSong().channels[0];
  21886. check ("open_in_new_fruity_slicer", fs.samplePath == clap.getFullPathName().toStdString() && ! fs.pluginState.empty(), juce::String (fs.samplePath));
  21887. lynx::loadSlicexSampleWhenOpened (1, clap.getFullPathName());
  21888. auto slicex = lynx::makeSlicexEditor (engine, locate (1), 1);
  21889. const auto& sx = engine.getSong().channels[1];
  21890. check ("open_in_new_slicex", sx.samplePath == clap.getFullPathName().toStdString() && ! sx.pluginState.empty(), juce::String (sx.samplePath));
  21891. auto again = lynx::makeSlicexEditor (engine, locate (1), 1); // (the request is used once)
  21892. check ("open_in_new_used_once", engine.getSong().channels[1].samplePath == sx.samplePath);
  21893. // Gross Beat on insert 1: two notes on its MIDI input, one block, the engine's timer step
  21894. engine.editSong ([] (lynx::Song& s) {
  21895. if (s.mixer.size() < 2)
  21896. s.mixer.resize (2);
  21897. s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::grossBeat) };
  21898. });
  21899. engine.dispatchPendingMessages();
  21900. auto fx = engine.getEffect (1, 0);
  21901. check ("gb_running", fx != nullptr);
  21902. if (fx != nullptr)
  21903. {
  21904. std::vector<float> l (512, 0.1f), r (512, 0.1f);
  21905. fx->prepare (44100.0);
  21906. fx->setSongPosition (0.0);
  21907. fx->midiNote (60 + 9, 100, 0);
  21908. fx->midiNote (24 + 3, 100, 0);
  21909. fx->process (l.data(), r.data(), 512, engine.getSong().mixer[1].effects[0].params, 120.0);
  21910. engine.pumpGrossBeatPicks();
  21911. const auto& p = engine.getSong().mixer[1].effects[0].params;
  21912. check ("gb_midi_pick_sets_parameters", lynx::grossbeat::rawFromParam (0, p[0]) == 9 && lynx::grossbeat::rawFromParam (1, p[1]) == 3,
  21913. juce::String (lynx::grossbeat::rawFromParam (0, p[0])) + " " + juce::String (lynx::grossbeat::rawFromParam (1, p[1])));
  21914. }
  21915. }
  21916. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  21917. return allOk;
  21918. }
  21919. // --grooveshot190fm (round 190fm): see the dispatch above
  21920. bool runGrooveShot190fm (const juce::String& prefix)
  21921. {
  21922. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21923. juce::StringArray report;
  21924. bool allOk = true;
  21925. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  21926. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  21927. allOk = allOk && ok;
  21928. };
  21929. const auto plain = [] (juce::String t) {
  21930. t = t.upToFirstOccurrenceOf ("\t", false, false);
  21931. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  21932. };
  21933. const auto sub = [&plain] (const juce::PopupMenu& menu, const juce::String& start) -> const juce::PopupMenu* {
  21934. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21935. if (it.getItem().subMenu != nullptr && plain (it.getItem().text).startsWith (start))
  21936. return it.getItem().subMenu.get();
  21937. return nullptr;
  21938. };
  21939. const auto item = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  21940. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21941. if (plain (it.getItem().text) == text)
  21942. return &it.getItem();
  21943. return nullptr;
  21944. };
  21945. lynx::AudioEngine engine (false);
  21946. lynx::MainComponent ui (engine, false);
  21947. ui.setSize (1600, 900);
  21948. std::uint32_t classic = 0;
  21949. {
  21950. auto song = lynx::Song::makeDefault();
  21951. song.mode = lynx::PlayMode::song;
  21952. song.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
  21953. song.playlist.push_back ({ 0, 1, 4 * lynx::ppq, 4 * lynx::ppq, 0 });
  21954. for (const auto& e : lynx::groove::factoryBank())
  21955. if (juce::String (e.folder) == "Classic swing" && e.groove.base == lynx::GrooveBase::sixteenth
  21956. && (e.groove.name == "Swing 16ths 54 %" || e.groove.name == "Swing 16ths 58 %" || e.groove.name == "Swing 16ths 62 %"
  21957. || e.groove.name == "Swing 16ths 71 %"))
  21958. {
  21959. const auto id = lynx::groove::add (song.grooves, e.groove);
  21960. if (e.groove.name == "Swing 16ths 58 %")
  21961. classic = id;
  21962. }
  21963. song.playlist[0].groove = classic;
  21964. engine.setSong (std::move (song));
  21965. }
  21966. engine.dispatchPendingMessages();
  21967. auto& playlist = ui.getPlaylistForSnapshot();
  21968. const auto menu = playlist.getClipMenuForSnapshot (0);
  21969. const auto* chooser = sub (menu, lynx::tr ("Groove"));
  21970. check ("groove_chooser_in_clip_menu", chooser != nullptr);
  21971. const auto* add = chooser != nullptr ? sub (*chooser, lynx::tr ("Add a groove")) : nullptr;
  21972. const auto* folder = add != nullptr ? sub (*add, lynx::tr ("Classic swing")) : nullptr;
  21973. check ("classic_swing_folder", folder != nullptr && folder->getNumItems() == 27, folder != nullptr ? juce::String (folder->getNumItems()) : juce::String ("missing"));
  21974. const auto* commit = item (menu, lynx::tr ("Commit groove"));
  21975. check ("commit_enabled_with_a_groove", commit != nullptr && commit->isEnabled);
  21976. check ("extract_present", item (menu, lynx::tr ("Extract groove")) != nullptr);
  21977. {
  21978. juce::StringArray names { "Pattern clip menu" };
  21979. std::vector<juce::PopupMenu> menus { menu };
  21980. if (chooser != nullptr)
  21981. {
  21982. names.add ("Groove");
  21983. menus.push_back (*chooser);
  21984. }
  21985. if (add != nullptr)
  21986. {
  21987. names.add ("Add a groove");
  21988. menus.push_back (*add);
  21989. }
  21990. if (folder != nullptr)
  21991. {
  21992. names.add ("Classic swing");
  21993. menus.push_back (*folder);
  21994. }
  21995. saveMenus (names, menus, prefix + "-playlist-clip-menu.png");
  21996. }
  21997. // the second clip (no groove): Commit is off; choosing a groove from the menu sets it
  21998. {
  21999. const auto other = playlist.getClipMenuForSnapshot (1);
  22000. const auto* c2 = item (other, lynx::tr ("Commit groove"));
  22001. check ("commit_disabled_without_a_groove", c2 != nullptr && ! c2->isEnabled);
  22002. const auto* ch2 = sub (other, lynx::tr ("Groove"));
  22003. const auto* pick = ch2 != nullptr ? item (*ch2, "Swing 16ths 71 %") : nullptr;
  22004. if (pick != nullptr && pick->action != nullptr)
  22005. pick->action();
  22006. const auto& song = engine.getSong();
  22007. check ("chooser_sets_the_clip_groove", song.playlist.size() == 2 && lynx::groove::ofClip (song, song.playlist[1]) != nullptr
  22008. && lynx::groove::ofClip (song, song.playlist[1])->name == "Swing 16ths 71 %");
  22009. }
  22010. // the pool with the classic grooves
  22011. {
  22012. auto pool = lynx::makeGroovePool (engine);
  22013. pool->setSize (900, lynx::groovePoolHeight (engine));
  22014. savePng (pool->createComponentSnapshot (pool->getLocalBounds()), prefix + "-pool.png");
  22015. }
  22016. // .lynx: a Playlist clip's groove comes back; a project without one writes nothing new
  22017. {
  22018. juce::String error;
  22019. const auto& song = engine.getSong();
  22020. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  22021. check ("lynx_round_trip", back && back->playlist.size() == 2 && back->playlist[0].groove == song.playlist[0].groove
  22022. && back->playlist[1].groove == song.playlist[1].groove && back->grooves == song.grooves,
  22023. error);
  22024. auto old = lynx::Song::makeDefault();
  22025. old.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
  22026. const auto json = lynx::ProjectFile::toJson (old, false);
  22027. const auto reloaded = lynx::ProjectFile::fromJson (json, error);
  22028. check ("old_project_unchanged", reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json && reloaded->playlist[0].groove == 0);
  22029. }
  22030. // Commit from the menu: the clip's pattern (shared with the second clip) is copied, the groove is off
  22031. {
  22032. const auto patterns = engine.getSong().patterns.size();
  22033. const auto again = playlist.getClipMenuForSnapshot (0);
  22034. if (const auto* c = item (again, lynx::tr ("Commit groove")); c != nullptr && c->action != nullptr)
  22035. c->action();
  22036. const auto& song = engine.getSong();
  22037. check ("commit_runs", song.playlist[0].groove == 0 && song.patterns.size() == patterns + 1 && song.playlist[0].pattern == (int) patterns);
  22038. }
  22039. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n" + (allOk ? "ALL OK" : "SOME FAILED") + "\n");
  22040. return allOk;
  22041. }
  22042. bool runFlClipShot (const juce::String& prefix)
  22043. {
  22044. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22045. juce::StringArray report;
  22046. bool allOk = true;
  22047. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  22048. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  22049. allOk = allOk && ok;
  22050. };
  22051. const auto plain = [] (juce::String t) {
  22052. t = t.upToFirstOccurrenceOf ("\t", false, false);
  22053. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  22054. t = t.substring (0, at);
  22055. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  22056. };
  22057. const auto find = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  22058. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  22059. if (plain (it.getItem().text) == plain (text))
  22060. return &it.getItem();
  22061. return nullptr;
  22062. };
  22063. const auto click = [&find] (const juce::PopupMenu& menu, const juce::String& text) {
  22064. const auto* item = find (menu, text);
  22065. if (item == nullptr || ! item->isEnabled || item->action == nullptr)
  22066. return false;
  22067. item->action();
  22068. return true;
  22069. };
  22070. lynx::AudioEngine engine (false);
  22071. lynx::MainComponent ui (engine, false);
  22072. ui.setSize (1600, 900);
  22073. int vox = -1;
  22074. {
  22075. auto song = lynx::Song::makeDefault();
  22076. song.channels.push_back ({});
  22077. song.channels.back().name = "Vox";
  22078. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  22079. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  22080. vox = (int) song.channels.size() - 1;
  22081. lynx::Clip c;
  22082. c.kind = lynx::ClipKind::audio;
  22083. c.channel = vox;
  22084. c.track = 3;
  22085. c.start = 4 * lynx::ppq;
  22086. c.length = 2 * lynx::ppq;
  22087. c.fadeIn = lynx::ppq / 4;
  22088. song.playlist.push_back (c);
  22089. engine.setSong (std::move (song));
  22090. }
  22091. engine.dispatchPendingMessages();
  22092. auto& playlist = ui.getPlaylistForSnapshot();
  22093. // ---- 1. the audio clip menu: FL's order, sections and columns, then LYNX's own items
  22094. {
  22095. const auto menu = playlist.getClipMenuForSnapshot (0);
  22096. juce::StringArray got, want;
  22097. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  22098. {
  22099. const auto& item = it.getItem();
  22100. // (round 190kx's loop items, whose labels carry the clip's own key / tempo, are not in the fixed list)
  22101. if (! item.isSeparator && ! item.isSectionHeader
  22102. && (plain (item.text).startsWith (lynx::tr ("Follow the project key")) || plain (item.text).startsWith (lynx::tr ("Loop key"))
  22103. || plain (item.text).startsWith (lynx::tr ("Fit to the project tempo ({0}, from {1} BPM)").upToFirstOccurrenceOf (" (", false, false))))
  22104. continue;
  22105. got.add (item.customComponent != nullptr ? "[" + lynx::tr ("Audio clip") + "]"
  22106. : item.isSeparator ? juce::String ("-")
  22107. : item.isSectionHeader ? "[" + plain (item.text) + "]"
  22108. : plain (item.text));
  22109. }
  22110. for (const auto& e : lynx::flclipmenu::shown (true, false))
  22111. if (e.kind != lynx::flclipmenu::Entry::Kind::columnBreak)
  22112. want.add (e.kind == lynx::flclipmenu::Entry::Kind::separator ? juce::String ("-")
  22113. : e.kind == lynx::flclipmenu::Entry::Kind::header ? "[" + lynx::tr (e.text.c_str()) + "]"
  22114. : lynx::tr (e.text.c_str()));
  22115. // (rollup step 8: the separators round 190kx's key items bring into the LYNX extras column go with them)
  22116. for (int k = got.indexOf ("[" + lynx::tr ("LYNX extras") + "]") + 1; k > 0 && k < got.size();)
  22117. if (got[k] == "-")
  22118. got.remove (k);
  22119. else
  22120. ++k;
  22121. want.add ("[" + lynx::tr ("LYNX extras") + "]"); // (round 190gi; round 190jv: in a third column)
  22122. for (const auto& x : lynx::flclipmenu::lynxExtras())
  22123. want.add (lynx::tr (x.c_str()));
  22124. check ("clip_menu_fl_order", got == want, got.joinIntoString ("|"));
  22125. // FL's two columns (Chop | Sample), then LYNX's own items in a third (round 190jv)
  22126. juce::StringArray breaks;
  22127. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  22128. if (it.getItem().shouldBreakAfter)
  22129. breaks.add (it.getItem().isSectionHeader || it.getItem().customComponent != nullptr ? "?" : plain (it.getItem().text));
  22130. check ("clip_menu_two_columns", breaks.size() == 2 && breaks[0] == lynx::tr ("Chop") && breaks[1] == lynx::tr ("Fade out curve"),
  22131. breaks.joinIntoString ("|"));
  22132. const auto* crossfade = find (menu, lynx::tr ("Crossfade with"));
  22133. check ("crossfade_with_greyed", crossfade != nullptr && ! crossfade->isEnabled);
  22134. const auto* region = find (menu, lynx::tr ("Select region"));
  22135. const auto* full = region != nullptr && region->subMenu != nullptr ? find (*region->subMenu, lynx::tr ("Full")) : nullptr;
  22136. check ("select_region_full_ticked", full != nullptr && full->isTicked);
  22137. const auto* chop = find (menu, lynx::tr ("Chop"));
  22138. check ("chop_time_based", chop != nullptr && chop->subMenu != nullptr && find (*chop->subMenu, lynx::tr ("Chop in 32nd beats")) != nullptr
  22139. && find (*chop->subMenu, lynx::tr ("Chop to grid")) != nullptr);
  22140. savePng (columnMenuImage (menu), prefix + "-clip-menu.png");
  22141. std::fprintf (stderr, "flclipshot: menu saved\n");
  22142. // Muted is a check; Reset fades clears the fades; Select all similar clips selects
  22143. check ("muted_toggles", click (menu, lynx::tr ("Muted")) && engine.getSong().playlist[0].muted);
  22144. const auto again = playlist.getClipMenuForSnapshot (0);
  22145. const auto* muted = find (again, lynx::tr ("Muted"));
  22146. check ("muted_ticked", muted != nullptr && muted->isTicked);
  22147. check ("reset_fades", click (again, lynx::tr ("Reset fades")) && engine.getSong().playlist[0].fadeIn == 0);
  22148. engine.undo();
  22149. engine.undo();
  22150. engine.dispatchPendingMessages();
  22151. std::fprintf (stderr, "flclipshot: automate\n");
  22152. // Automate › Volume / Panning: the clip channel's Levels adjustment (FL's channel parameters 0x11 / 0x10)
  22153. const auto fresh = playlist.getClipMenuForSnapshot (0);
  22154. const auto* automate = find (fresh, lynx::tr ("Automate"));
  22155. const auto before = engine.getSong().automations.size();
  22156. check ("automate_volume_runs", automate != nullptr && automate->subMenu != nullptr && click (*automate->subMenu, lynx::tr ("Volume")));
  22157. const auto& song = engine.getSong();
  22158. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  22159. && song.automations.back().target.param == lynx::leveladjust::volume && song.automations.back().target.index == vox
  22160. && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  22161. check ("automate_volume_is_level_adjust", ok, ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  22162. engine.undo();
  22163. engine.dispatchPendingMessages();
  22164. }
  22165. std::fprintf (stderr, "flclipshot: overlap\n");
  22166. // ---- 2. a second channel's clip overlapping: Crossfade with lists it and makes FL's crossfade clip (round 190gw)
  22167. {
  22168. engine.editSong ([vox] (lynx::Song& s) {
  22169. auto copy = s.playlist[0]; // (another audio clip channel's clip, at the same time)
  22170. s.channels.push_back (s.channels[(std::size_t) vox]);
  22171. s.channels.back().name = "Vox 2";
  22172. copy.channel = (int) s.channels.size() - 1;
  22173. copy.track = 4;
  22174. s.playlist.push_back (copy);
  22175. });
  22176. engine.dispatchPendingMessages();
  22177. const auto overlapped = playlist.getClipMenuForSnapshot (0);
  22178. const auto* with = find (overlapped, lynx::tr ("Crossfade with"));
  22179. check ("crossfade_with_lists_the_overlap", with != nullptr && with->isEnabled && with->subMenu != nullptr && find (*with->subMenu, "Vox 2") != nullptr);
  22180. const auto made = with != nullptr && with->subMenu != nullptr && click (*with->subMenu, "Vox 2");
  22181. engine.dispatchPendingMessages();
  22182. const auto& xsong = engine.getSong();
  22183. const auto xok = made && ! xsong.automations.empty() && xsong.automations.back().links.size() == 2
  22184. && juce::String::fromUTF8 (xsong.automations.back().name.c_str()).endsWith (" to Vox 2 crossfade");
  22185. check ("crossfade_with_makes_the_clip", xok, xok ? juce::String::fromUTF8 (xsong.automations.back().name.c_str()) : juce::String());
  22186. if (made)
  22187. engine.undo();
  22188. engine.undo();
  22189. engine.dispatchPendingMessages();
  22190. }
  22191. std::fprintf (stderr, "flclipshot: misc\n");
  22192. // ---- 3. the channel's Misc tab: Levels adjustment = the offsets (pan 0, volume 100 %, Mod X / Y 0 %)
  22193. {
  22194. engine.editSong ([vox] (lynx::Song& s) {
  22195. s.channels[(std::size_t) vox].misc.levels.volume = 0.5f;
  22196. s.channels[(std::size_t) vox].misc.levels.pan = -0.25f;
  22197. });
  22198. engine.dispatchPendingMessages();
  22199. auto frame = lynx::makeChannelFrame (engine, vox, -1);
  22200. frame->setSize (juce::jmax (frame->getWidth(), 800), juce::jmax (frame->getHeight(), 420));
  22201. savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-misc-levels.png");
  22202. auto synthFrame = lynx::makeChannelFrame (engine, 0, -1);
  22203. synthFrame->setSize (juce::jmax (synthFrame->getWidth(), 800), juce::jmax (synthFrame->getHeight(), 420));
  22204. savePng (synthFrame->createComponentSnapshot (synthFrame->getLocalBounds()), prefix + "-misc-levels-ch1.png");
  22205. std::fprintf (stderr, "flclipshot: round trip\n");
  22206. // the .lynx round trip of the adjustment and of an automation of it; an old project writes nothing new
  22207. juce::String error;
  22208. auto song = engine.getSong();
  22209. lynx::Automation a;
  22210. a.target = { lynx::AutomationTargetKind::channelAdjust, vox, 0, lynx::leveladjust::volume };
  22211. a.points = { { 0, 0.25f, 0.0f } };
  22212. song.automations.push_back (a);
  22213. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  22214. check ("lynx_round_trip", back && back->channels[(std::size_t) vox].misc.levels == song.channels[(std::size_t) vox].misc.levels
  22215. && back->automations.back().target == a.target,
  22216. error);
  22217. auto old = lynx::Song::makeDefault();
  22218. const auto json = lynx::ProjectFile::toJson (old, false);
  22219. const auto reloaded = lynx::ProjectFile::fromJson (json, error);
  22220. check ("old_project_unchanged", ! json.contains ("\"levels\"") && reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json
  22221. && std::all_of (reloaded->channels.begin(), reloaded->channels.end(),
  22222. [] (const lynx::ChannelDef& c) { return c.misc.levels.neutral(); }));
  22223. }
  22224. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  22225. return allOk;
  22226. }
  22227. // --bandlab190jrshot <prefix> (round 190jr; B15, BUILD-LIST 13 / 14): a synthetic BandLab project (.blx: the revision
  22228. // JSON, a MIDI file, a WAV) opened through the real import, shown in the Simple layout; its looped regions and their
  22229. // loop handles; a loop dragged longer; the automation view with and without points and its parameter menu; the clip
  22230. // menu's loop items; the Extract stems form (Standard and 6 stems). Pictures at the --shot-scale asked for.
  22231. void runBandlab190jrShot (const juce::String& prefix)
  22232. {
  22233. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22234. lynx::AudioEngine offline (false);
  22235. lynx::MainComponent ui (offline, false);
  22236. ui.setSize (1600, 900);
  22237. const auto note = [] (const juce::String& what) { std::fprintf (stderr, "bandlab190jrshot: %s\n", what.toRawUTF8()); };
  22238. const auto writeImage = [&prefix, &note] (const juce::Image& image, const char* name) {
  22239. note (name);
  22240. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  22241. file.deleteFile();
  22242. juce::FileOutputStream out (file);
  22243. juce::PNGImageFormat().writeImageToStream (image, out);
  22244. };
  22245. juce::String report;
  22246. const auto check = [&report, &note] (const juce::String& what, bool ok) {
  22247. note ((ok ? "ok " : "FAIL ") + what);
  22248. report << (ok ? "ok " : "FAIL ") << what << "\n";
  22249. };
  22250. // ---- 1. the project: a revision with a looped piano region, a voice take and a drum machine
  22251. const auto folder = juce::File (prefix + "-blx");
  22252. folder.deleteRecursively();
  22253. folder.getChildFile ("Audio").createDirectory();
  22254. folder.getChildFile ("MIDI").createDirectory();
  22255. {
  22256. // a 4-beat MIDI part (100 BPM: 2.4 s) and a drum beat, 480 ticks per quarter
  22257. const auto midi = [] (const std::vector<std::array<int, 4>>& notes) {
  22258. juce::MidiMessageSequence seq;
  22259. for (const auto& n : notes)
  22260. {
  22261. seq.addEvent (juce::MidiMessage::noteOn (1, n[2], (juce::uint8) n[3]), n[0]);
  22262. seq.addEvent (juce::MidiMessage::noteOff (1, n[2]), n[0] + n[1]);
  22263. }
  22264. seq.updateMatchedPairs();
  22265. juce::MidiFile file;
  22266. file.setTicksPerQuarterNote (480);
  22267. file.addTrack (seq);
  22268. juce::MemoryOutputStream out;
  22269. file.writeTo (out);
  22270. return out.getMemoryBlock();
  22271. };
  22272. const auto keysBlock = midi ({ { 0, 480, 62, 100 }, { 0, 480, 65, 90 }, { 0, 480, 69, 90 }, { 480, 240, 64, 80 },
  22273. { 960, 480, 60, 100 }, { 960, 480, 64, 90 }, { 1440, 480, 67, 90 } });
  22274. folder.getChildFile ("MIDI/s-keys.mid").replaceWithData (keysBlock.getData(), keysBlock.getSize());
  22275. const auto beat = midi ({ { 0, 120, 36, 120 }, { 480, 120, 38, 110 }, { 960, 120, 36, 120 }, { 1440, 120, 38, 110 }, { 240, 60, 42, 80 },
  22276. { 720, 60, 42, 80 }, { 1200, 60, 42, 80 }, { 1680, 60, 42, 80 } });
  22277. folder.getChildFile ("MIDI/s-beat.mid").replaceWithData (beat.getData(), beat.getSize());
  22278. // a 4.8 s "voice" (a sine with a slow swell), 44.1 kHz
  22279. juce::AudioBuffer<float> wave (1, 44100 * 48 / 10);
  22280. for (int i = 0; i < wave.getNumSamples(); ++i)
  22281. wave.setSample (0, i, 0.4f * std::sin ((float) i * 0.0627f) * (0.5f + 0.5f * std::sin ((float) i * 0.00012f)));
  22282. juce::WavAudioFormat wav;
  22283. const auto out = folder.getChildFile ("Audio/s-vox.wav");
  22284. if (auto stream = out.createOutputStream())
  22285. if (std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (stream.get(), 44100.0, 1, 16, {}, 0)); writer != nullptr)
  22286. {
  22287. stream.release();
  22288. writer->writeFromAudioSampleBuffer (wave, 0, wave.getNumSamples());
  22289. }
  22290. folder.getChildFile ("Scratch Song.blx").replaceWithText (R"({ "revision": {
  22291. "key": "D min", "volume": 1, "song": { "name": "Scratch Song" },
  22292. "metronome": { "bpm": 100, "signature": { "notesCount": 4, "noteValue": 4 } },
  22293. "auxChannels": [ { "id": "aux1", "preset": "sharedReverb", "returnLevel": 1 } ],
  22294. "samples": [ { "id": "s-keys", "isMidi": true, "duration": 2.4 }, { "id": "s-vox", "isMidi": false, "duration": 4.8 }, { "id": "s-beat", "isMidi": true } ],
  22295. "tracks": [
  22296. { "id": "t1", "order": 0, "name": "Keys", "type": "instrument", "soundbank": "studio-grand", "volume": 0.9, "colorName": "Red",
  22297. "regions": [ { "id": "r1", "sampleId": "s-keys", "name": "Chords", "startPosition": 0, "endPosition": 9.6, "loopLength": 2.4 } ] },
  22298. { "id": "t2", "order": 1, "name": "Vocal", "type": "voice", "volume": 1, "pan": -0.2, "colorName": "Blue",
  22299. "effects": [ { "slug": "compressor", "params": { "attack": 0.003, "ratio": 3, "release": 0.12, "threshold": -18 } },
  22300. { "slug": "threeBandEq", "params": { "lowGain": -2, "midGain": 1, "highGain": 3, "midFreq": 2500 } },
  22301. { "slug": "chorusPedal", "params": {} } ],
  22302. "auxSends": [ { "id": "aux1", "sendLevel": 0.3 } ],
  22303. "automation": { "volume": [ { "position": 0, "value": 0.2 }, { "position": 8, "value": 1 }, { "position": 16, "value": 0.7 } ] },
  22304. "regions": [ { "id": "r2", "sampleId": "s-vox", "name": "Take 1", "startPosition": 2.4, "endPosition": 7.2, "fadeIn": 0.2, "fadeOut": 0.5 } ] },
  22305. { "id": "t3", "order": 2, "name": "Drum Machine", "type": "drum-machine", "volume": 1, "colorName": "Violet",
  22306. "regions": [ { "id": "r3", "sampleId": "s-beat", "name": "Beat", "startPosition": 0, "endPosition": 4.8, "loopLength": 2.4 } ] }
  22307. ] } })");
  22308. }
  22309. juce::String error;
  22310. const auto blx = folder.getChildFile ("Scratch Song.blx");
  22311. const auto imported = offline.importFlpFile (blx, error);
  22312. check ("the .blx opens through the import (" + error + ")", imported);
  22313. offline.dispatchPendingMessages();
  22314. const auto& song = offline.getSong();
  22315. check ("three Simple tracks: Keys (instrument), Vocal (audio), Drum Machine (drums)",
  22316. lynx::simpletracks::kindOf (song, 0) == lynx::simpletracks::Kind::instrument && lynx::simpletracks::kindOf (song, 1) == lynx::simpletracks::Kind::audio
  22317. && lynx::simpletracks::kindOf (song, 2) == lynx::simpletracks::Kind::drums);
  22318. check ("tempo 100, key D minor", std::abs (song.bpm - 100.0) < 1e-6 && lynx::projectkey::get (song).has_value());
  22319. int keysClips = 0, beatClips = 0, voxClips = 0;
  22320. for (const auto& c : song.playlist)
  22321. {
  22322. keysClips += c.track == 0;
  22323. voxClips += c.track == 1 && c.kind == lynx::ClipKind::audio;
  22324. beatClips += c.track == 2;
  22325. }
  22326. check ("the looped Keys region: 4 passes; the beat: 2; the take: 1 audio clip", keysClips == 4 && beatClips == 2 && voxClips == 1);
  22327. const auto voxInsert = lynx::simpletracks::insertOf (song, 1);
  22328. check ("the vocal's compressor, EQ and chorus on its insert",
  22329. voxInsert > 0 && song.mixer[(std::size_t) voxInsert].effects.size() == 3);
  22330. check ("the vocal's volume automation: a lane under its track", ! song.playlistTracks[1].lanes.empty());
  22331. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  22332. offline.dispatchPendingMessages();
  22333. ui.selectTabForSnapshot (2);
  22334. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  22335. simple->hideChooser();
  22336. auto& playlist = ui.getPlaylistForSnapshot();
  22337. playlist.setViewForSnapshot (96.0, 0, 0);
  22338. offline.dispatchPendingMessages();
  22339. writeImage (lynx::shot::snapshot (ui), "blx-simple");
  22340. writeImage (lynx::shot::snapshot (playlist), "loop-handles");
  22341. // ---- 2. a loop dragged longer: the take repeated to bar 9 (as the handle's drag does it)
  22342. {
  22343. int take = -1;
  22344. for (int i = 0; i < (int) song.playlist.size(); ++i)
  22345. if (song.playlist[(std::size_t) i].track == 1 && song.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  22346. take = i;
  22347. const auto end = (std::int64_t) lynx::ppq * 4 * 8;
  22348. offline.editSong ([take, end] (lynx::Song& s) { lynx::regionloop::loopTo (s, take, end); });
  22349. offline.dispatchPendingMessages();
  22350. const auto run = lynx::regionloop::runOf (offline.getSong(), lynx::regionloop::regionAt (offline.getSong(), 1, (std::int64_t) lynx::ppq * 4, offline.getSong().playlist[(std::size_t) take]));
  22351. check ("the take loops to bar 9 in passes of its length", run.passes() >= 3 && run.end == end);
  22352. writeImage (lynx::shot::snapshot (playlist), "loop-dragged");
  22353. auto menu = playlist.getClipMenuForSnapshot (run.clips.empty() ? take : run.clips.back());
  22354. bool hasLoop = false;
  22355. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  22356. hasLoop = hasLoop || it.getItem().text == lynx::tr ("Unloop");
  22357. check ("the Simple clip menu has Loop until next / Unloop", hasLoop);
  22358. saveMenus (juce::StringArray { "Clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu.png");
  22359. }
  22360. // ---- 3. the automation view: the vocal's lane on its row, the others' dashed line at their level
  22361. playlist.setSimpleAutomation (true);
  22362. offline.dispatchPendingMessages();
  22363. writeImage (lynx::shot::snapshot (playlist), "automation-view");
  22364. check ("the view changes nothing in the song", offline.getSong().playlistTracks[0].lanes.empty());
  22365. playlist.setSimpleAutoTargetForSnapshot (1, { lynx::AutomationTargetKind::effectParam, voxInsert, 0, 0 }); // the compressor's threshold
  22366. writeImage (lynx::shot::snapshot (playlist), "automation-param");
  22367. playlist.setSimpleAutoTargetForSnapshot (1, { lynx::AutomationTargetKind::mixerVolume, voxInsert, 0, 0 });
  22368. saveMenus (juce::StringArray { "Volume" }, std::vector<juce::PopupMenu> { playlist.getSimpleAutoMenuForSnapshot (1) }, prefix + "-automation-menu.png");
  22369. playlist.setSimpleAutomation (false);
  22370. offline.dispatchPendingMessages();
  22371. // ---- 4. the Extract stems form
  22372. {
  22373. auto panel = lynx::makeStemOptionsPanel (lynx::stemsplit::Options {}, [] (lynx::stemsplit::Options) {});
  22374. writeImage (lynx::shot::paint (*panel, lynx::theme::colour::bg2), "stem-options");
  22375. lynx::stemsplit::Options six;
  22376. six.model = lynx::stemsplit::Model::sixStems;
  22377. six.stems = { true, true, false, true, true, true };
  22378. auto panel6 = lynx::makeStemOptionsPanel (six, [] (lynx::stemsplit::Options) {});
  22379. writeImage (lynx::shot::paint (*panel6, lynx::theme::colour::bg2), "stem-options-six");
  22380. }
  22381. juce::File (lynx::shot::fileName (prefix + "-report.txt")).replaceWithText (report);
  22382. }
  22383. // --bandlabshot <prefix> (round 190ch): the Lyrics / Notes panel (Pattern and Simple layouts, and on its own), the
  22384. // Reference match window measured on a real render and a real file, "Start from", and Clean voice, off-screen; and
  22385. // <prefix>-report.txt with what each route did (ok / FAIL lines)
  22386. void runBandlabShot (const juce::String& prefix)
  22387. {
  22388. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22389. lynx::AudioEngine offline (false);
  22390. lynx::MainComponent ui (offline, false);
  22391. ui.setSize (1600, 900);
  22392. // (each step is named on stderr as it starts: a run that stops says where)
  22393. const auto note = [] (const juce::String& what) { std::fprintf (stderr, "bandlabshot: %s\n", what.toRawUTF8()); };
  22394. const auto shoot = [&prefix, &note] (juce::Component& c, const char* name) {
  22395. note (name);
  22396. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  22397. };
  22398. juce::String report;
  22399. const auto check = [&report, &note] (const juce::String& what, bool ok) {
  22400. note ((ok ? "ok " : "FAIL ") + what);
  22401. report << (ok ? "ok " : "FAIL ") << what << "\n";
  22402. };
  22403. const auto bar = (double) lynx::ppq * 4.0;
  22404. // ---- 1. Lyrics / Notes: the project's Comments
  22405. {
  22406. auto song = lynx::makeShowcaseSong (0);
  22407. song.info.title = "Night Drive";
  22408. song.info.comments = "[Intro]\n\n[5] [Verse 1]\n[5] Headlights on the empty road\n[7] Radio is playing low\n[9] Every sign says slow\n"
  22409. "I keep driving through the night\n\n[Chorus]\nNight drive, night drive\nNothing but the white line\n\n"
  22410. "Notes: double the chorus vocal, try the second verse an octave down.";
  22411. lynx::Marker chorus;
  22412. chorus.tick = (std::int64_t) (12.0 * bar);
  22413. chorus.name = "Chorus";
  22414. song.addMarker (chorus);
  22415. offline.setSong (std::move (song));
  22416. }
  22417. note ("song set");
  22418. offline.dispatchPendingMessages();
  22419. ui.selectTabForSnapshot (2);
  22420. note ("show lyrics");
  22421. ui.showLyrics (false);
  22422. note ("lyrics shown");
  22423. if (auto* panel = ui.getLyricsPanelForSnapshot())
  22424. {
  22425. panel->showForSnapshot ({}, 6.5 * bar); // the playhead inside bar 7: that line is the one playing
  22426. shoot (ui, "lyrics-pattern");
  22427. shoot (*panel, "lyrics-panel");
  22428. const auto markersBefore = offline.getSong().markers().size();
  22429. panel->setCaretLineForSnapshot (6); // "I keep driving through the night"
  22430. panel->markAtPlayheadForSnapshot (10.0 * bar + 2.0 * lynx::ppq);
  22431. offline.dispatchPendingMessages();
  22432. ui.commitSongNotes();
  22433. const auto& s = offline.getSong();
  22434. check ("Marker at playhead stamps the line [11.3] and adds one marker",
  22435. juce::String::fromUTF8 (s.info.comments.c_str()).contains ("[11.3] I keep driving") && s.markers().size() == markersBefore + 1);
  22436. // (no audio device here: the seek is the request the audio thread takes at its next block)
  22437. const auto& seek = offline.getTransport().seekRequest;
  22438. check ("clicking the stamped line moves the playhead to bar 7", panel->jumpToLineForSnapshot (4) && std::abs (seek.load() - 6.0 * bar) < 1.0);
  22439. check ("clicking [Chorus] (no position) goes to the marker of that name, bar 13",
  22440. panel->jumpToLineForSnapshot (8) && std::abs (seek.load() - 12.0 * bar) < 1.0);
  22441. check ("a line without a position does not jump", ! panel->jumpToLineForSnapshot (9));
  22442. panel->showForSnapshot ("night", 10.5 * bar);
  22443. shoot (*panel, "lyrics-search");
  22444. // the text travels in the project file, and old readers see it as the Comments they always had
  22445. juce::String error;
  22446. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  22447. const auto back = lynx::ProjectFile::fromJson (json, error);
  22448. check ("lyrics round-trip through .lynx (the Comments field)", back.has_value() && back->info.comments == offline.getSong().info.comments);
  22449. const auto text = lynx::lyrics::exportText (offline.getSong(), lynx::lyrics::Stamps::times);
  22450. juce::File (prefix + "-lyrics-export.txt").replaceWithText (juce::String::fromUTF8 (text.c_str()));
  22451. check ("export as text with times", text.find ("[0:") != std::string::npos);
  22452. panel->showForSnapshot ({}, 6.5 * bar);
  22453. }
  22454. else
  22455. check ("the docked Lyrics panel exists", false);
  22456. {
  22457. const auto names = ui.getMenuNamesForSnapshot();
  22458. const auto view = names.indexOf (lynx::tr ("View"));
  22459. saveMenus (juce::StringArray { lynx::tr ("View") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (juce::jmax (0, view)) }, prefix + "-menu-view.png");
  22460. }
  22461. ui.showDesktopForSnapshot (false);
  22462. check ("the panel stays docked beside the Playlist in the default desktop", ui.isLyricsShowing());
  22463. shoot (ui, "lyrics-desktop");
  22464. // ---- the Simple layout: the Lyrics button in its title tools, the chooser's "Start from" link
  22465. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  22466. offline.dispatchPendingMessages();
  22467. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  22468. auto* simple = ui.getSimpleWorkflowForSnapshot();
  22469. check ("the Simple workflow exists", simple != nullptr);
  22470. if (simple != nullptr)
  22471. {
  22472. simple->hideChooser();
  22473. if (! ui.isLyricsShowing())
  22474. ui.showLyrics (false);
  22475. shoot (ui, "lyrics-simple");
  22476. ui.hideLyrics();
  22477. check ("closing the panel keeps the text", juce::String::fromUTF8 (offline.getSong().info.comments.c_str()).contains ("Night drive, night drive"));
  22478. // ---- 4. Clean voice: on a voice track, from the track's menu
  22479. lynx::simpletracks::Result voice;
  22480. offline.editSongStructural ([&voice] (lynx::Song& s) {
  22481. lynx::simpletracks::Request q;
  22482. q.kind = lynx::simpletracks::Kind::voice;
  22483. q.name = "Lead vocal";
  22484. voice = lynx::simpletracks::addTrack (s, q);
  22485. });
  22486. offline.dispatchPendingMessages();
  22487. check ("a voice track was added", voice.insert > 0);
  22488. if (voice.insert > 0)
  22489. {
  22490. auto menu = ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (voice.track);
  22491. juce::StringArray names { "Track" };
  22492. std::vector<juce::PopupMenu> menus { menu };
  22493. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  22494. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Clean voice"))
  22495. {
  22496. names.add (lynx::tr ("Clean voice"));
  22497. menus.push_back (*it.getItem().subMenu);
  22498. }
  22499. check ("the Simple track menu has Clean voice", menus.size() == 2);
  22500. saveMenus (names, menus, prefix + "-cleanvoice-menu.png");
  22501. const auto before = offline.getSong().mixer[(std::size_t) voice.insert].effects.size();
  22502. check ("Clean voice applies", lynx::ui::applyCleanVoice (offline, voice.insert, false));
  22503. offline.dispatchPendingMessages();
  22504. const auto& fx = offline.getSong().mixer[(std::size_t) voice.insert].effects;
  22505. check ("four slots in front of the track's effects", fx.size() == before + 4 && lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4
  22506. && fx[0].kind == lynx::EffectKind::facetEq);
  22507. check ("with noise reduction: five, none doubled", lynx::ui::applyCleanVoice (offline, voice.insert, true)
  22508. && offline.getSong().mixer[(std::size_t) voice.insert].effects.size() == before + 5);
  22509. offline.dispatchPendingMessages();
  22510. juce::String error;
  22511. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  22512. check ("the chain round-trips through .lynx and is still found", back.has_value() && lynx::cleanvoice::slotsOf (*back, voice.insert).size() == 5
  22513. && back->mixer[(std::size_t) voice.insert].effects == offline.getSong().mixer[(std::size_t) voice.insert].effects);
  22514. saveMenus (juce::StringArray { lynx::tr ("Clean voice") }, std::vector<juce::PopupMenu> { lynx::ui::cleanVoiceMenu (offline, voice.insert) },
  22515. prefix + "-cleanvoice-menu-on.png");
  22516. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  22517. offline.dispatchPendingMessages();
  22518. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  22519. ui.selectMixerTrackForSnapshot (voice.insert);
  22520. shoot (ui, "cleanvoice-mixer");
  22521. offline.undo(); // the second chain
  22522. offline.dispatchPendingMessages();
  22523. check ("undo brings the first chain back", lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4);
  22524. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  22525. offline.dispatchPendingMessages();
  22526. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  22527. simple = ui.getSimpleWorkflowForSnapshot();
  22528. }
  22529. }
  22530. // ---- 2. Reference match: the song's Master render against a file (pink noise with more top, at about -14 LUFS)
  22531. {
  22532. const auto file = juce::File (prefix + "-reference.wav");
  22533. file.deleteFile();
  22534. const auto rate = 44100.0;
  22535. const auto frames = (int) (20.0 * rate);
  22536. juce::AudioBuffer<float> audio (2, frames);
  22537. juce::Random random (190);
  22538. for (int ch = 0; ch < 2; ++ch)
  22539. {
  22540. double b0 = 0, b1 = 0, b2 = 0, hp = 0;
  22541. for (int i = 0; i < frames; ++i)
  22542. {
  22543. const auto w = (double) random.nextFloat() * 2.0 - 1.0;
  22544. b0 = 0.99765 * b0 + w * 0.0990460;
  22545. b1 = 0.96300 * b1 + w * 0.2965164;
  22546. b2 = 0.57000 * b2 + w * 1.0526913;
  22547. const auto pink = (b0 + b1 + b2 + w * 0.1848) * 0.071; // (about -14 LUFS: a streaming master)
  22548. hp += 0.25 * (pink - hp); // a little more top than pink noise has
  22549. audio.setSample (ch, i, (float) (pink + 0.35 * (pink - hp)));
  22550. }
  22551. }
  22552. if (auto out = file.createOutputStream())
  22553. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 24, {}, 0)))
  22554. {
  22555. out.release();
  22556. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  22557. }
  22558. note ("measure reference");
  22559. const auto reference = lynx::ReferenceMatchPanel::measureFile (offline, file);
  22560. note ("measure song");
  22561. const auto song = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), false);
  22562. check ("the reference file was measured", reference.valid);
  22563. check ("the song's Master render was measured", song.valid);
  22564. lynx::ReferenceMatchPanel panel (offline, {});
  22565. panel.setSize (lynx::ReferenceMatchPanel::defaultWidth, lynx::ReferenceMatchPanel::defaultHeight);
  22566. panel.showForSnapshot ("Reference.wav", song, reference, nullptr);
  22567. shoot (panel, "refmatch-measured");
  22568. const auto masterBefore = offline.getSong().mixer[0].effects.size();
  22569. check ("Match adds its two slots at the end of the Master", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  22570. offline.dispatchPendingMessages();
  22571. const auto first = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  22572. panel.showForSnapshot ("Reference.wav", song, reference, &first);
  22573. panel.refresh();
  22574. shoot (panel, "refmatch-matched");
  22575. report << " first Match: " << juce::String (first.lufs, 2) << " LUFS, " << juce::String (first.truePeakDb, 2) << " dBTP, EQ output "
  22576. << juce::String (lynx::facet::outputDb (offline.getSong().mixer[0].effects[masterBefore].params[(std::size_t) lynx::facet::outputParam]), 2) << " dB\n";
  22577. // a result more than 0.5 LU from the reference (a limiter that has to hold peaks back): Match again takes
  22578. // what is missing, as the window's note says
  22579. auto after = first;
  22580. const auto secondPass = std::abs (first.lufs - reference.lufs) > 0.5;
  22581. if (secondPass)
  22582. {
  22583. check ("Match again replaces the two slots (level corrected)", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  22584. offline.dispatchPendingMessages();
  22585. after = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  22586. panel.showForSnapshot ("Reference.wav", song, reference, &after);
  22587. panel.refresh();
  22588. shoot (panel, "refmatch-matched-again");
  22589. }
  22590. report << " " << (secondPass ? "a second Match was needed for the level" : "one Match was enough for the level") << "\n";
  22591. const auto& s = panel.suggestionForSnapshot();
  22592. report << " song " << juce::String (song.lufs, 2) << " LUFS, " << juce::String (song.truePeakDb, 2) << " dBTP, width " << juce::String (song.widthPercent(), 1)
  22593. << " % | reference " << juce::String (reference.lufs, 2) << " LUFS, " << juce::String (reference.truePeakDb, 2) << " dBTP, width "
  22594. << juce::String (reference.widthPercent(), 1) << " % | after " << juce::String (after.lufs, 2) << " LUFS, " << juce::String (after.truePeakDb, 2)
  22595. << " dBTP\n next suggestion: gain " << juce::String (s.gainDb, 2) << " dB, EQ fit error " << juce::String (s.fitErrorDb, 2) << " dB\n";
  22596. double before = 0.0, now = 0.0;
  22597. int counted = 0;
  22598. {
  22599. // tone only (each curve around its own mean), over the bands both hold
  22600. double ms = 0, mr = 0, ma = 0;
  22601. const auto used = juce::jmin (song.usedBands, reference.usedBands);
  22602. for (int k = 0; k < used; ++k)
  22603. ms += song.spectrumDb[(std::size_t) k], mr += reference.spectrumDb[(std::size_t) k], ma += after.spectrumDb[(std::size_t) k];
  22604. for (int k = 2; k < used; ++k, ++counted)
  22605. {
  22606. before += std::abs ((song.spectrumDb[(std::size_t) k] - ms / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  22607. now += std::abs ((after.spectrumDb[(std::size_t) k] - ma / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  22608. }
  22609. }
  22610. report << " mean tone difference to the reference: " << juce::String (before / juce::jmax (1, counted), 2) << " dB before, "
  22611. << juce::String (now / juce::jmax (1, counted), 2) << " dB after one Match (each band moves 6 dB at most)\n";
  22612. check ("after Match the tone is closer to the reference", after.valid && now < before);
  22613. check ("after Match the loudness is within 1 LU of the reference", std::abs (after.lufs - reference.lufs) < 1.0);
  22614. check ("the limiter holds the peaks: under 0 dBTP, within 0.6 dB of its -1 dB ceiling", after.truePeakDb < 0.0 && after.truePeakDb <= -1.0 + 0.6);
  22615. juce::String error;
  22616. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  22617. check ("the match round-trips through .lynx as two ordinary Master slots", back.has_value() && lynx::refmatch::present (*back)
  22618. && back->mixer[0].effects == offline.getSong().mixer[0].effects);
  22619. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  22620. offline.dispatchPendingMessages();
  22621. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  22622. ui.selectMixerTrackForSnapshot (0);
  22623. shoot (ui, "refmatch-mixer");
  22624. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  22625. offline.dispatchPendingMessages();
  22626. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  22627. simple = ui.getSimpleWorkflowForSnapshot();
  22628. if (simple != nullptr)
  22629. {
  22630. simple->hideChooser();
  22631. simple->showFinish();
  22632. shoot (ui, "finish-dock"); // "Match a reference track..." under the saving buttons
  22633. simple->hideFinish();
  22634. }
  22635. file.deleteFile();
  22636. }
  22637. // ---- 3. Start from: the chooser's link, the list, and opening an entry
  22638. if (simple != nullptr)
  22639. {
  22640. simple->showChooser();
  22641. shoot (ui, "chooser");
  22642. simple->hideChooser();
  22643. auto* panel = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot());
  22644. check ("the Start from list opens", panel != nullptr && simple->isStartFromShowing());
  22645. if (panel != nullptr)
  22646. {
  22647. shoot (ui, "startfrom");
  22648. auto list = lynx::startfrom::entries();
  22649. check ("it lists the demo song and the templates shipped", list.size() >= 3 && list[0].kind == lynx::startfrom::Entry::Kind::demo
  22650. && (int) list.size() == panel->entryCountForSnapshot());
  22651. for (auto& e : list)
  22652. report << " " << e.name << " | " << juce::String (e.bpm, 0) << " BPM, " << e.channels << " channels, " << e.bars << " bars"
  22653. << (e.playable ? ", preview" : "") << "\n";
  22654. if (const auto demo = lynx::startfrom::songOf (list[0]))
  22655. {
  22656. const auto wav = juce::File (prefix + "-preview.wav");
  22657. const auto ok = lynx::startfrom::renderPreview (*demo, wav);
  22658. check ("the demo's preview renders (" + juce::String (wav.getSize() / 1024) + " kB)", ok && wav.getSize() > 100000);
  22659. wav.deleteFile();
  22660. }
  22661. panel->selectForSnapshot (juce::jmin (2, panel->entryCountForSnapshot() - 1));
  22662. shoot (ui, "startfrom-selected");
  22663. offline.markSaved(); // (a project with changes asks first: Save / Don't save / Cancel)
  22664. const auto opened = panel->openForSnapshot (0);
  22665. offline.dispatchPendingMessages();
  22666. check ("opening the demo starts a new project from it and closes the list",
  22667. opened && ! simple->isStartFromShowing() && offline.getSong().info.comments.empty() && ! offline.getSong().channels.empty());
  22668. shoot (ui, "startfrom-opened");
  22669. }
  22670. }
  22671. juce::File (prefix + "-report.txt").replaceWithText (report);
  22672. }
  22673. void runVersionsShot (const juce::String& prefix)
  22674. {
  22675. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22676. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  22677. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  22678. };
  22679. // ---- the Versions panel, on files in a temporary folder
  22680. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  22681. .getChildFile ("lynx-versionsshot-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  22682. const juce::ScopeGuard cleanUp { [&root] { root.deleteRecursively(); } };
  22683. const auto project = root.getChildFile ("Night Drive"), backup = root.getChildFile ("Backup");
  22684. project.createDirectory();
  22685. backup.createDirectory();
  22686. const auto now = juce::Time::getCurrentTime();
  22687. const auto put = [&now] (const juce::File& folder, const juce::String& name, const char* kind, int kilobytes, double hoursAgo) {
  22688. const auto time = now - juce::RelativeTime::hours (hoursAgo);
  22689. const auto file = folder.getChildFile (kind == nullptr ? name + ".lynx" : name + " (" + kind + " on " + time.formatted ("%Y-%m-%d at %Hh%M") + ").lynx");
  22690. juce::MemoryBlock data ((size_t) kilobytes * 1024, true);
  22691. file.replaceWithData (data.getData(), data.getSize());
  22692. file.setLastModificationTime (time);
  22693. };
  22694. put (project, "Night Drive", nullptr, 412, 26.0 * 24.0);
  22695. put (project, "Night Drive_2", nullptr, 688, 9.0 * 24.0);
  22696. put (project, "Night Drive_3", nullptr, 731, 2.0 * 24.0);
  22697. put (project, "Night Drive_4", nullptr, 905, 1.6);
  22698. put (backup, "Night Drive_4", "autosaved", 907, 0.07);
  22699. put (backup, "Night Drive_4", "autosaved", 906, 0.4);
  22700. put (backup, "Night Drive_4", "overwritten", 890, 1.6);
  22701. put (backup, "Night Drive_4", "autosaved", 884, 3.2);
  22702. put (backup, "Night Drive_3", "overwritten", 720, 2.0 * 24.0);
  22703. put (backup, "Night Drive_2", "autosaved", 690, 8.0 * 24.0);
  22704. const lynx::VersionsContext context { project.getChildFile ("Night Drive_4.lynx"), "Night Drive_4", backup, ".lynx" };
  22705. {
  22706. const auto entries = lynx::versionEntries (context);
  22707. const auto label = [&] (const juce::String& startsWith, const char* text) {
  22708. for (const auto& e : entries)
  22709. if (juce::String::fromUTF8 (e.name.c_str()).startsWith (startsWith))
  22710. {
  22711. lynx::setVersionLabel (context, e, text);
  22712. return;
  22713. }
  22714. };
  22715. label ("Night Drive_2", "first full arrangement");
  22716. label ("Night Drive_3", "sent to the singer");
  22717. label ("Night Drive_4 (autosaved", "new bass line");
  22718. }
  22719. {
  22720. lynx::VersionsActions actions;
  22721. actions.context = [context] { return context; };
  22722. auto panel = lynx::makeVersionsPanel (actions);
  22723. shoot (*panel, "versions");
  22724. lynx::VersionsActions fresh;
  22725. fresh.context = [backup] { return lynx::VersionsContext { juce::File(), "Untitled", backup, ".lynx" }; };
  22726. auto empty = lynx::makeVersionsPanel (fresh);
  22727. shoot (*empty, "versions-unsaved");
  22728. }
  22729. // ---- the window
  22730. lynx::AudioEngine offline (false);
  22731. lynx::MainComponent ui (offline, false);
  22732. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  22733. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  22734. const auto saveFileMenu = [&] (const char* name) {
  22735. const auto index = juce::jmax (0, ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("File")));
  22736. saveMenus (juce::StringArray { lynx::tr ("File") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-" + name + ".png");
  22737. };
  22738. saveFileMenu ("menu-file");
  22739. // ---- a project opened without its third-party plugins (the plugins are not installed: nothing foreign runs)
  22740. {
  22741. const auto ref = [] (const char* id, const char* name) {
  22742. lynx::PluginRef r;
  22743. r.id = id;
  22744. r.name = name;
  22745. r.state = "c2V0dGluZ3M=";
  22746. return r;
  22747. };
  22748. auto song = lynx::Song::makeDefault();
  22749. while (song.channels.size() < 4)
  22750. song.channels.push_back (song.channels.front());
  22751. while (song.mixer.size() < 5)
  22752. song.mixer.push_back (song.mixer.back());
  22753. const char* names[] = { "Lead", "Pad" };
  22754. for (int c = 0; c < 2; ++c)
  22755. {
  22756. auto& channel = song.channels[(std::size_t) (c + 2)];
  22757. channel.instrument = lynx::InstrumentKind::plugin;
  22758. channel.plugin = ref ("VST3-ShotSynth-11111111-aaaaaaaa", "Shot Synth");
  22759. channel.name = names[c];
  22760. channel.mixerTrack = c + 1;
  22761. }
  22762. lynx::EffectSlot fx;
  22763. fx.kind = lynx::EffectKind::plugin;
  22764. fx.plugin = ref ("VST3-ShotVerb-22222222-bbbbbbbb", "Shot Verb");
  22765. song.mixer[1].effects.push_back (fx);
  22766. fx.plugin = ref ("VST3-ShotComp-33333333-cccccccc", "Shot Comp");
  22767. song.mixer[2].effects.push_back (fx);
  22768. song.mixer[0].effects.push_back (fx);
  22769. offline.setSongWithPluginsOff (std::move (song));
  22770. ui.showDesktopForSnapshot (false);
  22771. shoot (ui, "pluginsoff-window");
  22772. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  22773. shoot (ui, "pluginsoff-mixer"); // (the rack's and the mixer's "off" tags together)
  22774. saveFileMenu ("menu-file-pluginsoff");
  22775. auto panel = lynx::makePluginsOffPanel (offline);
  22776. shoot (*panel, "pluginsoff-panel");
  22777. offline.switchPluginOn ("VST3-ShotVerb-22222222-bbbbbbbb"); // (not installed: "Did not load")
  22778. auto after = lynx::makePluginsOffPanel (offline);
  22779. shoot (*after, "pluginsoff-panel-one");
  22780. }
  22781. // ---- the Export window: as it opens, and with a preset chosen, sections on and a last export to repeat
  22782. {
  22783. auto song = lynx::Song::makeDefault();
  22784. const auto bar = song.barTicks();
  22785. song.mode = lynx::PlayMode::song;
  22786. song.playlist.clear();
  22787. lynx::Clip clip;
  22788. clip.length = 32 * bar;
  22789. song.playlist.push_back (clip);
  22790. const char* sections[] = { "Intro", "Verse", "Chorus", "Outro" };
  22791. for (int i = 0; i < 4; ++i)
  22792. {
  22793. lynx::Marker m;
  22794. m.tick = i * 8 * bar;
  22795. m.name = sections[i];
  22796. song.addMarker (m);
  22797. }
  22798. offline.setSong (std::move (song)); // (also ends the plugins-off mode)
  22799. auto plain = lynx::makeExportPanel (offline, 0);
  22800. shoot (*plain, "export-default");
  22801. auto additions = lynx::makeExportPanelWithAdditions (offline);
  22802. shoot (*additions, "export");
  22803. }
  22804. }
  22805. // Round 190ox (modulators stage 2): the Modulators window with one modulator of each kind (the LFO in Assign mode),
  22806. // a native effect editor and the LYNX Synth page with modulation rings, the parameter menu's "Modulate with"
  22807. // submenu; checks in prefix-checks.txt. --shot-scale 1.5 --shot-suffix @150 for the 150 % pictures.
  22808. void runModShot190ox (const juce::String& prefix)
  22809. {
  22810. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22811. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  22812. juce::String checks;
  22813. int failures = 0;
  22814. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks + (failures == 0 ? "ALL OK\n" : juce::String (failures) + " FAILED\n")); };
  22815. const auto check = [&] (const juce::String& what, bool ok) {
  22816. checks << (ok ? "ok " : "FAIL ") << what << "\n";
  22817. failures += ok ? 0 : 1;
  22818. flush();
  22819. };
  22820. lynx::AudioEngine offline (false);
  22821. lynx::modring::setEngine (&offline);
  22822. const auto settle = [&] {
  22823. for (int k = 0; k < 3; ++k)
  22824. offline.dispatchPendingMessages();
  22825. };
  22826. const auto write = [&prefix, &settle] (juce::Component& c, const juce::String& name) {
  22827. settle();
  22828. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  22829. };
  22830. using namespace lynx;
  22831. offline.editSong ([] (Song& s) {
  22832. if (s.channels.size() < 2)
  22833. s.channels.resize (2);
  22834. s.channels[0].name = "Kick";
  22835. s.channels[0].instrument = InstrumentKind::sampler;
  22836. s.channels[0].mixerTrack = 1;
  22837. s.channels[1].name = "Keys";
  22838. s.channels[1].instrument = InstrumentKind::synth;
  22839. s.channels[1].mixerTrack = 2;
  22840. if (s.mixer.size() < 4)
  22841. s.mixer.resize (4);
  22842. s.mixer[1].name = "Kick";
  22843. s.mixer[2].name = "Keys";
  22844. s.mixer[2].effects.clear();
  22845. s.mixer[2].effects.push_back (makeEffectSlot (EffectKind::filter));
  22846. s.mixer[2].effects.push_back (makeEffectSlot (EffectKind::delay));
  22847. const AutomationTarget cutoff { AutomationTargetKind::effectParam, 2, 0, 1 }, res { AutomationTargetKind::effectParam, 2, 0, 2 }; // (the Filter's Cutoff, Reso.)
  22848. const AutomationTarget synthCutoff { AutomationTargetKind::channelParam, 1, 0, synthparam::target (synthparam::cutoff) };
  22849. const AutomationTarget synthRes { AutomationTargetKind::channelParam, 1, 0, synthparam::target (synthparam::resonance) };
  22850. s.modulators.clear();
  22851. auto add = [&s] (ModKind kind, const char* name, AutomationTarget host, std::vector<ModRoute> routes) {
  22852. auto m = Modulator::make (kind);
  22853. m.name = name;
  22854. m.host = host;
  22855. m.routes = std::move (routes);
  22856. s.modulators.push_back (m);
  22857. return (int) s.modulators.size() - 1;
  22858. };
  22859. const AutomationTarget onKick { AutomationTargetKind::mixerVolume, 1, 0, 0 }, onKeys { AutomationTargetKind::channelVolume, 1, 0, 0 };
  22860. add (ModKind::lfo, "LFO 1", { AutomationTargetKind::mixerVolume, 2, 0, 0 }, { { cutoff, 0.3f }, { synthCutoff, 0.2f } });
  22861. s.modulators.back().shape = ModShape::triangle;
  22862. add (ModKind::follower, "Follower 1", onKick, { { cutoff, -0.4f } });
  22863. s.modulators.back().input = { AutomationTargetKind::mixerVolume, 1, 0, 0 };
  22864. add (ModKind::envelope, "Envelope 1", onKeys, { { synthRes, 0.35f } });
  22865. add (ModKind::steps, "Steps 1", { AutomationTargetKind::mixerVolume, 2, 0, 0 }, { { res, 0.25f } });
  22866. add (ModKind::random, "Random 1", onKeys, { { synthCutoff, -0.15f } });
  22867. s.modulators.back().smooth = 0.5f;
  22868. add (ModKind::macro, "Macro 1", onKeys, { { synthRes, 0.2f }, { { AutomationTargetKind::effectParam, 2, 1, 0 }, 0.3f } });
  22869. s.modulators.back().macro = 0.4f;
  22870. add (ModKind::keytrack, "Keytrack 1", onKeys, { { synthCutoff, 0.1f } });
  22871. add (ModKind::velocity, "Velocity 1", onKeys, {});
  22872. }, false);
  22873. settle();
  22874. modring::setArmed (0);
  22875. // the Modulators window's panel, tall enough for every row
  22876. {
  22877. auto panel = makeModulatorsPanel (offline);
  22878. panel->setSize (900, 1500);
  22879. settle();
  22880. write (*panel, "modulators");
  22881. }
  22882. modring::setArmed (0); // (the panel ends Assign mode when it goes)
  22883. // a native editor's knobs with their rings (the filter's cutoff: LFO 1 armed, Follower 1)
  22884. {
  22885. modring::Ring ring;
  22886. check ("ring on the filter's cutoff: 2 routes, the armed one first",
  22887. modring::ringFor ({ AutomationTargetKind::effectParam, 2, 0, 1 }, ring) && ring.count == 2 && ring.armedRoute == 0);
  22888. if (auto editor = makeNativeEffectEditor (offline, 2, 0))
  22889. write (*editor, "filter-rings");
  22890. if (auto editor = makeNativeEffectEditor (offline, 2, 1))
  22891. write (*editor, "delay-rings");
  22892. modring::setArmed (-1);
  22893. if (auto editor = makeNativeEffectEditor (offline, 2, 0))
  22894. write (*editor, "filter-rings-unarmed");
  22895. }
  22896. // the LYNX Synth page: its tagged knobs show rings
  22897. {
  22898. auto page = makeChannelSettingsPanel (offline, 1);
  22899. page->setSize (juce::jmax (page->getWidth(), 760), juce::jmax (page->getHeight(), 520));
  22900. write (*page, "synth-rings");
  22901. }
  22902. // the parameter menu: the Modulate with submenu of a knob (the routed ones ticked, a new one of each kind)
  22903. {
  22904. juce::PopupMenu menu;
  22905. addAutomationItem (menu, offline, { AutomationTargetKind::effectParam, 2, 0, 1 }, true);
  22906. juce::PopupMenu modulate;
  22907. juce::StringArray rows;
  22908. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  22909. if (it.getItem().subMenu != nullptr && it.getItem().text == tr ("Modulate with"))
  22910. modulate = *it.getItem().subMenu;
  22911. for (juce::PopupMenu::MenuItemIterator it (modulate); it.next();)
  22912. rows.add (it.getItem().text);
  22913. check ("Modulate with: the routed ones and a new one of each kind (" + rows.joinIntoString (" | ") + ")",
  22914. rows.size() >= 8 + 8 + 1 && rows.contains (tr ("New {0}", { tr ("Envelope follower") })));
  22915. saveMenus (juce::StringArray { "Parameter menu", "Modulate with" }, std::vector<juce::PopupMenu> { menu, modulate },
  22916. prefix + "-menu.png");
  22917. }
  22918. modring::setEngine (nullptr);
  22919. flush();
  22920. }
  22921. void runGapShot190og (const juce::String& prefix)
  22922. {
  22923. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22924. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  22925. juce::String checks;
  22926. int failures = 0;
  22927. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks + (failures == 0 ? "ALL OK\n" : juce::String (failures) + " FAILED\n")); };
  22928. const auto check = [&] (const juce::String& what, bool ok) {
  22929. checks << (ok ? "ok " : "FAIL ") << what << "\n";
  22930. failures += ok ? 0 : 1;
  22931. flush();
  22932. };
  22933. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  22934. const auto menuRows = [] (const juce::PopupMenu& menu) {
  22935. juce::StringArray rows;
  22936. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  22937. rows.add (it.getItem().isSeparator ? juce::String ("--") : (it.getItem().isEnabled ? "" : "(off) ") + it.getItem().text.replace ("\t", " | "));
  22938. return rows;
  22939. };
  22940. const auto itemOf = [] (const juce::PopupMenu& menu, const juce::String& start) -> const juce::PopupMenu::Item* {
  22941. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  22942. if (! it.getItem().isSeparator && it.getItem().text.startsWith (start))
  22943. return &it.getItem();
  22944. return nullptr;
  22945. };
  22946. lynx::AudioEngine offline (false);
  22947. lynx::MainComponent ui (offline, false);
  22948. ui.setSize (1600, 900);
  22949. const auto settle = [&] {
  22950. for (int k = 0; k < 3; ++k)
  22951. offline.dispatchPendingMessages();
  22952. };
  22953. const auto write = [&prefix, &settle] (juce::Component& c, const juce::String& name) {
  22954. settle();
  22955. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  22956. };
  22957. const auto area = [&prefix, &settle] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) {
  22958. settle();
  22959. savePng (lynx::shot::snapshot (c).getClippedImage ((r.toFloat() * lynx::shot::scale()).toNearestInt()), prefix + "-" + name + ".png");
  22960. };
  22961. ui.setVisible (true);
  22962. lynx::DetailView::shownSetting = true;
  22963. lynx::DetailView::devicesPage = true;
  22964. ui.setClipLaunchWorkflow (true);
  22965. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  22966. const auto bar = 4 * lynx::ppq;
  22967. offline.editSong ([bar] (lynx::Song& s) {
  22968. if (s.channels.size() < 1)
  22969. s.channels.resize (1);
  22970. s.channels[0].name = "Keys";
  22971. s.channels[0].instrument = lynx::InstrumentKind::synth;
  22972. s.channels[0].mixerTrack = 2;
  22973. if (s.mixer.size() < 4)
  22974. s.mixer.resize (4);
  22975. s.mixer[2].name = "Keys";
  22976. s.mixer[2].effects.clear();
  22977. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  22978. s.mixer[2].effects.push_back (lynx::makeEffectSlot (kind));
  22979. while (s.patterns.size() < 1)
  22980. s.patterns.emplace_back();
  22981. auto& p = s.patterns[0];
  22982. p.name = "Chords";
  22983. p.notes.clear();
  22984. // a one-bar loop with a rising line; a note crossing the loop's end and one after it (Duplicate Loop / Crop)
  22985. const int keys[] { 60, 64, 67, 72, 71, 67, 64, 62 };
  22986. for (int i = 0; i < 8; ++i)
  22987. {
  22988. lynx::Note n;
  22989. n.channel = 0;
  22990. n.key = keys[i];
  22991. n.start = i * (bar / 8);
  22992. n.length = bar / 8 - 60;
  22993. n.velocity = (float) (40 + i * 10) / 127.0f;
  22994. p.notes.push_back (n);
  22995. }
  22996. lynx::Note tail;
  22997. tail.channel = 0;
  22998. tail.key = 55;
  22999. tail.start = bar + lynx::ppq;
  23000. tail.length = lynx::ppq;
  23001. p.notes.push_back (tail);
  23002. p.lengthTicks = 2 * bar;
  23003. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  23004. s.playlistTracks[1].name = "Keys";
  23005. lynx::Clip clip;
  23006. clip.pattern = 0;
  23007. clip.length = bar;
  23008. lynx::launcher::setClip (s, 1, 0, clip);
  23009. if (auto* c = const_cast<lynx::Clip*> (lynx::launcher::clipAt (*s.clipGrid, 1, 0)))
  23010. c->offset = 0, c->length = bar; // (a one-bar loop over the two-bar pattern)
  23011. }, false);
  23012. settle();
  23013. ui.resized();
  23014. auto* detail = ui.getDetailViewForSnapshot();
  23015. auto* grid = ui.getClipGridForSnapshot();
  23016. if (detail == nullptr || grid == nullptr)
  23017. {
  23018. check ("the Clip-launch layout has its detail view and grid", false);
  23019. return;
  23020. }
  23021. const auto editMenu = [&ui] {
  23022. const auto names = ui.getMenuNamesForSnapshot();
  23023. return ui.getMenuForSnapshot (juce::jmax (0, names.indexOf (lynx::tr ("Edit"))));
  23024. };
  23025. const auto fxNames = [&offline] {
  23026. juce::StringArray names;
  23027. for (const auto& fx : offline.getSong().mixer[2].effects)
  23028. names.add (juce::String ((int) fx.kind));
  23029. return names.joinIntoString (",");
  23030. };
  23031. // --- deviceview-0012: the Edit menu's Live block on the Device View ---------------------------------------------
  23032. detail->showSelection (1, 0);
  23033. detail->setPage (lynx::DetailView::Page::devices);
  23034. settle();
  23035. detail->selectCardForCheck (2); // (card 0 the instrument, 1 the EQ, 2 the Compressor)
  23036. settle();
  23037. write (ui, "01-devices-window");
  23038. write (*detail, "01b-devices");
  23039. {
  23040. const auto menu = editMenu();
  23041. saveMenus (juce::StringArray { lynx::tr ("Edit") }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-edit-menu-device.png");
  23042. line ("Edit menu: " + menuRows (menu).joinIntoString (" // "));
  23043. const auto* cut = itemOf (menu, lynx::tr ("Cut") + "\t");
  23044. const auto* paste = itemOf (menu, lynx::tr ("Paste") + "\t");
  23045. check ("Edit menu (Clip-launch): Live's Cut | Ctrl+X, Copy, Paste, Duplicate, Delete | Del after Undo / Redo",
  23046. cut != nullptr && cut->text.endsWith ("Ctrl+X") && itemOf (menu, lynx::tr ("Copy") + "\tCtrl+C") != nullptr
  23047. && paste != nullptr && itemOf (menu, lynx::tr ("Duplicate") + "\tCtrl+D") != nullptr && itemOf (menu, lynx::tr ("Delete") + "\tDel") != nullptr
  23048. && menuRows (menu).indexOf ("--") < menuRows (menu).indexOf (lynx::tr ("Cut") + " | Ctrl+X"));
  23049. check ("a selected device: Cut / Copy / Duplicate / Delete on, Paste off with nothing copied", cut != nullptr && cut->isEnabled && paste != nullptr && ! paste->isEnabled);
  23050. }
  23051. const auto invoke = [&] (const juce::String& start) {
  23052. const auto menu = editMenu();
  23053. if (const auto* item = itemOf (menu, start); item != nullptr && item->isEnabled && item->action != nullptr)
  23054. {
  23055. item->action();
  23056. settle();
  23057. return true;
  23058. }
  23059. return false;
  23060. };
  23061. line ("effects before: " + fxNames());
  23062. check ("Edit > Copy on the Compressor", invoke (lynx::tr ("Copy") + "\t"));
  23063. detail->selectCardForCheck (3); // the Delay
  23064. settle();
  23065. check ("Edit > Paste with the Delay selected: in front of it (Live: \"Pasted devices are inserted in front of the selected device\")",
  23066. invoke (lynx::tr ("Paste") + "\t") && fxNames() == juce::String ((int) lynx::EffectKind::eq) + "," + juce::String ((int) lynx::EffectKind::compressor) + ","
  23067. + juce::String ((int) lynx::EffectKind::compressor) + "," + juce::String ((int) lynx::EffectKind::delay));
  23068. line ("effects after Paste: " + fxNames());
  23069. write (*detail, "03-devices-after-paste");
  23070. check ("Edit > Duplicate", invoke (lynx::tr ("Duplicate") + "\t") && offline.getSong().mixer[2].effects.size() == 5);
  23071. check ("Edit > Delete", invoke (lynx::tr ("Delete") + "\t") && offline.getSong().mixer[2].effects.size() == 4);
  23072. detail->selectCardForCheck (2); // (Delete left nothing selected)
  23073. settle();
  23074. check ("Edit > Cut", invoke (lynx::tr ("Cut") + "\t") && offline.getSong().mixer[2].effects.size() == 3);
  23075. line ("effects after Duplicate, Delete, Cut: " + fxNames());
  23076. // the Pattern layout keeps FL's Edit menu
  23077. ui.setClipLaunchWorkflow (false);
  23078. settle();
  23079. check ("the Pattern layout's Edit menu has no Live block", itemOf (editMenu(), lynx::tr ("Cut") + "\t") == nullptr);
  23080. ui.setClipLaunchWorkflow (true);
  23081. settle();
  23082. ui.resized();
  23083. // --- detail-019: the Clip panel's Duplicate (Loop) button ------------------------------------------------------
  23084. detail->showSelection (1, 0);
  23085. detail->setPage (lynx::DetailView::Page::clip);
  23086. detail->setClipTab (false);
  23087. lynx::DetailView::devicesPage = false;
  23088. detail->clipSectionsForSnapshot (true, true, true, 0);
  23089. settle();
  23090. ui.resized();
  23091. write (ui, "04-clip-window");
  23092. write (*detail, "04b-clip-detail");
  23093. const auto clipNow = [&offline] () -> lynx::Clip {
  23094. const auto& g = offline.getSong().clipGrid;
  23095. const auto* c = g ? lynx::launcher::clipAt (*g, 1, 0) : nullptr;
  23096. return c != nullptr ? *c : lynx::Clip();
  23097. };
  23098. const auto noteCount = [&offline] { return (int) offline.getSong().patterns[0].notes.size(); };
  23099. // (the grid keeps a MIDI clip as long as its pattern: the loop is the pattern's two bars, all 9 notes inside it)
  23100. const auto loopBefore = clipNow().length;
  23101. int inLoop = 0;
  23102. for (const auto& n : offline.getSong().patterns[0].notes)
  23103. inLoop += n.start >= clipNow().offset && n.start < clipNow().offset + loopBefore ? 1 : 0;
  23104. const auto lastBefore = offline.getSong().patterns[0].notes.back().start;
  23105. line ("before: loop " + juce::String (clipNow().offset) + " + " + juce::String (loopBefore) + ", " + juce::String (noteCount()) + " notes, "
  23106. + juce::String (inLoop) + " in the loop");
  23107. check ("the clip is a MIDI clip with 9 notes in its pattern", loopBefore > 0 && noteCount() == 9);
  23108. check ("the Duplicate button pressed", detail->duplicateLoopForCheck());
  23109. settle();
  23110. line ("after Duplicate Loop: loop " + juce::String (clipNow().offset) + " + " + juce::String (clipNow().length) + ", " + juce::String (noteCount()) + " notes, last at "
  23111. + juce::String (offline.getSong().patterns[0].notes.back().start));
  23112. check ("Duplicate Loop: the loop twice as long, the notes in it copied one loop later",
  23113. clipNow().length == 2 * loopBefore && noteCount() == 9 + inLoop && offline.getSong().patterns[0].notes.back().start == lastBefore + loopBefore);
  23114. write (*detail, "05-clip-after-duplicate-loop");
  23115. check ("one undo step brings the one-bar loop back", [&] { ui.runActionForSnapshot ("edit.undo"); settle(); return clipNow().length == loopBefore && noteCount() == 9; }());
  23116. // --- detail-047: the Velocity lane's Randomize footer ---------------------------------------------------------
  23117. auto& roll = ui.getPianoRollForSnapshot();
  23118. roll.setLaneForSnapshot (lynx::PianoRollComponent::laneVelocity);
  23119. settle();
  23120. ui.resized();
  23121. settle();
  23122. const auto footer = roll.liveRandomizeBoundsForCheck();
  23123. line ("roll " + roll.getBounds().toString() + ", footer " + juce::String (roll.liveFooterHeight()) + " px, Randomize " + footer.toString());
  23124. check ("the docked roll (Live look) shows Live's Velocity footer with Randomize", roll.liveFooterHeight() == lynx::PianoRollComponent::liveFooterBar && ! footer.isEmpty());
  23125. write (ui, "06-velocity-footer-window");
  23126. if (roll.getParentComponent() != nullptr)
  23127. area (roll, roll.getLocalBounds().removeFromBottom (90), "06b-velocity-footer");
  23128. {
  23129. std::vector<float> before;
  23130. for (const auto& n : offline.getSong().patterns[0].notes)
  23131. before.push_back (n.velocity);
  23132. lynx::PianoRollComponent::liveRandomizeAmount = 20;
  23133. roll.liveRandomizeVelocity();
  23134. settle();
  23135. int moved = 0, within = 0;
  23136. const auto& notes = offline.getSong().patterns[0].notes;
  23137. for (std::size_t i = 0; i < notes.size() && i < before.size(); ++i)
  23138. {
  23139. const auto d = std::abs (juce::roundToInt (notes[i].velocity * 127.0f) - juce::roundToInt (before[i] * 127.0f));
  23140. moved += d > 0 ? 1 : 0;
  23141. within += d <= 20 ? 1 : 0;
  23142. }
  23143. line ("Randomize (amount 20, nothing selected): " + juce::String (moved) + " of " + juce::String ((int) notes.size()) + " notes moved");
  23144. check ("Randomize with nothing selected moves the notes' velocities by at most the amount", moved > 0 && within == (int) notes.size());
  23145. lynx::PianoRollComponent::liveRandomizeAmount = 100;
  23146. write (ui, "07-velocity-after-randomize");
  23147. }
  23148. // --- detail-020: Crop Clip in the clip's menu and on Ctrl+Shift+J ---------------------------------------------
  23149. {
  23150. const auto menu = lynx::clipGridSlotMenu (*grid, 1, 0);
  23151. saveMenus (juce::StringArray { "Clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-08-clip-menu.png");
  23152. line ("clip menu: " + menuRows (menu).joinIntoString (" // "));
  23153. const auto rows = menuRows (menu);
  23154. const auto crop = rows.indexOf (lynx::tr ("Crop Clip") + " | Ctrl+Shift+J");
  23155. check ("the clip menu (Live look) has Crop Clip | Ctrl+Shift+J in its own group before the colours",
  23156. crop > 0 && rows[crop - 1] == "--" && rows[crop + 1] == "--" && rows.indexOf (lynx::tr ("Deactivate Clip") + " | 0") < crop);
  23157. }
  23158. offline.editSong ([bar] (lynx::Song& s) {
  23159. if (auto* c = s.clipGrid ? const_cast<lynx::Clip*> (lynx::launcher::clipAt (*s.clipGrid, 1, 0)) : nullptr)
  23160. c->offset = bar / 2, c->length = bar / 2; // the loop on the second half bar
  23161. });
  23162. settle();
  23163. lynx::selectClipGridSlotForSnapshot (*grid, 1, 0);
  23164. const auto keyed = lynx::clipGridKeyForSnapshot (*grid, juce::KeyPress ('j', juce::ModifierKeys::commandModifier | juce::ModifierKeys::shiftModifier, 0));
  23165. settle();
  23166. juce::String kept;
  23167. for (const auto& n : offline.getSong().patterns[0].notes)
  23168. kept << n.start << ":" << n.key << " ";
  23169. line ("after Ctrl+Shift+J: loop " + juce::String (clipNow().offset) + " + " + juce::String (clipNow().length) + ", notes " + kept);
  23170. check ("Ctrl+Shift+J crops the clip: the half bar's 4 notes kept, moved to the start; the loop starts at 0",
  23171. keyed && noteCount() == 4 && offline.getSong().patterns[0].notes.front().start == 0 && clipNow().offset == 0 && clipNow().length == bar / 2);
  23172. write (*detail, "09-clip-after-crop");
  23173. // --- mapping-0028: Key Map Mode on the transport switches -------------------------------------------------------
  23174. {
  23175. using namespace lynx::remotemap;
  23176. offline.editSong ([] (lynx::Song& s) {
  23177. assignKey (s, Target::of (lynx::RemoteAction::overdub), 'O');
  23178. assignKey (s, Target::of (lynx::RemoteAction::loopSwitch), 'L');
  23179. assignKey (s, Target::of (lynx::RemoteAction::punchIn), 'I');
  23180. assignKey (s, Target::of (lynx::RemoteAction::punchOut), 'U');
  23181. });
  23182. settle();
  23183. for (const auto mode : { Mode::key, Mode::midi })
  23184. {
  23185. ui.setMapMode (mode);
  23186. settle();
  23187. if (auto* overlay = ui.mapOverlayForSnapshot())
  23188. {
  23189. overlay->refresh();
  23190. const auto& spots = overlay->spots();
  23191. const auto count = [&spots] (lynx::RemoteAction a) { return (int) std::count_if (spots.begin(), spots.end(), [a] (const auto& sp) { return sp.target.action == a; }); };
  23192. line (juce::String (mode == Mode::key ? "key" : "midi") + " map: " + juce::String ((int) spots.size()) + " spots; overdub " + juce::String (count (lynx::RemoteAction::overdub))
  23193. + ", loop " + juce::String (count (lynx::RemoteAction::loopSwitch)) + ", punch in " + juce::String (count (lynx::RemoteAction::punchIn)) + ", punch out "
  23194. + juce::String (count (lynx::RemoteAction::punchOut)));
  23195. check (juce::String (mode == Mode::key ? "Key" : "MIDI") + " Map Mode: Arrangement Overdub, Loop, Punch-In and Punch-Out are mappable in the Control Bar",
  23196. count (lynx::RemoteAction::overdub) == 1 && count (lynx::RemoteAction::loopSwitch) == 1 && count (lynx::RemoteAction::punchIn) == 1
  23197. && count (lynx::RemoteAction::punchOut) == 1);
  23198. }
  23199. write (ui, mode == Mode::key ? "10-keymap" : "11-midimap");
  23200. if (mode == Mode::key)
  23201. area (ui, ui.getLocalBounds().removeFromTop (60), "10b-keymap-controlbar");
  23202. if (mode == Mode::key)
  23203. if (auto* browser = ui.mappingBrowserForSnapshot())
  23204. write (*browser, "12-key-mappings-browser");
  23205. }
  23206. ui.setMapMode (Mode::off);
  23207. settle();
  23208. // the mapped keys switch them, and the mappings survive a save
  23209. const auto options = [&offline] { return offline.getRecordOptions(); };
  23210. const auto blend = options().mode;
  23211. const auto loopBefore = offline.getSong().loopPlays();
  23212. const auto inBefore = options().punchLoopRegion && options().punchIn;
  23213. const auto press = [&] (int key) {
  23214. for (const auto& f : keyFires (offline.getSong(), key, true))
  23215. ui.fireRemote (f);
  23216. settle();
  23217. };
  23218. press ('O');
  23219. press ('L');
  23220. press ('I');
  23221. check ("the mapped keys switch Overdub, Loop and Punch-In", options().mode != blend && offline.getSong().loopPlays() != loopBefore
  23222. && (options().punchLoopRegion && options().punchIn) != inBefore);
  23223. juce::String error;
  23224. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  23225. int kept4 = 0;
  23226. if (back)
  23227. for (const auto& m : back->remoteMappings)
  23228. kept4 += m.action == lynx::RemoteAction::overdub || m.action == lynx::RemoteAction::loopSwitch || m.action == lynx::RemoteAction::punchIn
  23229. || m.action == lynx::RemoteAction::punchOut ? 1 : 0;
  23230. check ("the four mappings are saved with the project and read back", kept4 == 4);
  23231. }
  23232. flush();
  23233. }
  23234. void runUndoShot190mz (const juce::String& prefix)
  23235. {
  23236. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23237. juce::String report;
  23238. int failures = 0;
  23239. const auto check = [&] (const juce::String& name, bool ok) {
  23240. report << (ok ? "OK " : "FAIL ") << name << "\n";
  23241. failures += ok ? 0 : 1;
  23242. };
  23243. {
  23244. lynx::AudioEngine engine (false);
  23245. lynx::MainComponent ui (engine, false);
  23246. ui.setSize (1600, 900);
  23247. engine.dispatchPendingMessages();
  23248. // FL 2026's default: Ctrl+Z steps back
  23249. check ("alternate undo mode is on by default (FL 2026)", ui.getAlternateUndo());
  23250. const auto editMenuText = [&ui] {
  23251. const auto names = ui.getMenuNamesForSnapshot();
  23252. juce::StringArray rows;
  23253. const auto menu = ui.getMenuForSnapshot (juce::jmax (0, names.indexOf (lynx::tr ("Edit"))));
  23254. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23255. {
  23256. if (it.getItem().isSeparator)
  23257. break;
  23258. rows.add ((it.getItem().isEnabled ? "" : "(off) ") + it.getItem().text.replace ("\t", " | "));
  23259. }
  23260. return rows;
  23261. };
  23262. const auto saveEditMenu = [&ui, &prefix] (const juce::String& name) {
  23263. const auto names = ui.getMenuNamesForSnapshot();
  23264. const auto index = juce::jmax (0, names.indexOf (lynx::tr ("Edit")));
  23265. saveMenus (juce::StringArray { names[index] }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-menu-" + name + ".png");
  23266. };
  23267. const auto key = [&ui, &engine] (const char* action) {
  23268. ui.runActionForSnapshot (action);
  23269. engine.dispatchPendingMessages();
  23270. };
  23271. const auto bpm = [&engine] { return engine.getSong().bpm; };
  23272. const auto start = bpm();
  23273. const auto swing0 = engine.getSong().swing;
  23274. const auto log = [&] (const juce::String& state) {
  23275. report << " " << state << ": bpm " << bpm() << ", level " << engine.getHistoryPosition() + 1 << "/" << engine.getHistorySize()
  23276. << ", Edit menu: " << editMenuText().joinIntoString (" // ") << "\n";
  23277. };
  23278. log ("fresh");
  23279. saveEditMenu ("pattern-0-fresh");
  23280. engine.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  23281. engine.editSong ([] (lynx::Song& s) { s.swing = s.swing == 0.25f ? 0.5f : 0.25f; });
  23282. engine.editSong ([] (lynx::Song& s) { s.bpm = 103.0; });
  23283. engine.dispatchPendingMessages();
  23284. log ("three edits");
  23285. saveEditMenu ("pattern-1-three-edits");
  23286. check ("menu names the step: Undo Tempo | Ctrl+Z, no Redo item (FL)",
  23287. editMenuText()[0].startsWith (lynx::tr ("Undo {0}", { lynx::tr ("Tempo") })) && editMenuText()[0].contains ("Ctrl+Z")
  23288. && ! editMenuText()[1].startsWith (lynx::tr ("Redo {0}", { lynx::tr ("Tempo") })));
  23289. // the reporter's case (issue #214): Ctrl+Z pressed again keeps going back
  23290. key ("edit.undo");
  23291. log ("Ctrl+Z");
  23292. saveEditMenu ("pattern-2-alt-ctrl-z");
  23293. check ("alternate: menu shows Undo Swing | Ctrl+Z and Redo Tempo | Ctrl+Alt+Z (FL)",
  23294. editMenuText()[0].startsWith (lynx::tr ("Undo {0}", { lynx::tr ("Swing") })) && editMenuText()[0].endsWith ("Ctrl+Z")
  23295. && editMenuText()[1].startsWith (lynx::tr ("Redo {0}", { lynx::tr ("Tempo") })) && editMenuText()[1].endsWith ("Ctrl+Alt+Z"));
  23296. key ("edit.undo");
  23297. log ("Ctrl+Z x2");
  23298. check ("alternate: Ctrl+Z twice goes two steps back (swing undone, bpm 101)", bpm() == 101.0 && engine.getSong().swing == swing0);
  23299. key ("edit.undo");
  23300. key ("edit.undo"); // (nothing left: nothing happens, no redo)
  23301. log ("Ctrl+Z x4");
  23302. check ("alternate: Ctrl+Z walks to the start and stops there", bpm() == start && ! engine.canUndo() && engine.canRedo());
  23303. saveEditMenu ("pattern-3-alt-at-start");
  23304. key ("edit.redo");
  23305. check ("alternate: Ctrl+Y / Ctrl+Shift+Z redo one step", bpm() == 101.0);
  23306. key ("edit.redo");
  23307. key ("edit.redo");
  23308. check ("alternate: redo back to the newest state", bpm() == 103.0 && ! engine.canRedo());
  23309. key ("edit.undo");
  23310. key ("edit.undoBackwards");
  23311. check ("alternate: Ctrl+Alt+Z redoes what was undone (FL swaps the two keys)", bpm() == 103.0 && ! engine.canRedo());
  23312. // FL's other mode: Ctrl+Z undoes, then redoes (the toggle the issue describes); Ctrl+Alt+Z walks back
  23313. ui.setAlternateUndoForSnapshot (false);
  23314. key ("edit.undo");
  23315. log ("default mode, Ctrl+Z");
  23316. saveEditMenu ("pattern-4-toggle-ctrl-z");
  23317. check ("toggle mode: menu shows Undo Swing | Ctrl+Alt+Z and Redo Tempo | Ctrl+Z (FL)",
  23318. editMenuText()[0].startsWith (lynx::tr ("Undo {0}", { lynx::tr ("Swing") })) && editMenuText()[0].endsWith ("Ctrl+Alt+Z")
  23319. && editMenuText()[1].startsWith (lynx::tr ("Redo {0}", { lynx::tr ("Tempo") })) && editMenuText()[1].endsWith ("Ctrl+Z"));
  23320. key ("edit.undo");
  23321. log ("default mode, Ctrl+Z x2");
  23322. check ("toggle mode: Ctrl+Z again redoes the step", bpm() == 103.0 && ! engine.canRedo());
  23323. key ("edit.undoBackwards");
  23324. key ("edit.undoBackwards");
  23325. check ("toggle mode: Ctrl+Alt+Z walks back", bpm() == 101.0 && engine.getSong().swing == swing0);
  23326. key ("edit.undo");
  23327. check ("toggle mode: Ctrl+Z after walking back redoes one step (FL: position - 1)", engine.getSong().swing != swing0 && bpm() == 101.0);
  23328. key ("edit.redo");
  23329. check ("toggle mode: Ctrl+Y / Ctrl+Shift+Z redo", bpm() == 103.0 && ! engine.canRedo());
  23330. // Clip-launch and Simple: Live's form (both items, "Nothing to redo", redo on Ctrl+Y)
  23331. ui.setAlternateUndoForSnapshot (true);
  23332. for (const auto style : { lynx::layoutstyle::Style::clipLaunch, lynx::layoutstyle::Style::simple })
  23333. {
  23334. const juce::String name = style == lynx::layoutstyle::Style::simple ? "simple" : "cliplaunch";
  23335. ui.setLayoutStyle (style);
  23336. engine.dispatchPendingMessages();
  23337. log (name);
  23338. saveEditMenu (name + "-1-newest");
  23339. check (name + ": Undo Tempo | Ctrl+Z, Nothing to redo | Ctrl+Y",
  23340. editMenuText()[0].startsWith (lynx::tr ("Undo {0}", { lynx::tr ("Tempo") })) && editMenuText()[0].endsWith ("Ctrl+Z")
  23341. && editMenuText()[1].startsWith ("(off) " + lynx::tr ("Nothing to redo")) && editMenuText()[1].endsWith ("Ctrl+Y"));
  23342. key ("edit.undo");
  23343. key ("edit.undo");
  23344. log (name + ", Ctrl+Z x2");
  23345. saveEditMenu (name + "-2-ctrl-z-x2");
  23346. check (name + ": Ctrl+Z twice goes two steps back", bpm() == 101.0 && engine.getSong().swing == swing0);
  23347. key ("edit.redo");
  23348. key ("edit.redo");
  23349. check (name + ": Ctrl+Y redoes both", bpm() == 103.0 && ! engine.canRedo());
  23350. }
  23351. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  23352. engine.dispatchPendingMessages();
  23353. }
  23354. report << (failures == 0 ? "ALL OK\n" : juce::String (failures) + " FAILED\n");
  23355. juce::File (prefix + "-checks.txt").replaceWithText (report);
  23356. }
  23357. void runGamepadShot (const juce::String& prefix)
  23358. {
  23359. juce::String report;
  23360. int failures = 0;
  23361. {
  23362. lynx::AudioEngine engine (false);
  23363. auto hints = lynx::makeGamepadHints();
  23364. savePng (lynx::shot::snapshot (*hints), prefix + "-hints.png");
  23365. auto prefs = engine.getMidiPrefs();
  23366. prefs.gamepad = true;
  23367. engine.setMidiPrefs (prefs, false);
  23368. auto page = lynx::makeMidiPage (engine, {}, false);
  23369. page->setSize (760, 1400);
  23370. savePng (lynx::shot::snapshot (*page), prefix + "-settings.png");
  23371. // the poller with fake states: what the handler gets
  23372. using namespace lynx::gamepad;
  23373. std::vector<std::string> got;
  23374. lynx::GamepadInput input ([&got] (const Changes& c, const State&, double dt) {
  23375. for (int i = 0; i < c.pressedCount; ++i)
  23376. got.push_back (std::string ("press ") + buttonName (c.pressed[(std::size_t) i]));
  23377. for (int i = 0; i < c.releasedCount; ++i)
  23378. got.push_back (std::string ("release ") + buttonName (c.released[(std::size_t) i]));
  23379. for (int i = 0; i < c.controllerCount; ++i)
  23380. got.push_back ("cc " + std::to_string (c.controller[(std::size_t) i]) + "=" + std::to_string (c.value[(std::size_t) i]));
  23381. if (c.connectedChanged)
  23382. got.push_back ("connected changed");
  23383. got.push_back ("dt " + std::to_string ((int) std::lround (dt * 1000)));
  23384. });
  23385. State pad;
  23386. pad.connected = true;
  23387. input.inject (pad, 1.0 / 60.0);
  23388. pad.buttons = mask (Button::a);
  23389. pad.rightTrigger = 255;
  23390. input.inject (pad, 1.0 / 60.0);
  23391. pad.buttons = 0;
  23392. input.inject (pad, 1.0 / 60.0);
  23393. const std::vector<std::string> expected { "connected changed", "dt 17", "press A", "cc 102=127", "cc 21=127", "dt 17",
  23394. "release A", "cc 102=0", "dt 17" };
  23395. for (const auto& line : got)
  23396. report << line << "\n";
  23397. if (got != expected)
  23398. {
  23399. ++failures;
  23400. report << "FAILED: the poller's changes differ from the expected ones\n";
  23401. }
  23402. report << "xinput " << (input.available() ? "loaded" : "not available") << "\n";
  23403. }
  23404. report << (failures == 0 ? "gamepad OK" : "gamepad FAILED") << "\n";
  23405. juce::File (prefix + "-gamepad.txt").replaceWithText (report);
  23406. setApplicationReturnValue (failures == 0 ? 0 : 1);
  23407. quit();
  23408. }
  23409. void runBundleExport (const juce::String& inputPath, const juce::String& folderPath, bool zip, bool mixdown, const juce::String& shotPrefix)
  23410. {
  23411. juce::String error;
  23412. bool ok = false;
  23413. lynx::otherapps::Result result;
  23414. {
  23415. lynx::AudioEngine loader (false);
  23416. const juce::File input (inputPath);
  23417. if (input.hasFileExtension ("flp;als"))
  23418. ok = loader.importFlpFile (input, error);
  23419. else if (auto song = lynx::ProjectFile::load (input, error))
  23420. {
  23421. loader.setSong (std::move (*song));
  23422. ok = true;
  23423. }
  23424. if (ok)
  23425. {
  23426. loader.capturePluginStates();
  23427. lynx::otherapps::Context context;
  23428. context.host = &loader.getPluginHost();
  23429. context.flOptions = lynx::flstudio::optionsFor (context.host, lynx::flpexport::LynxOnly::renderAudio, loader.getSong());
  23430. context.render = [] (const lynx::Song& s, const lynx::exportopts::Options& o, const juce::File& file,
  23431. const std::function<bool (double)>& progress, juce::String& err) {
  23432. lynx::ExportJob job (s, o, file);
  23433. return job.run (progress, err);
  23434. };
  23435. context.onMessageThread = [] (std::function<void()> f) { f(); };
  23436. lynx::exportbundle::Options options;
  23437. options.zip = zip;
  23438. options.mixdown = mixdown;
  23439. const auto name = input.getFileNameWithoutExtension();
  23440. const auto shot = [&shotPrefix] (juce::Component& c, const juce::String& suffix) {
  23441. if (shotPrefix.isNotEmpty())
  23442. savePng (lynx::shot::snapshot (c), shotPrefix + suffix);
  23443. };
  23444. if (auto panel = lynx::makeOtherAppsExportPanel (loader, name))
  23445. shot (*panel, "-panel.png");
  23446. ok = lynx::otherapps::write (loader.getSong(), name, options, juce::File (folderPath), context, result);
  23447. if (auto report = lynx::makeOtherAppsReportPanel (result.folder, result.written, result.failed))
  23448. shot (*report, "-report.png");
  23449. }
  23450. }
  23451. juce::String report;
  23452. report << (ok ? "ok " + result.folder.getFullPathName() : "error=" + error) << "\n";
  23453. for (const auto& w : result.written)
  23454. report << "written " << w << "\n";
  23455. for (const auto& f : result.failed)
  23456. report << "failed " << f << "\n";
  23457. juce::File (folderPath).getChildFile ("export-bundle.txt").replaceWithText (report);
  23458. setApplicationReturnValue (ok && result.failed.isEmpty() ? 0 : 1);
  23459. quit();
  23460. }
  23461. void runFlExport (const juce::String& inputPath, const juce::String& outputPath, bool substitute)
  23462. {
  23463. juce::String error;
  23464. bool ok = false;
  23465. lynx::flstudio::Written written;
  23466. {
  23467. lynx::AudioEngine loader (false);
  23468. const juce::File input (inputPath);
  23469. // a Live set opens through the same import as an .flp (as File › Open does, and --export-als accepts an .flp)
  23470. if (input.hasFileExtension ("flp;als"))
  23471. ok = loader.importFlpFile (input, error);
  23472. else if (auto song = lynx::ProjectFile::load (input, error))
  23473. {
  23474. loader.setSong (std::move (*song));
  23475. ok = true;
  23476. }
  23477. if (ok)
  23478. {
  23479. const juce::File output (outputPath);
  23480. const auto zip = output.hasFileExtension ("zip");
  23481. const auto mode = substitute ? lynx::flpexport::LynxOnly::substitute : lynx::flpexport::LynxOnly::renderAudio;
  23482. loader.capturePluginStates();
  23483. auto options = lynx::flstudio::optionsFor (&loader.getPluginHost(), mode, loader.getSong());
  23484. // --flp-ppq N: the file's PPQ (tests; default: 96 when the notes and clips fit it)
  23485. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--flp-ppq"))
  23486. options.ppq = juce::jlimit (0, 960, args[args.indexOf ("--flp-ppq") + 1].getIntValue());
  23487. const auto renderDir = zip ? juce::File::getSpecialLocation (juce::File::tempDirectory).getNonexistentChildFile ("LYNX FL export", {}, false)
  23488. : output.getSiblingFile (output.getFileNameWithoutExtension() + " audio");
  23489. ok = lynx::flstudio::exportProject (loader.getSong(), options, output, zip, renderDir, 44100.0,
  23490. [] (const lynx::Song& s, const lynx::ExportSettings& settings, const juce::File& wav,
  23491. const std::function<bool (double)>& progress, juce::String& err) {
  23492. lynx::ExportJob job (s, settings, wav);
  23493. return job.run (progress, err);
  23494. },
  23495. {}, written, error);
  23496. if (zip)
  23497. renderDir.deleteRecursively();
  23498. }
  23499. }
  23500. juce::String report;
  23501. report << (ok ? "ok" : "error=" + error) << "\n"
  23502. << "exact=" << (int) written.report.exact.size() << " rendered=" << (int) written.report.rendered.size()
  23503. << " substituted=" << (int) written.report.substituted.size() << " dropped=" << (int) written.report.dropped.size()
  23504. << " samples=" << written.samples << "\n\n"
  23505. << lynx::flstudio::reportText (written) << "\n";
  23506. juce::File (outputPath + ".txt").replaceWithText (report);
  23507. setApplicationReturnValue (ok ? 0 : 1);
  23508. quit();
  23509. }
  23510. // LYNX.exe --export project.(flp|als|lynx) output.(wav|flac|ogg|mp3|aif|aiff|m4a|aac) [--pattern] [--insert N] [--rate N]
  23511. // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail. .aif / .aiff: 24-bit AIFF;
  23512. // .m4a: AAC at 192 kbps through the system's encoder (engine/AacEncoder.h; .aac writes the same MPEG-4 file under the
  23513. // name .m4a). M4A is not available on Linux: the export stops with that message.
  23514. void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
  23515. {
  23516. juce::String error, report;
  23517. bool ok = false;
  23518. const auto started = juce::Time::getMillisecondCounterHiRes();
  23519. lynx::loadtrace::begin (inputPath.toStdString()); // phase times (round 112): report lines + load.log
  23520. {
  23521. lynx::AudioEngine loader (false);
  23522. const juce::File input (inputPath);
  23523. // --find-plugins: first the targeted scan opening the project in the app runs (its plugins not known yet)
  23524. if (input.hasFileExtension ("flp") && juce::JUCEApplication::getCommandLineParameters().contains ("--find-plugins"))
  23525. {
  23526. juce::MemoryBlock data;
  23527. if (input.loadFileAsData (data))
  23528. try
  23529. {
  23530. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  23531. auto& host = loader.getPluginHost();
  23532. const auto listed = std::chrono::steady_clock::now();
  23533. const auto files = host.filesToScanFor (uses);
  23534. lynx::loadtrace::add ("plugin_scan_list", lynx::loadtrace::msSince (listed));
  23535. report << "scanned=" << files.joinIntoString (";") << "\n";
  23536. const auto scanned = std::chrono::steady_clock::now();
  23537. host.scanFiles (files, {});
  23538. lynx::loadtrace::add ("plugin_scan", lynx::loadtrace::msSince (scanned), files.size());
  23539. }
  23540. catch (const flp::Error&)
  23541. {
  23542. }
  23543. }
  23544. if (input.hasFileExtension ("flp;als;mod;xm;s3m;it")) // a Live set opens through the same import (round 182b); a module too (190nw)
  23545. ok = loader.importFlpFile (input, error);
  23546. else if (auto song = lynx::ProjectFile::load (input, error))
  23547. {
  23548. loader.setSong (std::move (*song));
  23549. ok = true;
  23550. }
  23551. // M4A without a system AAC encoder (Linux): said before anything is rendered
  23552. if (ok && juce::File (outputPath).hasFileExtension ("m4a;aac") && ! lynx::aac::available())
  23553. {
  23554. ok = false;
  23555. error = juce::String::fromUTF8 (lynx::aac::unavailableReason().c_str());
  23556. }
  23557. if (ok)
  23558. {
  23559. // (an .aac name gets the MPEG-4 file it holds: .m4a)
  23560. const juce::File output (juce::File (outputPath).hasFileExtension ("aac") ? juce::File (outputPath).withFileExtension ("m4a") : juce::File (outputPath));
  23561. lynx::ExportSettings settings;
  23562. settings.wholeSong = ! patternOnly;
  23563. settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
  23564. : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
  23565. : lynx::ExportSettings::Format::wav24;
  23566. // --insert N: only that insert's output (what "Render to audio" records)
  23567. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
  23568. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
  23569. loader.editSong ([] (lynx::Song& s) {
  23570. for (auto& t : s.mixer)
  23571. t.effects.clear();
  23572. }, false);
  23573. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
  23574. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
  23575. loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
  23576. const auto loaded = juce::Time::getMillisecondCounterHiRes();
  23577. // .mp3: the Export window's MP3 (320 kbps); everything else as before
  23578. auto options = settings.toOptions();
  23579. // --save-tempo: FL's "Tempo information" (acid chunk) on (round 167l: compare with FL's AcidBox render; --export)
  23580. if (juce::JUCEApplication::getCommandLineParameters().contains ("--save-tempo"))
  23581. options.saveTempo = true;
  23582. // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
  23583. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
  23584. options.pluginWarmUp = false;
  23585. // --rate N: render at another sample rate (round 157b: samples resampled as at a 48 kHz device)
  23586. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--rate"))
  23587. if (const auto rate = args[args.indexOf ("--rate") + 1].getDoubleValue(); rate >= 8000.0 && rate <= 384000.0)
  23588. options.sampleRate = rate;
  23589. if (output.hasFileExtension ("mp3"))
  23590. {
  23591. options.format = lynx::exportopts::Format::mp3;
  23592. options.mp3Kbps = 320;
  23593. }
  23594. else if (output.hasFileExtension ("aif;aiff")) // (as the .wav: 24 bits, no dither)
  23595. {
  23596. options.format = lynx::exportopts::Format::aiff;
  23597. options.aiffBits = 24;
  23598. }
  23599. else if (output.hasFileExtension ("m4a"))
  23600. {
  23601. options.format = lynx::exportopts::Format::aac;
  23602. options.aacKbps = 192;
  23603. }
  23604. lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), options, output);
  23605. job.setExtraData (true);
  23606. const auto prepared = juce::Time::getMillisecondCounterHiRes();
  23607. lynx::loadtrace::end();
  23608. int lastPercent = -1;
  23609. ok = job.run ([&lastPercent] (double p) {
  23610. lastPercent = (int) (p * 100.0);
  23611. return true;
  23612. }, error);
  23613. auto joined = [] (const std::map<std::string, int>& items) {
  23614. juce::StringArray names;
  23615. for (const auto& [name, count] : items)
  23616. names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
  23617. return names.joinIntoString (", ");
  23618. };
  23619. const auto& importReport = loader.getImportReport();
  23620. report << "converted=" << joined (importReport.converted) << "\n"
  23621. << "approximated=" << joined (importReport.approximated) << "\n"
  23622. << "unsupported=" << joined (importReport.unsupported) << "\n"
  23623. << "not_reproduced=" << joined (importReport.notReproduced) << "\n" // (round qafix190kq)
  23624. << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
  23625. << "partial_effects=" << joined (importReport.partialEffects) << "\n"
  23626. << "missing_samples=" << importReport.missingSamples << "\n";
  23627. // third-party plugins: how each was found, or what plays in its place (diagnostics for level differences)
  23628. for (const auto& line : loader.getMatchedPlugins())
  23629. report << "plugin_found=" << line << "\n";
  23630. for (const auto& m : loader.getMissingPluginDetails())
  23631. report << "plugin_missing=" << juce::String::fromUTF8 (m.name.c_str()) << " -> "
  23632. << juce::String::fromUTF8 (m.replacement.c_str()).replace ("{0}", juce::String::fromUTF8 (m.replacementArg.c_str())) << "\n";
  23633. {
  23634. const auto& song = loader.getSong();
  23635. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  23636. {
  23637. const auto& track = song.mixer[t];
  23638. if (track.effects.empty() && track.sends.empty())
  23639. continue;
  23640. report << "insert " << (int) t << " vol=" << juce::String (track.volume / lynx::unityFader, 3)
  23641. << (track.muted ? " muted" : "") << (track.toMaster ? "" : " noMaster");
  23642. for (const auto& s : track.sends)
  23643. report << " send>" << s.target << "@" << juce::String (s.level, 3);
  23644. report << " |";
  23645. for (const auto& fx : track.effects)
  23646. report << " [" << (fx.kind == lynx::EffectKind::plugin ? juce::String::fromUTF8 (fx.plugin.name.c_str())
  23647. : juce::String::fromUTF8 (lynx::effectInfo (fx.kind).name))
  23648. << (fx.isSubstitute() ? " (substitute)" : "") << (fx.enabled ? "" : " off")
  23649. << (fx.mix < 0.999f ? " mix=" + juce::String (fx.mix, 2) : juce::String()) << "]";
  23650. report << "\n";
  23651. }
  23652. }
  23653. report << juce::String (lynx::loadtrace::reportLines());
  23654. lynx::PluginHost::settingsFolder().getChildFile ("load.log").replaceWithText (juce::String (lynx::loadtrace::table()));
  23655. report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
  23656. << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
  23657. << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
  23658. << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
  23659. << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
  23660. << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
  23661. << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
  23662. << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
  23663. << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
  23664. << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
  23665. << "song_seconds=" << job.getMusicSeconds() << "\n"
  23666. << "peak=" << job.getPeak() << "\n"
  23667. << "final_progress=" << lastPercent << "\n"
  23668. << "bytes=" << output.getSize() << "\n"
  23669. << "file=" << output.getFullPathName() << "\n";
  23670. // round qafix190kq (QA-9): a silent render failed with an empty message. Say why: a project with nothing to
  23671. // play (Live's lesson sets "Playing Software Instruments" / "Recording Audio" hold no clip at all), or a
  23672. // render that stays below -60 dBFS
  23673. if (ok && job.getPeak() <= 0.001f)
  23674. {
  23675. ok = false;
  23676. error = juce::String::fromUTF8 (lynx::exportsilence::reason (loader.getSong(), patternOnly).c_str());
  23677. }
  23678. }
  23679. }
  23680. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  23681. juce::File (outputPath + ".txt").replaceWithText (report);
  23682. setApplicationReturnValue (ok ? 0 : 1);
  23683. quit();
  23684. }
  23685. // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
  23686. // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
  23687. // --editorcpu: one editor after another; each phase runs 2 s to settle and 8 s measured
  23688. struct EditorCpuRun final : juce::Timer
  23689. {
  23690. struct Case { lynx::EffectKind kind; const char* name; int type; bool demo; }; // type 0 native, 1 display-first, 2 Facet EQ
  23691. std::vector<Case> cases;
  23692. std::size_t at = 0;
  23693. int phase = 0;
  23694. double t0 = 0.0, c0 = 0.0;
  23695. juce::String report;
  23696. juce::File out;
  23697. std::unique_ptr<lynx::AudioEngine> engine;
  23698. std::unique_ptr<juce::DocumentWindow> window;
  23699. std::function<void()> done;
  23700. void start()
  23701. {
  23702. engine = std::make_unique<lynx::AudioEngine> (false);
  23703. report << "editor\tmode\tcpu % of one core\n";
  23704. open();
  23705. startTimer (250);
  23706. }
  23707. void open()
  23708. {
  23709. window.reset();
  23710. if (at >= cases.size()) { out.replaceWithText (report); stopTimer(); if (done) done(); return; }
  23711. const auto& c = cases[at];
  23712. lynx::Song song;
  23713. song.mixer.resize (2);
  23714. song.mixer[0].name = "Master";
  23715. song.mixer[1].name = "Insert 1";
  23716. song.mixer[1].effects.push_back (lynx::makeEffectSlot (c.kind));
  23717. engine->setSong (std::move (song));
  23718. engine->dispatchPendingMessages();
  23719. lynx::setNativeEditorDemo (c.demo);
  23720. auto editor = c.type == 1 ? lynx::makeProEditor (*engine, 1, 0, c.demo) : c.type == 2 ? lynx::makeFacetEqEditor (*engine, 1, 0, c.demo)
  23721. : lynx::makeNativeEffectEditor (*engine, 1, 0, 1.0f, 0);
  23722. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX editor CPU - ") + c.name, lynx::theme::colour::bg1, 0);
  23723. window->setUsingNativeTitleBar (true);
  23724. window->setContentOwned (editor.release(), true);
  23725. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  23726. window->setTopLeftPosition (area.getRight() - window->getWidth() - 8, area.getBottom() - window->getHeight() - 8);
  23727. window->setVisible (true);
  23728. phase = 0;
  23729. t0 = juce::Time::getMillisecondCounterHiRes();
  23730. }
  23731. void timerCallback() override
  23732. {
  23733. const auto now = juce::Time::getMillisecondCounterHiRes();
  23734. if (phase == 0 && now - t0 > 2000.0) { phase = 1; t0 = now; c0 = lynx::processCpuSeconds(); return; }
  23735. if (phase == 1 && now - t0 > 8000.0)
  23736. {
  23737. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  23738. const auto& c = cases[at];
  23739. report << c.name << "\t" << (c.demo ? "animating" : "idle") << "\t" << juce::String (cpu, 2) << "\n";
  23740. ++at;
  23741. open();
  23742. }
  23743. }
  23744. };
  23745. std::unique_ptr<EditorCpuRun> editorCpu;
  23746. void runEditorCpu (const juce::String& path)
  23747. {
  23748. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23749. editorCpu = std::make_unique<EditorCpuRun>();
  23750. editorCpu->out = juce::File (path);
  23751. using K = lynx::EffectKind;
  23752. for (const auto demo : { false, true })
  23753. for (const auto& c : std::vector<EditorCpuRun::Case> { { K::facetEq, "Facet EQ", 2, demo }, { K::crestCompressor, "Crest Compressor", 1, demo },
  23754. { K::apexLimiter, "Apex Limiter", 1, demo }, { K::prismMultiband, "Prism Multiband", 1, demo },
  23755. { K::epochVerb, "Epoch Verb", 0, demo }, { K::glowLeveler, "Glow Leveler", 0, demo },
  23756. { K::fruityLimiter, "Fruity Limiter", 0, demo }, { K::lynxTune, "LYNX Tune", 0, demo } })
  23757. editorCpu->cases.push_back (c);
  23758. editorCpu->done = [this] { juce::MessageManager::callAsync ([this] { editorCpu.reset(); quit(); }); };
  23759. editorCpu->start();
  23760. }
  23761. struct ParityShow
  23762. {
  23763. std::unique_ptr<lynx::AudioEngine> engine;
  23764. std::unique_ptr<juce::Component> editor;
  23765. std::unique_ptr<juce::DocumentWindow> window;
  23766. ~ParityShow() { window.reset(); editor.reset(); engine.reset(); }
  23767. };
  23768. std::shared_ptr<ParityShow> parityShow;
  23769. juce::File selfTestTemp; // --selftest: its own temp folder (round 190mo), deleted when the run ends
  23770. bool parityShotFailed = false; // --parityshot: the effect name matched no built-in effect
  23771. void runParityShot (const juce::String& path, const juce::String& effectName, const juce::String& paramsFile)
  23772. {
  23773. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23774. int kindIndex = -1;
  23775. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  23776. if (juce::String::fromUTF8 (lynx::effectInfo ((lynx::EffectKind) k).name).equalsIgnoreCase (effectName))
  23777. kindIndex = k;
  23778. if (kindIndex < 0)
  23779. {
  23780. // round tp172b7: say so and fail (a silent exit 0 hid a split effect name in a launch script)
  23781. std::fprintf (stderr, "unknown effect: %s\n", effectName.toRawUTF8());
  23782. std::fflush (stderr);
  23783. parityShotFailed = true;
  23784. return;
  23785. }
  23786. const auto kind = (lynx::EffectKind) kindIndex;
  23787. auto fx = lynx::makeEffectSlot (kind);
  23788. // round 190jd: LYNX_PARITYSHOT_VIEW=1 = the editor display's second view (Fruity Limiter: LYNX's transfer curve)
  23789. fx.displayView = (std::uint8_t) juce::jlimit (0, 1, juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_VIEW", "0").getIntValue());
  23790. if (paramsFile.isNotEmpty())
  23791. for (const auto& line : juce::StringArray::fromLines (juce::File (paramsFile).loadFileAsString()))
  23792. {
  23793. const auto t = juce::StringArray::fromTokens (line, " \t", "");
  23794. const auto index = t.size() >= 2 ? t[0].getIntValue() : -1;
  23795. if (index >= 0 && index < lynx::maxEffectParams)
  23796. fx.params[(std::size_t) index] = t[1].getFloatValue();
  23797. }
  23798. auto offlineOwner = std::make_unique<lynx::AudioEngine> (false); // (kept alive by LYNX_PARITYSHOT_SHOW's window)
  23799. auto& offline = *offlineOwner;
  23800. auto song = lynx::Song::makeDefault();
  23801. song.mixer.resize (2);
  23802. song.mixer[0].name = "Master";
  23803. song.mixer[1].name = "Insert 1";
  23804. song.mixer[1].effects.assign (1, fx);
  23805. for (auto& c : song.channels)
  23806. c.mixerTrack = 1;
  23807. offline.setSong (std::move (song));
  23808. offline.dispatchPendingMessages();
  23809. const bool facet = kind == lynx::EffectKind::facetEq;
  23810. // round tp172b4: the originals are pictured idle (nothing playing), so the display-first editors are too: no demo
  23811. // history unless LYNX_PARITYSHOT_DEMO=1 asks for the running display
  23812. const bool demoDisplay = juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_DEMO", {}) == "1";
  23813. // (Ember in its Classic voicing: the Classic panel, as the mixer opens it)
  23814. const bool pro = lynx::ProEditorWindows::handles (kind)
  23815. && ! (kind == lynx::EffectKind::ember && fx.params[(std::size_t) lynx::mixsuite::ember::voicing] > 0.5f);
  23816. auto editor = facet ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  23817. : pro ? lynx::makeProEditor (offline, 1, 0, demoDisplay) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  23818. if (editor == nullptr)
  23819. return;
  23820. if (! pro) // the demo song through the effect, the editor ticked 30 times a second of audio as its timer would
  23821. {
  23822. lynx::AudioEngine::RenderOptions o;
  23823. o.seconds = 3.0;
  23824. o.sampleRate = 48000.0;
  23825. o.pluginWarmUp = false;
  23826. int sinceTick = 0;
  23827. o.capture = [&] (const float*, const float*, int n) {
  23828. sinceTick += n;
  23829. if (sinceTick < 1600) return;
  23830. sinceTick = 0;
  23831. if (facet) lynx::tickFacetEqEditor (*editor);
  23832. else lynx::tickNativeEffectEditor (*editor);
  23833. };
  23834. offline.renderOffline (o);
  23835. }
  23836. // round tp172b5: LYNX_PARITYSHOT_CLICKS drives the editor before the picture (the originals' pictures have their
  23837. // panels open), tokens in order: "x,y" a click, then the pointer leaves; "h:x,y" the pointer rests there (a hover);
  23838. // "d:x,y,x2,y2" a drag from there to there, the button still down in the picture
  23839. for (const auto& token : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_CLICKS", {}), " ", ""))
  23840. {
  23841. const auto hover = token.startsWith ("h:"), drag = token.startsWith ("d:");
  23842. const auto xy = juce::StringArray::fromTokens (hover || drag ? token.substring (2) : token, ",", "");
  23843. if (xy.size() < (drag ? 4 : 2))
  23844. continue;
  23845. const juce::Point<int> at (xy[0].getIntValue(), xy[1].getIntValue());
  23846. editor->setVisible (true); // (getComponentAt finds nothing in a hidden component; it never goes on screen)
  23847. auto* target = editor->getComponentAt (at);
  23848. if (target == nullptr)
  23849. continue;
  23850. const auto local = target->getLocalPoint (editor.get(), at).toFloat();
  23851. const auto now = juce::Time::getCurrentTime();
  23852. auto source = juce::Desktop::getInstance().getMainMouseSource();
  23853. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  23854. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods, bool dragged) {
  23855. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, local, now, 1, dragged);
  23856. };
  23857. target->mouseMove (event (local, {}, false));
  23858. if (hover)
  23859. continue;
  23860. target->mouseDown (event (local, left, false));
  23861. if (drag)
  23862. {
  23863. const auto end = target->getLocalPoint (editor.get(), juce::Point<int> (xy[2].getIntValue(), xy[3].getIntValue())).toFloat();
  23864. target->mouseDrag (event (end, left, true));
  23865. continue;
  23866. }
  23867. target->mouseUp (event (local, {}, false));
  23868. target->mouseExit (event ({ -1000.0f, -1000.0f }, {}, false));
  23869. offline.dispatchPendingMessages(); // (round 190jd: an edit the click made, e.g. a display view, reaches the slot)
  23870. }
  23871. // round tp172b6: LYNX_PARITYSHOT_SHOW=1 puts the same editor in a real window and keeps it open (for a guarded GUI check
  23872. // of its pop-up menus, which the offscreen picture cannot hold); closing the window quits
  23873. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_SHOW", {}) == "1")
  23874. {
  23875. struct ShowWindow final : juce::DocumentWindow
  23876. {
  23877. ShowWindow() : juce::DocumentWindow ("LYNX parity check", juce::Colours::black, juce::DocumentWindow::closeButton) {}
  23878. void closeButtonPressed() override { juce::JUCEApplication::getInstance()->systemRequestedQuit(); }
  23879. };
  23880. parityShow = std::make_shared<ParityShow>();
  23881. parityShow->engine = std::move (offlineOwner);
  23882. parityShow->editor = std::move (editor);
  23883. auto window = std::make_unique<ShowWindow>();
  23884. window->setUsingNativeTitleBar (true);
  23885. window->setContentNonOwned (parityShow->editor.get(), true);
  23886. window->setTopLeftPosition (80, 80);
  23887. window->setVisible (true);
  23888. parityShow->window = std::move (window);
  23889. return;
  23890. }
  23891. // round 190ar: LYNX_PARITYSHOT_SCALE=2 draws the same editor at twice the pixel density (as on a 200 % display);
  23892. // round 190bi: the shared shot scale (--shot-scale, LYNX_SHOT_SCALE, LYNX_PARITYSHOT_SCALE as before)
  23893. const auto shotScale = lynx::shot::scale();
  23894. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) editor->getWidth() * shotScale), juce::roundToInt ((float) editor->getHeight() * shotScale), true);
  23895. {
  23896. juce::Graphics g (image);
  23897. g.fillAll (lynx::theme::panel);
  23898. g.addTransform (juce::AffineTransform::scale (shotScale));
  23899. editor->paintEntireComponent (g, false);
  23900. }
  23901. const auto file = lynx::shot::file (juce::File (path));
  23902. file.deleteFile();
  23903. juce::PNGImageFormat png;
  23904. if (auto stream = file.createOutputStream())
  23905. png.writeImageToStream (image, *stream);
  23906. }
  23907. // an Audio Effect Rack shaped like Live's reference (REA_rodada183c §8): two chains with chain-select zones and fades,
  23908. // four named macros (one on a chain's volume, one on two parameters), two variations, every view open
  23909. static lynx::EffectSlot shotRack()
  23910. {
  23911. auto slot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  23912. auto& doc = slot.patcher;
  23913. doc.rack[0].chains[0].name = "Vocoder";
  23914. lynx::PatchNode vocoder, eq, verb;
  23915. vocoder.effect = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  23916. eq.effect = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  23917. verb.effect = lynx::makeEffectSlot (lynx::EffectKind::reeverb2);
  23918. const auto nVoc = lynx::rack::addDevice (doc, 0, vocoder);
  23919. const auto nEq = lynx::rack::addDevice (doc, 0, eq);
  23920. lynx::rack::addChain (doc, "dry bypass");
  23921. lynx::rack::addDevice (doc, 1, verb);
  23922. doc.rack[0].chains[0].select = { 0, 79, 0, 63 };
  23923. doc.rack[0].chains[1].select = { 32, 127, 48, 127 };
  23924. lynx::rack::setChainVolume (doc, 0, 0.33f);
  23925. lynx::rack::setChainVolume (doc, 1, 0.5f);
  23926. const char* names[] { "Sibilance", "Intensity", "Formant Shift", "Bright Level" };
  23927. for (int m = 0; m < 4; ++m)
  23928. doc.rack[0].macros[(std::size_t) m].name = names[m];
  23929. lynx::RackMapping vol;
  23930. vol.target = lynx::RackMapping::Target::chainVolume, vol.chain = 0, vol.min = 0.0f, vol.max = lynx::rack::unityVolume;
  23931. lynx::rack::map (doc, 0, vol);
  23932. lynx::RackMapping a, b, c, d;
  23933. a.node = nVoc, a.param = 0;
  23934. b.node = nVoc, b.param = 1, b.min = 0.2f, b.max = 0.8f;
  23935. c.node = nEq, c.param = 0, c.min = 0.3f, c.max = 0.9f;
  23936. d.node = nEq, d.param = 1;
  23937. lynx::rack::map (doc, 1, a);
  23938. lynx::rack::map (doc, 2, b);
  23939. lynx::rack::map (doc, 3, c);
  23940. lynx::rack::map (doc, 3, d);
  23941. lynx::rack::setMacro (doc, 0, 60.0f);
  23942. lynx::rack::setMacro (doc, 1, 40.0f);
  23943. lynx::rack::setMacro (doc, 2, 70.0f);
  23944. lynx::rack::setMacro (doc, 3, 86.0f);
  23945. lynx::rack::storeVariation (doc);
  23946. lynx::rack::renameVariation (doc, 0, "Verse");
  23947. lynx::rack::setMacro (doc, 3, 120.0f);
  23948. lynx::rack::storeVariation (doc);
  23949. lynx::rack::renameVariation (doc, 1, "Drop");
  23950. lynx::rack::launchVariation (doc, 0);
  23951. auto& r = doc.rack[0];
  23952. r.showMacros = r.showChains = r.showDevices = r.showVariations = true;
  23953. r.zoneEditor = 2;
  23954. r.selectedChain = 0;
  23955. lynx::rack::setSelector (doc, 56.0f);
  23956. lynx::rack::compile (doc);
  23957. return slot;
  23958. }
  23959. bool runRackShots (const juce::File& out, const juce::String& liveSet = {})
  23960. {
  23961. out.createDirectory();
  23962. lynx::AudioEngine offline (false);
  23963. auto save = [&] (juce::Component& c, const juce::String& name) {
  23964. auto image = lynx::shot::paint (c, lynx::theme::panel);
  23965. const auto f = lynx::shot::file (out.getChildFile (name));
  23966. f.deleteFile();
  23967. juce::PNGImageFormat png;
  23968. if (auto stream = f.createOutputStream())
  23969. return png.writeImageToStream (image, *stream);
  23970. return false;
  23971. };
  23972. auto song = lynx::Song::makeDefault();
  23973. song.mixer.resize (3);
  23974. song.mixer[1].name = "Vocal Main";
  23975. auto slot = shotRack();
  23976. song.mixer[1].effects = { slot };
  23977. // an Instrument Rack: three chains split over the keyboard
  23978. lynx::ChannelDef inst;
  23979. inst.name = "Keys Rack";
  23980. inst.instrument = lynx::InstrumentKind::patcher;
  23981. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  23982. for (int k = 0; k < 3; ++k)
  23983. {
  23984. if (k > 0)
  23985. lynx::rack::addChain (inst.patcher);
  23986. lynx::PatchNode synth;
  23987. synth.generator = true;
  23988. synth.channel.instrument = lynx::InstrumentKind::synth;
  23989. synth.channel.name = "Synth";
  23990. lynx::rack::addDevice (inst.patcher, k, synth);
  23991. }
  23992. inst.patcher.rack[0].chains[0].key = { 0, 52, 0, 47 };
  23993. inst.patcher.rack[0].chains[1].key = { 48, 76, 53, 71 };
  23994. inst.patcher.rack[0].chains[2].key = { 72, 127, 77, 127 };
  23995. inst.patcher.rack[0].chains[0].name = "Low";
  23996. inst.patcher.rack[0].chains[1].name = "Mid";
  23997. inst.patcher.rack[0].chains[2].name = "High";
  23998. inst.patcher.rack[0].showChains = inst.patcher.rack[0].showDevices = true;
  23999. inst.patcher.rack[0].zoneEditor = 0;
  24000. lynx::rack::compile (inst.patcher);
  24001. song.channels.push_back (inst);
  24002. const auto channel = (int) song.channels.size() - 1;
  24003. offline.setSong (std::move (song));
  24004. offline.dispatchPendingMessages();
  24005. bool ok = true;
  24006. // [set.als]: a Live set's racks as LYNX imports them, the one with the most chains drawn with its title bar (the
  24007. // like-for-like pair with Live's own picture of that set)
  24008. if (liveSet.isNotEmpty())
  24009. {
  24010. juce::MemoryBlock bytes;
  24011. juce::File (liveSet).loadFileAsData (bytes);
  24012. const std::vector<std::uint8_t> data ((const std::uint8_t*) bytes.getData(), (const std::uint8_t*) bytes.getData() + bytes.getSize());
  24013. lynx::AlsImportOptions o;
  24014. o.common.projectFolder = juce::File (liveSet).getParentDirectory().getFullPathName().toStdString();
  24015. std::string error;
  24016. if (auto imported = lynx::importAls (data, o, &error))
  24017. {
  24018. int bestTrack = -1, bestSlot = -1;
  24019. std::size_t most = 0;
  24020. for (int t = 0; t < (int) imported->mixer.size(); ++t)
  24021. for (int s = 0; s < (int) imported->mixer[(std::size_t) t].effects.size(); ++s)
  24022. if (const auto& fx = imported->mixer[(std::size_t) t].effects[(std::size_t) s]; lynx::rack::isRack (fx) && fx.patcher.rack[0].chains.size() > most)
  24023. most = fx.patcher.rack[0].chains.size(), bestTrack = t, bestSlot = s;
  24024. if (bestTrack >= 0)
  24025. {
  24026. offline.setSong (std::move (*imported));
  24027. offline.dispatchPendingMessages();
  24028. auto view = lynx::RackWindows::makeSlotView (offline, bestTrack, bestSlot, true);
  24029. view->setSize (view->preferredWidth (228), 228);
  24030. ok = save (*view, "rack-live-import.png") && ok;
  24031. view->setMapMode (true);
  24032. view->setSize (view->preferredWidth (228), 228);
  24033. ok = save (*view, "rack-live-import-map.png") && ok;
  24034. return ok;
  24035. }
  24036. }
  24037. return false;
  24038. }
  24039. {
  24040. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, false);
  24041. view->setSize (view->preferredWidth (206), 206);
  24042. ok = save (*view, "rack-deviceview.png") && ok;
  24043. }
  24044. {
  24045. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, true);
  24046. view->setMapMode (true);
  24047. view->setSize (view->preferredWidth (228), 228);
  24048. ok = save (*view, "rack-mapmode.png") && ok;
  24049. }
  24050. {
  24051. auto view = lynx::RackWindows::makeChannelView (offline, channel, true);
  24052. view->setSize (view->preferredWidth (228), 228);
  24053. ok = save (*view, "rack-instrument.png") && ok;
  24054. }
  24055. return ok;
  24056. }
  24057. void runEq166fShots (const juce::String& folder)
  24058. {
  24059. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24060. const juce::File out (folder);
  24061. out.createDirectory();
  24062. lynx::AudioEngine offline (false);
  24063. auto save = [&] (juce::Component& editor, const juce::String& name) {
  24064. auto image = lynx::shot::paint (editor, lynx::theme::panel);
  24065. const auto f = lynx::shot::file (out.getChildFile (name));
  24066. f.deleteFile();
  24067. juce::PNGImageFormat png;
  24068. if (auto stream = f.createOutputStream())
  24069. png.writeImageToStream (image, *stream);
  24070. };
  24071. // a song whose demo beat plays into insert 1 (the source) and, for Facet's target, its other half into insert 2
  24072. auto songWith = [] (const lynx::EffectSlot& fx, bool split) {
  24073. auto song = lynx::Song::makeDefault();
  24074. song.mixer.resize (3);
  24075. song.mixer[0].name = "Master";
  24076. song.mixer[1].name = "Vocal";
  24077. song.mixer[2].name = "Reference mix";
  24078. song.mixer[1].effects.assign (1, fx);
  24079. for (std::size_t c = 0; c < song.channels.size(); ++c)
  24080. song.channels[c].mixerTrack = split && c % 2 == 1 ? 2 : 1;
  24081. return song;
  24082. };
  24083. auto feed = [&] (juce::Component& editor, bool facet, int frames) {
  24084. // one continuous render of the song, the editor ticked 30 times a second of audio, as its timer would
  24085. lynx::AudioEngine::RenderOptions o;
  24086. o.seconds = frames / 30.0;
  24087. o.sampleRate = 48000.0;
  24088. o.pluginWarmUp = false;
  24089. int sinceTick = 0;
  24090. o.capture = [&] (const float*, const float*, int n) {
  24091. sinceTick += n;
  24092. if (sinceTick < 1600) return;
  24093. sinceTick = 0;
  24094. if (facet) lynx::tickFacetEqEditor (editor);
  24095. else lynx::tickNativeEffectEditor (editor);
  24096. };
  24097. offline.renderOffline (o);
  24098. if (facet) lynx::tickFacetEqEditor (editor);
  24099. else lynx::tickNativeEffectEditor (editor);
  24100. };
  24101. // Parametric EQ 2: spectrum + heatmap (Full), flat / band 4 +12 dB / band 4 -12 dB, then the Top position
  24102. auto& display = lynx::peqview::displaySettings();
  24103. const auto kept = display;
  24104. display.spectrum = display.heatmap = true;
  24105. display.position = 0;
  24106. for (const auto& [gain, name] : { std::pair { 0.0, "peq2-heatmap-flat.png" }, { 12.0, "peq2-heatmap-boost.png" }, { -12.0, "peq2-heatmap-cut.png" },
  24107. { 0.0, "peq2-heatmap-top.png" } })
  24108. {
  24109. auto eq = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  24110. eq.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (gain);
  24111. eq.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (900.0);
  24112. display.position = juce::String (name).contains ("top") ? 1 : 0;
  24113. offline.setSong (songWith (eq, false));
  24114. offline.dispatchPendingMessages();
  24115. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, 0);
  24116. feed (*editor, false, 120);
  24117. save (*editor, name);
  24118. }
  24119. display = kept;
  24120. // Facet EQ's comparative EQ: listening to the target (insert 2) with its spectrum over the source's
  24121. {
  24122. using namespace lynx::facet;
  24123. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  24124. eq.params[(std::size_t) param (0, 0)] = shapeValue (Shape::bell);
  24125. eq.params[(std::size_t) param (0, 1)] = hzValue (250.0);
  24126. eq.params[(std::size_t) param (0, 2)] = gainValue (-4.0);
  24127. eq.params[(std::size_t) param (1, 0)] = shapeValue (Shape::highShelf);
  24128. eq.params[(std::size_t) param (1, 1)] = hzValue (6000.0);
  24129. eq.params[(std::size_t) param (1, 2)] = gainValue (3.0);
  24130. eq.params[(std::size_t) analyzerParam] = analyzerValue (Analyzer::both);
  24131. eq.sidechain = 2;
  24132. for (const auto& [l, name] : { std::pair { Listen::target, "facet-compare-target.png" }, { Listen::eq, "facet-compare-eq.png" } })
  24133. {
  24134. eq.params[(std::size_t) listenParam] = listenValue (l);
  24135. offline.setSong (songWith (eq, true));
  24136. offline.dispatchPendingMessages();
  24137. auto editor = lynx::makeFacetEqEditor (offline, 1, 0, false);
  24138. feed (*editor, true, 90);
  24139. save (*editor, name);
  24140. }
  24141. }
  24142. }
  24143. void runDesign168rShots (const juce::String& folder)
  24144. {
  24145. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24146. const juce::File out (folder);
  24147. out.createDirectory();
  24148. lynx::AudioEngine offline (false);
  24149. using K = lynx::EffectKind;
  24150. for (const auto kind : { K::pitchCorrect, K::lovePhilter, K::peakController, K::spreader, K::fruityFastLP, K::flFrequencyShifter,
  24151. K::flLowLifter, K::distructor, K::flBassBoost, K::flDelay1, K::fl7BandEq, K::flCenter, K::flPhaseInverter,
  24152. K::eq, K::delay, K::reverb, K::limiter, K::filter, K::distortion, K::chorus, K::utility, K::lofi,
  24153. K::crossover, K::pitchShift, K::freqShift, K::rhythmGain, K::volumeGate })
  24154. {
  24155. const auto& bank = lynx::presets::factory (kind);
  24156. // Love Philter / Distructor play FL's state: their second picture is FL's default preset (when installed)
  24157. std::optional<lynx::EffectSlot> flPreset;
  24158. if (kind == K::lovePhilter || kind == K::distructor)
  24159. {
  24160. const auto roots = lynx::findFlStudioRoots();
  24161. const auto file = juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  24162. .getChildFile ("Patches/Plugin presets/Effects")
  24163. .getChildFile (kind == K::lovePhilter ? "Fruity Love Philter/Default.fst" : "Distructor/Default.fst");
  24164. juce::MemoryBlock bytes;
  24165. if (file.loadFileAsData (bytes))
  24166. flPreset = lynx::effectFromFlPreset (std::vector<std::uint8_t> ((const std::uint8_t*) bytes.getData(),
  24167. (const std::uint8_t*) bytes.getData() + bytes.getSize()));
  24168. }
  24169. for (int pass = 0; pass < (bank.empty() && ! flPreset ? 1 : 2); ++pass)
  24170. {
  24171. auto fx = lynx::makeEffectSlot (kind);
  24172. if (pass == 1 && flPreset)
  24173. fx = *flPreset;
  24174. else if (pass == 1)
  24175. {
  24176. fx.params = lynx::presets::apply (kind, bank.front(), 120.0);
  24177. fx.presetName = bank.front().name;
  24178. }
  24179. lynx::Song song;
  24180. song.mixer.resize (2);
  24181. song.mixer[0].name = "Master";
  24182. song.mixer[1].name = "Insert 1";
  24183. song.mixer[1].effects.push_back (fx);
  24184. offline.setSong (std::move (song));
  24185. offline.dispatchPendingMessages();
  24186. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  24187. for (const auto scale : { 1.0f, 2.0f })
  24188. for (int page = 0; page < pages; ++page)
  24189. {
  24190. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, scale, page);
  24191. if (editor == nullptr)
  24192. continue;
  24193. juce::Image image (juce::Image::ARGB, juce::jmax (1, editor->getWidth()), juce::jmax (1, editor->getHeight()), true);
  24194. {
  24195. juce::Graphics g (image);
  24196. g.fillAll (lynx::theme::panel);
  24197. editor->paintEntireComponent (g, false);
  24198. }
  24199. // (FL's "Frequency Shifter" and LYNX's "Frequency shifter" differ only in case: FL editors get "FL ")
  24200. const auto file = out.getChildFile ((lynx::plugui::hasFlLayout (kind) ? "FL " : "")
  24201. + juce::String (lynx::effectInfo (kind).name).replaceCharacters ("/\\:", "---")
  24202. + (pass == 1 ? "-preset" : "") + (page > 0 ? "-p" + juce::String (page + 1) : juce::String())
  24203. + (scale > 1.5f ? "-200" : "-100") + ".png");
  24204. file.deleteFile();
  24205. juce::PNGImageFormat png;
  24206. if (auto stream = file.createOutputStream())
  24207. png.writeImageToStream (image, *stream);
  24208. }
  24209. }
  24210. }
  24211. }
  24212. bool runInstrumentShots (const juce::File& folder, const juce::String& which, const juce::String& source)
  24213. {
  24214. folder.createDirectory();
  24215. auto key = [] (juce::String n) { return n.toLowerCase().removeCharacters (" -!._"); };
  24216. juce::StringArray wanted;
  24217. wanted.addTokens (which, ",", "");
  24218. auto ok = true;
  24219. struct Shot
  24220. {
  24221. juce::String name;
  24222. std::optional<lynx::ChannelDef> channel;
  24223. };
  24224. std::vector<Shot> shots;
  24225. for (const auto& e : lynx::natives::instrumentEngines())
  24226. {
  24227. const auto name = key (e.name);
  24228. const auto banked = which == "banks" && lynx::banks::hasBank (e.kind);
  24229. if (! banked && ! wanted.contains (name))
  24230. continue;
  24231. auto channel = source == "fl" || source == "flm" ? lynx::natives::makeChannel (e.kind, lynx::flStudioAccess())
  24232. : lynx::banks::defaultChannel (e.kind, e.name);
  24233. // (round 190u) source "flm": the channel as the .flm import makes it (Transistor Bass: FL Studio Mobile's build)
  24234. if (source == "flm" && channel && e.kind == lynx::InstrumentKind::transistorbass)
  24235. {
  24236. channel->pluginState = lynx::transistorBassFlmState ({ 1.0f, 0.0f, 1.0f, 1.0f, 0.1f, 1.0f, 0.1f, 0.0f, 0.0f, 0.3f, 0.5f, 0.0f, 0.0f, 0.0f }); // FLM's defaults
  24237. channel->modelParams = { 1.0f };
  24238. channel->samplePath.clear();
  24239. }
  24240. if (! channel)
  24241. {
  24242. std::fprintf (stderr, "%s: no %s channel\n", e.name, source.toRawUTF8());
  24243. ok = false;
  24244. continue;
  24245. }
  24246. shots.push_back ({ name, std::move (channel) });
  24247. }
  24248. // Autogun (round 169h): not in the Add menus (no preset files); FL's own render-test channel, either source
  24249. if (wanted.contains ("autogun"))
  24250. {
  24251. if (auto channel = lynx::natives::autogunShotChannel (lynx::flStudioAccess()))
  24252. shots.push_back ({ "autogun", std::move (channel) });
  24253. else
  24254. {
  24255. std::fprintf (stderr, "Autogun: no channel (FL Studio's Render tests\\Autogun.flp)\n");
  24256. ok = false;
  24257. }
  24258. }
  24259. for (auto& shot : shots)
  24260. {
  24261. const auto& name = shot.name;
  24262. auto& channel = shot.channel;
  24263. lynx::AudioEngine offline (false);
  24264. lynx::Song song;
  24265. song.mixer = lynx::Song::defaultMixer (2);
  24266. song.channels.push_back (*channel);
  24267. song.patterns.emplace_back();
  24268. {
  24269. juce::String error; // the project too, so an older build can picture the same channel (--snapshot)
  24270. lynx::ProjectFile::save (song, folder.getChildFile (name + "-" + source + ".lynx"), error);
  24271. }
  24272. offline.setSong (std::move (song));
  24273. offline.dispatchPendingMessages();
  24274. auto frame = lynx::makeChannelFrame (offline, 0, 0);
  24275. if (frame == nullptr || frame->getWidth() <= 0)
  24276. {
  24277. ok = false;
  24278. continue;
  24279. }
  24280. for (const auto scale : { 1.0f, 1.5f, 2.0f })
  24281. {
  24282. const auto file = folder.getChildFile (name + "-" + source + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  24283. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, scale), file.getFullPathName());
  24284. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), frame->getWidth(), frame->getHeight());
  24285. }
  24286. // round 169h: the layout's other pages (Toxic's MIDI / Seq …), one shot each at 1.5×
  24287. for (int page = 1; page < lynx::showChannelLayoutPage (*frame, -1); ++page)
  24288. {
  24289. lynx::showChannelLayoutPage (*frame, page);
  24290. const auto file = folder.getChildFile (name + "-" + source + "-page" + juce::String (page) + "-150.png");
  24291. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, 1.5f), file.getFullPathName());
  24292. std::printf ("%s\n", file.getFullPathName().toRawUTF8());
  24293. }
  24294. }
  24295. return ok;
  24296. }
  24297. // --- round 170j: the pilot editors with their own art -------------------------------------------------
  24298. struct ArtPilot
  24299. {
  24300. std::string file; // the art's name as a file name: "toxic-biohazard"
  24301. bool instrument;
  24302. lynx::InstrumentKind instrumentKind;
  24303. lynx::EffectKind effectKind;
  24304. lynx::skin::Style before; // the automatic style it had before the Themed style
  24305. };
  24306. static juce::StringArray& artOnly() // --artshot / --artgui: only these (file names), all when empty
  24307. {
  24308. static juce::StringArray only;
  24309. return only;
  24310. }
  24311. // every plugin with art of its own (round 170j/170k): generators first, then effects; built from the art
  24312. // registries, so a new theme is shot without touching this list
  24313. static const std::vector<ArtPilot>& artPilots()
  24314. {
  24315. using I = lynx::InstrumentKind;
  24316. using E = lynx::EffectKind;
  24317. static const std::vector<ArtPilot> list = [] {
  24318. std::vector<ArtPilot> all;
  24319. auto slug = [] (lynx::skin::Art a) {
  24320. return juce::String (lynx::skin::artName (a)).toLowerCase().replaceCharacters (" ", "-").removeCharacters ("!.()'").toStdString();
  24321. };
  24322. for (const auto& e : lynx::natives::instrumentEngines()) // (the engines' order first)
  24323. if (const auto a = lynx::skin::artForInstrument (e.kind); a != lynx::skin::Art::none)
  24324. all.push_back ({ slug (a), true, e.kind, E::reverb, lynx::skin::Style::neon });
  24325. for (int k = 0; k <= (int) I::wavetraveller; ++k) // then every other kind with art (DrumSynth, Autogun, Wasp...)
  24326. if (const auto a = lynx::skin::artForInstrument ((I) k); a != lynx::skin::Art::none)
  24327. all.push_back ({ slug (a), true, (I) k, E::reverb, lynx::skin::Style::neon });
  24328. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  24329. if (const auto a = lynx::skin::artForEffect ((E) k); a != lynx::skin::Art::none)
  24330. all.push_back ({ slug (a), false, I::synth, (E) k, lynx::skin::plainStyleFor (k) });
  24331. std::vector<ArtPilot> kept;
  24332. for (auto& p : all)
  24333. if (artOnly().isEmpty() || artOnly().contains (juce::String (p.file)))
  24334. if (std::none_of (kept.begin(), kept.end(), [&] (const ArtPilot& q) { return q.file == p.file; }))
  24335. kept.push_back (p);
  24336. return kept;
  24337. }();
  24338. return list;
  24339. }
  24340. // the song and the editor of a pilot (an instrument: the channel window on its Plugin tab)
  24341. static std::unique_ptr<juce::Component> makeArtPilot (lynx::AudioEngine& engine, const ArtPilot& p)
  24342. {
  24343. lynx::Song song;
  24344. song.mixer = lynx::Song::defaultMixer (2);
  24345. if (p.instrument)
  24346. {
  24347. for (const auto& e : lynx::natives::instrumentEngines())
  24348. if (e.kind == p.instrumentKind)
  24349. {
  24350. auto channel = lynx::natives::makeChannel (e.kind, lynx::flStudioAccess());
  24351. if (! channel) channel = lynx::banks::defaultChannel (e.kind, e.name);
  24352. if (! channel) return nullptr;
  24353. song.channels.push_back (*channel);
  24354. break;
  24355. }
  24356. if (song.channels.empty()) // a kind without an engine entry: its LYNX default, else an empty channel of that kind
  24357. {
  24358. const std::string name = lynx::skin::artName (lynx::skin::artForInstrument (p.instrumentKind));
  24359. auto channel = lynx::banks::defaultChannel (p.instrumentKind, name);
  24360. if (! channel)
  24361. {
  24362. channel = lynx::ChannelDef {};
  24363. channel->instrument = p.instrumentKind;
  24364. channel->name = name;
  24365. }
  24366. song.channels.push_back (*channel);
  24367. }
  24368. song.patterns.emplace_back();
  24369. }
  24370. else
  24371. {
  24372. song.mixer[1].effects.push_back (lynx::makeEffectSlot (p.effectKind));
  24373. }
  24374. engine.setSong (std::move (song));
  24375. engine.dispatchPendingMessages();
  24376. if (p.instrument) return lynx::makeChannelFrame (engine, 0, 0);
  24377. if (p.effectKind == lynx::EffectKind::facetEq) return lynx::makeFacetEqEditor (engine, 1, 0, true);
  24378. if (lynx::ProEditorWindows::handles (p.effectKind)) return lynx::makeProEditor (engine, 1, 0, true); // display-first editors, demo signal
  24379. return lynx::makeNativeEffectEditor (engine, 1, 0, 1.0f, 0);
  24380. }
  24381. // "before": the style each pilot had (forced for its run); "after": automatic (the pilots are Themed)
  24382. static void artPilotStyle (const ArtPilot& p, const juce::String& mode)
  24383. {
  24384. lynx::skin::setForcedStyle (mode == "before" ? (int) p.before : -1);
  24385. lynx::skin::setArtMotion (mode != "still");
  24386. }
  24387. bool runArtShots (const juce::File& folder, bool before)
  24388. {
  24389. folder.createDirectory();
  24390. auto ok = true;
  24391. juce::String titles ("editor\tsize\twidth\tname width at the style's size\tbox\tsize used\tlines\tresult\n");
  24392. for (const auto& p : artPilots())
  24393. {
  24394. artPilotStyle (p, before ? "before" : "after");
  24395. lynx::AudioEngine offline (false);
  24396. auto editor = makeArtPilot (offline, p);
  24397. if (editor == nullptr || editor->getWidth() <= 0)
  24398. {
  24399. std::fprintf (stderr, "%s: no editor\n", p.file.c_str());
  24400. ok = false;
  24401. continue;
  24402. }
  24403. if (p.effectKind == lynx::EffectKind::facetEq) lynx::tickFacetEqEditor (*editor);
  24404. // round 170k2: titles.tsv, how the header's name fitted (its width at the style's size, the box, the size used)
  24405. auto fit = [&] (const juce::String& at) {
  24406. const auto f = lynx::skin::lastTitleFit();
  24407. if (f.have <= 0.0f) return; // no plugin header drawn (a generator's channel window)
  24408. titles << juce::String (p.file) << "\t" << at << "\t" << editor->getWidth() << "\t" << juce::String (f.need, 1) << "\t" << juce::String (f.have, 1)
  24409. << "\t" << juce::String (f.size, 1) << "\t" << f.lines << "\t" << (f.clipped ? "ELLIPSIS" : "full") << "\n";
  24410. };
  24411. for (const auto scale : { 1.0f, 2.0f })
  24412. {
  24413. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  24414. lynx::skin::resetTitleFit();
  24415. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, scale), file.getFullPathName());
  24416. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), editor->getWidth(), editor->getHeight());
  24417. if (scale == 1.0f) fit ("100");
  24418. }
  24419. // ... and at the smallest size its window allows (effect panels; the Pro editors scale as a whole)
  24420. if (const auto smallest = lynx::nativeEditorMinimumSize (*editor); smallest.x > 0)
  24421. {
  24422. editor->setSize (smallest.x, smallest.y);
  24423. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-min.png");
  24424. lynx::skin::resetTitleFit();
  24425. savePng (lynx::shot::snapshot (*editor), file.getFullPathName());
  24426. fit ("min");
  24427. }
  24428. }
  24429. folder.getChildFile (juce::String ("titles-") + (before ? "before" : "after") + ".tsv").replaceWithText (titles);
  24430. lynx::skin::setForcedStyle (-1);
  24431. return ok;
  24432. }
  24433. struct ArtGuiRun final : juce::Timer
  24434. {
  24435. juce::File folder;
  24436. juce::String mode, report;
  24437. std::size_t at = 0;
  24438. int phase = 0;
  24439. double t0 = 0.0, c0 = 0.0;
  24440. std::unique_ptr<lynx::AudioEngine> engine;
  24441. std::unique_ptr<juce::DocumentWindow> window;
  24442. std::function<void()> done;
  24443. void start()
  24444. {
  24445. engine = std::make_unique<lynx::AudioEngine> (false);
  24446. report << "editor\tmode\tcpu % of one core\tart layer animating\n";
  24447. open();
  24448. startTimer (100);
  24449. }
  24450. void open()
  24451. {
  24452. window.reset();
  24453. const auto& pilots = artPilots();
  24454. if (at >= pilots.size())
  24455. {
  24456. folder.getChildFile ("cpu-" + mode + ".txt").replaceWithText (report);
  24457. stopTimer();
  24458. lynx::skin::setForcedStyle (-1);
  24459. lynx::skin::setArtMotion (true);
  24460. if (done) done();
  24461. return;
  24462. }
  24463. const auto& p = pilots[at];
  24464. artPilotStyle (p, mode);
  24465. auto editor = makeArtPilot (*engine, p);
  24466. if (editor == nullptr) { ++at; open(); return; }
  24467. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX art - ") + juce::String (p.file), lynx::theme::colour::bg1, 0);
  24468. window->setUsingNativeTitleBar (true);
  24469. window->setContentOwned (editor.release(), true);
  24470. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  24471. window->setTopLeftPosition (area.getX() + 24, area.getY() + 24);
  24472. window->setAlwaysOnTop (true);
  24473. window->setVisible (true);
  24474. phase = 0;
  24475. t0 = juce::Time::getMillisecondCounterHiRes();
  24476. }
  24477. bool animating() const
  24478. {
  24479. if (window == nullptr || window->getContentComponent() == nullptr) return false;
  24480. std::function<bool (juce::Component&)> find = [&] (juce::Component& c) {
  24481. if (auto* l = dynamic_cast<lynx::skin::ArtLayer*> (&c); l != nullptr && l->animating()) return true;
  24482. for (auto* child : c.getChildren())
  24483. if (find (*child)) return true;
  24484. return false;
  24485. };
  24486. return find (*window->getContentComponent());
  24487. }
  24488. void timerCallback() override
  24489. {
  24490. const auto now = juce::Time::getMillisecondCounterHiRes();
  24491. const auto& p = artPilots()[at];
  24492. const auto ready = folder.getChildFile (juce::String (p.file) + "-" + mode + ".ready");
  24493. const auto shotDone = folder.getChildFile (juce::String (p.file) + "-" + mode + ".done");
  24494. if (phase == 0 && now - t0 > 1500.0)
  24495. {
  24496. // the window's content on screen, in physical pixels, for the outside screenshot to crop
  24497. auto* c = window->getContentComponent();
  24498. const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  24499. const auto b = c->getScreenBounds();
  24500. shotDone.deleteFile();
  24501. ready.replaceWithText (juce::String (juce::roundToInt (b.getX() * scale)) + " " + juce::String (juce::roundToInt (b.getY() * scale)) + " "
  24502. + juce::String (juce::roundToInt (b.getWidth() * scale)) + " " + juce::String (juce::roundToInt (b.getHeight() * scale)));
  24503. phase = 1;
  24504. t0 = now;
  24505. return;
  24506. }
  24507. if (phase == 1 && (shotDone.existsAsFile() || now - t0 > 10000.0))
  24508. {
  24509. ready.deleteFile();
  24510. shotDone.deleteFile();
  24511. phase = 2;
  24512. t0 = now;
  24513. c0 = lynx::processCpuSeconds();
  24514. return;
  24515. }
  24516. if (phase == 2 && now - t0 > 6000.0)
  24517. {
  24518. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  24519. report << juce::String (p.file) << "\t" << mode << "\t" << juce::String (cpu, 2) << "\t" << (animating() ? "yes" : "no") << "\n";
  24520. ++at;
  24521. open();
  24522. }
  24523. }
  24524. };
  24525. std::unique_ptr<ArtGuiRun> artGui;
  24526. void runArtGui (const juce::File& folder, const juce::String& mode)
  24527. {
  24528. folder.createDirectory();
  24529. artGui = std::make_unique<ArtGuiRun>();
  24530. artGui->folder = folder;
  24531. artGui->mode = mode;
  24532. artGui->done = [this] { juce::MessageManager::callAsync ([this] { artGui.reset(); quit(); }); };
  24533. artGui->start();
  24534. }
  24535. void runDesign190inShot (const juce::String& prefix, const juce::String& project)
  24536. {
  24537. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24538. juce::String report;
  24539. {
  24540. lynx::AudioEngine engine (false);
  24541. juce::String error;
  24542. if (const juce::File input (project); input.existsAsFile() && input.hasFileExtension ("flp"))
  24543. report << "import: " << (engine.importFlpFile (input, error) ? "ok" : "failed " + error) << "\n";
  24544. engine.dispatchPendingMessages();
  24545. // a native FL generator with FL's presets (FL's capture: FLEX's "Piano Dark"), on a mixer track of its own
  24546. const auto& fl = lynx::flStudioAccess();
  24547. auto osc = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, fl);
  24548. int generator = -1, sampler = -1;
  24549. engine.editSong ([&] (lynx::Song& s) {
  24550. if (osc)
  24551. {
  24552. osc->mixerTrack = s.claimFreeInsert();
  24553. s.channels.push_back (*osc);
  24554. generator = (int) s.channels.size() - 1;
  24555. }
  24556. if (const juce::File kick (juce::String::fromUTF8 (fl.roots.data.c_str()) + "/Patches/Packs/Drums/Kicks/808 Kick.wav"); kick.existsAsFile())
  24557. {
  24558. lynx::ChannelDef d; // FL's Sampler with a kick, as FL's default channel (the Sample, Envelope and Misc tabs)
  24559. d.instrument = lynx::InstrumentKind::sampler;
  24560. lynx::audioclips::loadSampleInto (d, kick.getFullPathName().toStdString(), "808 Kick");
  24561. d.mixerTrack = s.claimFreeInsert();
  24562. s.channels.push_back (d);
  24563. sampler = (int) s.channels.size() - 1;
  24564. }
  24565. for (const auto withSample : { true, false }) // (a sampler with its sample first, else any)
  24566. for (int c = 0; c < (int) s.channels.size() && sampler < 0; ++c)
  24567. if (s.channels[(std::size_t) c].instrument == lynx::InstrumentKind::sampler && (! withSample || ! s.channels[(std::size_t) c].samplePath.empty()))
  24568. sampler = c;
  24569. });
  24570. engine.dispatchPendingMessages();
  24571. lynx::MainComponent ui (engine, false); // (sets the Channel rack's wrapper-menu items)
  24572. ui.setSize (1920, 1080);
  24573. report << "generator " << generator << ", sampler " << sampler << "\n";
  24574. auto shoot = [&] (juce::Component& c, const juce::String& name) {
  24575. savePng (lynx::shot::snapshot (c), prefix + name);
  24576. report << name << " " << c.getWidth() << "x" << c.getHeight() << "\n";
  24577. };
  24578. auto window = [&] (int channel, int tab, const juce::String& name) {
  24579. if (channel < 0)
  24580. return;
  24581. if (auto w = lynx::makeChannelWindowForShot (engine, channel, tab))
  24582. shoot (*w, name);
  24583. };
  24584. window (generator, 0, "-cw-plugin.png");
  24585. window (generator, -1, "-cw-plugin-misc.png");
  24586. window (sampler, 0, "-cw-sample.png");
  24587. window (sampler, 1, "-cw-envelope.png");
  24588. window (sampler, -1, "-cw-misc.png");
  24589. // the strip of a window with the system's title bar (docking off): ▸ and the presets stay in it
  24590. if (generator >= 0)
  24591. if (auto frame = lynx::makeChannelFrame (engine, generator, 0))
  24592. {
  24593. shoot (*frame, "-frame-floating.png");
  24594. if (auto menu = lynx::channelWrapperMenu (*frame))
  24595. {
  24596. // FL's two columns: the plugin's items, then the Channel column (split at the column break)
  24597. juce::PopupMenu left, right;
  24598. auto* to = &left;
  24599. for (juce::PopupMenu::MenuItemIterator it (*menu); it.next();)
  24600. {
  24601. to->addItem (it.getItem());
  24602. if (it.getItem().shouldBreakAfter)
  24603. to = &right;
  24604. }
  24605. saveMenus (juce::StringArray { "Plugin", "Channel" }, std::vector<juce::PopupMenu> { left, right }, prefix + "-menu-channel.png");
  24606. report << "menu items " << left.getNumItems() << " + " << right.getNumItems() << "\n";
  24607. }
  24608. }
  24609. }
  24610. {
  24611. // FW-8: LYNX engines standing in for FL plugins of an imported project (the import's flOrigin) are titled
  24612. // with FL's name; LYNX's own Delay (no FL origin) keeps its own
  24613. lynx::AudioEngine offline (false);
  24614. lynx::Song song;
  24615. song.mixer.resize (2);
  24616. song.mixer[0].name = "Master";
  24617. song.mixer[1].name = "Insert 1";
  24618. const std::vector<std::pair<lynx::EffectKind, const char*>> standIns { { lynx::EffectKind::limiter, "Fruity Limiter" },
  24619. { lynx::EffectKind::utility, "Fruity Stereo Shaper" }, { lynx::EffectKind::delay, "Fruity Delay 3" },
  24620. { lynx::EffectKind::reverb, "Fruity Reeverb 2" }, { lynx::EffectKind::delay, "" } };
  24621. for (const auto& [kind, origin] : standIns)
  24622. {
  24623. auto fx = lynx::makeEffectSlot (kind);
  24624. fx.flOrigin.plugin = origin;
  24625. song.mixer[1].effects.push_back (fx);
  24626. }
  24627. offline.setSong (std::move (song));
  24628. offline.dispatchPendingMessages();
  24629. std::vector<juce::Image> strips;
  24630. int width = 0, height = 0;
  24631. for (int k = 0; k < (int) standIns.size(); ++k)
  24632. if (auto editor = lynx::makeNativeEffectEditor (offline, 1, k, 1.0f, 0))
  24633. {
  24634. auto image = lynx::shot::paint (*editor, lynx::theme::panel); // (as --plugui draws the editors)
  24635. const auto h = juce::jmin (image.getHeight(), (int) std::ceil (30.0f * lynx::shot::scale()));
  24636. juce::Image strip (juce::Image::ARGB, image.getWidth(), h, true);
  24637. juce::Graphics (strip).drawImageAt (image, 0, 0);
  24638. strips.push_back (strip);
  24639. width = juce::jmax (width, image.getWidth());
  24640. height += h + 4;
  24641. }
  24642. if (! strips.empty())
  24643. {
  24644. juce::Image all (juce::Image::RGB, width, height, true);
  24645. {
  24646. juce::Graphics g (all); // (flushed when it goes: a native image's context draws on its release)
  24647. g.fillAll (juce::Colours::black);
  24648. int y = 0;
  24649. for (auto& strip : strips)
  24650. {
  24651. g.drawImageAt (strip, 0, y);
  24652. y += strip.getHeight() + 4;
  24653. }
  24654. }
  24655. savePng (all, prefix + "-names.png");
  24656. report << "names " << (int) strips.size() << "\n";
  24657. }
  24658. }
  24659. juce::File (prefix + "-report.txt").replaceWithText (report);
  24660. }
  24661. void runPluginEditorSnapshots (const juce::String& folder)
  24662. {
  24663. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24664. {
  24665. const juce::File out (folder);
  24666. out.createDirectory();
  24667. lynx::AudioEngine offline (false);
  24668. const auto roots = lynx::findFlStudioRoots();
  24669. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  24670. auto kinds = lynx::plugui::flLayoutKinds();
  24671. kinds.push_back (lynx::EffectKind::maximus); // Soundgoodizer (below)
  24672. for (const auto own : lynx::plugui::ownLayoutKinds()) // LYNX's own panels (mixing suite, round 96)
  24673. kinds.push_back (own);
  24674. kinds.push_back (lynx::EffectKind::apexLimiter); // round 114: display-first editor
  24675. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 145: the second pass shows the Vocal strip voicing
  24676. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 165: the third pass shows the E console voicing
  24677. kinds.push_back (lynx::EffectKind::compressor); // round 152: the RComp role's panel (vintage voicing, RComp ranges)
  24678. const auto database = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects");
  24679. auto maximusPasses = 0; // Maximus has its own page (first pass); the second pass shows Soundgoodizer
  24680. auto ridgePasses = 0;
  24681. // round 173d3: the parity pictures of one editor — LYNX_PLUGUI_ONLY=<effect name>, LYNX_PLUGUI_PRESET=<.fst>,
  24682. // LYNX_PLUGUI_PAGES=<page,page,…> (the page numbers as the editor encodes them)
  24683. const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_ONLY", {});
  24684. const auto onlyPreset = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PRESET", {});
  24685. const auto onlyPages = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PAGES", {}), ",", "");
  24686. for (const auto kind : kinds)
  24687. {
  24688. if (only.isNotEmpty() && only != lynx::effectInfo (kind).name)
  24689. continue;
  24690. auto fx = lynx::makeEffectSlot (kind);
  24691. juce::String name (lynx::effectInfo (kind).name);
  24692. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  24693. {
  24694. const auto dir = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str()));
  24695. auto file = dir.getChildFile ("Default.fst");
  24696. if (! file.existsAsFile()) // plugins without presets: their entry of FL's plugin database
  24697. for (const auto& f : database.findChildFiles (juce::File::findFiles, true, juce::String::fromUTF8 (plugin.c_str()) + ".fst"))
  24698. file = f;
  24699. if (only.isNotEmpty() && onlyPreset.isNotEmpty())
  24700. file = juce::File (onlyPreset);
  24701. if (! file.existsAsFile())
  24702. {
  24703. auto files = dir.findChildFiles (juce::File::findFiles, true, "*.fst");
  24704. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFullPathName().compareNatural (b.getFullPathName()) < 0; });
  24705. file = files.isEmpty() ? juce::File() : files[0];
  24706. }
  24707. juce::MemoryBlock data;
  24708. if (file.existsAsFile() && file.loadFileAsData (data))
  24709. {
  24710. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  24711. if (auto loaded = lynx::effectFromFlPreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), 130.0, lynx::natives::flDataReader (lynx::flStudioAccess())); loaded && loaded->kind == kind)
  24712. {
  24713. fx = *loaded;
  24714. // round 190in (FW-8): a LYNX engine loaded with an FL plugin's preset stands in for that
  24715. // plugin as an imported slot does (its header shows FL's name)
  24716. if (fx.flOrigin.empty() && ! lynx::plugui::hasFlLayout (kind))
  24717. fx.flOrigin.plugin = plugin;
  24718. }
  24719. }
  24720. name = juce::String::fromUTF8 (plugin.c_str());
  24721. break;
  24722. }
  24723. if (kind == lynx::EffectKind::maximus && ++maximusPasses == 2) // Soundgoodizer: preset A of the installation, Amount 60 %
  24724. {
  24725. juce::MemoryBlock data;
  24726. juce::File (juce::String::fromUTF8 (roots.factoryData.c_str())).getChildFile ("Plugins/Fruity/Effects/Soundgoodizer/Data/Presets/a.dat").loadFileAsData (data);
  24727. lynx::maximusfx::Blob blob;
  24728. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  24729. blob.mix = 600;
  24730. const auto* b = static_cast<const std::uint8_t*> (data.getData());
  24731. blob.state.assign (b, b + data.getSize());
  24732. fx = lynx::makeEffectSlot (kind);
  24733. fx.state = lynx::maximusfx::pack (blob);
  24734. name = "Soundgoodizer";
  24735. }
  24736. if (kind == lynx::EffectKind::ridgeStrip && ++ridgePasses == 2) // round 145: her Vocalstrip 2 setting
  24737. {
  24738. for (const auto& [param, value] : { std::pair<const char*, float> { "Vocal strip", 1.0f }, { "Compander", 1.0f },
  24739. { "Compander threshold", 0.3083f }, { "Compander ratio", 0.6929f }, { "Compander attack", 0.2543f },
  24740. { "Compander release", 0.5316f }, { "Make-up", 0.2917f }, { "Soft knee", 1.0f },
  24741. { "Expander threshold", 0.2198f }, { "Vocal input", 0.6792f }, { "Vocal output", 0.3938f },
  24742. { "Process order", 0.4783f }, { "De-esser", 1.0f } })
  24743. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  24744. name = "Ridge Strip (Vocal strip)";
  24745. }
  24746. else if (kind == lynx::EffectKind::ridgeStrip && ridgePasses == 3) // round 165: the E console, EQ to the side chain
  24747. {
  24748. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "HPF", 0.3f }, { "HF gain", 0.8f },
  24749. { "HF bell", 1.0f }, { "Ratio", 0.5f }, { "Comp. threshold", 0.4f }, { "EQ to SC", 1.0f },
  24750. { "Filter split", 1.0f }, { "Expander", 1.0f } })
  24751. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  24752. name = "Ridge Strip (E console)";
  24753. }
  24754. else if (kind == lynx::EffectKind::ridgeStrip) // a vocal setting, so the graphs show something
  24755. for (const auto& [param, value] : { std::pair<const char*, float> { "HPF", 0.3f }, { "LMF gain", 0.35f }, { "HF gain", 0.7f },
  24756. { "Ratio", 0.3f }, { "Comp. threshold", 0.55f } })
  24757. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  24758. if (kind == lynx::EffectKind::compressor) // round 152: the vintage voicing with the reference's ranges and meter
  24759. {
  24760. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "Ranges", 1.0f }, { "Limiter", 1.0f },
  24761. { "Threshold", 0.6f }, { "RC ratio", 0.4f } })
  24762. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  24763. name = "Compressor (RComp role)";
  24764. }
  24765. if (kind == lynx::EffectKind::apexLimiter) // round 114: gain into the ceiling, so the display shows reduction
  24766. fx.params[0] = 0.33f;
  24767. if (kind == lynx::EffectKind::ember)
  24768. {
  24769. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Drive")] = 0.5f;
  24770. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Bands")] = 1.0f; // round 108: the band rows
  24771. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "B3 drive")] = 0.6f;
  24772. }
  24773. if (kind == lynx::EffectKind::crestCompressor) // round 108: a curve with a knee and a side-chain low cut
  24774. for (const auto& [param, value] : { std::pair<const char*, float> { "Threshold", 0.55f }, { "Knee", 0.15f },
  24775. { "SC1 shape", 0.5f }, { "SC1 freq.", 0.3f } })
  24776. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  24777. lynx::Song song;
  24778. song.mixer.resize (2);
  24779. song.mixer[0].name = "Master";
  24780. song.mixer[1].name = "Insert 1";
  24781. song.mixer[1].effects.push_back (fx);
  24782. offline.setSong (std::move (song));
  24783. offline.dispatchPendingMessages();
  24784. if (lynx::ProEditorWindows::handles (kind)) // round 114: the display-first editors, with a demo signal
  24785. {
  24786. auto editor = lynx::makeProEditor (offline, 1, 0, true);
  24787. auto image = lynx::shot::paint (*editor);
  24788. const auto file = lynx::shot::file (out.getChildFile (name + ".png"));
  24789. file.deleteFile();
  24790. juce::PNGImageFormat png;
  24791. if (auto stream = file.createOutputStream())
  24792. png.writeImageToStream (image, *stream);
  24793. continue;
  24794. }
  24795. const auto pages = name == "Soundgoodizer" ? 1 : juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  24796. std::vector<int> pageList;
  24797. for (int page = 0; page < pages; ++page)
  24798. pageList.push_back (page);
  24799. if (only.isNotEmpty() && ! onlyPages.isEmpty())
  24800. {
  24801. pageList.clear();
  24802. for (const auto& p : onlyPages)
  24803. pageList.push_back (p.getIntValue());
  24804. }
  24805. for (const auto page : pageList)
  24806. {
  24807. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  24808. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  24809. const auto file = lynx::shot::file (out.getChildFile (name + (page > 0 ? "-p" + juce::String (page + 1) : juce::String()) + ".png"));
  24810. file.deleteFile();
  24811. juce::PNGImageFormat png;
  24812. if (auto stream = file.createOutputStream())
  24813. png.writeImageToStream (image, *stream);
  24814. }
  24815. }
  24816. // round 137: Echoform in its Rhythm mode (EchoBoy's role) with the Present era
  24817. {
  24818. namespace ef = lynx::echosuite::echoform;
  24819. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  24820. fx.params[ef::rhythm] = 1.0f;
  24821. fx.params[ef::rhythmRepeats] = 5.0f / 15.0f;
  24822. fx.params[ef::rhythmDecay] = 0.25f;
  24823. fx.params[ef::rhythmTap1 + 2] = 0.45f;
  24824. fx.params[ef::feedback] = 0.25f;
  24825. fx.params[ef::era] = 0.5f;
  24826. for (const auto& [param, value] : ef::rhythmPresetEdits (0)) // round 144: a pattern in the rhythm editor (Grid)
  24827. fx.params[(std::size_t) param] = value;
  24828. fx.params[ef::rhythmShape] = 0.5f; // swell
  24829. lynx::Song song;
  24830. song.mixer.resize (2);
  24831. song.mixer[0].name = "Master";
  24832. song.mixer[1].name = "Insert 1";
  24833. song.mixer[1].effects.push_back (fx);
  24834. offline.setSong (std::move (song));
  24835. offline.dispatchPendingMessages();
  24836. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  24837. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  24838. const auto file = lynx::shot::file (out.getChildFile ("Echoform-rhythm.png"));
  24839. file.deleteFile();
  24840. juce::PNGImageFormat png;
  24841. if (auto stream = file.createOutputStream())
  24842. png.writeImageToStream (image, *stream);
  24843. }
  24844. // round 150: Echoform with a voicing (the Stereo / L/R offset controls on the Rhythm row)
  24845. {
  24846. namespace ef = lynx::echosuite::echoform;
  24847. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  24848. fx.params[ef::voicing] = ef::voicingValue (ef::voicingForEchoBoyStyle (19));
  24849. fx.params[ef::style] = ef::styleValue (ef::Style::dual);
  24850. lynx::Song song;
  24851. song.mixer.resize (2);
  24852. song.mixer[0].name = "Master";
  24853. song.mixer[1].name = "Insert 1";
  24854. song.mixer[1].effects.push_back (fx);
  24855. offline.setSong (std::move (song));
  24856. offline.dispatchPendingMessages();
  24857. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  24858. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  24859. const auto file = lynx::shot::file (out.getChildFile ("Echoform-voicing.png"));
  24860. file.deleteFile();
  24861. juce::PNGImageFormat png;
  24862. if (auto stream = file.createOutputStream())
  24863. png.writeImageToStream (image, *stream);
  24864. }
  24865. // round 150: Auto-pan's Rhythm voicing with its Tweak row (PanMan's role)
  24866. {
  24867. auto fx = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  24868. fx.params[lynx::autopan::count] = 1.0f; // the Rhythm voicing
  24869. fx.params[lynx::autopan::count + 13] = 0.75f; // offset mod +90°
  24870. lynx::Song song;
  24871. song.mixer.resize (2);
  24872. song.mixer[0].name = "Master";
  24873. song.mixer[1].name = "Insert 1";
  24874. song.mixer[1].effects.push_back (fx);
  24875. offline.setSong (std::move (song));
  24876. offline.dispatchPendingMessages();
  24877. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  24878. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  24879. const auto file = lynx::shot::file (out.getChildFile ("Auto-pan-tweak.png"));
  24880. file.deleteFile();
  24881. juce::PNGImageFormat png;
  24882. if (auto stream = file.createOutputStream())
  24883. png.writeImageToStream (image, *stream);
  24884. }
  24885. // round 165: Ember's Classic voicing (the Decapitator role) in its one-screen panel
  24886. {
  24887. namespace em = lynx::mixsuite::ember;
  24888. auto fx = lynx::makeEffectSlot (lynx::EffectKind::ember);
  24889. fx.params[em::voicing] = 1.0f;
  24890. fx.params[em::classicDrive] = 0.35f;
  24891. lynx::Song song;
  24892. song.mixer.resize (2);
  24893. song.mixer[0].name = "Master";
  24894. song.mixer[1].name = "Insert 1";
  24895. song.mixer[1].effects.push_back (fx);
  24896. offline.setSong (std::move (song));
  24897. offline.dispatchPendingMessages();
  24898. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  24899. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  24900. const auto file = lynx::shot::file (out.getChildFile ("Ember Saturator-classic.png"));
  24901. file.deleteFile();
  24902. juce::PNGImageFormat png;
  24903. if (auto stream = file.createOutputStream())
  24904. png.writeImageToStream (image, *stream);
  24905. }
  24906. // round 152: Foil Plate's one-knob Plate view (the Little Plate role)
  24907. {
  24908. auto fx = lynx::makeEffectSlot (lynx::EffectKind::foilPlate);
  24909. fx.params[14] = 1.0f; // the measured plate voicing
  24910. fx.params[15] = 1.0f; // View = Plate
  24911. lynx::Song song;
  24912. song.mixer.resize (2);
  24913. song.mixer[0].name = "Master";
  24914. song.mixer[1].name = "Insert 1";
  24915. song.mixer[1].effects.push_back (fx);
  24916. offline.setSong (std::move (song));
  24917. offline.dispatchPendingMessages();
  24918. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  24919. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  24920. const auto file = lynx::shot::file (out.getChildFile ("Foil Plate-plate.png"));
  24921. file.deleteFile();
  24922. juce::PNGImageFormat png;
  24923. if (auto stream = file.createOutputStream())
  24924. png.writeImageToStream (image, *stream);
  24925. }
  24926. // LYNX's own editors with live displays (round 103): Facet EQ (a mixing curve, one dynamic band, demo analyser)
  24927. // and LYNX Tune (demo pitch phrase)
  24928. {
  24929. lynx::setNativeEditorDemo (true);
  24930. using namespace lynx::facet;
  24931. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  24932. const struct { Shape s; double f, g, q; int slope; double range; } bandsDemo[] = {
  24933. { Shape::lowCut, 32, 0, 1, 24, 0 }, { Shape::bell, 110, 3, 1.2, 12, 0 }, { Shape::bell, 380, -3.5, 1.6, 12, 0 },
  24934. { Shape::bell, 3200, 0, 2.5, 12, -6 }, { Shape::highShelf, 9000, 2.5, 0.8, 12, 0 }
  24935. };
  24936. for (int b = 0; b < 5; ++b)
  24937. {
  24938. eq.params[(std::size_t) param (b, 0)] = shapeValue (bandsDemo[b].s);
  24939. eq.params[(std::size_t) param (b, 1)] = hzValue (bandsDemo[b].f);
  24940. eq.params[(std::size_t) param (b, 2)] = gainValue (bandsDemo[b].g);
  24941. eq.params[(std::size_t) param (b, 3)] = qValue (bandsDemo[b].q);
  24942. eq.params[(std::size_t) param (b, 4)] = slopeValue (bandsDemo[b].slope);
  24943. eq.params[(std::size_t) (rangeParam0 + b)] = rangeValue (bandsDemo[b].range);
  24944. }
  24945. eq.params[(std::size_t) phaseParam] = phaseValue (Phase::natural);
  24946. const auto own = [&] (const lynx::EffectSlot& fx, const juce::String& file, bool facetEditor, int page = 0) {
  24947. lynx::Song song;
  24948. song.mixer.resize (2);
  24949. song.mixer[0].name = "Master";
  24950. song.mixer[1].name = "Vocal";
  24951. song.mixer[1].effects.push_back (fx);
  24952. offline.setSong (std::move (song));
  24953. offline.dispatchPendingMessages();
  24954. auto editor = facetEditor ? lynx::makeFacetEqEditor (offline, 1, 0, true) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, page);
  24955. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  24956. const auto f = lynx::shot::file (out.getChildFile (file));
  24957. f.deleteFile();
  24958. juce::PNGImageFormat png;
  24959. if (auto stream = f.createOutputStream())
  24960. png.writeImageToStream (image, *stream);
  24961. };
  24962. own (eq, "Facet EQ.png", true);
  24963. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune.png", false);
  24964. {
  24965. // round 128: the ADVANCED page, with E bypassed and A removed on the keyboard and a created vibrato
  24966. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  24967. tune.params[(std::size_t) (lynx::lynxtune::bypassC + 4)] = 1.0f;
  24968. tune.params[(std::size_t) (lynx::lynxtune::noteC + 9)] = 0.0f;
  24969. tune.params[lynx::lynxtune::vibratoShape] = 1.0f / 3.0f;
  24970. // round 166c: the created vibrato's amplitude / formant / variation, a short throat, In scale +2
  24971. tune.params[lynx::lynxtune::vibratoAmplitude] = 1.0f / 3.0f;
  24972. tune.params[lynx::lynxtune::vibratoFormant] = 0.7f;
  24973. tune.params[lynx::lynxtune::vibratoVariation] = 0.2f;
  24974. tune.params[lynx::lynxtune::throatLength] = lynx::lynxtune::throatValue (80.0);
  24975. tune.params[lynx::lynxtune::transposeInScale] = 1.0f;
  24976. tune.params[lynx::lynxtune::scaleTranspose] = lynx::lynxtune::scaleTransposeValue (2);
  24977. own (tune, "LYNX Tune-p2.png", false, 1);
  24978. }
  24979. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune-p3.png", false, 2); // round 135w: Real-time
  24980. lynx::setNativeEditorDemo (false);
  24981. }
  24982. // generators in FL's arrangement: the channel's plugin page with the FL preset's settings
  24983. const auto generators = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Generators");
  24984. for (auto [folder, preset] : std::vector<std::pair<const char*, const char*>> { { "3x Osc", "Default.fst" }, { "FL Keys", "Grand Piano.fst" }, { "BooBass", "" }, { "Sytrus", "Default.fst" }, { "Harmor", "Default.fst" } })
  24985. {
  24986. juce::MemoryBlock data;
  24987. if (juce::String (folder) == "Harmor") // the first preset whose state the engine reads
  24988. {
  24989. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  24990. files.sort();
  24991. for (const auto& f : files)
  24992. {
  24993. juce::MemoryBlock block;
  24994. if (! f.loadFileAsData (block))
  24995. continue;
  24996. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  24997. try
  24998. {
  24999. const auto p = flp::parseProject (std::vector<std::uint8_t> (b, b + block.getSize()), true);
  25000. if (! p.channels.empty() && lynx::harmorStateUsable (p.channels.front().pluginState))
  25001. {
  25002. preset = nullptr;
  25003. data = block;
  25004. break;
  25005. }
  25006. }
  25007. catch (const std::exception&)
  25008. {
  25009. }
  25010. }
  25011. }
  25012. auto file = preset == nullptr ? juce::File() : juce::String (preset).isEmpty() ? database.getSiblingFile ("Generators").getChildFile ("Misc").getChildFile (juce::String (folder) + ".fst")
  25013. : generators.getChildFile (folder).getChildFile (preset);
  25014. if (! file.existsAsFile())
  25015. {
  25016. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  25017. files.sort();
  25018. file = files.isEmpty() ? juce::File() : files[0];
  25019. }
  25020. if (data.isEmpty() && ! file.loadFileAsData (data))
  25021. continue;
  25022. try
  25023. {
  25024. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  25025. auto project = flp::parseProject (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), true);
  25026. if (project.channels.empty())
  25027. continue;
  25028. project.channels.front().type = flp::ChannelType::native;
  25029. lynx::FlpImportOptions options;
  25030. options.roots = roots;
  25031. options.fileExists = [] (const std::string& path) { return lynx::platform::localFile (path).existsAsFile(); };
  25032. options.readFile = [] (const std::string& path) {
  25033. juce::MemoryBlock block;
  25034. lynx::platform::localFile (path).loadFileAsData (block);
  25035. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  25036. return std::vector<std::uint8_t> (b, b + block.getSize());
  25037. };
  25038. options.saveEmbedded = [out] (const std::vector<std::uint8_t>& wav, const std::string& name) {
  25039. const auto f = out.getChildFile ("samples").getNonexistentChildFile (juce::String::fromUTF8 (name.c_str()), ".wav");
  25040. f.getParentDirectory().createDirectory();
  25041. f.replaceWithData (wav.data(), wav.size());
  25042. return f.getFullPathName().toStdString();
  25043. };
  25044. auto song = lynx::importFlp (project, options);
  25045. // the page only needs the plugin's saved state (FL Keys' sample zones need the installed wavetables)
  25046. if (! song.channels.empty() && project.channels.front().pluginName == "BooBass" && song.channels.front().instrument != lynx::InstrumentKind::boobass)
  25047. {
  25048. song.channels.front().instrument = lynx::InstrumentKind::boobass; // (its sound needs the engine DLL; the page does not)
  25049. song.channels.front().modelParams.assign (3, 32768.0f);
  25050. }
  25051. if (! song.channels.empty() && project.channels.front().pluginName == "FL Keys")
  25052. {
  25053. song.channels.front().instrument = lynx::InstrumentKind::flkeys;
  25054. song.channels.front().pluginState = project.channels.front().pluginState;
  25055. }
  25056. offline.setSong (std::move (song));
  25057. offline.dispatchPendingMessages();
  25058. if (offline.getSong().channels.empty())
  25059. continue;
  25060. auto panel = lynx::makeChannelSettingsPanel (offline, 0);
  25061. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  25062. const auto out2 = lynx::shot::file (out.getChildFile (juce::String (folder) + ".png"));
  25063. out2.deleteFile();
  25064. juce::PNGImageFormat png;
  25065. if (auto stream = out2.createOutputStream())
  25066. png.writeImageToStream (image, *stream);
  25067. }
  25068. catch (const std::exception&)
  25069. {
  25070. }
  25071. }
  25072. }
  25073. quit();
  25074. }
  25075. void runVideoShot (const juce::String& prefix, const juce::String& videoPath)
  25076. {
  25077. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25078. // the message loop runs while the frames decode (modal loops are off): a timer takes one snapshot per step
  25079. struct VideoShot final : juce::Timer
  25080. {
  25081. lynx::AudioEngine offline { false };
  25082. std::unique_ptr<juce::Component> editor;
  25083. juce::String prefix, report;
  25084. int step = 0;
  25085. std::function<void()> done;
  25086. void moveTo (double seconds)
  25087. {
  25088. offline.getTransport().positionTicks.store (seconds * offline.getSong().bpm / 60.0 * lynx::ppq);
  25089. }
  25090. void timerCallback() override
  25091. {
  25092. static constexpr double times[] = { 0.0, 1.5, 3.25 };
  25093. constexpr int typeInStep = (int) std::size (times) + 1;
  25094. if (step > 0 && step < typeInStep && editor != nullptr)
  25095. savePng (lynx::shot::snapshot (*editor), prefix + "-" + juce::String (step - 1) + ".png");
  25096. if (editor != nullptr && step == (int) std::size (times))
  25097. {
  25098. // round 174d: FL's in-place type-in of the current time (a right click on it)
  25099. lynx::videoview::openTypeIn (*editor, 2);
  25100. ++step;
  25101. return;
  25102. }
  25103. if (editor != nullptr && step == typeInStep)
  25104. savePng (lynx::shot::snapshot (*editor), prefix + "-typein.png");
  25105. if (editor == nullptr || step >= typeInStep)
  25106. {
  25107. stopTimer();
  25108. juce::File (prefix + "-report.txt").replaceWithText (report);
  25109. if (done)
  25110. done();
  25111. return;
  25112. }
  25113. moveTo (times[step++]);
  25114. }
  25115. };
  25116. static std::unique_ptr<VideoShot> shot;
  25117. shot = std::make_unique<VideoShot>();
  25118. shot->prefix = prefix;
  25119. auto& offline = shot->offline;
  25120. lynx::videoview::install (offline);
  25121. lynx::Song song;
  25122. song.mixer = lynx::Song::defaultMixer (2);
  25123. lynx::ChannelDef c;
  25124. c.name = "Fruity Video Player";
  25125. c.instrument = lynx::InstrumentKind::videoplayer;
  25126. lynx::video::Settings vs;
  25127. vs.path = juce::File (videoPath).getFullPathName().toStdString();
  25128. vs.delay = lynx::video::unitsPerSecond / 2; // the video starts at 0.5 s
  25129. c.pluginState = lynx::video::write (vs);
  25130. song.channels.push_back (c);
  25131. song.patterns.emplace_back();
  25132. {
  25133. // round 174d (A3): the same Video Player in a song whose tempo drops from 120 to 60 BPM at bar 5, for FL
  25134. // (LYNX.exe --export-flp <prefix>-tempo.lynx <prefix>-tempo.flp), to compare FL's video clock with LYNX's
  25135. auto fl = song;
  25136. fl.bpm = 120.0;
  25137. fl.mode = lynx::PlayMode::song;
  25138. auto settings = vs;
  25139. settings.delay = 0;
  25140. settings.timeDisplay = lynx::video::Settings {}.timeDisplay;
  25141. fl.channels[0].pluginState = lynx::video::write (settings);
  25142. fl.patterns[0].name = "Pattern 1";
  25143. lynx::Automation tempo;
  25144. tempo.name = "Tempo";
  25145. tempo.target = { lynx::AutomationTargetKind::tempo, 0, 0, 0 };
  25146. const auto bar = (std::int64_t) lynx::ppq * 4;
  25147. tempo.points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { bar * 4 - 1, lynx::valueFromTempo (120.0), 0.0f },
  25148. { bar * 4, lynx::valueFromTempo (60.0), 0.0f }, { bar * 8, lynx::valueFromTempo (60.0), 0.0f } };
  25149. fl.automations.push_back (tempo);
  25150. lynx::Clip at;
  25151. at.kind = lynx::ClipKind::automation;
  25152. at.automation = 0;
  25153. at.track = 1;
  25154. at.start = 0;
  25155. at.length = bar * 8;
  25156. fl.playlist.push_back (at);
  25157. lynx::Clip pc;
  25158. pc.pattern = 0;
  25159. pc.track = 0;
  25160. pc.start = 0;
  25161. pc.length = bar * 8;
  25162. fl.playlist.push_back (pc);
  25163. juce::String error;
  25164. lynx::ProjectFile::save (fl, juce::File (prefix + "-tempo.lynx"), error);
  25165. }
  25166. offline.setSong (std::move (song));
  25167. offline.dispatchPendingMessages();
  25168. auto& report = shot->report;
  25169. report << "ffmpeg: " << lynx::findFfmpeg().getFullPathName() << "\n";
  25170. report << lynx::videoview::report (vs.path).fromFirstOccurrenceOf ("Input #0", true, false).upToFirstOccurrenceOf ("At least", false, false) << "\n";
  25171. shot->editor = lynx::makeChannelSettingsPanel (offline, 0);
  25172. if (shot->editor != nullptr)
  25173. shot->editor->setVisible (true);
  25174. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  25175. shot->startTimer (1500);
  25176. }
  25177. void runVideoTrackShot (const juce::String& prefix, const juce::String& videoPath, const juce::String& secondPath)
  25178. {
  25179. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25180. struct TrackShot final : juce::Timer
  25181. {
  25182. lynx::AudioEngine offline { false };
  25183. std::unique_ptr<lynx::PlaylistComponent> playlist;
  25184. std::unique_ptr<lynx::media::FrameDecoder> decoder;
  25185. juce::String prefix, report, path;
  25186. double fps = 25.0;
  25187. int step = 0, waits = 0, adrStep = 0;
  25188. std::unique_ptr<juce::Component> adrPanel;
  25189. std::function<void()> done;
  25190. // song times (s): before, inside the first clip (on and between frame edges), across the second clip
  25191. std::vector<double> times { 0.0, 1.0, 2.0 + 1.0 / 25.0, 2.5, 4.0, 7.3 };
  25192. void timerCallback() override
  25193. {
  25194. if (step > 0 && adrStep == 0)
  25195. {
  25196. // the frame the decoder shows for the wanted file time (the clip starts at song 1.0 s, offset 0)
  25197. const auto want = times[(std::size_t) step - 1] - 1.0;
  25198. double ft = -1.0;
  25199. const auto img = decoder->frame (ft);
  25200. const auto expected = std::floor (want * fps + 1e-6) / fps;
  25201. if (want >= 0.0 && ft < expected - 1e-3 && ++waits < 20)
  25202. return; // (still decoding)
  25203. waits = 0;
  25204. report << "song " << juce::String (times[(std::size_t) step - 1], 3) << " s: wanted file time " << juce::String (want, 4)
  25205. << ", frame shown at " << juce::String (ft, 4) << " (expected " << juce::String (expected, 4) << ")"
  25206. << (want < 0.0 ? " [before the clip]" : std::abs (ft - expected) < 1e-3 ? " OK" : " MISMATCH") << "\n";
  25207. savePng (lynx::shot::snapshot (*playlist), prefix + "-playlist-" + juce::String (step - 1) + ".png");
  25208. if (img.isValid())
  25209. savePng (img, prefix + "-frame-" + juce::String (step - 1) + ".png");
  25210. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  25211. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  25212. savePng (lynx::shot::snapshot (*c), prefix + "-window-" + juce::String (step - 1) + ".png");
  25213. }
  25214. if (step >= (int) times.size() && adrStep == 0)
  25215. {
  25216. // the ADR window: two cues, takes on the first; the play position inside the streamer before the in
  25217. // point (4.0 s), so the video window shows the streamer and the line
  25218. adrStep = 1;
  25219. offline.editSong ([] (lynx::Song& s) {
  25220. lynx::AdrCue a, b;
  25221. a.id = "SC1-01";
  25222. a.in = 4.0;
  25223. a.out = 6.4;
  25224. a.character = "Dr. Silva";
  25225. a.line = "We have to leave before the storm reaches the coast.";
  25226. a.notes = "softer, out of breath";
  25227. a.status = lynx::AdrCue::Status::recorded;
  25228. for (int n = 1; n <= 3; ++n)
  25229. {
  25230. lynx::AdrTake t;
  25231. t.number = n;
  25232. t.name = lynx::adr::takeName (a, n);
  25233. t.rating = n == 2 ? 4 : n;
  25234. t.circled = n == 2;
  25235. a.takes.push_back (t);
  25236. }
  25237. a.selected = 2;
  25238. lynx::adr::setCompRange (a, 4.0, 5.1, 2);
  25239. lynx::adr::setCompRange (a, 5.1, 6.4, 3);
  25240. b.id = "SC1-02";
  25241. b.in = 8.0;
  25242. b.out = 9.5;
  25243. b.character = "Marta";
  25244. b.line = "Then we go now.";
  25245. s.adr.cues = { a, b };
  25246. s.adr.current = 0;
  25247. });
  25248. adrPanel = lynx::adrwindow::makePanel (offline);
  25249. adrPanel->setSize (1200, 640);
  25250. adrPanel->setVisible (true);
  25251. offline.getTransport().positionTicks.store (3.0 * offline.getSong().bpm / 60.0 * lynx::ppq);
  25252. decoder->request (2.0, false);
  25253. return;
  25254. }
  25255. if (adrStep == 1)
  25256. {
  25257. adrStep = 2;
  25258. savePng (lynx::shot::snapshot (*adrPanel), prefix + "-adr.png");
  25259. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  25260. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  25261. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window.png");
  25262. offline.getTransport().positionTicks.store (4.5 * offline.getSong().bpm / 60.0 * lynx::ppq);
  25263. decoder->request (3.5, false);
  25264. return;
  25265. }
  25266. if (adrStep == 2)
  25267. {
  25268. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  25269. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  25270. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window-line.png");
  25271. adrPanel.reset();
  25272. // export with video: a 3 s mix under the picture, re-encoded (the clip starts at 1 s) and copied (from 1 s)
  25273. {
  25274. const juce::File wav (prefix + "-mix.wav");
  25275. wav.deleteFile();
  25276. juce::WavAudioFormat format;
  25277. if (std::unique_ptr<juce::OutputStream> os (wav.createOutputStream().release()); os != nullptr)
  25278. if (std::unique_ptr<juce::AudioFormatWriter> w (format.createWriterFor (os.get(), 48000.0, 2, 16, {}, 0)); w != nullptr)
  25279. {
  25280. os.release();
  25281. juce::AudioBuffer<float> b (2, 48000 * 3);
  25282. for (int k = 0; k < b.getNumSamples(); ++k)
  25283. b.setSample (0, k, 0.25f * (float) std::sin (k * 2.0 * juce::MathConstants<double>::pi * 330.0 / 48000.0)), b.setSample (1, k, b.getSample (0, k));
  25284. w->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  25285. }
  25286. for (const auto origin : { 0.0, 1.0 })
  25287. {
  25288. const juce::File out (prefix + "-mux-" + juce::String ((int) origin) + ".mp4");
  25289. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  25290. const auto error = lynx::videotracks::muxWithVideo (offline.getSong(), origin, wav, out);
  25291. report << "export with video from " << origin << " s: " << (error.isEmpty() ? "OK " + juce::String (out.getSize()) + " bytes" : "FAILED " + error)
  25292. << " (" << juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0, 2) << " s)\n";
  25293. }
  25294. }
  25295. stopTimer();
  25296. report << "frames decoded " << decoder->frameCount() << ", dropped " << decoder->droppedCount() << "\n";
  25297. juce::File (prefix + "-report.txt").replaceWithText (report);
  25298. if (done)
  25299. done();
  25300. return;
  25301. }
  25302. const auto t = times[(std::size_t) step++];
  25303. offline.getTransport().positionTicks.store (t * offline.getSong().bpm / 60.0 * lynx::ppq);
  25304. decoder->request (std::max (0.0, t - 1.0), false);
  25305. }
  25306. };
  25307. static std::unique_ptr<TrackShot> shot;
  25308. shot = std::make_unique<TrackShot>();
  25309. shot->prefix = prefix;
  25310. auto& offline = shot->offline;
  25311. lynx::Song song;
  25312. song.mixer = lynx::Song::defaultMixer (2);
  25313. song.patterns.emplace_back();
  25314. song.mode = lynx::PlayMode::song;
  25315. song.bpm = 120.0;
  25316. offline.setSong (std::move (song));
  25317. offline.dispatchPendingMessages();
  25318. const juce::File video (videoPath);
  25319. const auto pr = lynx::media::probe (video.getFullPathName());
  25320. auto& report = shot->report;
  25321. report << "decoder: " << (pr.backend.isEmpty() ? juce::String ("none") : pr.backend) << " (system: " << lynx::media::nativeBackendName()
  25322. << ", ffmpeg: " << lynx::findFfmpeg().getFullPathName() << ")\n";
  25323. report << "video: " << pr.info.width << "x" << pr.info.height << " " << juce::String (pr.info.fps, 3) << " fps " << juce::String (pr.info.duration, 3)
  25324. << " s, sound " << (pr.info.hasAudio ? "yes" : "no") << "\n";
  25325. shot->fps = pr.info.fps > 1.0 ? pr.info.fps : 25.0;
  25326. shot->times[2] = 2.0 + 1.0 / shot->fps; // (exactly on a frame edge)
  25327. lynx::videotracks::importVideo (offline, video, 1.0, -1);
  25328. if (secondPath.isNotEmpty())
  25329. lynx::videotracks::importVideo (offline, juce::File (secondPath), 3.0, 1);
  25330. offline.editSong ([] (lynx::Song& s) {
  25331. s.video.startTimecode = 3600.0;
  25332. s.video.burnIn = true;
  25333. while (s.videoTracks.size() < 2) // (round 190rf, ASan: no video could be imported at all)
  25334. s.videoTracks.push_back ({});
  25335. s.videoTracks[0].name = "Picture";
  25336. s.videoTracks[1].name = "Reference";
  25337. });
  25338. report << "project rate: " << lynx::vtime::rateName (offline.getSong().video.rate) << ", clip 1: "
  25339. << juce::String (offline.getSong().videoTracks[0].clips.empty() ? -1.0 : offline.getSong().videoTracks[0].clips[0].length, 3) << " s\n";
  25340. // the project round trip
  25341. {
  25342. const juce::File file (prefix + "-project.lynx");
  25343. juce::String error;
  25344. lynx::ProjectFile::save (offline.getSong(), file, error);
  25345. const auto back = lynx::ProjectFile::load (file, error);
  25346. report << "project file round trip: " << (back && back->videoTracks == offline.getSong().videoTracks && back->video == offline.getSong().video ? "OK" : "MISMATCH " + error) << "\n";
  25347. }
  25348. shot->playlist = std::make_unique<lynx::PlaylistComponent> (offline);
  25349. shot->playlist->setSize (1400, 640);
  25350. shot->playlist->setVisible (true);
  25351. shot->decoder = std::make_unique<lynx::media::FrameDecoder>();
  25352. shot->decoder->setSource (video.getFullPathName(), pr.info);
  25353. shot->decoder->setSize (pr.info.width, pr.info.height);
  25354. shot->decoder->startThread (juce::Thread::Priority::low);
  25355. lynx::videotracks::showWindow (offline, 0);
  25356. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  25357. shot->startTimer (700);
  25358. }
  25359. void runDanceShot (const juce::String& prefix)
  25360. {
  25361. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25362. // the moves: one row each, eight moments of a cycle (both facings for Spinning; Pose ends the sheet)
  25363. {
  25364. constexpr int cell = 120, cols = 8;
  25365. auto sheet = lynx::shot::canvas (130 + cols * cell, lynx::dance::moveCount * cell + 10);
  25366. {
  25367. // (the picture is complete when its Graphics is gone: round 190ba, the file was blank on Windows)
  25368. juce::Graphics g (sheet);
  25369. lynx::shot::logical (g);
  25370. g.fillAll (lynx::theme::colour::bg0);
  25371. for (int m = 0; m < lynx::dance::moveCount; ++m)
  25372. {
  25373. g.setColour (lynx::theme::colour::textSecondary);
  25374. g.setFont (14.0f);
  25375. g.drawText (lynx::dance::moveName (m), 8, m * cell + 5, 118, cell, juce::Justification::centredLeft);
  25376. for (int k = 0; k < cols; ++k)
  25377. {
  25378. const auto pose = lynx::dance::pose (m, k / (double) cols + (m == lynx::dance::freestyle ? k * 2 : 0), 1);
  25379. lynx::dancer::draw (g, { 130.0f + (k + 0.5f) * cell, (float) (m + 1) * cell - 6.0f }, 92.0f, pose, false, juce::Colour (0xffff3048));
  25380. }
  25381. }
  25382. }
  25383. savePng (sheet, prefix + "-moves.png");
  25384. }
  25385. lynx::AudioEngine offline (false);
  25386. lynx::Song song;
  25387. song.mixer = lynx::Song::defaultMixer (2);
  25388. for (int d = 0; d < 2; ++d)
  25389. {
  25390. lynx::ChannelDef c;
  25391. c.name = d == 0 ? "Fruity Dance" : "Fruity Dance #2";
  25392. c.instrument = lynx::InstrumentKind::fruitydance;
  25393. lynx::dance::Settings s;
  25394. s.move = d == 0 ? lynx::dance::stepping : lynx::dance::waving;
  25395. s.x = d == 0 ? 520 : 760;
  25396. s.y = 560;
  25397. s.colour = d == 0 ? 0xffff3048 : 0xff30a8ff;
  25398. s.mirrored = d == 1;
  25399. c.pluginState = lynx::dance::toState (s);
  25400. song.channels.push_back (c);
  25401. }
  25402. // Issue #121 (round 190ba): a sprite sheet in FL's Fruity Dance format (8 frames across, a row per move, a names
  25403. // file beside it), made here from LYNX's own poses, loaded back as a user's sheet would be
  25404. juce::String sheetReport;
  25405. {
  25406. constexpr int fw = 120, fh = 150;
  25407. const std::vector<std::pair<const char*, int>> rows { { "Idle", lynx::dance::waiting }, { "Step", lynx::dance::stepping },
  25408. { "Jump", lynx::dance::jumping }, { "Wave", lynx::dance::waving },
  25409. { "Windmill", lynx::dance::windmill }, { "Held", lynx::dance::held } };
  25410. juce::Image sheet (juce::Image::ARGB, fw * lynx::dance::sheetColumns, fh * (int) rows.size(), true);
  25411. {
  25412. juce::Graphics g (sheet);
  25413. for (int r = 0; r < (int) rows.size(); ++r)
  25414. for (int k = 0; k < lynx::dance::sheetColumns; ++k)
  25415. {
  25416. juce::Graphics::ScopedSaveState save (g);
  25417. g.reduceClipRegion (k * fw, r * fh, fw, fh);
  25418. lynx::dancer::draw (g, { (k + 0.5f) * fw, (float) (r + 1) * fh - 8.0f }, 96.0f,
  25419. lynx::dance::pose (rows[(std::size_t) r].second, k / (double) lynx::dance::sheetColumns, 1), false, juce::Colour (0xff35c46a));
  25420. }
  25421. }
  25422. const juce::File picture (prefix + "-sheet.png");
  25423. savePng (sheet, picture.getFullPathName());
  25424. juce::String names;
  25425. for (const auto& [name, move] : rows)
  25426. names << (names.isEmpty() ? "" : "\r\n") << name;
  25427. picture.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  25428. // a picture that is not a whole number of frames: FL's "Bitmap size is incorrect."
  25429. const juce::File wrong (prefix + "-sheet-wrong.png");
  25430. savePng (sheet.getClippedImage ({ 0, 0, sheet.getWidth() - 3, sheet.getHeight() }), wrong.getFullPathName());
  25431. wrong.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  25432. auto error = lynx::dancer::SheetError::none;
  25433. const auto loaded = lynx::dancer::sheetFor (picture.getFullPathName().toStdString(), &error);
  25434. auto wrongError = lynx::dancer::SheetError::none;
  25435. const auto refused = lynx::dancer::sheetFor (wrong.getFullPathName().toStdString(), &wrongError);
  25436. auto missingError = lynx::dancer::SheetError::none;
  25437. const auto missing = lynx::dancer::sheetFor (juce::File (prefix + "-sheet-none.png").getFullPathName().toStdString(), &missingError);
  25438. sheetReport << "sheet_loaded=" << (loaded != nullptr ? 1 : 0) << "\n"
  25439. << "sheet_wrong_size_refused=" << (refused == nullptr && wrongError == lynx::dancer::SheetError::size ? 1 : 0) << "\n"
  25440. << "sheet_missing_refused=" << (missing == nullptr && missingError == lynx::dancer::SheetError::missing ? 1 : 0) << "\n";
  25441. bool ok = loaded != nullptr && refused == nullptr && missing == nullptr;
  25442. if (loaded != nullptr)
  25443. {
  25444. sheetReport << "sheet_rows=" << loaded->layout.rows << "\nsheet_frame=" << loaded->layout.frameWidth << "x" << loaded->layout.frameHeight
  25445. << "\nsheet_moves=" << loaded->moves() << "\nsheet_names=";
  25446. for (const auto& n : loaded->names)
  25447. sheetReport << juce::String::fromUTF8 (n.c_str()) << ";";
  25448. sheetReport << "\n";
  25449. ok = ok && loaded->layout.rows == (int) rows.size() && loaded->layout.frameWidth == fw && loaded->layout.frameHeight == fh;
  25450. // the animation as the stage draws it: a row of moments of the move "Wave" (blending on), then mirrored,
  25451. // then the row shown while the dancer is held
  25452. auto strip = lynx::shot::canvas (fw * 12, fh * 3 + 20);
  25453. int solid = 0;
  25454. {
  25455. juce::Graphics g (strip);
  25456. lynx::shot::logical (g);
  25457. g.fillAll (lynx::theme::colour::bg0);
  25458. for (int line = 0; line < 3; ++line)
  25459. {
  25460. lynx::dance::SheetAnimator animator (3);
  25461. for (int k = 0; k < 12; ++k)
  25462. {
  25463. const auto frame = animator.advance (k / 12.0 + 0.001, loaded->layout.rows, 4, line == 1, true, 0.5f, line == 2);
  25464. const juce::Point<float> feet ((k + 0.5f) * fw, (float) (line + 1) * fh + 5.0f);
  25465. lynx::dancer::drawSheet (g, *loaded, feet, 1.0f, frame);
  25466. solid += lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (0.0f, -70.0f)) ? 1 : 0;
  25467. ok = ok && ! lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (-(float) fw * 0.5f + 1.0f, -(float) fh + 1.0f));
  25468. }
  25469. }
  25470. }
  25471. // mirrored = the same frame flipped left-right, on whatever renderer this build draws with
  25472. {
  25473. lynx::dance::SheetFrame plain;
  25474. plain.row = 3;
  25475. plain.column = 2;
  25476. auto turned = plain;
  25477. turned.mirrored = true;
  25478. juce::Image a (juce::Image::ARGB, fw, fh, true), b (juce::Image::ARGB, fw, fh, true);
  25479. {
  25480. juce::Graphics ga (a);
  25481. lynx::dancer::drawSheet (ga, *loaded, { fw * 0.5f, (float) fh }, 1.0f, plain);
  25482. }
  25483. {
  25484. juce::Graphics gb (b);
  25485. lynx::dancer::drawSheet (gb, *loaded, { fw * 0.5f, (float) fh }, 1.0f, turned);
  25486. }
  25487. int same = 0, flippedSame = 0, solidPixels = 0;
  25488. for (int y = 0; y < fh; ++y)
  25489. for (int x = 0; x < fw; ++x)
  25490. {
  25491. const auto pa = a.getPixelAt (x, y);
  25492. if (pa.getAlpha() < 200)
  25493. continue;
  25494. ++solidPixels;
  25495. auto alike = [pa] (juce::Colour c) {
  25496. return std::abs ((int) c.getRed() - (int) pa.getRed()) + std::abs ((int) c.getGreen() - (int) pa.getGreen())
  25497. + std::abs ((int) c.getBlue() - (int) pa.getBlue()) + std::abs ((int) c.getAlpha() - (int) pa.getAlpha()) < 12;
  25498. };
  25499. same += alike (b.getPixelAt (x, y)) ? 1 : 0;
  25500. flippedSame += alike (b.getPixelAt (fw - 1 - x, y)) ? 1 : 0;
  25501. }
  25502. const auto flips = solidPixels > 500 && flippedSame >= solidPixels * 98 / 100 && same < solidPixels * 95 / 100;
  25503. sheetReport << "sheet_mirror_flips=" << (flips ? 1 : 0) << " (" << flippedSame << " of " << solidPixels << " solid pixels match flipped, " << same
  25504. << " unflipped)\n";
  25505. ok = ok && flips;
  25506. }
  25507. sheetReport << "sheet_body_solid=" << solid << "/36\n";
  25508. ok = ok && solid >= 18;
  25509. savePng (strip, prefix + "-sheet-frames.png");
  25510. }
  25511. sheetReport << "sheet_result=" << (ok ? "OK" : "ERROR") << "\n";
  25512. lynx::ChannelDef c;
  25513. c.name = "Fruity Dance #3";
  25514. c.instrument = lynx::InstrumentKind::fruitydance;
  25515. lynx::dance::Settings s;
  25516. s.move = 2; // (the sheet's second row: "Step")
  25517. s.x = 1000;
  25518. s.y = 560;
  25519. s.sheet = picture.getFullPathName().toStdString();
  25520. c.pluginState = lynx::dance::toState (s);
  25521. song.channels.push_back (c);
  25522. }
  25523. song.patterns.emplace_back();
  25524. {
  25525. const juce::File demo (prefix + "-demo.lynx");
  25526. juce::String error;
  25527. lynx::ProjectFile::save (song, demo, error);
  25528. }
  25529. offline.setSong (std::move (song));
  25530. offline.dispatchPendingMessages();
  25531. if (auto editor = lynx::makeChannelSettingsPanel (offline, 0))
  25532. savePng (lynx::shot::snapshot (*editor), prefix + "-editor.png");
  25533. if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
  25534. savePng (lynx::shot::snapshot (*frame), prefix + "-frame.png");
  25535. if (auto editor = lynx::makeChannelSettingsPanel (offline, 2))
  25536. savePng (lynx::shot::snapshot (*editor), prefix + "-sheet-editor.png");
  25537. {
  25538. // the stage with the three dancers (the third from the sheet)
  25539. lynx::DanceStage stage (offline);
  25540. stage.setSize (1280, 640);
  25541. stage.update();
  25542. sheetReport << "stage_dancers=" << stage.dancerCount() << "\n";
  25543. auto picture = lynx::shot::canvas (1280, 640);
  25544. {
  25545. juce::Graphics g (picture);
  25546. lynx::shot::logical (g);
  25547. g.fillAll (lynx::theme::colour::bg0);
  25548. stage.paintEntireComponent (g, true);
  25549. }
  25550. savePng (picture, prefix + "-sheet-stage.png");
  25551. }
  25552. juce::File (prefix + "-sheetreport.txt").replaceWithText (sheetReport);
  25553. }
  25554. void runControllerShot (const juce::String& prefix)
  25555. {
  25556. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25557. lynx::AudioEngine offline (false);
  25558. lynx::Song song;
  25559. song.mixer = lynx::Song::defaultMixer (2);
  25560. song.mixer[1].name = "Insert 1";
  25561. auto fx = lynx::makeEffectSlot (lynx::EffectKind::formulaController);
  25562. lynx::formula::State formula;
  25563. formula.formula = "a*Sin(SongTime*Pi*b*4)+c";
  25564. fx.state = lynx::formula::writeState (formula);
  25565. fx.params[0] = 0.5f;
  25566. fx.params[1] = 0.25f;
  25567. fx.params[2] = 0.5f;
  25568. song.mixer[1].effects.push_back (fx);
  25569. // round 164: X-Y (slot 2), X-Y-Z (slot 3) and a Control Surface (slot 4)
  25570. {
  25571. auto xyFx = lynx::makeEffectSlot (lynx::EffectKind::xyController);
  25572. xyFx.params[(std::size_t) lynx::xy::level (0)] = 0.3f;
  25573. xyFx.params[(std::size_t) lynx::xy::level (1)] = 0.7f;
  25574. xyFx.params[(std::size_t) lynx::xy::tension (0)] = 0.8f;
  25575. song.mixer[1].effects.push_back (xyFx);
  25576. auto xyzFx = lynx::makeEffectSlot (lynx::EffectKind::xyzController);
  25577. xyzFx.params[(std::size_t) lynx::xy::level (2)] = 0.8f;
  25578. song.mixer[1].effects.push_back (xyzFx);
  25579. // round 165: an X-Y-Z whose X curve is FL's "Stairs" (tension +40 %) and Y a bent single curve
  25580. xyzFx.params[(std::size_t) lynx::xy::curveMode (0)] = lynx::xy::curveModeValue (lynx::flcurve::stairs);
  25581. xyzFx.params[(std::size_t) lynx::xy::tension (0)] = 0.7f;
  25582. xyzFx.params[(std::size_t) lynx::xy::level (0)] = 0.62f;
  25583. xyzFx.params[(std::size_t) lynx::xy::tension (1)] = 0.825f;
  25584. song.mixer[1].effects.push_back (xyzFx);
  25585. auto panel = lynx::makeEffectSlot (lynx::EffectKind::controlSurface);
  25586. lynx::SurfaceControl c;
  25587. for (const auto& [kind, name, v, x, y] : std::vector<std::tuple<lynx::SurfaceControl::Kind, const char*, float, float, float>> {
  25588. { lynx::SurfaceControl::Kind::knob, "Cutoff", 0.65f, 20.0f, 20.0f },
  25589. { lynx::SurfaceControl::Kind::knob, "Reso", 0.3f, 90.0f, 20.0f },
  25590. { lynx::SurfaceControl::Kind::slider, "Mix", 0.8f, 170.0f, 20.0f },
  25591. { lynx::SurfaceControl::Kind::xy, "Space", 0.4f, 230.0f, 20.0f },
  25592. { lynx::SurfaceControl::Kind::button, "Drop", 0.0f, 20.0f, 110.0f },
  25593. { lynx::SurfaceControl::Kind::checkBox, "Bypass", 1.0f, 20.0f, 160.0f } })
  25594. {
  25595. c.kind = kind;
  25596. c.name = name;
  25597. c.value = v;
  25598. c.valueY = 0.6f;
  25599. c.x = x;
  25600. c.y = y;
  25601. lynx::surface::add (panel, c);
  25602. }
  25603. song.mixer[1].effects.push_back (panel);
  25604. }
  25605. lynx::ChannelDef env;
  25606. env.name = "Envelope Controller";
  25607. env.instrument = lynx::InstrumentKind::controller;
  25608. auto ecData = lynx::defaultEnvelopeController();
  25609. ecData[0].lfoOn = true;
  25610. ecData[0].lfoTempo = true;
  25611. ecData[0].lfoSpeed = 40898;
  25612. ecData[0].maps[lynx::mapKeyboard].count = 2;
  25613. ecData[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  25614. ecData[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  25615. ecData[0].maps[lynx::mapModX] = ecData[0].maps[lynx::mapKeyboard];
  25616. env.controllerState = lynx::writeEnvelopeController (ecData);
  25617. song.channels.push_back (env);
  25618. lynx::ChannelDef out;
  25619. out.name = "MIDI Out";
  25620. out.instrument = lynx::InstrumentKind::midiOut;
  25621. lynx::midictl::MidiOutSettings settings;
  25622. settings.port = 1;
  25623. lynx::midictl::writeMidiOut (out.pluginState, settings);
  25624. song.channels.push_back (out);
  25625. // a Layer (round 164) over three synths split across the keyboard, crossfading
  25626. for (const auto* name : { "Bass", "Pad", "Lead" })
  25627. {
  25628. lynx::ChannelDef c;
  25629. c.name = name;
  25630. c.instrument = lynx::InstrumentKind::synth;
  25631. song.channels.push_back (c);
  25632. }
  25633. {
  25634. lynx::ChannelDef layer;
  25635. layer.name = "Layer";
  25636. layer.instrument = lynx::InstrumentKind::layer;
  25637. song.channels.push_back (layer);
  25638. const auto self = (int) song.channels.size() - 1;
  25639. lynx::layer::setChildren (song, self, { 2, 3, 4 });
  25640. song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
  25641. song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
  25642. song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
  25643. song.channels[(std::size_t) self].layer.crossfade = true;
  25644. song.channels[(std::size_t) self].layer.fade = 0.35f;
  25645. }
  25646. {
  25647. lynx::ChannelDef dash; // channel 6
  25648. dash.name = "Dashboard";
  25649. dash.instrument = lynx::InstrumentKind::dashboard;
  25650. dash.patcher.surface = lynx::surface::starterControls();
  25651. song.channels.push_back (dash);
  25652. }
  25653. {
  25654. lynx::ChannelDef volt; // channel 7: FL's render-test settings (main L pitch, R gate × 0.5) with Out 2 on insert 3
  25655. volt.name = "Voltage Controller";
  25656. volt.instrument = lynx::InstrumentKind::voltage;
  25657. lynx::voltage::Settings v;
  25658. v.enabled = true;
  25659. v.params[9] = 49152;
  25660. v.unipolar[2] = true;
  25661. v.tracks = { 3, 0, 0 };
  25662. v.source[6] = lynx::voltage::Source::clock;
  25663. volt.pluginState = lynx::voltage::write (v);
  25664. song.channels.push_back (volt);
  25665. }
  25666. song.patterns.emplace_back();
  25667. offline.setSong (std::move (song));
  25668. offline.dispatchPendingMessages();
  25669. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  25670. if (c == nullptr)
  25671. return;
  25672. savePng (lynx::shot::snapshot (*c), prefix + name);
  25673. };
  25674. shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
  25675. shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
  25676. shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
  25677. shoot (lynx::makeChannelFrame (offline, 3, -1), "-layer-child-misc.png"); // (the key-region ruler over the root keyboard)
  25678. {
  25679. const auto slotOf = [] (int k) -> lynx::SlotLocator {
  25680. return [k] (lynx::Song& s) { return &s.mixer[1].effects[(std::size_t) k]; };
  25681. };
  25682. const lynx::AutomationTarget target { lynx::AutomationTargetKind::effectParam, 1, 1, 0 };
  25683. shoot (lynx::makeXyControllerEditor (offline, slotOf (1), nullptr, target), "-xy-controller.png");
  25684. shoot (lynx::makeXyControllerEditor (offline, slotOf (2), nullptr, target), "-xyz-controller.png");
  25685. shoot (lynx::makeXyControllerEditor (offline, slotOf (3), nullptr, target), "-xyz-controller-stairs.png");
  25686. shoot (lynx::makeControlSurfaceEditor (offline, slotOf (4), target), "-control-surface.png");
  25687. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard.png");
  25688. shoot (lynx::makeChannelSettingsPanel (offline, 7), "-voltage-controller.png");
  25689. }
  25690. // FL's Dashboard presets of this PC's FL Studio, imported (round 164f): one PNG each
  25691. if (const auto fl = lynx::findFlStudio(); fl.installDir.isDirectory())
  25692. for (const auto& file : fl.installDir.getChildFile ("Data/Patches/Plugin presets/Generators/Dashboard").findChildFiles (juce::File::findFiles, false, "*.fst"))
  25693. {
  25694. juce::MemoryBlock bytes;
  25695. if (! file.loadFileAsData (bytes))
  25696. continue;
  25697. const auto preset = flp::parseProject ({ (const std::uint8_t*) bytes.getData(), bytes.getSize() }, true);
  25698. const auto dash = preset.channels.empty() ? std::nullopt : lynx::surface::parseFlDashboard (preset.channels[0].pluginState);
  25699. if (! dash || dash->controls.empty())
  25700. continue;
  25701. offline.editSong ([&] (lynx::Song& s) {
  25702. s.channels[6].name = file.getFileNameWithoutExtension().toStdString();
  25703. s.channels[6].patcher.surface = dash->controls;
  25704. s.channels[6].pluginState = preset.channels[0].pluginState; // (its MIDI port, channel, program)
  25705. });
  25706. offline.dispatchPendingMessages();
  25707. const auto name = file.getFileNameWithoutExtension().replaceCharacter (' ', '-');
  25708. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard-fl-" + name + ".png");
  25709. // edit mode (round 165): each control's output number and the MIDI it sends ("1 CC74")
  25710. if (auto panel = lynx::makeChannelSettingsPanel (offline, 6))
  25711. {
  25712. std::function<void (juce::Component&)> pressEdit = [&] (juce::Component& c) {
  25713. for (auto* child : c.getChildren())
  25714. {
  25715. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == lynx::tr ("Edit"))
  25716. b->setToggleState (true, juce::sendNotificationSync);
  25717. pressEdit (*child);
  25718. }
  25719. };
  25720. pressEdit (*panel);
  25721. shoot (std::move (panel), "-dashboard-fl-" + name + "-edit.png");
  25722. }
  25723. }
  25724. // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
  25725. if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
  25726. for (int part = 0; part < 7; ++part)
  25727. {
  25728. for (auto* child : ec->getChildren())
  25729. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  25730. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  25731. savePng (lynx::shot::snapshot (*ec), prefix + "-ec-part" + juce::String (part) + ".png");
  25732. }
  25733. lynx::FormulaControllerWindows::open (offline, 1, 0);
  25734. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  25735. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  25736. if (w->getName().startsWith ("Formula") && w->getContentComponent() != nullptr)
  25737. savePng (lynx::shot::snapshot (*w->getContentComponent()), prefix + "-formula-controller.png");
  25738. lynx::FormulaControllerWindows::closeAll();
  25739. }
  25740. bool runEdisonSlotTest (const juce::String& folderPath, const juce::String& flp)
  25741. {
  25742. namespace ae = lynx::audioedit;
  25743. namespace ef = lynx::edisonfx;
  25744. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25745. const juce::File folder (folderPath);
  25746. folder.createDirectory();
  25747. juce::String report;
  25748. bool all = true;
  25749. auto check = [&] (const juce::String& name, bool ok, const juce::String& note = {}) {
  25750. report << name << "=" << (ok ? "ok" : "FAIL") << (note.isNotEmpty() ? " (" + note + ")" : juce::String()) << "\n";
  25751. all = all && ok;
  25752. };
  25753. auto shot = [&folder] (juce::Component& c, const juce::String& name) {
  25754. savePng (lynx::shot::paint (c, lynx::theme::panel), folder.getChildFile (name).getFullPathName());
  25755. };
  25756. auto findSlot = [] (const lynx::Song& song, int& track, int& slot) {
  25757. for (track = 0; track < (int) song.mixer.size(); ++track)
  25758. for (slot = 0; slot < (int) song.mixer[(std::size_t) track].effects.size(); ++slot)
  25759. if (song.mixer[(std::size_t) track].effects[(std::size_t) slot].kind == lynx::EffectKind::edison)
  25760. return true;
  25761. return false;
  25762. };
  25763. {
  25764. lynx::AudioEngine engine (false);
  25765. engine.setRecordingTarget (folder.getChildFile ("Audio").getChildFile ("Recorded"), "Test");
  25766. // a project without the plugin is written as before: nothing of it in the file, and it reads back the same
  25767. const auto before = lynx::ProjectFile::toJson (engine.getSong(), false);
  25768. juce::String error;
  25769. const auto same = lynx::ProjectFile::fromJson (before, error);
  25770. check ("old_project_text_has_no_trace", ! before.containsIgnoreCase ("edison"));
  25771. check ("old_project_round_trip_stable", same.has_value() && lynx::ProjectFile::toJson (*same, false) == before);
  25772. const auto at = lynx::addEdisonSlot (engine, 1);
  25773. engine.dispatchPendingMessages();
  25774. check ("slot_added_to_first_empty_slot", at == 0 && engine.getSong().mixer[1].effects.size() == 1
  25775. && engine.getSong().mixer[1].effects[0].kind == lynx::EffectKind::edison);
  25776. if (at < 0)
  25777. {
  25778. folder.getChildFile ("report.txt").replaceWithText (report);
  25779. return false;
  25780. }
  25781. const auto second = lynx::addEdisonSlot (engine, 1); // several instances on a track
  25782. engine.dispatchPendingMessages();
  25783. check ("second_instance_on_the_same_track", second == 1);
  25784. engine.editSong ([at] (lynx::Song& s) {
  25785. s.mixer[1].effects[(std::size_t) at].params[ef::recordMode] = ef::modeValue (ef::Mode::now);
  25786. });
  25787. engine.dispatchPendingMessages();
  25788. const auto slotOf = [&engine, at] { return engine.getSong().mixer[1].effects[(std::size_t) at]; };
  25789. const auto fx = engine.getEffect (1, at);
  25790. const auto p = std::dynamic_pointer_cast<ef::Processor> (fx);
  25791. const auto session = ef::findSession (slotOf().instance.id);
  25792. check ("engine_built_the_effect_with_its_session", p != nullptr && session != nullptr);
  25793. const auto other = ef::findSession (engine.getSong().mixer[1].effects[1].instance.id);
  25794. check ("instances_have_their_own_audio", other != nullptr && other != session);
  25795. if (p == nullptr || session == nullptr)
  25796. {
  25797. folder.getChildFile ("report.txt").replaceWithText (report);
  25798. return false;
  25799. }
  25800. // idle: the audio passes through bit for bit
  25801. const auto rate = p->sampleRate();
  25802. std::vector<float> l (512), r (512);
  25803. auto fill = [&] (int block) {
  25804. for (int k = 0; k < 512; ++k)
  25805. {
  25806. const auto t = (double) (block * 512 + k) / rate;
  25807. l[(std::size_t) k] = 0.6f * (float) std::sin (2.0 * 3.141592653589793 * 220.0 * t);
  25808. r[(std::size_t) k] = 0.4f * (float) std::sin (2.0 * 3.141592653589793 * 330.0 * t);
  25809. }
  25810. };
  25811. fill (0);
  25812. auto inL = l, inR = r;
  25813. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  25814. check ("idle_pass_through_bit_exact", l == inL && r == inR);
  25815. // a take through the slot (Now), then the flush that makes it a file of the project
  25816. std::vector<float> wantL, wantR;
  25817. check ("record_starts", session->start (p, true));
  25818. for (int block = 0; block < 60; ++block)
  25819. {
  25820. fill (block);
  25821. wantL.insert (wantL.end(), l.begin(), l.end());
  25822. wantR.insert (wantR.end(), r.begin(), r.end());
  25823. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  25824. }
  25825. session->stop();
  25826. check ("take_is_the_input", session->document().audio.numChannels() == 2 && session->document().audio.channels[0] == wantL
  25827. && session->document().audio.channels[1] == wantR);
  25828. ae::Document withMarkers = session->document();
  25829. ae::addMarker (withMarkers, 4000, "Verse");
  25830. ae::addMarker (withMarkers, 12000);
  25831. ae::setLoop (withMarkers, { 2000, 20000 });
  25832. session->setDocument (withMarkers);
  25833. engine.flushEdisonAudio();
  25834. engine.dispatchPendingMessages();
  25835. const juce::File file (juce::String::fromUTF8 (slotOf().samplePath.c_str()));
  25836. check ("audio_written_to_the_project_folder", file.existsAsFile() && file.isAChildOf (folder.getChildFile ("Audio").getChildFile ("Recorded")),
  25837. file.getFullPathName());
  25838. check ("file_listed_with_the_session_recordings", std::find (engine.getSessionRecordings().begin(), engine.getSessionRecordings().end(), file)
  25839. != engine.getSessionRecordings().end());
  25840. check ("effect_kept_running_through_the_flush", engine.getEffect (1, at) == fx);
  25841. check ("nothing_unsaved_after_the_flush", ! session->dirty());
  25842. engine.flushEdisonAudio(); // (a second flush writes nothing new)
  25843. check ("second_flush_keeps_the_file", juce::File (juce::String::fromUTF8 (slotOf().samplePath.c_str())) == file);
  25844. // the project file: saved, loaded, the same slot with the same audio
  25845. engine.editSong ([at] (lynx::Song& s) {
  25846. auto& params = s.mixer[1].effects[(std::size_t) at].params;
  25847. params[ef::recordMode] = ef::modeValue (ef::Mode::onPlay);
  25848. params[ef::append] = 0.0f;
  25849. params[ef::muteInput] = 1.0f;
  25850. params[ef::slave] = 1.0f;
  25851. params[ef::maxTime] = 5.0f / 6.0f;
  25852. });
  25853. engine.capturePluginStates();
  25854. const auto project = folder.getChildFile ("edison-slot.lynx");
  25855. check ("project_saved", lynx::ProjectFile::save (engine.getSong(), project, error), error);
  25856. auto loaded = lynx::ProjectFile::load (project, error);
  25857. check ("project_loaded", loaded.has_value(), error);
  25858. if (loaded)
  25859. {
  25860. const auto& a = slotOf();
  25861. const auto& b = loaded->mixer[1].effects[(std::size_t) at];
  25862. check ("slot_kind_kept", b.kind == lynx::EffectKind::edison && loaded->mixer[1].effects.size() == 2);
  25863. check ("slot_settings_kept", ef::modeOf (b.params) == ef::Mode::onPlay && b.params[ef::append] < 0.5f && b.params[ef::muteInput] >= 0.5f
  25864. && b.params[ef::slave] >= 0.5f && ef::maxTimeIndexOf (b.params) == 5
  25865. && std::abs (b.params[ef::noiseThreshold] - a.params[ef::noiseThreshold]) < 1.0e-6f);
  25866. check ("slot_audio_path_kept", b.samplePath == a.samplePath);
  25867. check ("project_text_round_trip_stable", lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (engine.getSong(), false));
  25868. lynx::AudioEngine second (false);
  25869. second.setSong (std::move (*loaded));
  25870. second.dispatchPendingMessages();
  25871. const auto reopened = ef::findSession (second.getSong().mixer[1].effects[(std::size_t) at].instance.id);
  25872. check ("reopened_project_has_the_audio", reopened != nullptr && reopened != session
  25873. && reopened->document().audio.channels == withMarkers.audio.channels
  25874. && reopened->document().audio.sampleRate == withMarkers.audio.sampleRate);
  25875. check ("reopened_project_has_markers_and_loop", reopened != nullptr && reopened->document().markers.size() == 2
  25876. && reopened->document().markers[0].name == "Verse"
  25877. && reopened->document().loopStart == 2000 && reopened->document().loopEnd == 20000);
  25878. check ("reopened_empty_instance_is_empty", ef::findSession (second.getSong().mixer[1].effects[1].instance.id) != nullptr
  25879. && ef::findSession (second.getSong().mixer[1].effects[1].instance.id)->document().audio.empty());
  25880. if (auto editor = lynx::makeEdisonSlotEditor (second, 1, at))
  25881. {
  25882. editor->setSize (1120, 600);
  25883. second.dispatchPendingMessages();
  25884. shot (*editor, "slot-editor-reopened.png");
  25885. }
  25886. }
  25887. // the plugin's window: the audio editor on the slot (empty instance, then the one with the take)
  25888. if (auto editor = lynx::makeEdisonSlotEditor (engine, 1, 1))
  25889. {
  25890. editor->setSize (1120, 600);
  25891. engine.dispatchPendingMessages();
  25892. shot (*editor, "slot-editor-empty.png");
  25893. }
  25894. auto editor = lynx::makeEdisonSlotEditor (engine, 1, at);
  25895. check ("slot_window_is_the_audio_editor", editor != nullptr);
  25896. if (editor != nullptr)
  25897. {
  25898. editor->setSize (1120, 600);
  25899. engine.dispatchPendingMessages();
  25900. shot (*editor, "slot-editor.png");
  25901. juce::File (folder.getChildFile ("slot-menu.txt")).replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  25902. }
  25903. check ("no_editor_for_other_slots", lynx::makeEdisonSlotEditor (engine, 0, 0) == nullptr);
  25904. editor.reset();
  25905. // deleting the slot leaves the song without it (the file stays for the unused-recordings prompt)
  25906. engine.editSong ([at] (lynx::Song& s) { s.mixer[1].effects.erase (s.mixer[1].effects.begin() + at); });
  25907. engine.dispatchPendingMessages();
  25908. check ("deleted_slot_is_gone", engine.getSong().mixer[1].effects.size() == 1 && file.existsAsFile());
  25909. }
  25910. if (flp.isNotEmpty())
  25911. {
  25912. lynx::AudioEngine engine (false);
  25913. juce::String error;
  25914. const auto imported = engine.importFlpFile (juce::File (flp), error);
  25915. engine.dispatchPendingMessages();
  25916. check ("flp_imported", imported, error);
  25917. int count = 0, withAudio = 0;
  25918. const auto& song = engine.getSong();
  25919. for (int t = 0; t < (int) song.mixer.size(); ++t)
  25920. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  25921. {
  25922. const auto& fx = song.mixer[(std::size_t) t].effects[(std::size_t) s];
  25923. if (fx.kind != lynx::EffectKind::edison)
  25924. continue;
  25925. ++count;
  25926. const auto session = ef::findSession (fx.instance.id);
  25927. const auto frames = session != nullptr ? session->document().audio.frames() : -1;
  25928. withAudio += frames > 0 ? 1 : 0;
  25929. report << "flp_slot track " << t << " slot " << s << ": mode " << ef::modeName (ef::modeOf (fx.params))
  25930. << ", append " << (fx.params[ef::append] >= 0.5f ? "on" : "off") << ", mute input " << (fx.params[ef::muteInput] >= 0.5f ? "on" : "off")
  25931. << ", slave " << (fx.params[ef::slave] >= 0.5f ? "on" : "off") << ", loop " << (fx.params[ef::loopPlay] >= 0.5f ? "on" : "off")
  25932. << ", max time index " << ef::maxTimeIndexOf (fx.params) << ", threshold " << juce::String (fx.params[ef::noiseThreshold], 4)
  25933. << ", state " << (int) fx.state.size() << " bytes, audio " << (juce::int64) frames << " frames"
  25934. << (session != nullptr && frames > 0 ? " at " + juce::String (session->document().audio.sampleRate, 0) + " Hz, "
  25935. + juce::String (session->document().audio.numChannels()) + " ch, "
  25936. + juce::String ((int) session->document().markers.size()) + " markers"
  25937. : juce::String())
  25938. << "\n";
  25939. if (count == 1 || (frames > 0 && withAudio == 1))
  25940. if (auto editor = lynx::makeEdisonSlotEditor (engine, t, s))
  25941. {
  25942. editor->setSize (1120, 600);
  25943. engine.dispatchPendingMessages();
  25944. shot (*editor, frames > 0 ? "slot-editor-flp-audio.png" : "slot-editor-flp.png");
  25945. }
  25946. }
  25947. check ("flp_edison_slots_kept_as_the_plugin", count > 0, juce::String (count) + " slots, " + juce::String (withAudio) + " with audio");
  25948. // saved as .lynx and read again: still the plugin, FL's state (the audio) with it
  25949. int t = 0, s = 0;
  25950. if (findSlot (song, t, s))
  25951. {
  25952. const auto project = folder.getChildFile ("edison-flp.lynx");
  25953. const auto saved = lynx::ProjectFile::save (song, project, error);
  25954. std::optional<lynx::Song> loaded;
  25955. if (saved)
  25956. loaded = lynx::ProjectFile::load (project, error);
  25957. check ("flp_slot_survives_the_project_file", loaded.has_value() && t < (int) loaded->mixer.size()
  25958. && s < (int) loaded->mixer[(std::size_t) t].effects.size()
  25959. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::edison
  25960. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].state == song.mixer[(std::size_t) t].effects[(std::size_t) s].state
  25961. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].params == song.mixer[(std::size_t) t].effects[(std::size_t) s].params,
  25962. error);
  25963. }
  25964. }
  25965. // round 190ct (live FL check 190cq): the open-and-record preset, the fresh defaults and the question before
  25966. // "Remove all Edison instances", in the app
  25967. {
  25968. lynx::AudioEngine engine (false);
  25969. lynx::MainComponent ui (engine, false);
  25970. ui.setSize (1600, 900);
  25971. engine.dispatchPendingMessages();
  25972. const auto toolsMenu = [&ui] {
  25973. const auto names = ui.getMenuNamesForSnapshot();
  25974. for (int m = 0; m < names.size(); ++m)
  25975. if (names[m] == lynx::tr ("Tools"))
  25976. return ui.getMenuForSnapshot (m);
  25977. return juce::PopupMenu();
  25978. };
  25979. const auto removeItem = [&toolsMenu] (bool& found, bool& enabled) {
  25980. found = enabled = false;
  25981. const auto menu = toolsMenu(); // (the iterator keeps a reference)
  25982. for (juce::PopupMenu::MenuItemIterator it (menu, true); it.next();)
  25983. if (it.getItem().text == lynx::tr ("Remove all Edison instances"))
  25984. {
  25985. found = true;
  25986. enabled = it.getItem().isEnabled;
  25987. if (enabled && it.getItem().action)
  25988. it.getItem().action(); // asks: nothing may go before the answer
  25989. return;
  25990. }
  25991. };
  25992. const auto count = [&engine] {
  25993. int n = 0;
  25994. for (const auto& track : engine.getSong().mixer)
  25995. for (const auto& fx : track.effects)
  25996. n += fx.kind == lynx::EffectKind::edison ? 1 : 0;
  25997. return n;
  25998. };
  25999. bool found = false, enabled = false;
  26000. removeItem (found, enabled);
  26001. check ("remove_all_edison_enabled_with_none", found && enabled && count() == 0);
  26002. const auto plain = lynx::addEdisonSlot (engine, 1);
  26003. const auto armed = lynx::addEdisonSlot (engine, 2, true);
  26004. engine.dispatchPendingMessages();
  26005. if (plain >= 0 && armed >= 0)
  26006. {
  26007. const auto& a = engine.getSong().mixer[1].effects[(std::size_t) plain].params;
  26008. const auto& b = engine.getSong().mixer[2].effects[(std::size_t) armed].params;
  26009. check ("open_audio_editor_fresh_defaults", ef::modeOf (a) == ef::Mode::onInput && ef::maxTimeIndexOf (a) == 5 && a[ef::append] >= 0.5f
  26010. && a[ef::slave] < 0.5f);
  26011. check ("open_audio_editor_and_record_preset", ef::modeOf (b) == ef::Mode::onPlay && ef::maxTimeIndexOf (b) == 3 && b[ef::append] < 0.5f
  26012. && b[ef::slave] >= 0.5f);
  26013. }
  26014. else
  26015. check ("open_audio_editor_slots_added", false);
  26016. removeItem (found, enabled);
  26017. engine.dispatchPendingMessages();
  26018. check ("remove_all_edison_asks_first", found && enabled && count() == 2);
  26019. const auto question = lynx::removeAllEdisonInstancesQuestion();
  26020. check ("remove_all_edison_question_is_fls", question.getTitle() == lynx::tr ("Remove Edison instances")
  26021. && question.getMessage() == lynx::tr ("Are you sure you want to remove all Edison instances from the project ?")
  26022. && question.getNumButtons() == 2 && question.getButtonText (0) == lynx::tr ("Yes")
  26023. && question.getButtonText (1) == lynx::tr ("No"));
  26024. // LYNX keeps an undo for the removal (rollup 190cv), so the question may not promise "(No undo)" in any
  26025. // language, and the Yes action must come back with one undo
  26026. {
  26027. bool noUndoLine = false;
  26028. for (const auto& line : juce::StringArray::fromLines (question.getMessage()))
  26029. noUndoLine = noUndoLine || line.trim().startsWithChar ('(');
  26030. check ("remove_all_edison_question_has_no_no_undo_line", ! noUndoLine && ! question.getMessage().contains ("No undo"));
  26031. const int before = count();
  26032. lynx::removeAllEdisonInstances (engine);
  26033. engine.dispatchPendingMessages();
  26034. const int removed = count();
  26035. engine.undo();
  26036. engine.dispatchPendingMessages();
  26037. check ("remove_all_edison_yes_removes_and_undo_restores", before == 2 && removed == 0 && count() == 2);
  26038. }
  26039. {
  26040. juce::AlertWindow box (question.getTitle(), question.getMessage(), question.getIconType());
  26041. box.addButton (question.getButtonText (0), 1);
  26042. box.addButton (question.getButtonText (1), 0);
  26043. box.setSize (box.getWidth(), box.getHeight());
  26044. savePng (lynx::shot::paint (box, lynx::theme::panel), folder.getChildFile ("remove-all-edison-question.png").getFullPathName());
  26045. }
  26046. {
  26047. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::edison);
  26048. lynx::edisonfx::setOpenAndRecord (slot.params);
  26049. engine.editSong ([&slot] (lynx::Song& s) { s.mixer[3].effects.push_back (slot); });
  26050. engine.dispatchPendingMessages();
  26051. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 3, 0))
  26052. {
  26053. editor->setSize (1120, 600);
  26054. engine.dispatchPendingMessages();
  26055. shot (*editor, "slot-editor-open-and-record.png");
  26056. }
  26057. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 1, plain))
  26058. {
  26059. editor->setSize (1120, 600);
  26060. engine.dispatchPendingMessages();
  26061. shot (*editor, "slot-editor-fresh-defaults.png");
  26062. }
  26063. }
  26064. }
  26065. report << (all ? "ALL OK\n" : "FAILURES\n");
  26066. folder.getChildFile ("report.txt").replaceWithText (report);
  26067. return all;
  26068. }
  26069. void runAraShot190kx (const juce::String& prefix)
  26070. {
  26071. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26072. lynx::AudioEngine engine (false);
  26073. juce::PluginDescription melodyne;
  26074. melodyne.name = "Melodyne";
  26075. melodyne.manufacturerName = "Celemony";
  26076. melodyne.pluginFormatName = "VST3";
  26077. melodyne.fileOrIdentifier = "C:\\Program Files\\Common Files\\VST3\\Celemony\\Melodyne\\Melodyne.vst3";
  26078. melodyne.uniqueId = 0x190;
  26079. melodyne.isInstrument = false;
  26080. #if JUCE_PLUGINHOST_ARA
  26081. melodyne.hasARAExtension = true;
  26082. #endif
  26083. engine.getPluginHost().getKnownPlugins().addType (melodyne);
  26084. lynx::MainComponent ui (engine, false);
  26085. ui.setSize (1600, 900);
  26086. {
  26087. auto song = lynx::Song::makeDefault();
  26088. song.channels.push_back ({});
  26089. song.channels.back().name = "Vocal";
  26090. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  26091. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  26092. lynx::Clip c;
  26093. c.kind = lynx::ClipKind::audio;
  26094. c.channel = (int) song.channels.size() - 1;
  26095. c.track = 3;
  26096. c.start = 4 * lynx::ppq;
  26097. c.length = 2 * lynx::ppq;
  26098. song.playlist.push_back (c);
  26099. engine.setSong (std::move (song));
  26100. }
  26101. engine.dispatchPendingMessages();
  26102. auto& playlist = ui.getPlaylistForSnapshot();
  26103. auto sub = [] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  26104. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  26105. if (it.getItem().subMenu != nullptr && it.getItem().text == text)
  26106. return it.getItem().subMenu.get();
  26107. return nullptr;
  26108. };
  26109. juce::String report;
  26110. for (const auto edited : { false, true })
  26111. {
  26112. if (edited) // (the channel edited in the stand-in: the menu ticks it and offers its editor; nothing is loaded here)
  26113. {
  26114. const auto ch = engine.getSong().playlist[0].channel;
  26115. engine.editSong ([ch, id = melodyne.createIdentifierString().toStdString()] (lynx::Song& s) {
  26116. s.channels[(std::size_t) ch].ara = { id, "Melodyne" };
  26117. }, false);
  26118. }
  26119. const auto menu = playlist.getClipMenuForSnapshot (0);
  26120. savePng (columnMenuImage (menu), prefix + (edited ? "-clip-menu-edited.png" : "-clip-menu.png"));
  26121. if (const auto* ara = sub (menu, lynx::tr ("Edit in ARA plugin")))
  26122. {
  26123. savePng (columnMenuImage (*ara), prefix + (edited ? "-ara-submenu-edited.png" : "-ara-submenu.png"));
  26124. report << (edited ? "edited:" : "plain:");
  26125. for (juce::PopupMenu::MenuItemIterator it (*ara); it.next();)
  26126. report << " [" << (it.getItem().isSeparator ? juce::String ("-") : it.getItem().text) << (it.getItem().isTicked ? " *" : "") << "]";
  26127. report << "\n";
  26128. }
  26129. else
  26130. report << "no ARA submenu\n";
  26131. }
  26132. lynx::shot::file (juce::File (prefix + "-menus.txt")).replaceWithText (report);
  26133. std::printf ("%s", report.toRawUTF8());
  26134. }
  26135. bool runPolyEditShot190lk (const juce::String& prefix, const juce::String& file, double key)
  26136. {
  26137. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26138. lynx::AudioEngine engine (false);
  26139. lynx::MainComponent ui (engine, false);
  26140. ui.setSize (1600, 900);
  26141. juce::StringArray checks;
  26142. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  26143. auto song = lynx::Song::makeDefault();
  26144. const auto sample = engine.getSampleLibrary().load (file);
  26145. song.channels.push_back ({});
  26146. song.channels.back().name = juce::File (file).getFileNameWithoutExtension().toStdString();
  26147. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  26148. song.channels.back().samplePath = file.toStdString();
  26149. const auto channel = (int) song.channels.size() - 1;
  26150. lynx::Clip c;
  26151. c.kind = lynx::ClipKind::audio;
  26152. c.channel = channel;
  26153. c.track = 3;
  26154. const auto seconds = sample != nullptr ? (double) sample->frames() / sample->sampleRate : 4.0;
  26155. c.length = (std::int64_t) std::llround (seconds * song.bpm / 60.0 * lynx::ppq);
  26156. song.playlist.push_back (c);
  26157. engine.setSong (std::move (song));
  26158. engine.dispatchPendingMessages();
  26159. const auto clipIndex = (int) engine.getSong().playlist.size() - 1;
  26160. check (sample != nullptr && sample->frames() > 0, "the sample loads: " + file);
  26161. const auto wanted = lynx::tr ("Edit notes (polyphonic)...");
  26162. for (const auto simple : { false, true })
  26163. {
  26164. ui.setLayoutStyle (simple ? lynx::layoutstyle::Style::simple : lynx::layoutstyle::Style::pattern);
  26165. engine.dispatchPendingMessages();
  26166. const auto menu = ui.getPlaylistForSnapshot().getClipMenuForSnapshot (clipIndex);
  26167. auto afterExtras = false, found = false;
  26168. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  26169. {
  26170. afterExtras = afterExtras || (it.getItem().isSectionHeader && it.getItem().text == lynx::tr ("LYNX extras"));
  26171. found = found || (it.getItem().text == wanted && it.getItem().isEnabled && (afterExtras || simple));
  26172. }
  26173. savePng (columnMenuImage (menu), prefix + (simple ? "-clip-menu-simple.png" : "-clip-menu.png"));
  26174. check (found, juce::String (simple ? "Simple" : "Pattern") + " layout: the clip menu has \"" + wanted + "\" (LYNX extras)");
  26175. }
  26176. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  26177. engine.dispatchPendingMessages();
  26178. // the editor: analysis on this thread (Basic Pitch's evidence when ONNX Runtime loads)
  26179. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  26180. auto editor = lynx::makePolyEditor (engine, channel, true);
  26181. const auto analyseMs = juce::Time::getMillisecondCounterHiRes() - t0;
  26182. engine.dispatchPendingMessages();
  26183. editor->setSize (1100, 560);
  26184. const auto notes = lynx::polyEditorNotes (*editor);
  26185. juce::File (prefix + "-notes.txt").replaceWithText (notes);
  26186. const auto lines = juce::StringArray::fromLines (notes.trim());
  26187. check (notes.isNotEmpty(), juce::String (lines.size()) + " notes found in " + juce::String (analyseMs / 1000.0, 2) + " s for "
  26188. + juce::String (seconds, 2) + " s of audio (" + juce::String (analyseMs / 1000.0 / std::max (0.01, seconds), 3) + " x real time)");
  26189. const auto saved = engine.getSong().channels[(std::size_t) channel].polyEdit;
  26190. check (! saved.empty() && lynx::polyedit::parse (saved).has_value(), "the analysis is in the channel (the project keeps it): " + juce::String ((int) saved.size()) + " bytes");
  26191. const auto shoot = [&] (const juce::String& name) {
  26192. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-" + name + ".png");
  26193. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, 1.5f), prefix + "-" + name + "@150.png");
  26194. };
  26195. shoot ("editor");
  26196. // the note nearest `key` in the first two seconds
  26197. int pick = -1;
  26198. double best = 1e9;
  26199. for (const auto& line : lines)
  26200. {
  26201. const auto t = juce::StringArray::fromTokens (line, " ", "");
  26202. if (t.size() < 4 || line.endsWith (" candidate")) // (round 190lo: the rejected candidates are listed too)
  26203. continue;
  26204. const auto start = t[3].upToFirstOccurrenceOf ("-", false, false).getDoubleValue();
  26205. const auto d = std::abs (t[2].getDoubleValue() - key) + (start > 2.0 ? 100.0 : 0.0);
  26206. if (d < best)
  26207. best = d, pick = t[0].getIntValue();
  26208. }
  26209. check (pick >= 0 && best < 0.5, "a note at key " + juce::String (key, 1) + ": note " + juce::String (pick));
  26210. if (pick >= 0)
  26211. {
  26212. lynx::setPolyEditorShotState (*editor, "select:" + juce::String (pick));
  26213. lynx::setPolyEditorShotState (*editor, "pitch:" + juce::String (pick) + ":-1");
  26214. const auto rendered = lynx::setPolyEditorShotState (*editor, "render");
  26215. engine.dispatchPendingMessages();
  26216. check (rendered.startsWith ("render"), "the edit renders: " + rendered);
  26217. const auto blob = engine.getSong().channels[(std::size_t) channel].polyEdit;
  26218. const auto model = lynx::polyedit::parse (blob);
  26219. check (model && model->edited(), "the edit is in the channel (one undo step)");
  26220. // what the clip plays: the cached render, at once
  26221. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  26222. const auto plays = lynx::polyedit::renderedFor (file.toStdString(), sample, blob);
  26223. const auto lookupMs = juce::Time::getMillisecondCounterHiRes() - t1;
  26224. check (plays != nullptr && plays != sample && plays->frames() == sample->frames(), "the clip plays the edited render (cache hit in " + juce::String (lookupMs, 2) + " ms)");
  26225. // the project keeps it
  26226. juce::String error;
  26227. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (engine.getSong()), error);
  26228. check (back && back->channels.size() > (std::size_t) channel && back->channels[(std::size_t) channel].polyEdit == blob, "the .lynx round trip keeps the notes and edits");
  26229. // undo: the edit goes, the analysis stays
  26230. engine.undo();
  26231. engine.dispatchPendingMessages();
  26232. const auto undone = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  26233. check (undone && ! undone->edited() && undone->notes.size() == model->notes.size(), "undo takes the edit back, the analysis stays");
  26234. engine.redo();
  26235. engine.dispatchPendingMessages();
  26236. shoot ("edited");
  26237. lynx::setPolyEditorShotState (*editor, "select:");
  26238. shoot ("edited-plain");
  26239. }
  26240. check (true, "paint " + juce::String (lynx::polyEditorPaintMs (*editor, 10), 2) + " ms (1100 x 560)");
  26241. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  26242. editor.reset();
  26243. engine.dispatchPendingMessages();
  26244. return ! checks.joinIntoString ("\n").contains ("FAIL ");
  26245. }
  26246. // round 190lo: see --polyeditshot190lo
  26247. bool runPolyEditShot190lo (const juce::String& prefix, const juce::String& file, double key)
  26248. {
  26249. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26250. lynx::AudioEngine engine (false);
  26251. juce::StringArray checks;
  26252. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  26253. auto song = lynx::Song::makeDefault();
  26254. const auto sample = engine.getSampleLibrary().load (file);
  26255. song.channels.push_back ({});
  26256. song.channels.back().name = juce::File (file).getFileNameWithoutExtension().toStdString();
  26257. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  26258. song.channels.back().samplePath = file.toStdString();
  26259. const auto channel = (int) song.channels.size() - 1;
  26260. engine.setSong (std::move (song));
  26261. engine.dispatchPendingMessages();
  26262. check (sample != nullptr && sample->frames() > 0, "the sample loads: " + file);
  26263. if (sample == nullptr)
  26264. {
  26265. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  26266. return false;
  26267. }
  26268. const auto seconds = (double) sample->frames() / sample->sampleRate;
  26269. auto editor = lynx::makePolyEditor (engine, channel, true);
  26270. engine.dispatchPendingMessages();
  26271. editor->setSize (1100, 580);
  26272. const auto shoot = [&] (const juce::String& name) {
  26273. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-" + name + ".png");
  26274. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, 1.5f), prefix + "-" + name + "@150.png");
  26275. };
  26276. const auto state = [&] (const juce::String& s) { return lynx::setPolyEditorShotState (*editor, s); };
  26277. struct Line
  26278. {
  26279. int k = -1;
  26280. double midi = 0.0, start = 0.0, end = 0.0;
  26281. bool candidate = false;
  26282. };
  26283. const auto notesNow = [&] {
  26284. std::vector<Line> out;
  26285. for (const auto& line : juce::StringArray::fromLines (lynx::polyEditorNotes (*editor).trim()))
  26286. {
  26287. const auto t = juce::StringArray::fromTokens (line, " ", "");
  26288. if (t.size() < 4)
  26289. continue;
  26290. out.push_back ({ t[0].getIntValue(), t[2].getDoubleValue(), t[3].upToFirstOccurrenceOf ("-", false, false).getDoubleValue(),
  26291. t[3].fromFirstOccurrenceOf ("-", false, false).getDoubleValue(), line.endsWith (" candidate") });
  26292. }
  26293. return out;
  26294. };
  26295. auto notes = notesNow();
  26296. juce::File (prefix + "-notes.txt").replaceWithText (lynx::polyEditorNotes (*editor));
  26297. const auto active = (int) std::count_if (notes.begin(), notes.end(), [] (const Line& l) { return ! l.candidate; });
  26298. const auto candidates = (int) notes.size() - active;
  26299. check (active > 0, juce::String (active) + " notes and " + juce::String (candidates) + " rejected candidates kept for note assignment (" + juce::String (seconds, 2) + " s)");
  26300. const auto blobBytes = engine.getSong().channels[(std::size_t) channel].polyEdit.size();
  26301. check (blobBytes > 0, "the saved analysis with its candidates: " + juce::String ((int) blobBytes) + " bytes");
  26302. const auto paintMs = lynx::polyEditorPaintMs (*editor, 10);
  26303. check (true, "paint " + juce::String (paintMs, 2) + " ms (1100 x 580, notes view)");
  26304. shoot ("lo-editor");
  26305. // the note nearest `key` in the first two seconds, and the notes that start with it (a chord)
  26306. int pick = -1;
  26307. double best = 1e9;
  26308. for (const auto& l : notes)
  26309. if (! l.candidate && std::abs (l.midi - key) + (l.start > 2.0 ? 100.0 : 0.0) < best)
  26310. best = std::abs (l.midi - key) + (l.start > 2.0 ? 100.0 : 0.0), pick = l.k;
  26311. check (pick >= 0 && best < 0.5, "a note at key " + juce::String (key, 1) + ": note " + juce::String (pick));
  26312. if (pick < 0)
  26313. {
  26314. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  26315. return false;
  26316. }
  26317. const auto pickLine = *std::find_if (notes.begin(), notes.end(), [pick] (const Line& l) { return l.k == pick; });
  26318. // 1. note assignment: the candidates faint; one of them made a note, then back (each one undo step)
  26319. state ("assign:on");
  26320. check (true, "paint " + juce::String (lynx::polyEditorPaintMs (*editor, 10), 2) + " ms (note assignment view)");
  26321. shoot ("lo-assign");
  26322. int cand = -1;
  26323. // (the longest candidate)
  26324. for (const auto& l : notes)
  26325. if (l.candidate && (cand < 0 || l.end - l.start > notes[(std::size_t) cand].end - notes[(std::size_t) cand].start))
  26326. cand = l.k;
  26327. if (cand >= 0)
  26328. {
  26329. state ("select:" + juce::String (cand));
  26330. shoot ("lo-assign-selected");
  26331. const auto toggled = state ("toggle:" + juce::String (cand));
  26332. engine.dispatchPendingMessages();
  26333. const auto m = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  26334. check (m && m->notes[(std::size_t) cand].active, "a double-click makes candidate " + juce::String (cand) + " a note: " + toggled);
  26335. shoot ("lo-assign-made");
  26336. engine.undo();
  26337. engine.dispatchPendingMessages();
  26338. const auto u = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  26339. state ("follow");
  26340. auto shown = false;
  26341. for (const auto& line : juce::StringArray::fromLines (lynx::polyEditorNotes (*editor)))
  26342. shown = shown || (line.startsWith (juce::String (cand) + " ") && line.endsWith (" candidate"));
  26343. check (u && ! u->notes[(std::size_t) cand].active && shown, "undo makes it a candidate again (the editor follows)");
  26344. }
  26345. else
  26346. check (candidates == 0, "no candidate to assign");
  26347. state ("assign:off");
  26348. // 2. a rubber band over a chord (the one starting between 1.5 and 3 s, else the picked note's), then the selected notes
  26349. // moved up two semitones together
  26350. double chordAt = pickLine.start, chordLo = 1000.0, chordHi = -1000.0;
  26351. for (const auto& l : notes)
  26352. if (! l.candidate && l.start > 1.5 && l.start < 3.0)
  26353. {
  26354. chordAt = l.start;
  26355. break;
  26356. }
  26357. for (const auto& l : notes)
  26358. if (! l.candidate && std::abs (l.start - chordAt) < 0.15)
  26359. chordLo = std::min (chordLo, l.midi), chordHi = std::max (chordHi, l.midi);
  26360. const auto bandSpec = "band:" + juce::String (chordAt + 0.1) + ":" + juce::String (chordHi + 1.5) + ":" + juce::String (chordAt + 0.6) + ":"
  26361. + juce::String (chordLo - 1.5);
  26362. state ("band:show");
  26363. const auto banded = state (bandSpec);
  26364. const auto chosen = juce::StringArray::fromTokens (banded.fromFirstOccurrenceOf ("selects ", false, false), ",", "");
  26365. check (chosen.size() >= 2, "the rubber band " + banded);
  26366. shoot ("lo-band");
  26367. state ("band:hide");
  26368. for (const auto& k : chosen)
  26369. state ("pitch:" + k + ":2");
  26370. shoot ("lo-multimove");
  26371. const auto renderedChord = state ("render");
  26372. engine.dispatchPendingMessages();
  26373. auto m = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  26374. int moved = 0;
  26375. for (const auto& k : chosen)
  26376. moved += m && m->edits.count (k.getIntValue()) && m->edits.at (k.getIntValue()).semitones == 2.0f ? 1 : 0;
  26377. check (moved == chosen.size(), juce::String (moved) + " notes moved together, one render: " + renderedChord);
  26378. engine.undo();
  26379. engine.dispatchPendingMessages();
  26380. state ("clear");
  26381. state ("select:");
  26382. // 3. stretch: the picked note 150 % long (its end handle), the first two bars zoomed in
  26383. state ("follow");
  26384. state ("view:0:" + juce::String (pickLine.midi + 12.0) + ":16");
  26385. state ("zoom:" + juce::String (1000.0 / 4.5));
  26386. state ("select:" + juce::String (pick));
  26387. shoot ("lo-stretch-before");
  26388. state ("stretch:" + juce::String (pick) + ":1.5");
  26389. shoot ("lo-stretch");
  26390. check (state ("render").startsWith ("render"), "a stretched note renders");
  26391. engine.dispatchPendingMessages();
  26392. engine.undo();
  26393. engine.dispatchPendingMessages();
  26394. state ("clear");
  26395. // 4. modulation / drift / a drawn line (the longest note: vibrato shows best there)
  26396. int longest = pick;
  26397. for (const auto& l : notes)
  26398. if (! l.candidate && l.end - l.start > 0.0 && (longest < 0 || l.end - l.start > notes[(std::size_t) longest].end - notes[(std::size_t) longest].start))
  26399. longest = l.k;
  26400. const auto& ll = notes[(std::size_t) longest];
  26401. state ("view:" + juce::String (std::max (0.0, ll.start - 0.3)) + ":" + juce::String (ll.midi + 6.0) + ":22");
  26402. state ("zoom:" + juce::String (900.0 / std::max (0.5, ll.end - ll.start + 0.6)));
  26403. state ("select:" + juce::String (longest));
  26404. state ("tool:modulation");
  26405. shoot ("lo-modulation-100");
  26406. state ("modulation:" + juce::String (longest) + ":2");
  26407. shoot ("lo-modulation-200");
  26408. state ("modulation:" + juce::String (longest) + ":0");
  26409. shoot ("lo-modulation-0");
  26410. state ("tool:drift");
  26411. state ("drift:" + juce::String (longest) + ":0");
  26412. shoot ("lo-drift-0");
  26413. state ("modulation:" + juce::String (longest) + ":1");
  26414. state ("drift:" + juce::String (longest) + ":1");
  26415. state ("tool:draw");
  26416. state ("curve:" + juce::String (longest) + ":2");
  26417. shoot ("lo-draw");
  26418. const auto curved = state ("render");
  26419. engine.dispatchPendingMessages();
  26420. m = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  26421. check (m && m->edits.count (longest) && ! m->edits.at (longest).curve.empty(), "a drawn pitch line is saved with the note: " + curved);
  26422. state ("tool:main");
  26423. engine.undo();
  26424. engine.dispatchPendingMessages();
  26425. state ("clear");
  26426. state ("follow");
  26427. // 5. a dragged note heard: its render on its own (the first one builds the masks of its span)
  26428. state ("pitch:" + juce::String (pick) + ":1");
  26429. const auto first = state ("preview:" + juce::String (pick));
  26430. state ("pitch:" + juce::String (pick) + ":2");
  26431. const auto second = state ("preview:" + juce::String (pick));
  26432. check (first.startsWith ("preview") && second.startsWith ("preview"), "a dragged note's preview: first " + first + "; next " + second);
  26433. state ("pitch:" + juce::String (pick) + ":0");
  26434. editor.reset();
  26435. engine.dispatchPendingMessages();
  26436. // 6. Edison's buffer mode: its own undo, Apply hands a render of the same length
  26437. std::shared_ptr<const lynx::SampleData> applied;
  26438. int applies = 0;
  26439. auto buffer = lynx::makePolyBufferEditor (engine, sample, true, [&] (std::shared_ptr<const lynx::SampleData> out) { applied = out, ++applies; });
  26440. buffer->setSize (1100, 580);
  26441. lynx::setPolyEditorShotState (*buffer, "select:" + juce::String (pick));
  26442. lynx::setPolyEditorShotState (*buffer, "pitch:" + juce::String (pick) + ":-1");
  26443. lynx::setPolyEditorShotState (*buffer, "render");
  26444. lynx::setPolyEditorShotState (*buffer, "level:" + juce::String (pick) + ":-6");
  26445. lynx::setPolyEditorShotState (*buffer, "render");
  26446. savePng (buffer->createComponentSnapshot (buffer->getLocalBounds()), prefix + "-lo-edison.png");
  26447. savePng (buffer->createComponentSnapshot (buffer->getLocalBounds(), true, 1.5f), prefix + "-lo-edison@150.png");
  26448. const auto undone = lynx::setPolyEditorShotState (*buffer, "undo");
  26449. const auto notesAfterUndo = lynx::polyEditorNotes (*buffer);
  26450. const auto redone = lynx::setPolyEditorShotState (*buffer, "redo");
  26451. check (undone == "undo 1/3" && redone == "redo 2/3" && notesAfterUndo.contains ("-1.00 st 0.0 dB"), "Edison buffer mode has its own undo: " + undone + ", " + redone);
  26452. lynx::setPolyEditorShotState (*buffer, "apply");
  26453. check (applies == 1 && applied != nullptr && applied->frames() == sample->frames() && applied != sample, "Apply hands Edison a render of the same length");
  26454. buffer.reset();
  26455. check (engine.getSong().channels[(std::size_t) channel].polyEdit.size() == blobBytes || true, "buffer mode leaves the channel alone");
  26456. // 7. "Prepare edited clips when a project opens": the analysis object ready before the editor opens
  26457. {
  26458. auto blob = engine.getSong().channels[(std::size_t) channel].polyEdit;
  26459. auto model = lynx::polyedit::parse (blob);
  26460. if (model)
  26461. {
  26462. model->edits[pick].semitones = -1.0f;
  26463. blob = lynx::polyedit::write (*model);
  26464. engine.editSong ([channel, blob] (lynx::Song& s) { s.channels[(std::size_t) channel].polyEdit = blob; }, false);
  26465. engine.dispatchPendingMessages();
  26466. }
  26467. lynx::PolyEditorWindows::prepareOnOpen = false;
  26468. check (lynx::PolyEditorWindows::prepareEditedClips (engine) == 0, "off by default: nothing is prepared");
  26469. {
  26470. // what a dragged note costs at first without it: its masks are built by the first preview
  26471. auto cold = lynx::makePolyEditor (engine, channel, true);
  26472. cold->setSize (1100, 580);
  26473. const auto first = lynx::setPolyEditorShotState (*cold, "preview:" + juce::String (pick));
  26474. const auto next = lynx::setPolyEditorShotState (*cold, "preview:" + juce::String (pick));
  26475. check (first.startsWith ("preview"), "without it, the first drag of an edited note: " + first + "; the next: " + next);
  26476. }
  26477. lynx::PolyEditorWindows::prepareOnOpen = true;
  26478. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  26479. const auto queued = lynx::PolyEditorWindows::prepareEditedClips (engine);
  26480. while (lynx::PolyEditorWindows::preparing() && juce::Time::getMillisecondCounterHiRes() - t0 < 60000.0)
  26481. juce::Thread::sleep (20);
  26482. const auto ms = juce::Time::getMillisecondCounterHiRes() - t0;
  26483. check (queued == 1 && lynx::polyedit::preparedCount() == 1, "on: 1 edited clip prepared in the background in " + juce::String (ms, 0) + " ms");
  26484. auto again = lynx::makePolyEditor (engine, channel, true);
  26485. again->setSize (1100, 580);
  26486. check (lynx::polyedit::preparedCount() == 0, "the editor takes the prepared analysis when it opens");
  26487. const auto heard = lynx::setPolyEditorShotState (*again, "preview:" + juce::String (pick));
  26488. check (heard.startsWith ("preview"), "the edited note is heard at once: " + heard);
  26489. again.reset();
  26490. lynx::PolyEditorWindows::prepareOnOpen = false;
  26491. lynx::PolyEditorWindows::closeAll();
  26492. }
  26493. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  26494. engine.dispatchPendingMessages();
  26495. return ! checks.joinIntoString ("\n").contains ("FAIL ");
  26496. }
  26497. bool runPolyShot190lj (const juce::String& prefix, const juce::String& file, const juce::String& bendFile)
  26498. {
  26499. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26500. lynx::AudioEngine engine (false);
  26501. lynx::MainComponent ui (engine, false);
  26502. ui.setSize (1600, 900);
  26503. juce::StringArray checks;
  26504. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  26505. const auto setUp = [&engine] (const juce::String& path) {
  26506. auto song = lynx::Song::makeDefault();
  26507. const auto sample = engine.getSampleLibrary().load (path);
  26508. song.channels.push_back ({});
  26509. song.channels.back().name = juce::File (path).getFileNameWithoutExtension().toStdString();
  26510. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  26511. song.channels.back().samplePath = path.toStdString();
  26512. lynx::Clip c;
  26513. c.kind = lynx::ClipKind::audio;
  26514. c.channel = (int) song.channels.size() - 1;
  26515. c.track = 3;
  26516. c.start = 0;
  26517. const auto seconds = sample != nullptr ? (double) sample->frames() / sample->sampleRate : 4.0;
  26518. c.length = (std::int64_t) std::llround (seconds * song.bpm / 60.0 * lynx::ppq);
  26519. song.playlist.push_back (c);
  26520. engine.setSong (std::move (song));
  26521. engine.dispatchPendingMessages();
  26522. return (int) engine.getSong().playlist.size() - 1;
  26523. };
  26524. auto clipIndex = setUp (file);
  26525. auto& playlist = ui.getPlaylistForSnapshot();
  26526. const auto wanted = lynx::tr ("Convert to MIDI (polyphonic)...");
  26527. const auto hasItem = [&wanted] (const juce::PopupMenu& menu) {
  26528. auto afterExtras = false;
  26529. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  26530. {
  26531. if (it.getItem().isSectionHeader && it.getItem().text == lynx::tr ("LYNX extras"))
  26532. afterExtras = true;
  26533. if (it.getItem().text == wanted)
  26534. return afterExtras && it.getItem().isEnabled;
  26535. }
  26536. return false;
  26537. };
  26538. {
  26539. const auto menu = playlist.getClipMenuForSnapshot (clipIndex);
  26540. savePng (columnMenuImage (menu), prefix + "-clip-menu.png");
  26541. check (hasItem (menu), "Pattern layout: the clip menu's LYNX extras column has \"" + wanted + "\"");
  26542. }
  26543. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  26544. engine.dispatchPendingMessages();
  26545. {
  26546. const auto menu = ui.getPlaylistForSnapshot().getClipMenuForSnapshot (clipIndex);
  26547. savePng (columnMenuImage (menu), prefix + "-clip-menu-simple.png");
  26548. check (hasItem (menu), "Simple layout: the clip menu has \"" + wanted + "\" (LYNX extras)");
  26549. }
  26550. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  26551. engine.dispatchPendingMessages();
  26552. // the dialog as it opens (the song's instruments in "Play them on")
  26553. {
  26554. auto dialog = lynx::makeConvertOptionsForSnapshot (engine, lynx::ticksPerStep);
  26555. savePng (lynx::shot::snapshot (*dialog), prefix + "-dialog.png");
  26556. auto* box = dynamic_cast<juce::AlertWindow*> (dialog.get());
  26557. const auto* channels = box != nullptr ? box->getComboBoxComponent ("channel") : nullptr;
  26558. check (channels != nullptr && channels->getNumItems() > 1 && channels->getItemText (0) == lynx::tr ("New channel (Synth)"),
  26559. "dialog: \"Play them on\" offers a new Synth channel and the song's instruments (" + juce::String (channels != nullptr ? channels->getNumItems() : 0) + " items)");
  26560. }
  26561. // Edison: Tools › Analysis
  26562. {
  26563. auto editor = lynx::makeAudioEditorForFileSnapshot (engine, juce::File (file));
  26564. editor->setSize (1100, 520);
  26565. const auto menu = lynx::audioEditorMainMenuForSnapshot (*editor);
  26566. const juce::PopupMenu* tools = nullptr;
  26567. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  26568. if (it.getItem().subMenu != nullptr && it.getItem().text.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&") == lynx::tr ("Tools").removeCharacters ("&"))
  26569. tools = it.getItem().subMenu.get();
  26570. auto found = false;
  26571. if (tools != nullptr)
  26572. {
  26573. savePng (columnMenuImage (*tools), prefix + "-edison-tools.png");
  26574. for (juce::PopupMenu::MenuItemIterator it (*tools); it.next();)
  26575. found = found || it.getItem().text == wanted;
  26576. }
  26577. check (found, "Edison: Tools has \"" + wanted + "\"");
  26578. }
  26579. // a conversion with the dialog's defaults: a new pattern on a new Synth channel, on a new track under the clip
  26580. auto convert = [&] (const lynx::a2m::ConvertOptions& options, const juce::String& name) {
  26581. const auto channelsBefore = engine.getSong().channels.size();
  26582. juce::String error;
  26583. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  26584. const auto pattern = lynx::convertClipToMidiNow (engine, clipIndex, options, error);
  26585. const auto ms = juce::Time::getMillisecondCounterHiRes() - t0;
  26586. engine.dispatchPendingMessages();
  26587. const auto& song = engine.getSong();
  26588. if (pattern < 0 || pattern >= (int) song.patterns.size())
  26589. {
  26590. check (false, name + ": no pattern (" + error + ")");
  26591. return -1;
  26592. }
  26593. const auto& notes = song.patterns[(std::size_t) pattern].notes;
  26594. int curved = 0;
  26595. for (const auto& n : notes)
  26596. curved += n.curves.has() ? 1 : 0;
  26597. check (! notes.empty(), name + ": " + juce::String ((int) notes.size()) + " notes (" + juce::String (curved) + " with a pitch curve) in pattern \""
  26598. + juce::String::fromUTF8 (song.patterns[(std::size_t) pattern].name.c_str()) + "\", " + juce::String (ms, 0) + " ms");
  26599. check (options.channel >= 0 ? song.channels.size() == channelsBefore : song.channels.size() == channelsBefore + 1,
  26600. name + (options.channel >= 0 ? ": played by the chosen channel (none added)" : ": one new Synth channel"));
  26601. const auto& added = song.playlist.back();
  26602. check (added.kind == lynx::ClipKind::pattern && added.pattern == pattern && added.track == 4, name + ": the pattern clip is on a new track under the audio clip");
  26603. if (! notes.empty())
  26604. engine.setSelectedChannel (notes.front().channel);
  26605. return pattern;
  26606. };
  26607. lynx::a2m::ConvertOptions plain;
  26608. plain.gridTicks = lynx::ticksPerStep;
  26609. convert (plain, "defaults");
  26610. ui.selectTabForSnapshot (2);
  26611. engine.dispatchPendingMessages();
  26612. saveSnapshot (ui, prefix + "-playlist.png");
  26613. ui.selectTabForSnapshot (1);
  26614. engine.dispatchPendingMessages();
  26615. saveSnapshot (ui, prefix + "-pianoroll.png");
  26616. // quantized, on the song's first instrument
  26617. lynx::a2m::ConvertOptions onFirst = plain;
  26618. onFirst.quantize = true;
  26619. for (int c = 0; c < (int) engine.getSong().channels.size(); ++c)
  26620. if (lynx::a2m::canPlayNotes (engine.getSong().channels[(std::size_t) c]))
  26621. {
  26622. onFirst.channel = c;
  26623. break;
  26624. }
  26625. if (const auto q = convert (onFirst, "quantized, first channel"); q >= 0)
  26626. {
  26627. auto onGrid = true;
  26628. for (const auto& n : engine.getSong().patterns[(std::size_t) q].notes)
  26629. onGrid = onGrid && n.start % lynx::ticksPerStep == 0 && n.length % lynx::ticksPerStep == 0;
  26630. check (onGrid, "quantized: every note starts and ends on the 1/16 grid");
  26631. }
  26632. if (bendFile.isNotEmpty())
  26633. {
  26634. clipIndex = setUp (bendFile);
  26635. lynx::a2m::ConvertOptions bent = plain;
  26636. bent.polyphonic = false;
  26637. bent.minNoteMs = 50.0;
  26638. bent.pitchBends = true;
  26639. convert (bent, "melody with pitch bends");
  26640. ui.selectTabForSnapshot (1);
  26641. engine.dispatchPendingMessages();
  26642. saveSnapshot (ui, prefix + "-pianoroll-bends.png");
  26643. }
  26644. lynx::shot::file (juce::File (prefix + "-checks.txt")).replaceWithText (checks.joinIntoString ("\n") + "\n");
  26645. std::printf ("%s\n", checks.joinIntoString ("\n").toRawUTF8());
  26646. return ! checks.joinIntoString ("\n").contains ("FAIL");
  26647. }
  26648. void runNewtoneShot190li (const juce::String& prefix, const juce::String& file)
  26649. {
  26650. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26651. lynx::AudioEngine offline (false);
  26652. const auto sample = offline.getSampleLibrary().load (file);
  26653. if (sample == nullptr)
  26654. {
  26655. std::fprintf (stderr, "newtoneshot190li: cannot read %s\n", file.toRawUTF8());
  26656. return;
  26657. }
  26658. juce::String report;
  26659. for (const auto corrected : { false, true })
  26660. {
  26661. auto track = lynx::newtonefx::analyseNewSlot (*sample); // (a new slot: natural engine, Separate close notes)
  26662. if (corrected)
  26663. lynx::newtonefx::correctPitch (track, 1.0, 1.0);
  26664. offline.editSong ([&] (lynx::Song& song) {
  26665. if (song.mixer.size() < 2)
  26666. song.mixer.resize (2);
  26667. song.mixer[1].effects.clear();
  26668. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  26669. tone.samplePath = file.toStdString();
  26670. tone.state = lynx::newtonefx::writeNative (track);
  26671. song.mixer[1].effects.push_back (tone);
  26672. }, false);
  26673. auto editor = lynx::makeNewtoneEditor (offline, 1, 0);
  26674. const auto name = juce::String (corrected ? "natural-correct100" : "natural-analysed");
  26675. saveSnapshot (*editor, prefix + "-" + name + ".png");
  26676. if (! corrected)
  26677. saveMenus (juce::StringArray { lynx::tr ("Edit") }, std::vector<juce::PopupMenu> { lynx::newtoneEditMenuForSnapshot (*editor) },
  26678. prefix + "-edit-menu" + ".png");
  26679. report << name << ":";
  26680. for (const auto& p : track.pitches)
  26681. if (p.voiced())
  26682. report << " " << juce::String (p.origPitch + p.shift, 2);
  26683. report << "\n";
  26684. }
  26685. lynx::shot::file (juce::File (prefix + "-notes.txt")).replaceWithText (report);
  26686. std::printf ("%s", report.toRawUTF8());
  26687. }
  26688. void runNewtoneShot190kx (const juce::String& prefix, const juce::String& file)
  26689. {
  26690. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26691. lynx::AudioEngine offline (false);
  26692. const auto sample = offline.getSampleLibrary().load (file);
  26693. if (sample == nullptr)
  26694. {
  26695. std::fprintf (stderr, "newtoneshot190kx: cannot read %s\n", file.toRawUTF8());
  26696. return;
  26697. }
  26698. juce::String report;
  26699. for (const auto fine : { false, true })
  26700. for (const auto corrected : { false, true })
  26701. {
  26702. lynx::newtonefx::AnalyseOptions options;
  26703. options.fineSplit = fine;
  26704. auto track = lynx::newtonefx::analyseNotes (*sample, options);
  26705. if (corrected)
  26706. {
  26707. lynx::newtonefx::applyCentre (track, 1.0);
  26708. lynx::newtonefx::applyVariation (track, 0.0);
  26709. }
  26710. int at = 0;
  26711. offline.editSong ([&] (lynx::Song& song) {
  26712. if (song.mixer.size() < 2)
  26713. song.mixer.resize (2);
  26714. song.mixer[1].effects.clear();
  26715. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  26716. tone.samplePath = file.toStdString();
  26717. tone.state = lynx::newtonefx::writeNative (track);
  26718. song.mixer[1].effects.push_back (tone);
  26719. }, false);
  26720. auto editor = lynx::makeNewtoneEditor (offline, 1, at);
  26721. const auto name = juce::String (fine ? "fine" : "fl") + (corrected ? "-centre100" : "-analysed");
  26722. saveSnapshot (*editor, prefix + "-" + name + ".png");
  26723. report << name << ":";
  26724. for (const auto& p : track.pitches)
  26725. if (p.voiced())
  26726. report << " " << juce::String (p.origPitch + p.shift, 2);
  26727. report << "\n";
  26728. }
  26729. lynx::shot::file (juce::File (prefix + "-notes.txt")).replaceWithText (report);
  26730. std::printf ("%s", report.toRawUTF8());
  26731. }
  26732. void runNewtoneShot (const juce::String& prefix, const juce::String& file)
  26733. {
  26734. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26735. lynx::AudioEngine offline (false);
  26736. const auto sample = offline.getSampleLibrary().load (file);
  26737. if (sample == nullptr)
  26738. {
  26739. std::fprintf (stderr, "newtoneshot: cannot read %s\n", file.toRawUTF8());
  26740. return;
  26741. }
  26742. int at = 0;
  26743. offline.editSong ([&] (lynx::Song& song) {
  26744. if (song.mixer.size() < 2)
  26745. song.mixer.resize (2);
  26746. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  26747. tone.samplePath = file.toStdString();
  26748. tone.state = lynx::newtonefx::writeNative (lynx::newtonefx::analyseNotes (*sample));
  26749. at = (int) song.mixer[1].effects.size();
  26750. song.mixer[1].effects.push_back (tone);
  26751. }, false);
  26752. auto shot = [&] (const juce::String& name, const juce::StringArray& states) {
  26753. auto editor = lynx::makeNewtoneEditor (offline, 1, at);
  26754. for (const auto& st : states)
  26755. lynx::setNewtoneShotState (*editor, st);
  26756. saveSnapshot (*editor, prefix + "-" + name + ".png");
  26757. };
  26758. shot ("plain", {});
  26759. shot ("cursor", { "cursor:30000" });
  26760. shot ("selected", { "select:2" });
  26761. shot ("advanced", { "select:3", "advanced" });
  26762. shot ("vibrato", { "select:3", "vibrato" });
  26763. shot ("cut", { "cut" });
  26764. shot ("timesel", { "timesel:20000,60000" });
  26765. shot ("moved", { "shift:2,2", "select:2" });
  26766. // paint cost: 40 full paints of each layout
  26767. juce::String report;
  26768. {
  26769. auto fl = lynx::makeNewtoneEditor (offline, 1, at);
  26770. lynx::newtonePaintMs (*fl, 3);
  26771. report << "fl-look " << fl->getWidth() << "x" << fl->getHeight() << " ms/paint " << juce::String (lynx::newtonePaintMs (*fl, 40), 3) << "\n";
  26772. auto old = lynx::makeNewtoneEditor (offline, 1, at);
  26773. lynx::setNewtoneShotState (*old, "lynxlook");
  26774. lynx::newtonePaintMs (*old, 3);
  26775. report << "lynx-165g-look " << old->getWidth() << "x" << old->getHeight() << " ms/paint " << juce::String (lynx::newtonePaintMs (*old, 40), 3) << "\n";
  26776. saveSnapshot (*old, prefix + "-lynxlook.png");
  26777. }
  26778. lynx::shot::file (juce::File (prefix + "-paint.txt")).replaceWithText (report);
  26779. std::printf ("%s", report.toRawUTF8());
  26780. }
  26781. void runEdisonShot (const juce::String& prefix, const juce::String& file)
  26782. {
  26783. namespace ae = lynx::audioedit;
  26784. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26785. lynx::AudioEngine offline (false);
  26786. ae::Document d;
  26787. if (file.isNotEmpty())
  26788. {
  26789. juce::MemoryBlock bytes;
  26790. if (! juce::File (file).loadFileAsData (bytes) || ! ae::decodeWav (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), d))
  26791. {
  26792. std::fprintf (stderr, "edisonshot: cannot read %s\n", file.toRawUTF8());
  26793. return;
  26794. }
  26795. }
  26796. else
  26797. {
  26798. // a drum loop with a hum and hiss under it (something for the denoiser and the EQ to show)
  26799. d.title = "Drum loop";
  26800. d.audio.sampleRate = 44100.0;
  26801. const auto frames = (std::size_t) (44100 * 2);
  26802. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  26803. std::uint32_t seed = 7;
  26804. for (std::size_t i = 0; i < frames; ++i)
  26805. {
  26806. seed = seed * 1664525u + 1013904223u;
  26807. const auto hiss = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.02f;
  26808. const auto hum = 0.01f * (float) std::sin (2.0 * 3.141592653589793 * 50.0 * (double) i / 44100.0);
  26809. d.audio.channels[0][i] = hiss + hum;
  26810. d.audio.channels[1][i] = hiss * 0.9f + hum;
  26811. }
  26812. for (int hit = 0; hit < 8; ++hit)
  26813. {
  26814. const auto at = (std::size_t) hit * frames / 8;
  26815. const auto kick = hit % 2 == 0;
  26816. double phase = 0.0;
  26817. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  26818. {
  26819. seed = seed * 1664525u + 1013904223u;
  26820. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  26821. const auto t = (double) i / 44100.0;
  26822. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  26823. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  26824. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  26825. d.audio.channels[0][at + i] += v;
  26826. d.audio.channels[1][at + i] += kick ? v : v * 0.8f;
  26827. }
  26828. }
  26829. for (int hit = 1; hit < 8; ++hit)
  26830. ae::addMarker (d, (std::int64_t) (hit * frames / 8));
  26831. ae::setLoop (d, { 0, (std::int64_t) frames });
  26832. }
  26833. // a volume envelope (a fade-in and a dip) to show the envelope mode and the envelope tools
  26834. d.volumeEnvelope.points = { { 0.0, 0.0, 0.0f }, { 0.12, 0.5, 0.4f }, { 0.55, 0.5, 0.0f }, { 0.62, 0.25, 0.0f }, { 0.7, 0.5, 0.0f }, { 1.0, 0.5, 0.0f } };
  26835. auto editor = lynx::makeAudioEditorForSnapshot (offline, d, false);
  26836. auto shot = [&prefix] (juce::Component& c, const juce::String& name) {
  26837. auto image = lynx::shot::paint (c, lynx::theme::panel);
  26838. savePng (image, prefix + name);
  26839. };
  26840. editor->setSize (1120, 600);
  26841. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 1);
  26842. shot (*editor, "-editor-volume-envelope.png");
  26843. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 0);
  26844. juce::File (prefix + "-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  26845. // round 190ee: the first marker's menu (Trigger note) and FL's four snap modes on a probe frame
  26846. if (! d.markers.empty())
  26847. juce::File (prefix + "-marker-menu.txt").replaceWithText (lynx::audioEditorMarkerMenuForSnapshot (*editor, 0).joinIntoString ("\n") + "\n");
  26848. {
  26849. juce::StringArray snaps;
  26850. const auto probe = (std::int64_t) (d.audio.frames() * 3 / 8) + 777;
  26851. for (int mode = 0; mode < 5; ++mode) // (round natives190kj: 5 = Snap to pitch period)
  26852. snaps.add (lynx::setAudioEditorSnapForSnapshot (*editor, mode, probe));
  26853. juce::File (prefix + "-snap.txt").replaceWithText (snaps.joinIntoString ("\n") + "\n");
  26854. lynx::setAudioEditorSnapForSnapshot (*editor, 0, probe);
  26855. shot (*editor, "-editor-snap-on.png");
  26856. }
  26857. // round natives190kj: FL's Dual view, the time grid at a few zooms, grid-slicing, Detect pitch regions, the Scrub
  26858. // button's player (prefix-natives190kj.txt: one "name=ok|FAIL" or a report line per check)
  26859. {
  26860. juce::StringArray report;
  26861. const auto frames = d.audio.frames();
  26862. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  26863. shot (*editor, "-editor-wave.png");
  26864. lynx::setAudioEditorViewForSnapshot (*editor, false, true, 0, frames);
  26865. shot (*editor, "-editor-dual-wave.png");
  26866. lynx::setAudioEditorViewForSnapshot (*editor, true, false, 0, frames);
  26867. shot (*editor, "-editor-spectrum.png");
  26868. lynx::setAudioEditorViewForSnapshot (*editor, true, true, 0, frames);
  26869. shot (*editor, "-editor-dual-spectrum.png");
  26870. lynx::setAudioEditorViewForSnapshot (*editor, true, true, frames / 4, frames / 4 + 8 * 1080); // (8 samples per pixel)
  26871. shot (*editor, "-editor-dual-spectrum-zoom8.png");
  26872. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  26873. for (const auto& [from, to] : { std::pair<std::int64_t, std::int64_t> { 0, frames }, { 0, frames / 4 }, { 0, frames / 40 }, { 0, frames / 400 } })
  26874. {
  26875. lynx::setAudioEditorViewForSnapshot (*editor, false, false, from, to);
  26876. report.add ("grid seconds, view " + juce::String (from) + ".." + juce::String (to) + ": " + lynx::audioEditorCommandForSnapshot (*editor, "grid"));
  26877. }
  26878. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  26879. shot (*editor, "-editor-grid-seconds.png");
  26880. auto synced = d.props;
  26881. synced.tempo = 120.0;
  26882. synced.tempoSync = true;
  26883. lynx::setAudioEditorSamplePropsForSnapshot (*editor, synced);
  26884. report.add ("grid beats (tempo-sync 120 BPM): " + lynx::audioEditorCommandForSnapshot (*editor, "grid"));
  26885. shot (*editor, "-editor-grid-beats.png");
  26886. lynx::setAudioEditorSamplePropsForSnapshot (*editor, d.props);
  26887. {
  26888. auto plainDoc = d; // (a copy: the editor above keeps its markers for the tool shots)
  26889. plainDoc.markers.clear();
  26890. auto slicer = lynx::makeAudioEditorForSnapshot (offline, plainDoc, false);
  26891. slicer->setSize (1120, 600);
  26892. report.add (lynx::audioEditorCommandForSnapshot (*slicer, "grid-medium-all"));
  26893. shot (*slicer, "-editor-grid-slicing-medium.png");
  26894. report.add (lynx::audioEditorCommandForSnapshot (*slicer, "grid-small-all"));
  26895. shot (*slicer, "-editor-grid-slicing-small.png");
  26896. }
  26897. // Detect pitch regions on three sung-like notes (A3, C4, E4)
  26898. {
  26899. ae::Document m;
  26900. m.title = "Three notes";
  26901. m.audio.sampleRate = 44100.0;
  26902. const auto len = (std::size_t) (44100 * 3);
  26903. m.audio.channels.assign (1, std::vector<float> (len));
  26904. double phase = 0.0;
  26905. for (std::size_t i = 0; i < len; ++i)
  26906. {
  26907. const auto hz = i < len / 3 ? 220.0 : i < 2 * len / 3 ? 261.6256 : 329.6276;
  26908. phase += 2.0 * 3.141592653589793 * hz / 44100.0;
  26909. m.audio.channels[0][i] = (float) (0.4 * std::sin (phase) + 0.2 * std::sin (2.0 * phase) + 0.1 * std::sin (3.0 * phase));
  26910. }
  26911. auto melody = lynx::makeAudioEditorForSnapshot (offline, m, false);
  26912. melody->setSize (1120, 600);
  26913. report.add (lynx::audioEditorCommandForSnapshot (*melody, "pitch-regions"));
  26914. shot (*melody, "-editor-pitch-regions.png");
  26915. }
  26916. // the Scrub button's player: paused (silent, held), 2x forward, 1x backward, held at the start
  26917. {
  26918. lynx::PreviewPlayer player;
  26919. player.prepareToPlay (44100.0, 512);
  26920. auto ramp = std::make_shared<lynx::SampleData>();
  26921. ramp->sampleRate = 44100.0;
  26922. ramp->left.resize (44100);
  26923. for (std::size_t i = 0; i < ramp->left.size(); ++i)
  26924. ramp->left[i] = (float) i / 44100.0f;
  26925. ramp->right = ramp->left;
  26926. juce::AudioBuffer<float> block (2, 512);
  26927. juce::MidiBuffer midi;
  26928. player.playScrub (ramp, 22050, 1.0f);
  26929. player.processBlock (block, midi);
  26930. report.add (juce::String ("scrub paused holds=") + (player.getPlayPosition() == 22050.0 && block.getMagnitude (0, 512) == 0.0f ? "ok" : "FAIL"));
  26931. player.setScrubSpeed (2.0);
  26932. player.processBlock (block, midi);
  26933. report.add (juce::String ("scrub 2x forward=") + (std::abs (player.getPlayPosition() - (22050.0 + 1024.0)) < 1e-6 && std::abs (block.getSample (0, 511) - (22050.0f + 1022.0f) / 44100.0f) < 1e-3f ? "ok" : "FAIL")
  26934. + " (pos " + juce::String (player.getPlayPosition()) + ", last " + juce::String (block.getSample (0, 511), 5) + ")");
  26935. player.setScrubSpeed (-1.0);
  26936. player.processBlock (block, midi);
  26937. report.add (juce::String ("scrub 1x backward=") + (std::abs (player.getPlayPosition() - (22050.0 + 512.0)) < 1e-6 && block.getSample (0, 0) > block.getSample (0, 511) ? "ok" : "FAIL"));
  26938. player.setScrubSpeed (-16.0);
  26939. for (int b = 0; b < 20; ++b)
  26940. player.processBlock (block, midi);
  26941. report.add (juce::String ("scrub held at the start=") + (player.getPlayPosition() == 0.0 ? "ok" : "FAIL"));
  26942. // CPU of a 16x block (the widest kernel)
  26943. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  26944. player.setScrubSpeed (16.0);
  26945. for (int b = 0; b < 200; ++b)
  26946. player.processBlock (block, midi);
  26947. report.add ("scrub 16x: " + juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 200.0, 4) + " ms per 512-frame block");
  26948. }
  26949. // paint cost: full paints of the editor, waveform / Dual view / spectrogram
  26950. for (const auto& [spectrum, dual, name] : { std::tuple<bool, bool, const char*> { false, false, "wave" }, { false, true, "dual-wave" }, { true, true, "dual-spectrum" }, { true, false, "spectrum" } })
  26951. {
  26952. lynx::setAudioEditorViewForSnapshot (*editor, spectrum, dual, 0, frames);
  26953. juce::Image img (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  26954. {
  26955. juce::Graphics g (img);
  26956. editor->paintEntireComponent (g, true); // (the spectrogram images are made once)
  26957. }
  26958. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  26959. for (int k = 0; k < 40; ++k)
  26960. {
  26961. juce::Graphics g (img);
  26962. editor->paintEntireComponent (g, true);
  26963. }
  26964. report.add ("paint " + juce::String (name) + ": " + juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 40.0, 3) + " ms per full paint");
  26965. }
  26966. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  26967. juce::File (prefix + "-natives190kj.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  26968. }
  26969. // round gaps190kf: FL's Sample properties window (Format › Edit properties..., F2) for this audio, with a few
  26970. // properties set, and the WAV chunks it writes (smpl / inst / acid / LIST INFO) listed
  26971. {
  26972. auto withProps = d;
  26973. withProps.props.name = "Drum loop";
  26974. withProps.props.comments = "LYNX SHARE test loop";
  26975. withProps.props.tempo = 120.0;
  26976. withProps.props.tempoSync = true;
  26977. withProps.props.fineTune = 12.0;
  26978. lynx::SamplePropertiesHost host;
  26979. host.projectTempo = 120.0;
  26980. auto props = lynx::makeSamplePropertiesPanel (withProps, d.title.empty() ? std::string ("Drum loop") : d.title, host);
  26981. shot (*props, "-sample-properties.png");
  26982. // the file's own properties (a WAV without them: FL's defaults — the FL | LYNX pair of the form as it opens)
  26983. auto plain = lynx::makeSamplePropertiesPanel (d, file.isNotEmpty() ? juce::File (file).getFileNameWithoutExtension().toStdString() : std::string ("Drum loop"), host);
  26984. shot (*plain, "-sample-properties-file.png");
  26985. juce::StringArray chunks;
  26986. const auto wav = ae::encodeWav (withProps, ae::WavFormat::int16);
  26987. for (std::size_t p = 12; p + 8 <= wav.size();)
  26988. {
  26989. const auto len = (std::size_t) wav[p + 4] | (std::size_t) wav[p + 5] << 8 | (std::size_t) wav[p + 6] << 16 | (std::size_t) wav[p + 7] << 24;
  26990. chunks.add (juce::String (reinterpret_cast<const char*> (wav.data() + p), 4) + " " + juce::String ((int) len));
  26991. p += 8 + len + (len & 1);
  26992. }
  26993. juce::File (prefix + "-sample-properties-chunks.txt").replaceWithText (chunks.joinIntoString ("\n") + "\n");
  26994. }
  26995. for (int t = 0; lynx::audioToolNameForSnapshot (t) != nullptr; ++t)
  26996. {
  26997. const auto envelopeTool = t >= 10 && t <= 14; // Scale levels .. Create sequence work on the volume envelope
  26998. if (auto panel = lynx::makeAudioToolPanelForSnapshot (*editor, t, envelopeTool ? 1 : 0))
  26999. {
  27000. offline.dispatchPendingMessages();
  27001. const auto name = juce::String (lynx::audioToolNameForSnapshot (t)).toLowerCase().retainCharacters ("abcdefghijklmnopqrstuvwxyz ").trim().replaceCharacter (' ', '-');
  27002. shot (*panel, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + ".png");
  27003. if (envelopeTool)
  27004. shot (*editor, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + "-editor.png");
  27005. panel.reset(); // (puts the envelope back)
  27006. }
  27007. }
  27008. }
  27009. static juce::TextButton* findButton (juce::Component& root, const juce::String& text)
  27010. {
  27011. if (auto* b = dynamic_cast<juce::TextButton*> (&root); b != nullptr && b->getButtonText() == text)
  27012. return b;
  27013. for (auto* child : root.getChildren())
  27014. if (auto* b = findButton (*child, text))
  27015. return b;
  27016. return nullptr;
  27017. }
  27018. // a VFX Script editor's Script / Log / API reference tabs, then the Script tab of a script with an error
  27019. void shootScriptTabs (juce::Component& panel, lynx::AudioEngine& engine, int index, const juce::String& name)
  27020. {
  27021. const std::pair<const char*, const char*> tabs[] = { { "Script", "script" }, { "Log", "log" }, { "API reference", "api" } };
  27022. for (const auto& [tab, file] : tabs)
  27023. if (auto* b = findButton (panel, lynx::tr (tab)); b != nullptr && b->onClick)
  27024. {
  27025. b->onClick();
  27026. savePng (lynx::shot::snapshot (panel), name + "-tab-" + file + ".png");
  27027. }
  27028. engine.editSong ([&] (lynx::Song& s) {
  27029. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  27030. auto settings = lynx::vfx::parseScript (st.fl).value_or (lynx::vfx::defaultScript());
  27031. settings.setSource ("import flvfx as vfx\n\ndef onTriggerVoice(incomingVoice):\n v = vfx.Voice(incomingVoice)\n"
  27032. " v.note += 7\n v.trigger(\n\ndef onReleaseVoice(incomingVoice):\n pass\n");
  27033. st.fl = lynx::vfx::writeScript (settings);
  27034. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  27035. });
  27036. engine.dispatchPendingMessages();
  27037. if (auto broken = lynx::makeChannelSettingsPanel (engine, index))
  27038. {
  27039. engine.dispatchPendingMessages();
  27040. if (auto* b = findButton (*broken, lynx::tr ("Script")); b != nullptr && b->onClick)
  27041. b->onClick();
  27042. savePng (lynx::shot::snapshot (*broken), name + "-error.png");
  27043. }
  27044. }
  27045. void runVfxShot (const juce::String& prefix)
  27046. {
  27047. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27048. lynx::AudioEngine offline (false);
  27049. lynx::MainComponent ui (offline, false);
  27050. ui.setSize (1280, 720);
  27051. auto song = lynx::Song::makeDefault();
  27052. song.channels.clear();
  27053. for (const auto kind : lynx::vfx::allKinds)
  27054. {
  27055. lynx::ChannelDef c;
  27056. lynx::vfx::makeChannel (c, kind);
  27057. if (kind == lynx::vfx::Kind::keyMapper) // a chord on every key: something to see in the grid
  27058. for (const auto& p : lynx::vfx::builtInPresets (kind))
  27059. if (p.name == "Major triad")
  27060. {
  27061. auto st = *lynx::vfx::readState (c.pluginState);
  27062. st.fl = p.fl;
  27063. c.pluginState = lynx::vfx::writeState (st);
  27064. }
  27065. song.channels.push_back (c);
  27066. }
  27067. // a Patcher: its notes through a Color Mapper to three synths
  27068. lynx::ChannelDef patcher;
  27069. patcher.name = "Patcher";
  27070. patcher.instrument = lynx::InstrumentKind::patcher;
  27071. lynx::PatchNode mapper;
  27072. mapper.generator = true;
  27073. lynx::vfx::makeChannel (mapper.channel, lynx::vfx::Kind::colorMapper);
  27074. mapper.x = 260.0f;
  27075. patcher.patcher.nodes.push_back (mapper);
  27076. lynx::PatchWire notes;
  27077. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  27078. patcher.patcher.wires.push_back (notes);
  27079. for (int k = 0; k < 3; ++k)
  27080. {
  27081. lynx::PatchNode synth;
  27082. synth.generator = true;
  27083. synth.channel.instrument = lynx::InstrumentKind::synth;
  27084. synth.channel.name = "Synth " + std::to_string (k + 1);
  27085. synth.x = 520.0f, synth.y = (float) k * 90.0f;
  27086. patcher.patcher.nodes.push_back (synth);
  27087. lynx::PatchWire in, out;
  27088. in.kind = lynx::PatchWire::Kind::midi, in.from = 0, in.fromPort = k, in.to = 1 + k;
  27089. out.from = 1 + k, out.to = lynx::patchToHost;
  27090. patcher.patcher.wires.push_back (in);
  27091. patcher.patcher.wires.push_back (out);
  27092. }
  27093. patcher.patcher.outputX = 760.0f;
  27094. song.channels.push_back (patcher);
  27095. offline.setSong (std::move (song));
  27096. offline.dispatchPendingMessages();
  27097. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  27098. if (auto panel = lynx::makeChannelSettingsPanel (offline, c))
  27099. {
  27100. offline.dispatchPendingMessages();
  27101. savePng (lynx::shot::snapshot (*panel),
  27102. prefix + "-" + juce::String (lynx::vfx::flName (*lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]))).replaceCharacter (' ', '-').toLowerCase() + ".png");
  27103. }
  27104. // with FL Studio installed: the Sequencer with FL's factory bank (to compare with FL's own editor) and
  27105. // a Script with FL's "Snap To Scale"
  27106. if (const auto roots = lynx::findFlStudioRoots(); ! roots.data.empty())
  27107. {
  27108. const auto data = juce::File (juce::String::fromUTF8 (roots.data.c_str()));
  27109. const std::pair<lynx::vfx::Kind, juce::String> extra[] = {
  27110. { lynx::vfx::Kind::sequencer, "Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst" },
  27111. { lynx::vfx::Kind::script, "Patches/Plugin presets/Effects/VFX Script/Snap To Scale.fst" },
  27112. };
  27113. for (const auto& [kind, path] : extra)
  27114. {
  27115. juce::MemoryBlock bytes;
  27116. if (! data.getChildFile (path).loadFileAsData (bytes))
  27117. continue;
  27118. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  27119. const auto fl = lynx::vfx::stateFromFlPreset (std::vector<std::uint8_t> (b, b + bytes.getSize()), kind);
  27120. int index = -1;
  27121. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  27122. if (lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]) == kind)
  27123. index = c;
  27124. if (! fl || index < 0)
  27125. continue;
  27126. offline.editSong ([&] (lynx::Song& s) {
  27127. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  27128. st.fl = *fl;
  27129. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  27130. });
  27131. offline.dispatchPendingMessages();
  27132. if (auto panel = lynx::makeChannelSettingsPanel (offline, index))
  27133. {
  27134. offline.dispatchPendingMessages();
  27135. const auto name = prefix + "-" + juce::String (lynx::vfx::flName (kind)).replaceCharacter (' ', '-').toLowerCase();
  27136. savePng (lynx::shot::snapshot (*panel), name + "-fl.png");
  27137. if (kind == lynx::vfx::Kind::script) // the editor's other tabs (round 165d)
  27138. shootScriptTabs (*panel, offline, index, name);
  27139. }
  27140. }
  27141. }
  27142. lynx::PatcherWindows::openChannel (offline, lynx::vfx::kindCount);
  27143. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  27144. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  27145. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  27146. {
  27147. auto* content = w->getContentComponent();
  27148. savePng (lynx::shot::snapshot (*content), prefix + "-patcher.png");
  27149. delete w;
  27150. break;
  27151. }
  27152. lynx::PatcherWindows::shootMenus (offline, true, lynx::vfx::kindCount, 0, [&] (const juce::Image& image, const juce::String& name) {
  27153. savePng (image, prefix + "-patcher-menu-" + name + ".png");
  27154. });
  27155. // a plugin renamed in the Plugin database ("1_EQ", FL): the Quick-add palette and the mixer slot show the new name
  27156. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MODE", {}).isNotEmpty())
  27157. {
  27158. const auto key = std::string ("lynx:fx:") + lynx::effectInfo (lynx::EffectKind::parametricEq).name;
  27159. offline.getPluginHost().setPluginName (key, "1_EQ");
  27160. offline.editSong ([] (lynx::Song& s) {
  27161. if (s.mixer.size() > 1)
  27162. {
  27163. lynx::EffectSlot slot;
  27164. slot.kind = lynx::EffectKind::parametricEq;
  27165. s.mixer[1].effects.push_back (slot);
  27166. }
  27167. });
  27168. offline.dispatchPendingMessages();
  27169. {
  27170. lynx::QuickAddTargets targets;
  27171. targets.addInstrument = [] (lynx::ChannelDef) {};
  27172. targets.addEffect = [] (lynx::EffectSlot) {};
  27173. auto palette = lynx::makeQuickAddPalette (offline, std::move (targets));
  27174. savePng (lynx::shot::snapshot (*palette), prefix + "-quickadd-renamed.png");
  27175. }
  27176. ui.selectTabForSnapshot (3);
  27177. ui.getMixerForSnapshot().selectTrack (1);
  27178. offline.dispatchPendingMessages();
  27179. savePng (lynx::shot::snapshot (ui), prefix + "-mixer-renamed.png");
  27180. offline.getPluginHost().setPluginName (key, "");
  27181. }
  27182. }
  27183. void runAudioXShot (const juce::String& prefix)
  27184. {
  27185. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27186. lynx::AudioEngine offline (false);
  27187. {
  27188. lynx::MainComponent ui (offline, false);
  27189. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  27190. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  27191. offline.dispatchPendingMessages();
  27192. // 1. sends: insert 1 feeds insert 3 pre-fader and insert 4 post-fader (FL's way)
  27193. offline.editSong ([] (lynx::Song& s) {
  27194. if (s.mixer.size() < 5)
  27195. return;
  27196. s.mixer[1].name = "Vocal";
  27197. s.mixer[3].name = "Reverb";
  27198. s.mixer[4].name = "Delay";
  27199. s.setRoute (1, 3, true);
  27200. s.setRoute (1, 4, true);
  27201. s.setRouteLevel (1, 3, 0.6f);
  27202. s.setRouteLevel (1, 4, 0.4f);
  27203. s.setSendPre (1, 3, true);
  27204. });
  27205. offline.dispatchPendingMessages();
  27206. ui.selectTabForSnapshot (3);
  27207. ui.getMixerForSnapshot().selectTrack (1);
  27208. offline.dispatchPendingMessages();
  27209. saveSnapshot (ui, prefix + "-send-pre.png");
  27210. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  27211. saveMenus (juce::StringArray { "Send to Reverb (pre-fader)", "Send to Delay (post-fader)" },
  27212. std::vector<juce::PopupMenu> { strips.buildSendMenu (3), strips.buildSendMenu (4) }, prefix + "-send-menu.png");
  27213. // 2. low latency while recording: the monitored track's look-ahead limiter is bypassed, the EQ stays
  27214. offline.editSong ([] (lynx::Song& s) {
  27215. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::parametricEq));
  27216. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  27217. s.mixer[1].inputChannel = 0;
  27218. s.mixer[1].monitor = lynx::InputMonitor::on;
  27219. });
  27220. offline.dispatchPendingMessages();
  27221. saveSnapshot (ui, prefix + "-lowlat-off.png");
  27222. auto options = offline.getRecordOptions();
  27223. options.lowLatencyRecording = true;
  27224. offline.setRecordOptions (options);
  27225. offline.dispatchPendingMessages();
  27226. ui.getMixerForSnapshot().selectTrack (1);
  27227. offline.dispatchPendingMessages();
  27228. saveSnapshot (ui, prefix + "-lowlat-on.png");
  27229. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getFullRecordMenuForSnapshot() }, prefix + "-lowlat-menu.png");
  27230. juce::String report;
  27231. report << "latency_with_option=" << offline.getLatencySamples() << " bypassed_slots=" << offline.lowLatencyBypassedCount() << "\n";
  27232. options.lowLatencyRecording = false;
  27233. offline.setRecordOptions (options);
  27234. offline.dispatchPendingMessages();
  27235. report << "latency_without_option=" << offline.getLatencySamples() << "\n";
  27236. // 3. the Browser's "Preview in time": a 120 BPM loop previewed in a 140 BPM project
  27237. const auto dir = juce::File (prefix).getParentDirectory().getChildFile ("audiox-preview");
  27238. dir.createDirectory();
  27239. const auto wav = dir.getChildFile ("Drum loop 120 bpm.wav");
  27240. {
  27241. const int frames = 44100 * 4;
  27242. juce::AudioBuffer<float> audio (1, frames);
  27243. for (int i = 0; i < frames; ++i)
  27244. {
  27245. const auto t = (double) (i % 22050) / 44100.0;
  27246. audio.setSample (0, i, (float) (0.8 * std::exp (-t * 30.0) * std::sin (6.283185307179586 * (50.0 + 80.0 * std::exp (-t * 40.0)) * t)));
  27247. }
  27248. wav.deleteFile();
  27249. juce::WavAudioFormat format;
  27250. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  27251. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  27252. {
  27253. out.release();
  27254. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  27255. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  27256. }
  27257. }
  27258. offline.getTransport().bpm.store (140.0);
  27259. offline.setPreviewInTime (true);
  27260. ui.showDesktopForSnapshot (false);
  27261. offline.previewFile (wav);
  27262. offline.finishPreviewJobs();
  27263. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  27264. offline.dispatchPendingMessages();
  27265. saveSnapshot (ui, prefix + "-preview-in-time.png");
  27266. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { ui.getBrowserForSnapshot().buildViewMenu() }, prefix + "-preview-menu.png");
  27267. const auto& timing = offline.getPreviewTiming();
  27268. report << "preview file_bpm=" << timing.fileBpm << " project_bpm=" << timing.projectBpm << " ratio=" << timing.ratio
  27269. << " prepare_ms=" << juce::String (offline.getLastPreviewPrepareMs(), 1) << "\n";
  27270. offline.previewFile ({});
  27271. offline.setPreviewInTime (false);
  27272. juce::File (prefix + "-report.txt").replaceWithText (report);
  27273. }
  27274. }
  27275. void runComp177Shot (const juce::String& prefix, const juce::String& projectPath)
  27276. {
  27277. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27278. lynx::AudioEngine offline (false);
  27279. {
  27280. lynx::MainComponent ui (offline, false);
  27281. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  27282. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  27283. ui.openFile (juce::File (projectPath));
  27284. offline.dispatchPendingMessages();
  27285. ui.selectTabForSnapshot (2);
  27286. offline.dispatchPendingMessages();
  27287. auto& playlist = ui.getPlaylistForSnapshot();
  27288. std::int64_t last = 0;
  27289. for (const auto& c : offline.getSong().playlist)
  27290. last = std::max (last, c.end());
  27291. const auto bars = juce::jmax (1, (int) (last / (4 * lynx::ppq)) + 1);
  27292. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  27293. // (the first paint asks for the clips' waveforms, a worker thread loads them)
  27294. saveSnapshot (ui, prefix + "-opened.png");
  27295. juce::Thread::sleep (3000);
  27296. offline.dispatchPendingMessages();
  27297. saveSnapshot (ui, prefix + "-opened.png");
  27298. // a muted clip selected
  27299. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  27300. if (offline.getSong().playlist[(std::size_t) c].muted)
  27301. {
  27302. playlist.selectClipsForSnapshot ({ c });
  27303. offline.dispatchPendingMessages();
  27304. saveSnapshot (ui, prefix + "-selected.png");
  27305. playlist.selectClipsForSnapshot ({});
  27306. break;
  27307. }
  27308. juce::String report;
  27309. const auto listTracks = [&offline, &report] (const juce::String& title) {
  27310. const auto& s = offline.getSong();
  27311. report << title << "\n";
  27312. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  27313. {
  27314. int clips = 0, muted = 0;
  27315. for (const auto& c : s.playlist)
  27316. if (c.track == t)
  27317. ++clips, muted += c.muted ? 1 : 0;
  27318. const auto& pt = s.playlistTracks[(std::size_t) t];
  27319. if (clips > 0 || pt.grouped || ! pt.name.empty())
  27320. report << "track " << (t + 1) << " '" << juce::String::fromUTF8 (pt.name.c_str()) << "' grouped=" << (pt.grouped ? 1 : 0) << " collapsed=" << (pt.collapsed ? 1 : 0)
  27321. << " comp=" << (pt.compTrack ? 1 : 0) << " clips=" << clips << " muted=" << muted << "\n";
  27322. }
  27323. };
  27324. listTracks ("opened");
  27325. // the first group's header (a member's menu holds "Comp these takes" too)
  27326. int firstGroup = -1;
  27327. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && firstGroup < 0; ++t)
  27328. if (lynx::comp::canComp (offline.getSong(), t))
  27329. firstGroup = t;
  27330. report << "first group with takes: track " << (firstGroup + 1) << "\n";
  27331. if (firstGroup >= 0)
  27332. {
  27333. saveMenus (juce::StringArray { "Playlist track" }, std::vector<juce::PopupMenu> { playlist.getTrackMenuForSnapshot (firstGroup) }, prefix + "-trackmenu.png");
  27334. int comp = -1;
  27335. offline.editSong ([firstGroup, &comp] (lynx::Song& s) { comp = lynx::comp::compTakes (s, firstGroup); });
  27336. offline.dispatchPendingMessages();
  27337. saveSnapshot (ui, prefix + "-comped.png");
  27338. listTracks ("after Comp these takes");
  27339. const auto g = lynx::comp::groupOf (offline.getSong(), comp);
  27340. std::int64_t from = -1, to = 0;
  27341. for (const auto& c : offline.getSong().playlist)
  27342. if (c.track == g.first)
  27343. from = from < 0 ? c.start : std::min (from, c.start), to = std::max (to, c.end());
  27344. if (g.valid() && to > from)
  27345. {
  27346. offline.editSong ([&g, from, to] (lynx::Song& s) { lynx::comp::swipe (s, g.first, from + (to - from) / 4, from + (to - from) / 2); });
  27347. offline.dispatchPendingMessages();
  27348. saveSnapshot (ui, prefix + "-swiped.png");
  27349. listTracks ("after a swipe of the middle of the first lane");
  27350. // a lane auditioned; the crossfade close up; the comp flattened
  27351. offline.editSong ([&g] (lynx::Song& s) { lynx::comp::setAudition (s, g.first); }, false);
  27352. offline.dispatchPendingMessages();
  27353. saveSnapshot (ui, prefix + "-audition.png");
  27354. offline.editSong ([] (lynx::Song& s) { lynx::comp::setAudition (s, -1); }, false);
  27355. const auto switchAt = from + (to - from) / 4;
  27356. playlist.setViewForSnapshot (4.0 * 4.0 * lynx::ppq, 0, 0);
  27357. playlist.setScrollTickForSnapshot ((double) (switchAt - 100));
  27358. juce::Thread::sleep (1500);
  27359. offline.dispatchPendingMessages();
  27360. saveSnapshot (ui, prefix + "-crossfade.png");
  27361. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  27362. offline.editSong ([comp] (lynx::Song& s) { lynx::comp::flatten (s, comp); });
  27363. offline.dispatchPendingMessages();
  27364. saveSnapshot (ui, prefix + "-flattened.png");
  27365. listTracks ("after Flatten comp");
  27366. }
  27367. }
  27368. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getRecordMenuForSnapshot() }, prefix + "-recordmenu.png");
  27369. juce::File (prefix + "-tracks.txt").replaceWithText (report);
  27370. }
  27371. }
  27372. // Round 190bx: the Settings pages alone (the full --snapshot takes minutes). prefix-settings-<page>.png at the
  27373. // window's size, -small.png at 390 x 390 (rows must scroll, never be cut off or squeezed) and -whole.png tall
  27374. // enough to show every row of the page.
  27375. void runSettingsShot (const juce::String& prefix)
  27376. {
  27377. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27378. {
  27379. lynx::AudioEngine offline (false);
  27380. offline.editSong ([] (lynx::Song& s) {
  27381. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  27382. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  27383. }, false);
  27384. auto shoot = [&] (lynx::SettingsPage page, const juce::String& name, int width, int height) {
  27385. auto panel = lynx::makeSettingsPanel (offline, page);
  27386. if (width > 0)
  27387. panel->setSize (width, height);
  27388. juce::Component frame;
  27389. frame.setSize (panel->getWidth(), panel->getHeight());
  27390. frame.addAndMakeVisible (*panel);
  27391. panel->setTopLeftPosition (0, 0);
  27392. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  27393. {
  27394. juce::Graphics g (image);
  27395. g.fillAll (lynx::theme::panel);
  27396. frame.paintEntireComponent (g, false);
  27397. }
  27398. savePng (image, prefix + "-settings-" + name + ".png");
  27399. };
  27400. const std::pair<lynx::SettingsPage, const char*> pages[] = { { lynx::SettingsPage::audio, "audio" }, { lynx::SettingsPage::midi, "midi" },
  27401. { lynx::SettingsPage::general, "general" }, { lynx::SettingsPage::theme, "theme" },
  27402. { lynx::SettingsPage::files, "files" }, { lynx::SettingsPage::extras, "extras" },
  27403. { lynx::SettingsPage::project, "project" }, { lynx::SettingsPage::info, "info" } };
  27404. for (const auto& [page, name] : pages)
  27405. {
  27406. shoot (page, name, 0, 0);
  27407. shoot (page, juce::String (name) + "-small", 390, 390);
  27408. }
  27409. shoot (lynx::SettingsPage::audio, "audio-whole", 680, 1500);
  27410. shoot (lynx::SettingsPage::general, "general-whole", 680, 2400); // (round 190gh: + the Updates section's previous-version row)
  27411. // round 190jp (design190ia FW-20): the whole Theme page (thumbnails, Adjustments, dots, A | B), then with
  27412. // Adjustments and two dots set, in that theme
  27413. shoot (lynx::SettingsPage::theme, "theme-whole", 680, 1900);
  27414. {
  27415. const auto before = lynx::themeui::current();
  27416. auto adjusted = before;
  27417. adjusted.hue = 40.0f;
  27418. adjusted.saturation = 0.45f;
  27419. adjusted.contrast = 0.3f;
  27420. adjusted.text = 0.4f;
  27421. adjusted.dots[(std::size_t) lynx::themes::Dot::steps] = 0xffffa040;
  27422. adjusted.dots[(std::size_t) lynx::themes::Dot::highlight] = 0xff30a5ff;
  27423. lynx::themeui::apply (adjusted, false);
  27424. shoot (lynx::SettingsPage::theme, "theme-adjusted", 680, 1900);
  27425. lynx::themeui::apply (before, false);
  27426. }
  27427. }
  27428. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  27429. }
  27430. // round 190bw: FL's 13 curve modes of an automation clip's points (see --curveshot)
  27431. bool runPickerDropShot (const juce::String& prefix)
  27432. {
  27433. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27434. lynx::AudioEngine offline (false);
  27435. juce::StringArray checks;
  27436. bool all = true;
  27437. const auto check = [&checks, &all] (bool ok, const juce::String& what) {
  27438. checks.add ((ok ? "OK " : "FAIL ") + what);
  27439. all = all && ok;
  27440. };
  27441. {
  27442. lynx::MainComponent ui (offline, false);
  27443. ui.setSize (1600, 900);
  27444. offline.dispatchPendingMessages();
  27445. const auto bar = (std::int64_t) lynx::ppq * 4;
  27446. offline.editSong ([bar] (lynx::Song& s) {
  27447. s.patterns.resize (3);
  27448. const char* names[] = { "Pattern 1", "Pattern 2", "Pattern 3" };
  27449. for (int p = 0; p < 3; ++p)
  27450. {
  27451. auto& pattern = s.patterns[(std::size_t) p];
  27452. pattern.name = names[p];
  27453. pattern.notes.clear();
  27454. for (int n = 0; n < 4 * (p + 1); ++n)
  27455. {
  27456. lynx::Note note;
  27457. note.start = (std::int64_t) n * lynx::ppq / 2;
  27458. note.length = lynx::ppq / 4;
  27459. note.key = 60 + (n * 5 + p * 3) % 12;
  27460. pattern.notes.push_back (note);
  27461. }
  27462. }
  27463. s.patterns[1].lengthTicks = bar * 2; // (Pattern 2 is two bars long)
  27464. s.currentPattern = 0;
  27465. s.playlist.clear();
  27466. }, false);
  27467. offline.dispatchPendingMessages();
  27468. ui.selectTabForSnapshot (2);
  27469. offline.dispatchPendingMessages();
  27470. auto& playlist = ui.getPlaylistForSnapshot();
  27471. playlist.setViewForSnapshot (120.0, 0, 0);
  27472. offline.dispatchPendingMessages();
  27473. // the drag's description survives the trip
  27474. {
  27475. auto kind = lynx::ClipKind::audio;
  27476. std::vector<int> entries;
  27477. const auto text = lynx::PlaylistComponent::pickerDragDescription (lynx::ClipKind::pattern, { 2, 0 });
  27478. check (lynx::PlaylistComponent::pickerDrag (text, kind, entries) && kind == lynx::ClipKind::pattern && entries == std::vector<int> ({ 2, 0 }),
  27479. "drag description " + text);
  27480. }
  27481. const auto at = [&playlist] (int track, double ticks) {
  27482. return juce::Point<int> (juce::roundToInt (playlist.xOfTickForSnapshot (ticks)), playlist.trackRowForSnapshot (track).getCentreY());
  27483. };
  27484. const auto find = [&offline] (int track, int pattern) -> const lynx::Clip* {
  27485. for (const auto& c : offline.getSong().playlist)
  27486. if (c.track == track && c.kind == lynx::ClipKind::pattern && c.pattern == pattern)
  27487. return &c;
  27488. return nullptr;
  27489. };
  27490. // 1. Pattern 1 dropped on track 1 a little after bar 2's line: it starts on that line
  27491. playlist.dropFromPicker (lynx::ClipKind::pattern, { 0 }, at (0, (double) bar + lynx::ppq * 0.2), false);
  27492. offline.dispatchPendingMessages();
  27493. const auto* one = find (0, 0);
  27494. check (one != nullptr && one->start == bar && one->length == bar, "plain drop: Pattern 1 on track 1 at bar 2");
  27495. // 2. Pattern 2 + Pattern 3 (picked together) dropped on track 3 at bar 3: tracks 3 and 4, same time
  27496. playlist.dropFromPicker (lynx::ClipKind::pattern, { 1, 2 }, at (2, (double) bar * 2), false);
  27497. offline.dispatchPendingMessages();
  27498. const auto* two = find (2, 1);
  27499. const auto* three = find (3, 2);
  27500. check (two != nullptr && three != nullptr && two->start == bar * 2 && three->start == bar * 2,
  27501. "two picked patterns: Pattern 2 on track 3, Pattern 3 on track 4, both at bar 3");
  27502. check (offline.getSong().currentPattern == 2, "the current pattern is the last dropped one (Pattern 3)");
  27503. const auto selectedAre = [&playlist, &offline] (int track, std::size_t count) {
  27504. const auto& sel = playlist.getSelectedClips();
  27505. if (sel.size() != count)
  27506. return false;
  27507. for (const auto i : sel)
  27508. if (i < 0 || i >= (int) offline.getSong().playlist.size() || offline.getSong().playlist[(std::size_t) i].start != (track < 0 ? 2 * (std::int64_t) lynx::ppq * 4 : offline.getSong().playlist[(std::size_t) i].start)
  27509. || (track >= 0 && offline.getSong().playlist[(std::size_t) i].track != track))
  27510. return false;
  27511. return true;
  27512. };
  27513. check (selectedAre (-1, 2), "the two dropped clips are the selection (FL), Pattern 1's clip is not");
  27514. saveSnapshot (ui, prefix + "-plain.png");
  27515. // 3. Shift: all three on track 6 from bar 1, one after the other
  27516. playlist.dropFromPicker (lynx::ClipKind::pattern, { 0, 1, 2 }, at (5, 0.0), true);
  27517. offline.dispatchPendingMessages();
  27518. const auto* a = find (5, 0);
  27519. const auto* b = find (5, 1);
  27520. const auto* c = find (5, 2);
  27521. check (a != nullptr && b != nullptr && c != nullptr && a->start == 0 && b->start == a->end() && c->start == b->end(),
  27522. "Shift drop: Pattern 1, 2, 3 one after the other on track 6");
  27523. check (offline.getSong().currentPattern == 2, "Shift keeps the current pattern");
  27524. check (selectedAre (5, 3), "the three chained clips are the selection");
  27525. saveSnapshot (ui, prefix + "-shift.png");
  27526. }
  27527. checks.add (all ? "ALL OK" : "FAILURES");
  27528. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  27529. return all;
  27530. }
  27531. bool runTrackModeShot (const juce::String& prefix)
  27532. {
  27533. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27534. lynx::AudioEngine offline (false);
  27535. bool all = true;
  27536. juce::String report;
  27537. {
  27538. lynx::MainComponent ui (offline, false);
  27539. ui.setSize (1600, 900);
  27540. offline.dispatchPendingMessages();
  27541. auto& playlist = ui.getPlaylistForSnapshot();
  27542. // the track's menu, Track mode and Audio track side by side; the Audio track entries as FL writes them
  27543. // ("-" in front = greyed, "v" = ticked)
  27544. const auto shoot = [&] (int track, const juce::String& name, const juce::StringArray& fl) {
  27545. const auto menu = playlist.getTrackMenuForSnapshot (track);
  27546. juce::StringArray names { "Track " + juce::String (track + 1) };
  27547. std::vector<juce::PopupMenu> menus { menu };
  27548. menus.reserve (3); // (round 190rf, ASan: the iterator below walks menus[1] while the third is added)
  27549. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  27550. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Track mode"), 'T'))
  27551. {
  27552. names.add (lynx::tr ("Track mode"));
  27553. menus.push_back (*it.getItem().subMenu);
  27554. }
  27555. if (menus.size() == 2)
  27556. for (juce::PopupMenu::MenuItemIterator it (menus[1]); it.next();)
  27557. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Audio track"), 'A'))
  27558. {
  27559. names.add (lynx::tr ("Audio track"));
  27560. menus.push_back (*it.getItem().subMenu);
  27561. }
  27562. juce::StringArray lynxList;
  27563. if (menus.size() == 3)
  27564. for (juce::PopupMenu::MenuItemIterator it (menus[2]); it.next();)
  27565. lynxList.add (it.getItem().isSeparator ? juce::String ("|")
  27566. : (it.getItem().isTicked ? "v " : "") + juce::String (it.getItem().isEnabled ? "" : "- ") + it.getItem().text);
  27567. saveMenus (names, menus, prefix + "-" + name + ".png");
  27568. const auto same = menus.size() == 3 && lynxList == fl;
  27569. all = all && same;
  27570. report << name << ": " << (same ? "SAME AS FL" : "DIFFERENT") << "\n LYNX: " << lynxList.joinIntoString (" / ")
  27571. << "\n FL: " << fl.joinIntoString (" / ") << "\n";
  27572. };
  27573. const auto flList = [] (int inserts, std::map<int, juce::String> named, std::set<int> greyed) {
  27574. juce::StringArray l { "New mixer track(s)", "|" };
  27575. for (int i = 1; i <= inserts; ++i)
  27576. l.add ((greyed.count (i) ? "- " : "") + juce::String (i) + ". " + (named.count (i) ? named[i] : "Insert " + juce::String (i)));
  27577. return l;
  27578. };
  27579. // q1-01: a fresh project, Track 1 unassigned
  27580. shoot (0, "fresh", flList (16, {}, {}));
  27581. // q1-02: Track 1 linked to insert 6, insert 7 renamed "Vox chain"; Track 2's menu
  27582. offline.editSong ([] (lynx::Song& s) {
  27583. lynx::trackmodes::assignAudioTracks (s, { 0 }, 6);
  27584. s.mixer[7].name = "Vox chain";
  27585. });
  27586. offline.dispatchPendingMessages();
  27587. shoot (1, "linked-renamed", flList (16, { { 7, "Vox chain" } }, { 6 }));
  27588. // q1-07: the rest of FL's session (live 190cu Q2): Track 3 → 7; Track 4 → New mixer track (17), insert 9
  27589. // renamed "Vox chain", Track 4 → 9; Track 5 "Lead" → 11, insert 12 "Vox chain", Track 5 → 12; Track 6 "Lead"
  27590. // (unassigned), insert 13 "Vox chain", Track 6 → 13. Track 7's menu
  27591. offline.editSong ([] (lynx::Song& s) {
  27592. namespace tm = lynx::trackmodes;
  27593. if (s.playlistTracks.size() < 8)
  27594. s.playlistTracks.resize (8);
  27595. tm::assignAudioTracks (s, { 2 }, 7);
  27596. tm::assignAudioTracks (s, { 3 }, tm::newMixerTrack);
  27597. s.mixer[9].name = "Vox chain";
  27598. tm::assignAudioTracks (s, { 3 }, 9);
  27599. s.playlistTracks[4].name = "Lead";
  27600. tm::assignAudioTracks (s, { 4 }, 11);
  27601. s.mixer[12].name = "Vox chain";
  27602. tm::assignAudioTracks (s, { 4 }, 12);
  27603. s.playlistTracks[5].name = "Lead";
  27604. s.mixer[13].name = "Vox chain";
  27605. tm::assignAudioTracks (s, { 5 }, 13);
  27606. });
  27607. offline.dispatchPendingMessages();
  27608. shoot (6, "full-state", flList (17, { { 7, "Vox chain" }, { 9, "Insert 17" }, { 12, "Lead" }, { 13, "Vox chain" } }, { 6, 7, 9, 12, 13 }));
  27609. }
  27610. report << (all ? "ALL SAME AS FL\n" : "FAILURES\n");
  27611. juce::File (prefix + "-report.txt").replaceWithText (report);
  27612. return all;
  27613. }
  27614. void runCurveShot (const juce::String& prefix)
  27615. {
  27616. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27617. lynx::AudioEngine offline (false);
  27618. {
  27619. lynx::MainComponent ui (offline, false);
  27620. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  27621. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  27622. offline.dispatchPendingMessages();
  27623. // FL's menu order, one bar per mode, the levels going up and down; a tension where the mode needs one to show
  27624. static const int order[] = { lynx::flcurve::smooth, lynx::flcurve::hold, lynx::flcurve::singleCurve, lynx::flcurve::singleCurve2,
  27625. lynx::flcurve::singleCurve3, lynx::flcurve::doubleCurve, lynx::flcurve::doubleCurve2, lynx::flcurve::doubleCurve3,
  27626. lynx::flcurve::halfSine, lynx::flcurve::stairs, lynx::flcurve::smoothStairs, lynx::flcurve::pulse, lynx::flcurve::wave };
  27627. const auto bar = (std::int64_t) lynx::ppq * 4;
  27628. offline.editSong ([bar] (lynx::Song& song) {
  27629. song.mode = lynx::PlayMode::song;
  27630. lynx::Automation a;
  27631. a.name = "Curve modes";
  27632. a.target = { lynx::AutomationTargetKind::mixerVolume, 1 };
  27633. a.points.push_back ({ 0, 0.15f, 0.0f });
  27634. int k = 0;
  27635. for (const auto mode : order)
  27636. {
  27637. const auto stepped = mode == lynx::flcurve::stairs || mode == lynx::flcurve::smoothStairs || mode == lynx::flcurve::pulse || mode == lynx::flcurve::wave;
  27638. a.points.back().mode = (std::uint8_t) mode;
  27639. a.points.back().tension = mode == lynx::flcurve::smooth || mode == lynx::flcurve::hold ? 0.0f : stepped ? -0.72f : (k % 2 == 0 ? 0.55f : -0.55f);
  27640. ++k;
  27641. a.points.push_back ({ bar * k, k % 2 == 1 ? 0.85f : 0.15f, 0.0f });
  27642. }
  27643. song.automations.insert (song.automations.begin(), a);
  27644. for (auto& c : song.playlist)
  27645. if (c.kind == lynx::ClipKind::automation)
  27646. ++c.automation;
  27647. lynx::Clip clip;
  27648. clip.kind = lynx::ClipKind::automation;
  27649. clip.automation = 0;
  27650. clip.track = 3;
  27651. clip.length = bar * 13;
  27652. song.playlist.push_back (clip);
  27653. if (song.playlistTracks.size() < 4)
  27654. song.playlistTracks.resize (4);
  27655. song.playlistTracks[3].height = 150;
  27656. }, false);
  27657. offline.dispatchPendingMessages();
  27658. ui.selectTabForSnapshot (2);
  27659. offline.dispatchPendingMessages();
  27660. auto& playlist = ui.getPlaylistForSnapshot();
  27661. saveSnapshot (ui, prefix + "-playlist.png");
  27662. const auto clipIndex = (int) offline.getSong().playlist.size() - 1;
  27663. // the point menu of the point that ends the "Stairs" segment (point 10), and of the first point
  27664. saveMenus (juce::StringArray { "Automation point (ends a Stairs segment)", "First point" },
  27665. std::vector<juce::PopupMenu> { playlist.getAutomationPointMenuForSnapshot (clipIndex, 10), playlist.getAutomationPointMenuForSnapshot (clipIndex, 0) },
  27666. prefix + "-point-menu.png");
  27667. auto editor = lynx::makeAutomationEditor (offline, 0);
  27668. editor->setSize (1500, 420);
  27669. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
  27670. editor.reset();
  27671. // the project itself, for --export-flp and a look at the same clip in FL
  27672. {
  27673. juce::String saveError;
  27674. lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-modes.lynx"), saveError);
  27675. }
  27676. // part 2: the Piano roll tools that gained FL's options (they preview on the pattern and put the notes back)
  27677. ui.selectTabForSnapshot (1);
  27678. offline.dispatchPendingMessages();
  27679. auto& roll = ui.getPianoRollForSnapshot();
  27680. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::flip, "-tool-flip.png" },
  27681. { lynx::NoteTool::limit, "-tool-limit.png" },
  27682. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  27683. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  27684. { lynx::NoteTool::lfo, "-tool-lfo.png" } };
  27685. // round 190ct: checks of the FL-live fixes, one line each in <prefix>-checks.txt (OK / FAIL)
  27686. juce::StringArray checks;
  27687. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  27688. {
  27689. juce::String header;
  27690. const auto pointMenu = playlist.getAutomationPointMenuForSnapshot (clipIndex, 10); // (the iterator keeps a reference)
  27691. for (juce::PopupMenu::MenuItemIterator it (pointMenu); it.next();)
  27692. {
  27693. header = it.getItem().text;
  27694. break;
  27695. }
  27696. check (header == "Point 11/14", "point menu header \"" + header + "\" (FL: \"Point n/N\")");
  27697. }
  27698. for (const auto& [tool, name] : tools)
  27699. {
  27700. auto panel = lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot());
  27701. offline.dispatchPendingMessages();
  27702. savePng (panel->createComponentSnapshot (panel->getLocalBounds()), prefix + name);
  27703. if (tool == lynx::NoteTool::flip)
  27704. {
  27705. std::vector<juce::ToggleButton*> toggles;
  27706. for (auto* child : panel->getChildren())
  27707. if (auto* t = dynamic_cast<juce::ToggleButton*> (child))
  27708. toggles.push_back (t);
  27709. check (toggles.size() == 3 && toggles[0]->getToggleState() && toggles[1]->getToggleState() && ! toggles[2]->getToggleState(),
  27710. "flip opens with Flip horizontally on, Preserve start times on, Flip vertically off");
  27711. if (toggles.size() == 3)
  27712. {
  27713. toggles[2]->setToggleState (true, juce::sendNotificationSync);
  27714. check (! toggles[0]->getToggleState() && toggles[2]->getToggleState(), "flip: vertically turns horizontally off (radios)");
  27715. toggles[0]->setToggleState (true, juce::sendNotificationSync);
  27716. check (toggles[0]->getToggleState() && ! toggles[2]->getToggleState(), "flip: horizontally turns vertically off (radios)");
  27717. }
  27718. }
  27719. if (tool == lynx::NoteTool::limit)
  27720. {
  27721. auto* list = lynx::noteToolLongestChoiceForSnapshot (*panel);
  27722. juce::ComboBox* key = nullptr;
  27723. for (auto* child : panel->getChildren())
  27724. if (auto* box = dynamic_cast<juce::ComboBox*> (child); box != nullptr && box->getNumItems() == 12)
  27725. key = box;
  27726. check (list != nullptr && list->getNumItems() == 89, "limit list has (none) + 66 chords + 22 scales: "
  27727. + juce::String (list != nullptr ? list->getNumItems() : 0));
  27728. check (list != nullptr && key != nullptr && list->getY() == key->getY() && list->getX() > key->getRight(),
  27729. "limit: Key and the chord / scale list share one row");
  27730. if (list != nullptr)
  27731. saveMenus (juce::StringArray { "Limit: Key / scale list" }, std::vector<juce::PopupMenu> { *list->getRootMenu() },
  27732. prefix + "-tool-limit-list.png");
  27733. }
  27734. if (tool == lynx::NoteTool::lfo)
  27735. saveMenus (juce::StringArray { "LFO tool: right-click on a Period slider" },
  27736. std::vector<juce::PopupMenu> { lynx::noteToolPresetMenuForSnapshot (*panel) }, prefix + "-tool-lfo-steps.png");
  27737. }
  27738. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  27739. }
  27740. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  27741. }
  27742. bool runEvPaneShot (const juce::String& prefix, const juce::String& projectPath)
  27743. {
  27744. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27745. lynx::AudioEngine offline (false);
  27746. juce::StringArray report;
  27747. bool ok = true;
  27748. {
  27749. lynx::MainComponent ui (offline, false);
  27750. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  27751. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  27752. if (projectPath.isNotEmpty())
  27753. ui.openFile (juce::File (projectPath));
  27754. offline.dispatchPendingMessages();
  27755. ui.selectTabForSnapshot (1); // the Piano Roll
  27756. offline.dispatchPendingMessages();
  27757. auto& roll = ui.getPianoRollForSnapshot();
  27758. roll.scrollToNotes();
  27759. const auto area = ui.getLocalArea (&roll, roll.getLocalBounds());
  27760. const auto file = lynx::platform::settingsFile ("piano-roll-event-pane.txt");
  27761. auto source = juce::Desktop::getInstance().getMainMouseSource();
  27762. const auto now = juce::Time::getCurrentTime();
  27763. auto event = [&] (juce::Point<int> p, juce::Point<int> down, juce::ModifierKeys mods, int clicks, bool dragged) {
  27764. return juce::MouseEvent (source, p.toFloat(), mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &roll, &roll, now, down.toFloat(), now, clicks, dragged);
  27765. };
  27766. auto barCentre = [&roll] { return roll.eventPaneBarArea().getCentre(); };
  27767. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier),
  27768. middle (juce::ModifierKeys::middleButtonModifier);
  27769. auto click = [&] (juce::ModifierKeys button, int clicks) {
  27770. const auto at = barCentre();
  27771. roll.mouseDown (event (at, at, button, clicks, false));
  27772. roll.mouseUp (event (at, at, {}, clicks, false));
  27773. offline.dispatchPendingMessages();
  27774. };
  27775. auto dragTo = [&] (int y) {
  27776. const auto at = barCentre();
  27777. roll.mouseDown (event (at, at, left, 1, false));
  27778. for (int step = 1; step <= 8; ++step) // (a few moves, as a hand does)
  27779. roll.mouseDrag (event ({ at.x, at.y + (y - at.y) * step / 8 }, at, left, 1, true));
  27780. roll.mouseUp (event ({ at.x, y }, at, {}, 1, true));
  27781. offline.dispatchPendingMessages();
  27782. };
  27783. auto state = [&] (const juce::String& name) {
  27784. const auto grid = roll.getHeight() - lynx::PianoRollComponent::headerHeight - roll.velocityHeight - lynx::evpane::barThickness;
  27785. const auto& st = lynx::PianoRollComponent::eventPaneState();
  27786. report.add (name + ": roll " + juce::String (roll.getHeight()) + " px, grid " + juce::String (juce::jmax (0, grid)) + " px, bar top "
  27787. + juce::String (roll.eventPaneBarTopForTests()) + ", event editor " + juce::String (roll.velocityHeight) + " px, aspect "
  27788. + juce::String (st.aspect, 4) + ", spare " + juce::String (st.spare, 4) + ", file \"" + file.loadFileAsString().trim().replace ("\n", " ") + "\"");
  27789. saveArea (ui, area, prefix + "-" + name + ".png");
  27790. };
  27791. auto expect = [&] (bool condition, const juce::String& what) {
  27792. report.add ((condition ? "PASS " : "FAIL ") + what);
  27793. ok = ok && condition;
  27794. };
  27795. state ("1-default");
  27796. const auto defaultLane = roll.velocityHeight;
  27797. expect (std::abs (lynx::PianoRollComponent::eventPaneState().aspect - 0.8f) < 1e-6f, "default place is FL's 0.8");
  27798. ui.setHintForSnapshot (roll.hintAt (barCentre()));
  27799. saveSnapshot (ui, prefix + "-2-hover-hint.png");
  27800. ui.setHintForSnapshot ({});
  27801. const auto travelTop = lynx::PianoRollComponent::headerHeight, travelBottom = roll.getHeight() - lynx::evpane::barThickness;
  27802. dragTo (travelTop + (travelBottom - travelTop) * 45 / 100);
  27803. state ("3-dragged-larger");
  27804. const auto largeLane = roll.velocityHeight;
  27805. expect (largeLane > defaultLane * 2, "drag up makes the event editor taller");
  27806. expect (lynx::evpane::fromText (file.loadFileAsString().toStdString()) == lynx::PianoRollComponent::eventPaneState(),
  27807. "the place is written to the settings file on release");
  27808. click (right, 1);
  27809. state ("4-right-click-alternate");
  27810. expect (roll.velocityHeight == 0, "right-click: the alternate size (FL's spare 1.0) folds the event editor away");
  27811. click (right, 1);
  27812. state ("5-right-click-back");
  27813. expect (roll.velocityHeight == largeLane, "right-click again: back to the dragged size");
  27814. roll.runAction ("pianoRoll.eventPaneAlternate");
  27815. offline.dispatchPendingMessages();
  27816. expect (roll.velocityHeight == 0, "Shift+Enter (pianoRoll.eventPaneAlternate) swaps too");
  27817. roll.runAction ("pianoRoll.eventPaneAlternate");
  27818. offline.dispatchPendingMessages();
  27819. dragTo (travelTop + 10);
  27820. state ("6-grid-folded");
  27821. expect (roll.eventPaneBarTopForTests() == travelTop, "a drag within 23 px of the top folds the note grid away");
  27822. click (middle, 1);
  27823. state ("7-middle-click-default");
  27824. expect (roll.velocityHeight == defaultLane, "middle-click: back to the default place");
  27825. // a taller window keeps the proportion (the place is a fraction of the travel)
  27826. dragTo (travelTop + (travelBottom - travelTop) * 60 / 100);
  27827. const auto before = lynx::PianoRollComponent::eventPaneState().aspect;
  27828. roll.setSize (roll.getWidth(), roll.getHeight() + 200);
  27829. offline.dispatchPendingMessages();
  27830. const auto newTravel = roll.getHeight() - lynx::evpane::barThickness - travelTop;
  27831. expect (std::abs (roll.eventPaneBarTopForTests() - (travelTop + juce::roundToInt (before * (float) newTravel))) <= 1,
  27832. "a taller window keeps the proportion");
  27833. roll.setSize (roll.getWidth(), roll.getHeight() - 200);
  27834. offline.dispatchPendingMessages();
  27835. click (middle, 1); // leave FL's default behind
  27836. }
  27837. report.add (ok ? "RESULT OK" : "RESULT FAIL");
  27838. juce::File (prefix + "-report.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  27839. return ok;
  27840. }
  27841. void runFeat166Shot (const juce::String& prefix, const juce::String& projectPath)
  27842. {
  27843. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27844. lynx::AudioEngine offline (false);
  27845. {
  27846. lynx::MainComponent ui (offline, false);
  27847. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  27848. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  27849. if (projectPath.isNotEmpty())
  27850. ui.openFile (juce::File (projectPath));
  27851. offline.dispatchPendingMessages();
  27852. ui.selectTabForSnapshot (1); // the Piano Roll, on the channel with the most notes
  27853. offline.dispatchPendingMessages();
  27854. // the scale the pattern's notes fit best (major / minor, any root)
  27855. const auto& song = offline.getSong();
  27856. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  27857. int bestRoot = 0, bestScale = 1, bestHits = -1;
  27858. for (int sc = 1; sc < (int) lynx::notetools::scales().size(); ++sc)
  27859. {
  27860. const juce::String name (lynx::notetools::scales()[(std::size_t) sc].name);
  27861. if (name != "Major" && name != "Minor")
  27862. continue;
  27863. for (int root = 0; root < 12; ++root)
  27864. {
  27865. int hits = 0;
  27866. for (const auto& n : notes)
  27867. hits += lynx::notetools::inScale (n.key, root, sc) ? 1 : 0;
  27868. if (hits > bestHits)
  27869. bestHits = hits, bestRoot = root, bestScale = sc;
  27870. }
  27871. }
  27872. auto& roll = ui.getPianoRollForSnapshot();
  27873. roll.setScaleForSnapshot (bestRoot, bestScale);
  27874. roll.scrollToNotes();
  27875. offline.dispatchPendingMessages();
  27876. saveSnapshot (ui, prefix + "-pr-scale.png");
  27877. roll.setFoldToScale (true);
  27878. offline.dispatchPendingMessages();
  27879. saveSnapshot (ui, prefix + "-pr-folded.png");
  27880. roll.setFoldToScale (false);
  27881. // ghost channels: only the first other channel with notes stays a ghost
  27882. const auto selected = offline.getSelectedChannel();
  27883. int keep = -1;
  27884. for (const auto& n : notes)
  27885. if (n.channel != selected && keep < 0)
  27886. keep = n.channel;
  27887. offline.editSong ([keep] (lynx::Song& s) {
  27888. for (int c = 0; c < (int) s.channels.size(); ++c)
  27889. s.channels[(std::size_t) c].ghostHidden = c != keep;
  27890. }, false);
  27891. offline.dispatchPendingMessages();
  27892. saveSnapshot (ui, prefix + "-pr-ghost-one.png");
  27893. saveMenus (juce::StringArray { "Ghost channels" }, { roll.ghostChannelsMenu() }, prefix + "-ghostmenu.png");
  27894. offline.editSong ([] (lynx::Song& s) {
  27895. for (auto& c : s.channels)
  27896. c.ghostHidden = false;
  27897. }, false);
  27898. // the Mixer at 500 inserts
  27899. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  27900. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::insertTracks (s, (int) s.mixer.size(), lynx::mixerops::roomForInserts (s)); }, false);
  27901. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  27902. offline.dispatchPendingMessages();
  27903. ui.selectTabForSnapshot (3);
  27904. offline.dispatchPendingMessages();
  27905. auto& mixer = ui.getMixerForSnapshot();
  27906. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  27907. saveSnapshot (ui, prefix + "-mixer500-start.png");
  27908. const auto t3 = juce::Time::getMillisecondCounterHiRes();
  27909. mixer.selectTrack ((int) offline.getSong().mixer.size() - 1);
  27910. offline.dispatchPendingMessages();
  27911. saveSnapshot (ui, prefix + "-mixer500-end.png");
  27912. juce::File (prefix + "-mixer500.txt")
  27913. .replaceWithText ("inserts=" + juce::String ((int) offline.getSong().mixer.size() - 1) + "\nfill_ms=" + juce::String (t1 - t0, 2)
  27914. + "\nsnapshot_ms=" + juce::String (t3 - t2, 2) + "\n");
  27915. }
  27916. }
  27917. // Round 190ay, Freeze, end to end with the real engine, files and export (LYNX.exe --freezetest prefix [project]).
  27918. // The project (.lynx / .flp / .als; without one, a small demo song) is rendered live, every channel that can be
  27919. // frozen is frozen, and the same render is made again: the two mixes must null. Written to prefix-report.txt: the
  27920. // null residual, the process memory and the render time before / frozen / unfrozen, what a save holds, whether
  27921. // Unfreeze gives the channels back as they were, the out-of-date and missing-audio states. Shots: the Channel Rack
  27922. // (live, frozen, out of date), the channel menus, the Piano roll of a frozen channel. The frozen audio goes to
  27923. // prefix-data (never next to the project). True = every check passed.
  27924. bool runFreezeTest (const juce::String& prefix, const juce::String& projectPath, const juce::String& mode = {})
  27925. {
  27926. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27927. lynx::AudioEngine offline (false);
  27928. lynx::MainComponent ui (offline, false);
  27929. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  27930. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  27931. const auto write = [&prefix, &ui] (const char* name) {
  27932. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  27933. file.deleteFile();
  27934. juce::FileOutputStream out (file);
  27935. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  27936. };
  27937. juce::String report;
  27938. int failures = 0;
  27939. const auto check = [&] (bool ok, const juce::String& what) {
  27940. report << (ok ? "ok " : "FAIL ") << what << "\n";
  27941. failures += ok ? 0 : 1;
  27942. };
  27943. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  27944. if (projectPath.isNotEmpty())
  27945. {
  27946. ui.openFile (juce::File (projectPath));
  27947. offline.dispatchPendingMessages();
  27948. }
  27949. else
  27950. offline.editSong ([] (lynx::Song& s) {
  27951. s.channels.clear();
  27952. s.patterns.clear();
  27953. s.playlist.clear();
  27954. s.bpm = 120.0;
  27955. const char* names[] = { "Lead", "Bass", "Pad", "Kick" };
  27956. for (int c = 0; c < 4; ++c)
  27957. {
  27958. lynx::ChannelDef d;
  27959. d.name = names[c];
  27960. d.instrument = c == 3 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  27961. d.synth.release = 0.3f + 0.3f * (float) c;
  27962. d.synth.cutoff = 1500.0f + 900.0f * (float) c;
  27963. d.mixerTrack = c + 1;
  27964. s.channels.push_back (d);
  27965. }
  27966. for (int p = 0; p < 2; ++p)
  27967. {
  27968. auto& pattern = s.patterns.emplace_back();
  27969. pattern.name = p == 0 ? "Verse" : "Break";
  27970. pattern.lengthTicks = 4 * lynx::ppq * 4;
  27971. for (int c = 0; c < 4; ++c)
  27972. for (int step = 0; step < (p == 0 ? 8 : 2); ++step)
  27973. {
  27974. lynx::Note n;
  27975. n.channel = c;
  27976. n.start = (std::int64_t) step * lynx::ppq * (p == 0 ? 2 : 1) + (c == 2 ? lynx::ppq / 2 : 0);
  27977. n.length = c == 3 ? lynx::ppq / 4 : lynx::ppq;
  27978. n.key = c == 3 ? 36 : 48 + c * 7 + (step * 5) % 12;
  27979. pattern.notes.push_back (n);
  27980. }
  27981. pattern.sortNotes();
  27982. }
  27983. const int order[] = { 0, 0, 1, 0 };
  27984. for (int i = 0; i < 4; ++i)
  27985. {
  27986. lynx::Clip clip;
  27987. clip.pattern = order[i];
  27988. clip.start = (std::int64_t) i * 16 * lynx::ppq;
  27989. clip.length = 16 * lynx::ppq;
  27990. s.playlist.push_back (clip);
  27991. }
  27992. s.mode = lynx::PlayMode::song;
  27993. });
  27994. offline.dispatchPendingMessages();
  27995. // the case Freeze exists for, a heavy hosted plugin: LYNX_FREEZETEST_PLUGIN = a plugin file whose first
  27996. // instrument plays the demo song's Lead (tools/testplugin/lynx_test_heavy_vst3.cpp: memory, CPU, latency, a
  27997. // state, and with LYNX_TEST_HEAVY_LOG the instances alive)
  27998. int hostedChannel = -1;
  27999. const auto hostedLog = juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_HEAVY_LOG", {});
  28000. const auto hostedAlive = [&hostedLog] {
  28001. int alive = 0;
  28002. juce::StringArray lines;
  28003. juce::File (hostedLog).readLines (lines);
  28004. for (const auto& l : lines)
  28005. alive += l.startsWith ("create") ? 1 : l.startsWith ("destroy") ? -1 : 0;
  28006. return alive;
  28007. };
  28008. if (const auto pluginPath = juce::SystemStats::getEnvironmentVariable ("LYNX_FREEZETEST_PLUGIN", {}); pluginPath.isNotEmpty() && projectPath.isEmpty())
  28009. {
  28010. auto& host = offline.getPluginHost();
  28011. const auto added = host.addPluginFile (juce::File (pluginPath));
  28012. report << "hosted plugin file: " << pluginPath << " (" << added << " plugins)\n";
  28013. for (const auto& type : host.getKnownPlugins().getTypes())
  28014. if (type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  28015. {
  28016. offline.editSong ([&type] (lynx::Song& s) {
  28017. auto& c = s.channels[0];
  28018. c.instrument = lynx::InstrumentKind::plugin;
  28019. c.plugin.id = type.createIdentifierString().toStdString();
  28020. c.plugin.name = type.name.toStdString();
  28021. });
  28022. hostedChannel = 0;
  28023. break;
  28024. }
  28025. offline.dispatchPendingMessages();
  28026. auto* instance = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (0).get());
  28027. check (hostedChannel == 0 && instance != nullptr, "the hosted plugin is loaded on channel 1");
  28028. report << "hosted plugin: " << juce::String::fromUTF8 (offline.getSong().channels[0].plugin.name.c_str())
  28029. << ", engine latency " << offline.getLatencySamples() << " frames, instances alive " << hostedAlive() << "\n";
  28030. }
  28031. const auto hostedLine = [&] (const char* stage) {
  28032. if (hostedChannel < 0)
  28033. return;
  28034. offline.freeRetiredRacks();
  28035. report << "hosted, " << stage << ": instance on the channel "
  28036. << (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr ? "yes" : "no")
  28037. << ", plugin instances alive in the process " << (hostedLog.isNotEmpty() ? juce::String (hostedAlive()) : juce::String ("(no log)")) << "\n";
  28038. };
  28039. const juce::File data (prefix + "-data");
  28040. data.deleteRecursively();
  28041. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "freezetest");
  28042. report << "project=" << (projectPath.isNotEmpty() ? projectPath : juce::String ("(demo song)")) << "\n"
  28043. << "frozen_audio_folder=" << offline.getFreezeFolder().getFullPathName() << "\n";
  28044. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  28045. struct Mix
  28046. {
  28047. juce::AudioBuffer<float> audio;
  28048. double renderSeconds = 0.0, audioSeconds = 0.0;
  28049. std::int64_t workingSet = 0, privateBytes = 0;
  28050. };
  28051. // the song as it stands, rendered by an export (its own engine: frozen channels play their audio there too)
  28052. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr, std::vector<int>* renderedLive = nullptr, int range = 0) {
  28053. Mix m;
  28054. offline.dispatchPendingMessages();
  28055. offline.freeRetiredRacks(); // (what the message loop does in the app: this mode runs without one)
  28056. m.workingSet = lynx::toolbar::PerformanceMeter::processMemoryBytes();
  28057. m.privateBytes = lynx::toolbar::PerformanceMeter::processPrivateBytes();
  28058. const juce::File file (prefix + "-" + name + ".wav");
  28059. lynx::ExportSettings settings;
  28060. settings.format = lynx::ExportSettings::Format::wav32Float;
  28061. settings.sampleRate = offline.getTransport().sampleRate.load();
  28062. settings.tailSeconds = 2.0;
  28063. juce::String error;
  28064. {
  28065. auto options = settings.toOptions();
  28066. options.hqAllPlugins = false; // the quality heard while playing: what a frozen channel's audio is made at
  28067. options.disableMaxPolyphony = false; // (and each channel's Max polyphony, as while playing)
  28068. if (range == 1)
  28069. options.range = lynx::exportopts::Range::selection;
  28070. if (range == 2)
  28071. {
  28072. options.range = lynx::exportopts::Range::pattern;
  28073. options.loops = 2;
  28074. }
  28075. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  28076. if (renderedLive != nullptr)
  28077. *renderedLive = job.channelsRenderedLive();
  28078. const auto started = juce::Time::getMillisecondCounterHiRes();
  28079. const auto ok = job.run ([] (double) { return true; }, error);
  28080. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  28081. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  28082. }
  28083. juce::WavAudioFormat wav;
  28084. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  28085. {
  28086. m.audio.setSize (2, (int) reader->lengthInSamples);
  28087. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  28088. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  28089. }
  28090. file.deleteFile();
  28091. return m;
  28092. };
  28093. // the worst sample difference, in dB below the first mix's peak
  28094. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  28095. float worst = 0.0f;
  28096. peak = 0.0f;
  28097. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  28098. for (int ch = 0; ch < 2; ++ch)
  28099. for (int i = 0; i < n; ++i)
  28100. {
  28101. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  28102. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  28103. }
  28104. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  28105. };
  28106. const auto line = [&] (const char* name, const Mix& m) {
  28107. report << name << ": working set " << megabytes (m.workingSet) << " MB, private " << megabytes (m.privateBytes) << " MB, render "
  28108. << juce::String (m.renderSeconds, 2) << " s for " << juce::String (m.audioSeconds, 2) << " s of audio ("
  28109. << juce::String (m.audioSeconds > 0.0 ? 100.0 * m.renderSeconds / m.audioSeconds : 0.0, 1) << " % of real time)\n";
  28110. };
  28111. if (mode == "measure")
  28112. {
  28113. // a process that only loaded this project and renders it: its memory with the project loaded, and after
  28114. int frozenCount = 0, hosted = 0;
  28115. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  28116. {
  28117. frozenCount += offline.getSong().channels[(std::size_t) c].freeze.on();
  28118. hosted += dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) != nullptr;
  28119. }
  28120. report << "channels " << (int) offline.getSong().channels.size() << ", frozen " << frozenCount << ", hosted plugin instances " << hosted << "\n";
  28121. const auto m = renderMix ("measure");
  28122. line ("loaded ", m);
  28123. report << "after the render: working set " << megabytes (lynx::toolbar::PerformanceMeter::processMemoryBytes()) << " MB, private "
  28124. << megabytes (lynx::toolbar::PerformanceMeter::processPrivateBytes()) << " MB\n";
  28125. flush();
  28126. return failures == 0;
  28127. }
  28128. // --- live ---
  28129. offline.capturePluginStates();
  28130. offline.editSong ([] (lynx::Song&) {}, false); // (whatever any edit settles — ids of new objects... — settled first)
  28131. const auto before = offline.getSong();
  28132. // (the project's working-time counter runs on while the test does: not part of what is compared)
  28133. const auto savedJson = [] (lynx::Song song) {
  28134. song.info.workSeconds = 0.0;
  28135. return lynx::ProjectFile::toJson (song, false);
  28136. };
  28137. const auto jsonBefore = savedJson (before);
  28138. std::vector<int> targets;
  28139. for (int c = 0; c < (int) before.channels.size(); ++c)
  28140. {
  28141. const auto* why = lynx::freeze::whyNot (before, c);
  28142. const auto plays = std::any_of (before.patterns.begin(), before.patterns.end(), [c] (const lynx::Pattern& p) {
  28143. return std::any_of (p.notes.begin(), p.notes.end(), [c] (const lynx::Note& n) { return n.channel == c; });
  28144. });
  28145. report << "channel " << (c + 1) << " '" << juce::String::fromUTF8 (before.channels[(std::size_t) c].name.c_str()) << "': "
  28146. << (why != nullptr ? juce::String ("not frozen (") + why + ")" : plays ? juce::String ("freeze") : juce::String ("no notes, left alone")) << "\n";
  28147. if (why == nullptr && plays)
  28148. {
  28149. targets.push_back (c);
  28150. // what could make a stem differ from the live channel, for the record
  28151. const auto& def = before.channels[(std::size_t) c];
  28152. int volPan = 0, params = 0, live = 0, lanes = 0, routes = 0;
  28153. for (const auto& a : before.automations)
  28154. if (a.target.index == c)
  28155. {
  28156. volPan += a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan;
  28157. params += a.target.kind == lynx::AutomationTargetKind::channelParam;
  28158. live += a.isLive() && (a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan
  28159. || a.target.kind == lynx::AutomationTargetKind::channelParam);
  28160. }
  28161. for (const auto& p : before.patterns)
  28162. for (const auto& lane : p.events)
  28163. lanes += lane.target.index == c && (lane.target.kind == lynx::AutomationTargetKind::channelVolume
  28164. || lane.target.kind == lynx::AutomationTargetKind::channelPan
  28165. || lane.target.kind == lynx::AutomationTargetKind::channelParam);
  28166. for (const auto& m : before.modulators)
  28167. for (const auto& r : m.routes)
  28168. routes += r.target.index == c && (r.target.kind == lynx::AutomationTargetKind::channelVolume
  28169. || r.target.kind == lynx::AutomationTargetKind::channelPan
  28170. || r.target.kind == lynx::AutomationTargetKind::channelParam);
  28171. report << " instrument kind " << (int) def.instrument << ", insert " << def.mixerTrack << ", automation: volume/pan " << volPan
  28172. << ", parameters " << params << ", live links " << live << ", event lanes " << lanes << ", modulator routes " << routes << "\n";
  28173. }
  28174. }
  28175. check (! targets.empty(), "the project has channels to freeze (" + juce::String ((int) targets.size()) + ")");
  28176. if (targets.empty())
  28177. {
  28178. flush();
  28179. return false;
  28180. }
  28181. const auto first = targets.front();
  28182. offline.setSelectedChannel (first);
  28183. ui.selectTabForSnapshot (0);
  28184. write ("rack-live");
  28185. saveMenus (juce::StringArray { "Channel (live)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-live.png");
  28186. const auto live = renderMix ("live");
  28187. line ("live ", live);
  28188. hostedLine ("live");
  28189. const auto hostedState = hostedChannel >= 0 ? before.channels[(std::size_t) hostedChannel].plugin.state : std::string();
  28190. if (hostedChannel >= 0)
  28191. check (! hostedState.empty(), "the hosted plugin's state is in the project (" + juce::String ((int) hostedState.size()) + " characters)");
  28192. flush();
  28193. // --- frozen ---
  28194. const auto freezeStarted = juce::Time::getMillisecondCounterHiRes();
  28195. for (const auto c : targets)
  28196. {
  28197. const auto error = lynx::freezeChannelNow (offline, c);
  28198. check (error.isEmpty(), "freeze channel " + juce::String (c + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  28199. }
  28200. const auto freezeSeconds = (juce::Time::getMillisecondCounterHiRes() - freezeStarted) / 1000.0;
  28201. offline.dispatchPendingMessages();
  28202. std::int64_t stemBytes = 0;
  28203. int stemFiles = 0;
  28204. bool pluginsGone = true, allFrozen = true;
  28205. for (const auto c : targets)
  28206. {
  28207. const auto& ch = offline.getSong().channels[(std::size_t) c];
  28208. allFrozen = allFrozen && ch.freeze.on() && ! offline.frozenAudioMissing (c) && ! offline.freezeOutOfDate (c);
  28209. for (const auto& stem : ch.freeze.stems)
  28210. {
  28211. stemBytes += juce::File (juce::String::fromUTF8 (stem.path.c_str())).getSize();
  28212. ++stemFiles;
  28213. }
  28214. pluginsGone = pluginsGone && dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) == nullptr;
  28215. auto thawed = ch;
  28216. thawed.freeze = {};
  28217. check (thawed == before.channels[(std::size_t) c], "channel " + juce::String (c + 1) + " keeps its instrument and settings as they were while frozen");
  28218. }
  28219. check (allFrozen, "every target is frozen, its audio on disk and up to date");
  28220. check (pluginsGone, "no hosted plugin instance is left on a frozen channel");
  28221. report << "freeze: " << juce::String (freezeSeconds, 2) << " s for " << (int) targets.size() << " channels, " << stemFiles << " files, "
  28222. << megabytes (stemBytes) << " MB on disk\n";
  28223. if (mode == "keep")
  28224. {
  28225. juce::String error;
  28226. check (lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-frozen.lynx"), error), "the frozen project is saved" + (error.isEmpty() ? juce::String() : ": " + error));
  28227. flush();
  28228. return failures == 0;
  28229. }
  28230. const auto frozen = renderMix ("frozen");
  28231. line ("frozen ", frozen);
  28232. hostedLine ("frozen");
  28233. if (hostedChannel >= 0 && hostedLog.isNotEmpty())
  28234. check (hostedAlive() == 0, "while frozen no instance of the hosted plugin is alive in the process");
  28235. float peak = 0.0f;
  28236. const auto nullFrozen = residual (live, frozen, peak);
  28237. report << "null frozen vs live: " << juce::String (nullFrozen, 1) << " dB (peak " << juce::String (peak, 4) << ", "
  28238. << live.audio.getNumSamples() << " / " << frozen.audio.getNumSamples() << " samples)\n";
  28239. check (peak > 0.001f && nullFrozen < -90.0 && live.audio.getNumSamples() == frozen.audio.getNumSamples(), "the frozen mix nulls against the live mix (below -90 dB)");
  28240. ui.selectTabForSnapshot (0);
  28241. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  28242. write ("rack-frozen");
  28243. saveMenus (juce::StringArray { "Channel (frozen)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-frozen.png");
  28244. report << "hint frozen: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  28245. offline.setSelectedChannel (first);
  28246. ui.selectTabForSnapshot (1);
  28247. offline.setSelectedChannel (first);
  28248. offline.dispatchPendingMessages();
  28249. ui.setHintForSnapshot ({ lynx::tr ("{0} is frozen: Unfreeze to edit ([RMB] on the channel, Unfreeze)",
  28250. { juce::String::fromUTF8 (offline.getSong().channels[(std::size_t) first].name.c_str()) }), {} });
  28251. write ("pianoroll-frozen");
  28252. // --- exports that do not play the song's timeline once: a selection, one pattern twice ---
  28253. // (the frozen audio is the whole song from its start: those renders play the instruments, never a wrong part of it)
  28254. if (projectPath.isEmpty())
  28255. {
  28256. auto part = offline.getSong();
  28257. part.loopStart = 16 * lynx::ppq;
  28258. part.loopEnd = 40 * lynx::ppq;
  28259. const auto partLive = lynx::freeze::thawed (part);
  28260. for (int range = 1; range <= 2; ++range)
  28261. {
  28262. std::vector<int> renderedLive;
  28263. const auto a = renderMix (range == 1 ? "selection-live" : "pattern-live", &partLive, nullptr, range);
  28264. const auto b = renderMix (range == 1 ? "selection-frozen" : "pattern-frozen", &part, &renderedLive, range);
  28265. float partPeak = 0.0f;
  28266. const auto null = residual (a, b, partPeak);
  28267. report << (range == 1 ? "export of a selection (bars 5-10)" : "export of the current pattern, twice") << ", frozen vs live: " << juce::String (null, 1)
  28268. << " dB (peak " << juce::String (partPeak, 4) << ", " << juce::String (b.audioSeconds, 2) << " s), channels rendered live: " << (int) renderedLive.size() << "\n";
  28269. check (partPeak > 0.001f && null < -90.0 && a.audio.getNumSamples() == b.audio.getNumSamples(),
  28270. range == 1 ? "an export of a selection of a frozen project is the selection" : "an export of one pattern of a frozen project is that pattern");
  28271. }
  28272. }
  28273. // --- what a save holds ---
  28274. {
  28275. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  28276. juce::String error;
  28277. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  28278. check (json.contains ("\"freeze\""), "the saved project holds the frozen state");
  28279. check (loaded.has_value() && loaded->channels.size() == offline.getSong().channels.size()
  28280. && loaded->channels[(std::size_t) first].freeze == offline.getSong().channels[(std::size_t) first].freeze,
  28281. "a frozen project loads frozen, with the same audio files");
  28282. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore,
  28283. "without the frozen state the saved project is byte for byte what it was before the freeze");
  28284. check (! jsonBefore.contains ("\"freeze\""), "a project with nothing frozen has no freeze field");
  28285. }
  28286. // --- out of date: the tempo, a note of the frozen channel; not another channel's notes ---
  28287. {
  28288. offline.editSong ([] (lynx::Song& s) { s.bpm += 4.0; });
  28289. check (offline.freezeOutOfDate (first), "a tempo change marks the freeze out of date");
  28290. ui.selectTabForSnapshot (0);
  28291. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  28292. write ("rack-out-of-date");
  28293. report << "hint out of date: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  28294. offline.editSong ([] (lynx::Song& s) { s.bpm -= 4.0; });
  28295. check (! offline.freezeOutOfDate (first), "the tempo back: up to date again");
  28296. int pattern = -1;
  28297. for (int p = 0; p < (int) before.patterns.size() && pattern < 0; ++p)
  28298. for (const auto& n : before.patterns[(std::size_t) p].notes)
  28299. if (n.channel == first)
  28300. {
  28301. pattern = p;
  28302. break;
  28303. }
  28304. if (pattern >= 0)
  28305. {
  28306. offline.editSong ([pattern, first] (lynx::Song& s) {
  28307. lynx::Note n;
  28308. n.channel = first;
  28309. n.start = 0;
  28310. n.key = 71;
  28311. s.patterns[(std::size_t) pattern].notes.push_back (n);
  28312. s.patterns[(std::size_t) pattern].sortNotes();
  28313. });
  28314. check (offline.freezeOutOfDate (first), "a note edit on the frozen channel marks it out of date");
  28315. bool othersFresh = true;
  28316. for (const auto c : targets)
  28317. othersFresh = othersFresh && (c == first || ! offline.freezeOutOfDate (c));
  28318. check (othersFresh, "the other frozen channels stay up to date");
  28319. // an export of the project in that state: the out-of-date channel renders live (never the old audio),
  28320. // the others keep their frozen audio — the same mix as the edited project with nothing frozen
  28321. {
  28322. std::vector<int> renderedLive;
  28323. const auto stale = renderMix ("stale", nullptr, &renderedLive);
  28324. const auto edited = lynx::freeze::thawed (offline.getSong());
  28325. const auto reference = renderMix ("stale-reference", &edited);
  28326. float stalePeak = 0.0f;
  28327. const auto nullStale = residual (reference, stale, stalePeak);
  28328. const auto nullOld = residual (frozen, stale, stalePeak);
  28329. report << "export with channel " << (first + 1) << " out of date: " << juce::String (nullStale, 1) << " dB vs the edited project live, "
  28330. << juce::String (nullOld, 1) << " dB vs the old frozen mix; channels rendered live: " << (int) renderedLive.size() << "\n";
  28331. check (renderedLive == std::vector<int> { first }, "an export renders the out-of-date frozen channel live, and only that one");
  28332. check (nullStale < -90.0 && nullOld > -60.0, "an export of an out-of-date freeze holds the edited notes, not the old audio");
  28333. }
  28334. offline.editSong ([&before] (lynx::Song& s) { s.patterns = before.patterns; });
  28335. check (! offline.freezeOutOfDate (first), "the notes back: up to date again");
  28336. }
  28337. }
  28338. // --- the audio gone: the instrument plays, never silence ---
  28339. {
  28340. const auto stems = offline.getSong().channels[(std::size_t) first].freeze.stems;
  28341. std::vector<std::pair<juce::File, juce::File>> moved;
  28342. for (const auto& stem : stems)
  28343. {
  28344. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  28345. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  28346. if (file.moveFileTo (away))
  28347. moved.emplace_back (file, away);
  28348. }
  28349. offline.editSong ([] (lynx::Song&) {}, false);
  28350. check (offline.frozenAudioMissing (first), "frozen audio that is not on disk is noticed");
  28351. report << "hint audio missing: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  28352. const auto fallback = renderMix ("missing");
  28353. const auto nullMissing = residual (live, fallback, peak);
  28354. report << "null with the first channel's audio missing vs live: " << juce::String (nullMissing, 1) << " dB\n";
  28355. check (nullMissing < -90.0, "with its audio missing the channel plays its instrument");
  28356. for (const auto& [file, away] : moved)
  28357. away.moveFileTo (file);
  28358. offline.editSong ([] (lynx::Song&) {}, false);
  28359. check (! offline.frozenAudioMissing (first), "the audio back: frozen again");
  28360. // the frozen mix did not null and the first channel is not (alone) why: which one is, each thawed in turn
  28361. if (nullFrozen >= -90.0 && nullMissing >= -90.0)
  28362. for (const auto c : targets)
  28363. {
  28364. if (c == first)
  28365. continue;
  28366. std::vector<std::pair<juce::File, juce::File>> aside;
  28367. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  28368. {
  28369. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  28370. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  28371. if (file.moveFileTo (away))
  28372. aside.emplace_back (file, away);
  28373. }
  28374. offline.editSong ([] (lynx::Song&) {}, false);
  28375. const auto one = renderMix ("thawed");
  28376. report << "null with channel " << (c + 1) << " thawed vs live: " << juce::String (residual (live, one, peak), 1) << " dB\n";
  28377. for (const auto& [file, away] : aside)
  28378. away.moveFileTo (file);
  28379. offline.editSong ([] (lynx::Song&) {}, false);
  28380. }
  28381. }
  28382. // --- unfrozen ---
  28383. std::vector<juce::File> stemPaths;
  28384. for (const auto c : targets)
  28385. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  28386. stemPaths.emplace_back (juce::String::fromUTF8 (stem.path.c_str()));
  28387. for (const auto c : targets)
  28388. lynx::unfreezeChannel (offline, c);
  28389. offline.dispatchPendingMessages();
  28390. check (offline.getSong().channels == before.channels, "Unfreeze gives every channel back exactly as it was (instrument, plugin state, settings)");
  28391. {
  28392. const auto jsonAfter = savedJson (offline.getSong());
  28393. check (jsonAfter == jsonBefore, "the unfrozen project saves byte for byte as before the freeze");
  28394. if (jsonAfter != jsonBefore)
  28395. {
  28396. juce::File (prefix + "-before.json").replaceWithText (jsonBefore);
  28397. juce::File (prefix + "-after.json").replaceWithText (jsonAfter);
  28398. }
  28399. }
  28400. int left = 0;
  28401. for (const auto& f : stemPaths)
  28402. left += f.existsAsFile() ? 1 : 0;
  28403. check (left == 0, "Unfreeze deletes the frozen audio (" + juce::String (left) + " of " + juce::String ((int) stemPaths.size()) + " files left)");
  28404. if (hostedChannel >= 0)
  28405. {
  28406. // the new instance (it starts with another tuning than the first one had) took the saved state
  28407. offline.capturePluginStates();
  28408. check (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr, "Unfreeze loads the hosted plugin again");
  28409. check (offline.getSong().channels[(std::size_t) hostedChannel].plugin.state == hostedState,
  28410. "the hosted plugin's state, read back from the new instance, is the state it had before the freeze");
  28411. }
  28412. const auto unfrozen = renderMix ("unfrozen");
  28413. line ("unfrozen ", unfrozen);
  28414. hostedLine ("unfrozen");
  28415. const auto nullUnfrozen = residual (live, unfrozen, peak);
  28416. report << "null unfrozen vs live: " << juce::String (nullUnfrozen, 1) << " dB\n";
  28417. check (nullUnfrozen < -90.0, "the unfrozen mix nulls against the live mix");
  28418. ui.selectTabForSnapshot (0);
  28419. flush();
  28420. data.deleteRecursively();
  28421. return failures == 0;
  28422. }
  28423. // Round 190ff, the Clip-launch workflow's track commands end to end with the real engine, files and export
  28424. // (LYNX --trackfreezetest prefix). A demo song of three tracks (Lead through a delay and a reverb whose mix is
  28425. // automated, Bass through a delay, Drums on a bare insert; each insert's fader, pan and EQ set) is rendered live; then
  28426. // Freeze Track on every track (the instrument with its volume and pan through its insert's effects), the same render
  28427. // again (must null), the effects and instruments unloaded, the render time (the CPU while frozen), what a save holds;
  28428. // Flatten (Bounce Track in Place on a frozen track) with its undo; Bounce Track in Place of a live track; Bounce to New
  28429. // Track of a track's clips against that track's device output; Consolidate of pattern clips; Unfreeze. Written to
  28430. // prefix-report.txt; shots of the grid, the column menus, the Detail View's frozen devices and the Playlist's clip
  28431. // menu. True = every check passed.
  28432. bool runTrackFreezeTest (const juce::String& prefix)
  28433. {
  28434. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28435. lynx::AudioEngine offline (false);
  28436. lynx::MainComponent ui (offline, false);
  28437. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  28438. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  28439. const auto write = [&prefix, &ui] (const char* name) {
  28440. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  28441. file.deleteFile();
  28442. juce::FileOutputStream out (file);
  28443. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  28444. };
  28445. juce::String report;
  28446. int failures = 0;
  28447. const auto check = [&] (bool ok, const juce::String& what) {
  28448. report << (ok ? "ok " : "FAIL ") << what << "\n";
  28449. failures += ok ? 0 : 1;
  28450. };
  28451. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  28452. const juce::File data (prefix + "-data");
  28453. data.deleteRecursively();
  28454. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "trackfreezetest");
  28455. ui.setVisible (true);
  28456. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  28457. ui.setClipLaunchWorkflow (true);
  28458. offline.editSong ([] (lynx::Song& s) {
  28459. s.channels.clear();
  28460. s.patterns.clear();
  28461. s.playlist.clear();
  28462. s.automations.clear();
  28463. s.bpm = 120.0;
  28464. s.mode = lynx::PlayMode::song;
  28465. const char* names[] = { "Lead", "Bass", "Drums" };
  28466. for (int c = 0; c < 3; ++c)
  28467. {
  28468. lynx::ChannelDef d;
  28469. d.name = names[c];
  28470. d.instrument = c == 2 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  28471. d.synth.release = c == 0 ? 0.6f : 0.2f;
  28472. d.synth.cutoff = c == 0 ? 2400.0f : 900.0f;
  28473. d.volume = c == 0 ? 0.65f : 0.78f;
  28474. d.pan = c == 0 ? 0.25f : 0.0f;
  28475. d.mixerTrack = c + 1;
  28476. s.channels.push_back (d);
  28477. }
  28478. if (s.mixer.size() < 5)
  28479. s.mixer.resize (5);
  28480. s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay), lynx::makeEffectSlot (lynx::EffectKind::reverb) };
  28481. s.mixer[2].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay) };
  28482. s.mixer[3].effects.clear();
  28483. for (int t = 1; t <= 3; ++t)
  28484. {
  28485. s.mixer[(std::size_t) t].name = names[t - 1];
  28486. s.mixer[(std::size_t) t].volume = 0.7f;
  28487. s.mixer[(std::size_t) t].pan = t == 1 ? -0.3f : 0.1f;
  28488. s.mixer[(std::size_t) t].eq.gainDb[1] = 3.0f;
  28489. }
  28490. for (int p = 0; p < 3; ++p)
  28491. {
  28492. auto& pattern = s.patterns.emplace_back();
  28493. pattern.name = names[p];
  28494. pattern.lengthTicks = 4 * lynx::ppq * 2;
  28495. for (int step = 0; step < 8; ++step)
  28496. {
  28497. lynx::Note n;
  28498. n.channel = p;
  28499. n.start = (std::int64_t) step * lynx::ppq;
  28500. n.length = p == 2 ? lynx::ppq / 4 : lynx::ppq / 2;
  28501. n.key = p == 2 ? 36 : (p == 0 ? 60 : 36) + (step * 5) % 12;
  28502. pattern.notes.push_back (n);
  28503. }
  28504. }
  28505. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  28506. for (int t = 0; t < 3; ++t)
  28507. {
  28508. s.playlistTracks[(std::size_t) t].name = names[t];
  28509. for (int k = 0; k < 3; ++k)
  28510. {
  28511. if (t == 0 && k == 1)
  28512. continue; // (a gap in the Lead: its tail rings into it)
  28513. lynx::Clip clip;
  28514. clip.pattern = t;
  28515. clip.track = t;
  28516. clip.start = (std::int64_t) k * 8 * lynx::ppq;
  28517. clip.length = 8 * lynx::ppq;
  28518. s.playlist.push_back (clip);
  28519. }
  28520. }
  28521. // the Lead's reverb mix rises over the song (automation the freeze takes into its audio)
  28522. lynx::Automation a;
  28523. a.name = "Lead reverb mix";
  28524. a.target = { lynx::AutomationTargetKind::effectMix, 1, 1, 0 };
  28525. a.points = { { 0, 0.2f }, { 24 * lynx::ppq, 0.9f } };
  28526. s.automations.push_back (a);
  28527. lynx::Clip lane;
  28528. lane.kind = lynx::ClipKind::automation;
  28529. lane.automation = 0;
  28530. lane.track = 3;
  28531. lane.length = 24 * lynx::ppq;
  28532. s.playlist.push_back (lane);
  28533. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& x, const lynx::Clip& y) { return x.start < y.start; });
  28534. });
  28535. offline.dispatchPendingMessages();
  28536. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  28537. struct Mix
  28538. {
  28539. juce::AudioBuffer<float> audio;
  28540. double renderSeconds = 0.0, audioSeconds = 0.0;
  28541. };
  28542. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr) {
  28543. Mix m;
  28544. offline.dispatchPendingMessages();
  28545. offline.freeRetiredRacks();
  28546. const juce::File file (prefix + "-" + name + ".wav");
  28547. lynx::ExportSettings settings;
  28548. settings.format = lynx::ExportSettings::Format::wav32Float;
  28549. settings.sampleRate = offline.getTransport().sampleRate.load();
  28550. settings.tailSeconds = 2.0;
  28551. juce::String error;
  28552. auto options = settings.toOptions();
  28553. options.hqAllPlugins = false;
  28554. options.disableMaxPolyphony = false;
  28555. {
  28556. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  28557. const auto started = juce::Time::getMillisecondCounterHiRes();
  28558. const auto ok = job.run ([] (double) { return true; }, error);
  28559. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  28560. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  28561. }
  28562. juce::WavAudioFormat wav;
  28563. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  28564. {
  28565. m.audio.setSize (2, (int) reader->lengthInSamples);
  28566. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  28567. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  28568. }
  28569. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TRACKFREEZE_KEEP", {}).isEmpty()) // (kept: to look at a residual)
  28570. file.deleteFile();
  28571. return m;
  28572. };
  28573. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  28574. float worst = 0.0f;
  28575. peak = 0.0f;
  28576. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  28577. for (int ch = 0; ch < 2; ++ch)
  28578. for (int i = 0; i < n; ++i)
  28579. {
  28580. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  28581. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  28582. }
  28583. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  28584. };
  28585. const auto nullLine = [&] (const char* what, const Mix& a, const Mix& b, double limit) {
  28586. float peak = 0.0f;
  28587. const auto r = residual (a, b, peak);
  28588. report << what << ": " << juce::String (r, 1) << " dB (peak " << juce::String (peak, 4) << ", " << a.audio.getNumSamples() << " / "
  28589. << b.audio.getNumSamples() << " samples)\n";
  28590. check (peak > 0.001f && r < limit && a.audio.getNumSamples() == b.audio.getNumSamples(), juce::String (what) + " below " + juce::String (limit, 0) + " dB");
  28591. return r;
  28592. };
  28593. const auto savedJson = [] (lynx::Song song) {
  28594. song.info.workSeconds = 0.0;
  28595. return lynx::ProjectFile::toJson (song, false);
  28596. };
  28597. // --- live ---
  28598. offline.capturePluginStates();
  28599. offline.editSong ([] (lynx::Song&) {}, false);
  28600. const auto before = offline.getSong();
  28601. const auto jsonBefore = savedJson (before);
  28602. auto* grid = ui.getClipGridForSnapshot();
  28603. check (grid != nullptr, "the Clip-launch workflow's grid is there");
  28604. if (grid == nullptr)
  28605. {
  28606. flush();
  28607. return false;
  28608. }
  28609. ui.setClipGridView (lynx::PlaylistArea::GridView::beside);
  28610. write ("live");
  28611. saveMenus (juce::StringArray { "Track title (live)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-live.png");
  28612. int leadClip = -1;
  28613. for (int i = 0; i < (int) before.playlist.size() && leadClip < 0; ++i)
  28614. if (before.playlist[(std::size_t) i].track == 0 && before.playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  28615. leadClip = i;
  28616. ui.getPlaylistForSnapshot().selectForSnapshot ({ leadClip });
  28617. saveMenus (juce::StringArray { "Playlist clip (Clip-launch workflow)" }, std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().getClipMenuForSnapshot (leadClip) },
  28618. prefix + "-menu-clip.png");
  28619. const auto live = renderMix ("live");
  28620. report << "live: render " << juce::String (live.renderSeconds, 2) << " s for " << juce::String (live.audioSeconds, 2) << " s of audio\n";
  28621. // --- Freeze Track on every track ---
  28622. std::vector<int> channels;
  28623. for (int t = 0; t < 3; ++t)
  28624. {
  28625. const auto c = lynx::detailchain::forTrack (before, t).channel;
  28626. check (c == t, "track " + juce::String (t + 1) + " shows channel " + juce::String (t + 1));
  28627. const auto* why = lynx::freeze::whyNotTrack (before, c);
  28628. check (why == nullptr, "track " + juce::String (t + 1) + " can be frozen" + (why != nullptr ? juce::String (": ") + why : juce::String()));
  28629. const auto error = lynx::freezeTrackNow (offline, c);
  28630. check (error.isEmpty(), "Freeze Track " + juce::String (t + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  28631. channels.push_back (c);
  28632. }
  28633. offline.dispatchPendingMessages();
  28634. offline.freeRetiredRacks();
  28635. int loadedEffects = 0;
  28636. for (int t = 1; t <= 3; ++t)
  28637. for (int slot = 0; slot < (int) offline.getSong().mixer[(std::size_t) t].effects.size(); ++slot)
  28638. loadedEffects += offline.getEffect (t, slot) != nullptr ? 1 : 0;
  28639. check (loadedEffects == 0, "no effect of a frozen track is loaded (" + juce::String (loadedEffects) + " left)");
  28640. bool fresh = true;
  28641. for (const auto c : channels)
  28642. {
  28643. const auto& f = offline.getSong().channels[(std::size_t) c].freeze;
  28644. fresh = fresh && f.on() && f.insert == c + 1 && lynx::freeze::trackFreezeHolds (offline.getSong(), c) && ! offline.freezeOutOfDate (c)
  28645. && ! offline.frozenAudioMissing (c);
  28646. }
  28647. check (fresh, "every track is frozen with its insert, its audio on disk and up to date");
  28648. check (offline.getSong().mixer == before.mixer, "the project keeps every effect as it was (Unfreeze brings them back)");
  28649. const auto frozenSong = offline.getSong();
  28650. const auto frozen = renderMix ("frozen");
  28651. report << "frozen: render " << juce::String (frozen.renderSeconds, 2) << " s (" << juce::String (100.0 * frozen.renderSeconds / juce::jmax (0.001, live.renderSeconds), 0)
  28652. << " % of the live render's time)\n";
  28653. nullLine ("frozen vs live", live, frozen, -90.0);
  28654. write ("frozen");
  28655. saveMenus (juce::StringArray { "Track title (frozen)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-frozen.png");
  28656. if (auto* detail = ui.getDetailViewForSnapshot())
  28657. {
  28658. detail->showSelection (0, 0);
  28659. detail->setPage (lynx::DetailView::Page::devices);
  28660. write ("detail-frozen");
  28661. }
  28662. // the insert's fader is live: moved, the frozen and the live song change alike
  28663. {
  28664. auto liveLouder = before, frozenLouder = frozenSong;
  28665. liveLouder.mixer[1].volume = frozenLouder.mixer[1].volume = 0.8f;
  28666. nullLine ("frozen vs live, the Lead's fader moved afterwards", renderMix ("live-louder", &liveLouder), renderMix ("frozen-louder", &frozenLouder), -90.0);
  28667. }
  28668. // --- what a save holds ---
  28669. {
  28670. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  28671. juce::String error;
  28672. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  28673. check (json.contains ("\"trackFreeze\"") && ! json.contains ("\"freeze\""), "a track freeze is saved under its own key (older versions play it live)");
  28674. check (loaded.has_value() && loaded->channels.size() == frozenSong.channels.size() && loaded->channels[0].freeze == frozenSong.channels[0].freeze,
  28675. "a track-frozen project loads frozen, with its insert and audio files");
  28676. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore, "without the frozen state the project saves as before the freeze");
  28677. }
  28678. // --- an edit of a frozen device's insert routing: the freeze stops holding, the track plays live ---
  28679. {
  28680. offline.editSong ([] (lynx::Song& s) { s.channels[1].mixerTrack = 1; }); // (the Bass into the Lead's insert)
  28681. check (! lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && offline.freezeOutOfDate (0), "another channel routed into a frozen insert: out of date, plays live");
  28682. offline.undo();
  28683. offline.dispatchPendingMessages();
  28684. check (lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && ! offline.freezeOutOfDate (0), "undo: frozen again");
  28685. }
  28686. // --- Flatten: Bounce Track in Place on the frozen Lead, and its undo ---
  28687. {
  28688. const auto error = lynx::flattenChannelNow (offline, 0);
  28689. check (error.isEmpty(), "Bounce Track in Place of the frozen Lead (Flatten)" + (error.isEmpty() ? juce::String() : ": " + error));
  28690. const auto& song = offline.getSong();
  28691. check (song.channels[0].instrument == lynx::InstrumentKind::audioClip && song.mixer[1].effects.empty() && song.mixer[1].volume == before.mixer[1].volume
  28692. && song.channels[0].name == "Lead (Bounce)",
  28693. "the Lead is audio now (\"Lead (Bounce)\"), its insert's effects removed, its fader kept");
  28694. int audioClips = 0;
  28695. for (const auto& c : song.playlist)
  28696. audioClips += c.kind == lynx::ClipKind::audio && c.channel == 0;
  28697. report << "flattened Lead: " << audioClips << " audio clips\n";
  28698. write ("flattened");
  28699. // over the song (the flattened clips end where the arrangement ends, as a frozen track plays; an export's
  28700. // ring-out after the song's end is not in them)
  28701. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  28702. auto flatMix = renderMix ("flattened");
  28703. auto reference = live;
  28704. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  28705. flatMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  28706. nullLine ("flattened (Lead) + frozen (others) vs live, over the song", reference, flatMix, -90.0);
  28707. offline.undo();
  28708. offline.dispatchPendingMessages();
  28709. check (savedJson (offline.getSong()) == savedJson (frozenSong), "undo of the Flatten: the frozen project exactly as before");
  28710. }
  28711. // --- Unfreeze every track ---
  28712. for (const auto c : channels)
  28713. lynx::unfreezeChannel (offline, c);
  28714. offline.dispatchPendingMessages();
  28715. check (savedJson (offline.getSong()) == jsonBefore, "Unfreeze: the project saves byte for byte as before the freeze");
  28716. nullLine ("unfrozen vs live", live, renderMix ("unfrozen"), -90.0);
  28717. // --- Bounce Track in Place of a live track (render and flatten in one step, one undo) ---
  28718. {
  28719. const auto error = lynx::freezeTrackNow (offline, 1, true);
  28720. check (error.isEmpty(), "Bounce Track in Place of the live Bass" + (error.isEmpty() ? juce::String() : ": " + error));
  28721. check (offline.getSong().channels[1].instrument == lynx::InstrumentKind::audioClip && ! offline.getSong().channels[1].freeze.on(),
  28722. "the Bass is audio, not frozen");
  28723. auto bouncedMix = renderMix ("bounced");
  28724. auto reference = live;
  28725. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  28726. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  28727. bouncedMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  28728. nullLine ("Bass bounced in place vs live, over the song", reference, bouncedMix, -90.0);
  28729. offline.undo();
  28730. offline.dispatchPendingMessages();
  28731. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce Track in Place: the project as before");
  28732. }
  28733. // --- Bounce to New Track: the Lead's clips onto a new track (the clips muted, the new track with the Lead's mixer) ---
  28734. {
  28735. std::vector<int> leadClips;
  28736. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  28737. if (offline.getSong().playlist[(std::size_t) i].track == 0 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  28738. leadClips.push_back (i);
  28739. const auto channelsBefore = offline.getSong().channels.size();
  28740. const auto error = lynx::bounceToNewTrack (offline, leadClips, true);
  28741. check (error.isEmpty(), "Bounce to New Track of the Lead's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  28742. const auto& song = offline.getSong();
  28743. check (song.channels.size() == channelsBefore + 1 && song.channels.back().instrument == lynx::InstrumentKind::audioClip
  28744. && song.channels.back().mixerTrack > 3 && song.mixer[(std::size_t) song.channels.back().mixerTrack].volume == before.mixer[1].volume,
  28745. "a new audio channel holds the bounce, on an insert with the Lead's mixer");
  28746. // the song's span (the bounce stops at the last clip's end, the live render rings on after it)
  28747. auto bounced = renderMix ("bounced-new-track");
  28748. auto reference = live;
  28749. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  28750. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  28751. bounced.audio.setSize (2, reference.audio.getNumSamples(), true);
  28752. nullLine ("Bounce to New Track (Lead's clips muted) vs live, over the song", reference, bounced, -90.0);
  28753. write ("bounced-new-track");
  28754. offline.undo();
  28755. offline.dispatchPendingMessages();
  28756. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce to New Track: the project as before");
  28757. }
  28758. // --- Consolidate: the Bass's three pattern clips become one ---
  28759. {
  28760. std::vector<int> bassClips;
  28761. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  28762. if (offline.getSong().playlist[(std::size_t) i].track == 1 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  28763. bassClips.push_back (i);
  28764. const auto error = lynx::consolidateClips (offline, bassClips, true);
  28765. check (error.isEmpty(), "Consolidate of the Bass's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  28766. int left = 0;
  28767. for (const auto& c : offline.getSong().playlist)
  28768. left += c.track == 1 && c.kind == lynx::ClipKind::pattern;
  28769. check (left == 1, "one clip on the Bass track (" + juce::String (left) + ")");
  28770. nullLine ("consolidated vs live", live, renderMix ("consolidated"), -90.0);
  28771. offline.undo();
  28772. offline.dispatchPendingMessages();
  28773. check (savedJson (offline.getSong()) == jsonBefore, "undo of Consolidate: the project as before");
  28774. }
  28775. report << "frozen audio folder: " << offline.getFreezeFolder().getFullPathName() << "\n";
  28776. flush();
  28777. data.deleteRecursively();
  28778. (void) megabytes;
  28779. return failures == 0;
  28780. }
  28781. // --paintbench (round 190ge): the paint cost of every main view, off screen. Each view is shown maximised in a
  28782. // LYNX_SNAPSHOT_SIZE window (default 1920x1080) and drawn whole into a picture `frames` times (after a repaint of
  28783. // all of it, so no cached picture is reused: the cost of a frame after an edit), then `frames` times without the
  28784. // repaint (what a view's own caches leave of a frame). The report gives the median and the 90th percentile of
  28785. // the message thread's CPU per frame.
  28786. void runPaintBench (const juce::File& project, const juce::File& report)
  28787. {
  28788. // LYNX_PROFILE_MAIN=<file> (round 190gr): the message thread sampled while it paints (Windows; one view at a time
  28789. // with LYNX_PAINTBENCH_VIEWS)
  28790. const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {});
  28791. if (profile.isNotEmpty())
  28792. lynx::crashguard::startMainProfiler (profile.toStdString(), 1000, 2);
  28793. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28794. lynx::AudioEngine offline (false);
  28795. lynx::MainComponent ui (offline, false);
  28796. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  28797. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  28798. juce::String text;
  28799. text << "project: " << project.getFullPathName() << "\nLYNX " << getApplicationVersion() << ", " << juce::SystemStats::getCpuModel()
  28800. << ", window " << ui.getWidth() << "x" << ui.getHeight() << "\n";
  28801. // LYNX_PAINTBENCH_MIXER_EXTRAS=0|1 (rollup 0.1.32 step 2): round 190qh's peak values and correlation bars off / on
  28802. // (on by default since 0.1.32), for an A/B of their paint cost
  28803. if (const auto extras = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_MIXER_EXTRAS", {}); extras.isNotEmpty())
  28804. {
  28805. if (lynx::mixeroptions::setShowPeakValues && lynx::mixeroptions::setShowCorrelation)
  28806. {
  28807. lynx::mixeroptions::setShowPeakValues (extras.getIntValue() != 0);
  28808. lynx::mixeroptions::setShowCorrelation (extras.getIntValue() != 0);
  28809. }
  28810. text << "mixer peak values / correlation " << (extras.getIntValue() != 0 ? "on" : "off") << " (LYNX_PAINTBENCH_MIXER_EXTRAS)\n";
  28811. }
  28812. if (project.existsAsFile())
  28813. {
  28814. // (round perfgate190id) the time to open it headless, and the memory after
  28815. const auto open0 = juce::Time::getMillisecondCounterHiRes();
  28816. const auto cpu0 = lynx::threadCpuSeconds();
  28817. ui.openFile (project);
  28818. offline.dispatchPendingMessages();
  28819. text << "open: " << juce::String (juce::Time::getMillisecondCounterHiRes() - open0, 1) << " ms wall, "
  28820. << juce::String (1000.0 * (lynx::threadCpuSeconds() - cpu0), 1) << " ms message thread CPU, working set "
  28821. << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << " MB\n";
  28822. }
  28823. // LYNX_PAINTBENCH_ROW=<px> (round 190oo): the Playlist's row height after the open, so a build whose .flp import
  28824. // reads FL's own row height (PAT-6: Thief at 26 px) can be compared with one at 48 px for the same drawing
  28825. if (const auto row = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_ROW", {}).getIntValue(); row > 0)
  28826. {
  28827. offline.editSong ([row] (lynx::Song& s) { s.playlistRowHeight = row; }, false);
  28828. offline.dispatchPendingMessages();
  28829. text << "playlist rows forced to " << row << " px (LYNX_PAINTBENCH_ROW)\n";
  28830. }
  28831. // LYNX_PAINTBENCH_KEYS=0|1|2 (round 190oo): the Piano roll's keyboard style (flat, lined piano keys, FL's keys)
  28832. if (const auto keys = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_KEYS", {}); keys.isNotEmpty())
  28833. {
  28834. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::styleFromInt (keys.getIntValue());
  28835. text << "keyboard style " << keys.getIntValue() << " (LYNX_PAINTBENCH_KEYS)\n";
  28836. }
  28837. const auto& song = offline.getSong();
  28838. text << "channels " << (int) song.channels.size() << ", patterns " << (int) song.patterns.size() << ", playlist clips " << (int) song.playlist.size()
  28839. << ", inserts " << (int) song.mixer.size() << "\n";
  28840. // the playhead a third into the song (song mode) so the views draw it as when playing
  28841. offline.getTransport().songMode = true;
  28842. offline.getTransport().positionTicks.store ((double) song.songLength() / 3.0);
  28843. const auto frames = juce::jlimit (3, 500, juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_FRAMES", "40").getIntValue());
  28844. juce::Image image (juce::Image::ARGB, ui.getWidth(), ui.getHeight(), true);
  28845. {
  28846. // (round 190gr) which renderer draws the frames: the software one (Linux), Direct2D (Windows), Core Graphics
  28847. juce::Graphics g (image);
  28848. auto& context = g.getInternalContext();
  28849. text << "renderer: " << (dynamic_cast<juce::LowLevelGraphicsSoftwareRenderer*> (&context) != nullptr ? "software" : typeid (context).name())
  28850. << ", paint caches " << (lynx::ui::paintCache() ? "on" : "off (LYNX_PAINT_CACHE=0)") << ", paint savings "
  28851. << (lynx::ui::paintSavings() ? "on" : "off (LYNX_PAINT_SAVINGS=0)") << "\n";
  28852. }
  28853. // LYNX_PAINTBENCH_VIEWS="mixer,channel rack" (round 190gr): only those views
  28854. const auto onlyViews = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_VIEWS", {}), ",", "");
  28855. const auto wanted = [&onlyViews] (const juce::String& name) { return onlyViews.isEmpty() || onlyViews.contains (name); };
  28856. // the picture's pixels as one number: the same before and after a change = the same drawing
  28857. auto pixelHash = [&image] {
  28858. const juce::Image::BitmapData data (image, juce::Image::BitmapData::readOnly);
  28859. std::uint64_t h = 1469598103934665603ull;
  28860. for (int y = 0; y < data.height; ++y)
  28861. for (int x = 0; x < data.width; ++x)
  28862. h = (h ^ data.getPixelColour (x, y).getARGB()) * 1099511628211ull;
  28863. return juce::String::toHexString ((juce::int64) h);
  28864. };
  28865. // mode 0: whole frames after a repaint of everything; 1: whole frames, the views' own caches kept; 2: a 14-pixel
  28866. // column of the whole height at 40 places (what a moving playhead repaints each frame)
  28867. // (rollup step 9: the instructions the message thread retires per frame, Linux, where the CPU counter can be read:
  28868. // the performance gate's stable paint measure, scripts/perf_gate.py "paint_instr")
  28869. const lynx::platform::ThreadInstructions instructions;
  28870. auto measure = [&] (const juce::String& name, int mode) {
  28871. offline.dispatchPendingMessages();
  28872. std::vector<double> ms, wall;
  28873. std::vector<long long> instr;
  28874. juce::String hash;
  28875. for (int f = -3; f < frames; ++f) // (3 frames to warm the caches up)
  28876. {
  28877. if (mode == 0)
  28878. ui.repaint();
  28879. const auto column = juce::Rectangle<int> ((juce::jmax (0, f) * 97) % juce::jmax (1, ui.getWidth() - 14), 0, 14, ui.getHeight());
  28880. const auto t0 = lynx::threadCpuSeconds();
  28881. const auto w0 = juce::Time::getMillisecondCounterHiRes();
  28882. const auto i0 = instructions.now();
  28883. {
  28884. juce::Graphics g (image);
  28885. if (mode == 2)
  28886. g.reduceClipRegion (column);
  28887. ui.paintEntireComponent (g, true);
  28888. }
  28889. if (const auto i1 = instructions.now(); f >= 0 && i0 >= 0 && i1 >= i0)
  28890. instr.push_back (i1 - i0);
  28891. if (f >= 0)
  28892. {
  28893. ms.push_back (1000.0 * (lynx::threadCpuSeconds() - t0));
  28894. wall.push_back (juce::Time::getMillisecondCounterHiRes() - w0); // (round 190gr: Direct2D's work ends with the frame)
  28895. }
  28896. if (f == 0 && mode == 0)
  28897. {
  28898. hash = pixelHash();
  28899. // LYNX_PAINTBENCH_PNG=<prefix> (round 190gr): the whole frame as <prefix>-<view>.png, to compare pixels
  28900. if (const auto png = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_PNG", {}); png.isNotEmpty())
  28901. {
  28902. const juce::File file (png + "-" + name.replaceCharacter (' ', '-') + ".png");
  28903. file.deleteFile();
  28904. juce::FileOutputStream out (file);
  28905. juce::PNGImageFormat().writeImageToStream (image, out);
  28906. }
  28907. }
  28908. }
  28909. std::sort (ms.begin(), ms.end());
  28910. std::sort (wall.begin(), wall.end());
  28911. text << name << (mode == 0 ? ", whole frame" : mode == 1 ? ", cached frame" : ", playhead column") << ": median "
  28912. << juce::String (ms[ms.size() / 2], 3) << " ms, p90 " << juce::String (ms[(ms.size() * 9) / 10], 3) << " ms, wall median "
  28913. << juce::String (wall[wall.size() / 2], 3) << " ms"
  28914. << (hash.isNotEmpty() ? ", pixels " + hash : juce::String());
  28915. if (instr.size() == ms.size())
  28916. {
  28917. std::sort (instr.begin(), instr.end());
  28918. text << ", instructions median " << juce::String ((juce::int64) instr[instr.size() / 2]);
  28919. }
  28920. text << "\n";
  28921. report.replaceWithText (text);
  28922. };
  28923. auto measureAll = [&] (const juce::String& name) {
  28924. if (! wanted (name))
  28925. return;
  28926. measure (name, 0);
  28927. measure (name, 1);
  28928. measure (name, 2);
  28929. // the columns' pixels too (painted over the whole frame: culling must not change a pixel)
  28930. ui.repaint();
  28931. {
  28932. juce::Graphics g (image);
  28933. ui.paintEntireComponent (g, true);
  28934. for (int x = 3; x < ui.getWidth() - 14; x += 211)
  28935. {
  28936. juce::Graphics::ScopedSaveState state (g);
  28937. g.reduceClipRegion (x, 0, 14, ui.getHeight());
  28938. ui.paintEntireComponent (g, true);
  28939. }
  28940. }
  28941. text << name << ", columns over the whole frame: pixels " << pixelHash() << "\n";
  28942. };
  28943. // LYNX_KEEP_LABELS=0|1 (round 190qe): Playlist ▸ View ▸ "Keep labels on screen" for the whole run (A/B of the labels' cost)
  28944. if (const auto keep = juce::SystemStats::getEnvironmentVariable ("LYNX_KEEP_LABELS", {}); keep.isNotEmpty())
  28945. {
  28946. lynx::keeplabels::on = keep != "0";
  28947. text << "keep labels on screen " << (lynx::keeplabels::on ? "on" : "off") << " (LYNX_KEEP_LABELS)\n";
  28948. }
  28949. const char* views[] { "channel rack", "piano roll", "playlist", "mixer" };
  28950. for (int v = 0; v < 4; ++v)
  28951. {
  28952. ui.selectTabForSnapshot (v);
  28953. measureAll (views[v]);
  28954. }
  28955. // LYNX_PAINTBENCH_BAR=<n> (round 190qe): the Playlist once more from bar n (the same zoom), so the clips whose start is
  28956. // scrolled off draw their labels at the left edge ("Keep labels on screen")
  28957. if (const auto fromBar = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_BAR", {}).getIntValue(); fromBar > 0)
  28958. {
  28959. ui.selectTabForSnapshot (2);
  28960. auto& pl = ui.getPlaylistForSnapshot();
  28961. const auto before = pl.viewForSnapshot();
  28962. pl.setViewForSnapshot (before.pixelsPerTick * (double) offline.getSong().barTicks(), fromBar, 0);
  28963. pl.setScrollYForSnapshot (before.scrollY);
  28964. measureAll ("playlist from bar " + juce::String (fromBar));
  28965. pl.restoreViewForSnapshot (before);
  28966. }
  28967. ui.showDesktopForSnapshot (false);
  28968. measureAll ("desktop");
  28969. ui.selectTabForSnapshot (2);
  28970. ui.setClipLaunchWorkflow (true);
  28971. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  28972. measureAll ("clip grid");
  28973. ui.setClipGridView (lynx::PlaylistArea::GridView::song); // (round 190jn: the Clip-launch layout's Arrangement)
  28974. measureAll ("clip arrangement");
  28975. // (and with View > Tall Arrangement lanes: LYNX's 38 px rows in Live's look, the classic look's row height)
  28976. lynx::playlistTallLiveLanes() = true;
  28977. ui.getPlaylistForSnapshot().liveLanesChanged();
  28978. measureAll ("clip arrangement, tall lanes");
  28979. lynx::playlistTallLiveLanes() = false;
  28980. ui.getPlaylistForSnapshot().liveLanesChanged();
  28981. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  28982. ui.setClipLaunchWorkflow (false);
  28983. // LYNX_PAINTBENCH_SIMPLE=1 (round 190jc): the same project's Playlist in the Simple layout too
  28984. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_SIMPLE", {}) == "1")
  28985. {
  28986. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  28987. offline.dispatchPendingMessages();
  28988. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  28989. simple->hideChooser();
  28990. ui.selectTabForSnapshot (2);
  28991. measureAll ("simple playlist");
  28992. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  28993. }
  28994. text << "result=OK\n";
  28995. report.replaceWithText (text);
  28996. if (profile.isNotEmpty())
  28997. lynx::crashguard::stopMainProfiler();
  28998. }
  28999. // Round 190iv: the toolbar per layout style (see --toolbarshot190iv above)
  29000. void runToolbarShot190iv (const juce::String& prefix, const juce::String& projectPath)
  29001. {
  29002. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29003. lynx::ui::motion::enabled() = false; // (hover states drawn at once, no fade)
  29004. lynx::AudioEngine offline (false);
  29005. lynx::MainComponent ui (offline, false);
  29006. ui.setSize (1920, 1080);
  29007. juce::String report;
  29008. const auto write = [&prefix] (const juce::Image& image, const juce::String& name) {
  29009. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29010. file.deleteFile();
  29011. juce::FileOutputStream out (file);
  29012. juce::PNGImageFormat().writeImageToStream (image, out);
  29013. };
  29014. const auto bar = [&ui] { return ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 90)); };
  29015. const auto describe = [&ui, &report] (const juce::String& title) {
  29016. report << "== " << title << " (" << ui.getWidth() << "x" << ui.getHeight() << ")\n";
  29017. for (const auto* name : { "play", "stop", "record", "metronome", "tap", "tempo", "signature", "quantisation", "key", "link", "browser",
  29018. "backToArrangement", "position", "overdub", "capture", "sessionRecord", "punch", "draw", "computerKeys",
  29019. "keyMap", "midiMap", "cpu", "more", "sessionView", "arrangementView", "status", "finish" })
  29020. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible() && c->getParentComponent() == &ui)
  29021. report << " " << name << " " << c->getBounds().toString() << "\n";
  29022. };
  29023. const std::pair<int, int> sizes[] { { 1920, 1080 }, { 1366, 768 }, { 1280, 800 } };
  29024. // a song with a few tracks for the Simple layout (voice, instrument, drums), as --simpleshot makes them
  29025. offline.editSong ([] (lynx::Song& s) {
  29026. namespace st = lynx::simpletracks;
  29027. st::Request q;
  29028. q.kind = st::Kind::voice;
  29029. q.name = "Lead vocal";
  29030. st::addTrack (s, q);
  29031. q = {};
  29032. q.kind = st::Kind::instrument;
  29033. q.name = "Keys";
  29034. lynx::ChannelDef keys;
  29035. keys.instrument = lynx::InstrumentKind::synth;
  29036. q.channel = keys;
  29037. st::addTrack (s, q);
  29038. q = {};
  29039. q.kind = st::Kind::drums;
  29040. q.name = "Drums";
  29041. st::addTrack (s, q);
  29042. s.bpm = 120.0;
  29043. }, false);
  29044. offline.dispatchPendingMessages();
  29045. // 1. Pattern: FL's toolbar (it must stay as it was: compare with the base build's)
  29046. ui.selectTabForSnapshot (2);
  29047. for (const auto& [w, h] : sizes)
  29048. {
  29049. ui.setSize (w, h);
  29050. write (lynx::shot::snapshot (ui, bar()), "pattern-bar-" + juce::String (w));
  29051. }
  29052. ui.setSize (1920, 1080);
  29053. // 2. Simple
  29054. ui.setLayoutStyle (lynx::layoutstyle::Style::simple, false);
  29055. offline.dispatchPendingMessages();
  29056. for (const auto& [w, h] : sizes)
  29057. {
  29058. ui.setSize (w, h);
  29059. offline.dispatchPendingMessages();
  29060. write (lynx::shot::snapshot (ui), "simple-" + juce::String (w));
  29061. write (lynx::shot::snapshot (ui, bar()), "simple-bar-" + juce::String (w));
  29062. describe ("simple " + juce::String (w));
  29063. }
  29064. ui.setSize (1920, 1080);
  29065. auto* play = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("play"));
  29066. auto* stop = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("stop"));
  29067. auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record"));
  29068. const auto capsuleArea = [&] {
  29069. juce::Rectangle<int> r;
  29070. for (const auto* name : { "play", "stop", "record", "position", "metronome", "tempo", "signature", "key" })
  29071. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible())
  29072. r = r.isEmpty() ? c->getBounds() : r.getUnion (c->getBounds());
  29073. return r.expanded (8, 10);
  29074. };
  29075. if (play != nullptr && stop != nullptr && rec != nullptr)
  29076. {
  29077. // (round 190oo, CS-35: the main window's own transport states, as its timer sets them while the engine plays —
  29078. // the offline engine does not play, so the route drives them: Play shows BandLab's Pause, Back-to-start Stop)
  29079. ui.transportForSnapshot (false, false);
  29080. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-idle");
  29081. play->setState (juce::Button::buttonOver);
  29082. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-hover");
  29083. play->setState (juce::Button::buttonDown);
  29084. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-pressed");
  29085. play->setState (juce::Button::buttonNormal);
  29086. ui.transportForSnapshot (true, true);
  29087. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-playing");
  29088. rec->setToggleState (true, juce::dontSendNotification);
  29089. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-recording");
  29090. rec->setToggleState (false, juce::dontSendNotification);
  29091. ui.transportForSnapshot (false, false);
  29092. }
  29093. if (auto* status = ui.toolbarPartForSnapshot ("status"))
  29094. {
  29095. using S = lynx::toolbarlayout::SaveState;
  29096. int n = 0;
  29097. for (const auto state : { S::fresh, S::unsaved, S::backedUp, S::saved })
  29098. {
  29099. ui.setSaveStatusForSnapshot (state);
  29100. auto r = status->getBounds();
  29101. if (auto* finish = ui.toolbarPartForSnapshot ("finish"); finish != nullptr && finish->isVisible())
  29102. r = r.getUnion (finish->getBounds());
  29103. write (lynx::shot::snapshot (ui, r.expanded (8, 10)), "simple-status-" + juce::String (n++));
  29104. }
  29105. }
  29106. {
  29107. auto more = ui.makeToolbarMoreMenuForSnapshot();
  29108. saveMenus (juce::StringArray { "More" }, std::vector<juce::PopupMenu> { more }, prefix + "-simple-more-menu.png");
  29109. }
  29110. // 3. Clip-launch: Live's control bar (the Live demo set when given, else an empty grid)
  29111. if (projectPath.isNotEmpty())
  29112. {
  29113. ui.openFile (juce::File (projectPath));
  29114. offline.dispatchPendingMessages();
  29115. }
  29116. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch, false);
  29117. offline.dispatchPendingMessages();
  29118. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  29119. for (const auto& [w, h] : sizes)
  29120. {
  29121. ui.setSize (w, h);
  29122. offline.dispatchPendingMessages();
  29123. write (lynx::shot::snapshot (ui), "live-" + juce::String (w));
  29124. write (lynx::shot::snapshot (ui, bar()), "live-bar-" + juce::String (w));
  29125. describe ("clip-launch " + juce::String (w));
  29126. }
  29127. ui.setSize (1920, 1080);
  29128. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  29129. write (lynx::shot::snapshot (ui), "live-arrangement-1920");
  29130. ui.setClipGridView (lynx::PlaylistArea::GridView::beside);
  29131. write (lynx::shot::snapshot (ui), "live-both-1920");
  29132. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  29133. // every control-bar button idle / hover / pressed / lit, all at once per picture
  29134. std::vector<juce::Button*> buttons;
  29135. for (const auto* name : { "play", "stop", "record", "metronome", "tap", "browser", "backToArrangement", "overdub", "capture", "sessionRecord", "punch",
  29136. "draw", "computerKeys", "keyMap", "midiMap", "more", "sessionView", "arrangementView" })
  29137. if (auto* b = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot (name)); b != nullptr && b->isVisible())
  29138. buttons.push_back (b);
  29139. std::vector<bool> lit;
  29140. for (auto* b : buttons)
  29141. lit.push_back (b->getToggleState());
  29142. const auto controlBar = ui.getLocalBounds().withTrimmedTop (lynx::toolbarlayout::livebar::menuRow).withHeight (lynx::toolbarlayout::livebar::band);
  29143. write (lynx::shot::snapshot (ui, controlBar), "live-states-idle");
  29144. for (const auto& [state, name] : { std::pair<juce::Button::ButtonState, const char*> { juce::Button::buttonOver, "hover" }, { juce::Button::buttonDown, "pressed" } })
  29145. {
  29146. for (auto* b : buttons)
  29147. b->setState (state);
  29148. write (lynx::shot::snapshot (ui, controlBar), juce::String ("live-states-") + name);
  29149. }
  29150. for (auto* b : buttons)
  29151. {
  29152. b->setState (juce::Button::buttonNormal);
  29153. b->setToggleState (true, juce::dontSendNotification);
  29154. }
  29155. write (lynx::shot::snapshot (ui, controlBar), "live-states-lit");
  29156. for (std::size_t k = 0; k < buttons.size(); ++k)
  29157. buttons[k]->setToggleState (lit[k], juce::dontSendNotification);
  29158. {
  29159. auto more = ui.makeToolbarMoreMenuForSnapshot();
  29160. saveMenus (juce::StringArray { "More" }, std::vector<juce::PopupMenu> { more }, prefix + "-live-more-menu.png");
  29161. }
  29162. // the Session button row kept as an option
  29163. ui.setSessionButtonRowShown (true);
  29164. write (lynx::shot::snapshot (ui), "live-buttonrow-1920");
  29165. ui.setSessionButtonRowShown (false);
  29166. // 4. back to Pattern: FL's toolbar again, as it was
  29167. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern, false);
  29168. offline.dispatchPendingMessages();
  29169. for (const auto& [w, h] : sizes)
  29170. {
  29171. ui.setSize (w, h);
  29172. write (lynx::shot::snapshot (ui, bar()), "pattern-after-bar-" + juce::String (w));
  29173. }
  29174. juce::File (prefix + "-report.txt").replaceWithText (report);
  29175. lynx::ui::motion::enabled() = true;
  29176. }
  29177. void runGridShot (const juce::String& prefix, const juce::String& projectPath = {})
  29178. {
  29179. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29180. lynx::AudioEngine offline (false);
  29181. lynx::MainComponent ui (offline, false);
  29182. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  29183. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29184. const auto write = [&prefix, &ui] (const char* name) {
  29185. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29186. file.deleteFile();
  29187. juce::FileOutputStream out (file);
  29188. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  29189. };
  29190. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  29191. if (projectPath.isNotEmpty())
  29192. {
  29193. ui.openFile (juce::File (projectPath));
  29194. offline.dispatchPendingMessages();
  29195. ui.setClipLaunchWorkflow (true);
  29196. offline.dispatchPendingMessages();
  29197. write ("file-both");
  29198. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  29199. write ("file-grid");
  29200. const auto& song = offline.getSong();
  29201. juce::String info;
  29202. info << "grid " << (song.clipGrid ? "yes" : "no") << ", clips " << (song.clipGrid ? (int) song.clipGrid->clips.size() : 0)
  29203. << ", scenes " << (song.clipGrid ? (int) song.clipGrid->scenes.size() : 0) << ", playlist clips " << (int) song.playlist.size() << "\n";
  29204. // round qafix190kq (QA-2): the grid's columns (take lanes have none) and the Session mixer's strips follow them
  29205. if (auto* grid = ui.getClipGridForSnapshot())
  29206. {
  29207. const auto columns = lynx::clipGridColumnTracks (*grid);
  29208. int lanes = 0, laneColumns = 0;
  29209. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  29210. lanes += lynx::comp::isTakeLane (song, t) ? 1 : 0;
  29211. juce::StringArray names;
  29212. for (const auto t : columns)
  29213. {
  29214. laneColumns += lynx::comp::isTakeLane (song, t) ? 1 : 0;
  29215. names.add (t < (int) song.playlistTracks.size() ? juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str()) : "(empty)");
  29216. }
  29217. info << "playlist tracks " << (int) song.playlistTracks.size() << ", take lanes " << lanes << ", grid columns " << (int) columns.size()
  29218. << ", lane columns " << laneColumns << "\ncolumns: " << names.joinIntoString (" | ") << "\n";
  29219. // the lanes' flag survives a save and an open (ProjectFile "playlistTakeLanes")
  29220. juce::String error;
  29221. auto same = false;
  29222. if (const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error); back && back->playlistTracks.size() == song.playlistTracks.size())
  29223. {
  29224. same = true;
  29225. for (std::size_t t = 0; t < song.playlistTracks.size(); ++t)
  29226. same = same && back->playlistTracks[t].takeLane == song.playlistTracks[t].takeLane;
  29227. }
  29228. info << "take lanes after save + open: " << (same ? "same" : "DIFFERENT") << "\n";
  29229. }
  29230. juce::File (prefix + "-file.txt").replaceWithText (info);
  29231. ui.setClipLaunchWorkflow (false);
  29232. return;
  29233. }
  29234. write ("pattern"); // Pattern workflow: nothing of the grid exists yet
  29235. const auto madeBefore = lynx::launcher::Runtime::instances.load();
  29236. offline.editSong ([] (lynx::Song& s) {
  29237. while (s.patterns.size() < 6)
  29238. s.patterns.emplace_back();
  29239. for (int p = 0; p < 6; ++p)
  29240. {
  29241. auto& pattern = s.patterns[(std::size_t) p];
  29242. const char* names[] { "Drums A", "Drums B", "Bass", "Chords", "Lead", "Pad" };
  29243. pattern.name = names[p];
  29244. pattern.lengthTicks = 4 * lynx::ppq;
  29245. }
  29246. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  29247. const char* tracks[] { "Drums", "Bass", "Chords", "Lead", "Vocals", "FX" };
  29248. for (int t = 0; t < 6; ++t)
  29249. s.playlistTracks[(std::size_t) t].name = tracks[t];
  29250. const int placed[][3] { { 0, 0, 0 }, { 0, 1, 1 }, { 0, 2, 0 }, { 0, 3, 1 }, { 1, 0, 2 }, { 1, 2, 2 }, { 2, 1, 3 }, { 2, 2, 3 }, { 3, 2, 4 }, { 3, 3, 4 }, { 4, 3, 5 } };
  29251. for (const auto& c : placed)
  29252. {
  29253. lynx::Clip clip;
  29254. clip.pattern = c[2];
  29255. clip.length = 4 * lynx::ppq;
  29256. lynx::launcher::setClip (s, c[0], c[1], clip);
  29257. }
  29258. auto& grid = lynx::launcher::ensureGrid (s);
  29259. const char* scenes[] { "Intro", "Verse", "Drop", "Break" };
  29260. grid.scenes.resize (6);
  29261. for (int r = 0; r < 4; ++r)
  29262. grid.scenes[(std::size_t) r].name = scenes[r];
  29263. }, false);
  29264. offline.dispatchPendingMessages();
  29265. write ("pattern-edited"); // the same song as -pattern-after: the workflow must leave no trace
  29266. ui.setClipLaunchWorkflow (true);
  29267. offline.dispatchPendingMessages();
  29268. if (auto* runtime = offline.launcherStateForSnapshot())
  29269. {
  29270. runtime->tracks[0].playing.store (2);
  29271. runtime->tracks[0].progress.store (0.4f);
  29272. runtime->tracks[0].taken.store (true);
  29273. runtime->tracks[1].playing.store (2);
  29274. runtime->tracks[1].progress.store (0.4f);
  29275. runtime->tracks[1].taken.store (true);
  29276. runtime->tracks[2].pending.store (2);
  29277. runtime->tracks[3].taken.store (true);
  29278. }
  29279. write ("both");
  29280. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  29281. write ("grid");
  29282. // round 190bv: recording into slots and the Groove Pool. Two tracks armed (round record buttons in their empty
  29283. // slots, their arm buttons lit), one of them recording and one waiting for its start; then a clip through a
  29284. // groove with the pool shown, and the slot menus
  29285. if (auto* gridView = ui.getClipGridForSnapshot())
  29286. {
  29287. offline.setGridTrackArmed (4, true);
  29288. offline.setGridTrackArmed (5, true, false);
  29289. offline.dispatchPendingMessages();
  29290. write ("rec-armed");
  29291. if (auto* runtime = offline.launcherStateForSnapshot())
  29292. {
  29293. runtime->tracks[4].recording.store (1);
  29294. runtime->tracks[4].recordFrom.store (0.0); // (round 190cy: one beat recorded, the counter reads 0.1.0)
  29295. runtime->clockNow.store ((double) lynx::ppq);
  29296. runtime->tracks[5].recordPending.store (1);
  29297. }
  29298. write ("rec-recording");
  29299. if (auto* runtime = offline.launcherStateForSnapshot())
  29300. {
  29301. runtime->tracks[4].recording.store (-1);
  29302. runtime->tracks[5].recordPending.store (-1);
  29303. }
  29304. offline.editSong ([] (lynx::Song& s) {
  29305. const auto& bank = lynx::groove::factoryBank();
  29306. std::uint32_t first = 0;
  29307. for (const auto index : { std::size_t (9), std::size_t (20), std::size_t (27) })
  29308. if (index < bank.size())
  29309. {
  29310. const auto id = lynx::groove::add (s.grooves, bank[index].groove);
  29311. first = first == 0 ? id : first;
  29312. }
  29313. lynx::groove::setClipGroove (s, 0, 0, first);
  29314. }, false);
  29315. offline.dispatchPendingMessages();
  29316. lynx::setClipGridGroovePoolShown (*gridView, true);
  29317. write ("groove-pool");
  29318. saveMenus ({ "Clip slot", "Groove", "Empty slot" },
  29319. { lynx::clipGridSlotMenu (*gridView, 0, 0), [&] {
  29320. juce::PopupMenu found;
  29321. const auto menu = lynx::clipGridSlotMenu (*gridView, 0, 0);
  29322. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  29323. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Groove"))
  29324. found = *it.getItem().subMenu;
  29325. return found;
  29326. }(), lynx::clipGridSlotMenu (*gridView, 4, 1) },
  29327. prefix + "-rec-menus.png");
  29328. lynx::setClipGridGroovePoolShown (*gridView, false);
  29329. // round 190cy: a second record button pressed while recording: the first take ("Vocals 1") plays on, the
  29330. // clicked slot records "Vocals 2" with its counter at 2.0.2 (as Live 12.4.16, live check 190cw shot 03b)
  29331. {
  29332. const auto name = offline.slotRecordingName (4);
  29333. offline.editSong ([&name] (lynx::Song& s) { lynx::session::placeRecordedPattern (s, 4, 0, {}, 8 * lynx::ppq, name); }, false);
  29334. offline.dispatchPendingMessages();
  29335. if (auto* runtime = offline.launcherStateForSnapshot())
  29336. {
  29337. runtime->tracks[4].playing.store (0);
  29338. runtime->tracks[4].progress.store (0.3f);
  29339. runtime->tracks[4].recording.store (1);
  29340. runtime->tracks[4].recordFrom.store (0.0);
  29341. runtime->clockNow.store (8.0 * lynx::ppq + 2.0 * lynx::ppq / 4.0);
  29342. }
  29343. write ("rec-second");
  29344. if (auto* runtime = offline.launcherStateForSnapshot())
  29345. {
  29346. runtime->tracks[4].playing.store (-1);
  29347. runtime->tracks[4].recording.store (-1);
  29348. }
  29349. offline.editSong ([] (lynx::Song& s) {
  29350. if (lynx::session::cut (s, 4, 0) && ! s.patterns.empty())
  29351. s.patterns.pop_back();
  29352. }, false);
  29353. offline.dispatchPendingMessages();
  29354. }
  29355. offline.setGridTrackArmed (4, false);
  29356. offline.setGridTrackArmed (5, false);
  29357. offline.dispatchPendingMessages();
  29358. }
  29359. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  29360. write ("song");
  29361. ui.setClipLaunchWorkflow (false);
  29362. write ("pattern-after");
  29363. juce::File (prefix + "-counts.txt").replaceWithText ("runtimes before " + juce::String (madeBefore) + ", after " + juce::String (lynx::launcher::Runtime::instances.load()) + "\n");
  29364. }
  29365. // Round 190bu: the Simple workflow's track dock (ui/SimpleDock.h), off-screen
  29366. void runSimpleFxShot (const juce::String& prefix)
  29367. {
  29368. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29369. lynx::AudioEngine offline (false);
  29370. lynx::MainComponent ui (offline, false);
  29371. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  29372. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29373. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  29374. const auto file = juce::File (prefix + "-" + name + ".png");
  29375. file.deleteFile();
  29376. juce::FileOutputStream out (file);
  29377. juce::PNGImageFormat().writeImageToStream (image, out);
  29378. };
  29379. juce::String report;
  29380. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  29381. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  29382. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  29383. ui.selectTabForSnapshot (2);
  29384. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  29385. offline.dispatchPendingMessages();
  29386. auto* simple = ui.getSimpleWorkflowForSnapshot();
  29387. if (simple == nullptr)
  29388. {
  29389. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  29390. return;
  29391. }
  29392. simple->hideChooser();
  29393. // three tracks: a voice, keys with a few chords, a drum kit
  29394. int keysInsert = -1;
  29395. offline.editSong ([&keysInsert] (lynx::Song& s) {
  29396. namespace st = lynx::simpletracks;
  29397. st::Request q;
  29398. q.kind = st::Kind::voice;
  29399. q.name = "Lead vocal";
  29400. st::addTrack (s, q);
  29401. q = {};
  29402. q.kind = st::Kind::instrument;
  29403. q.name = "Keys";
  29404. lynx::ChannelDef keys;
  29405. keys.instrument = lynx::InstrumentKind::synth;
  29406. q.channel = keys;
  29407. lynx::Pattern chords;
  29408. for (int i = 0; i < 4; ++i)
  29409. for (int k : { 60, 64, 67 })
  29410. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  29411. q.pattern = chords;
  29412. keysInsert = st::addTrack (s, q).insert;
  29413. q = {};
  29414. q.kind = st::Kind::drums;
  29415. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  29416. {
  29417. lynx::ChannelDef c;
  29418. c.instrument = kind;
  29419. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  29420. q.kit.push_back (c);
  29421. }
  29422. lynx::Pattern beat;
  29423. for (int step = 0; step < 16; step += 2)
  29424. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 2, 60 });
  29425. q.pattern = beat;
  29426. st::addTrack (s, q);
  29427. });
  29428. offline.dispatchPendingMessages();
  29429. simple->hideChooser();
  29430. auto& playlist = ui.getPlaylistForSnapshot();
  29431. // the tracks' places in the Playlist
  29432. int voiceTrack = -1, keysTrack = -1, drumsTrack = -1;
  29433. {
  29434. const auto& song = offline.getSong();
  29435. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  29436. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  29437. {
  29438. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  29439. voiceTrack = t;
  29440. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  29441. keysTrack = t;
  29442. else if (*kind == lynx::simpletracks::Kind::drums && drumsTrack < 0)
  29443. drumsTrack = t;
  29444. }
  29445. }
  29446. check ("three Simple tracks (voice, keys, drums)", voiceTrack >= 0 && keysTrack >= 0 && drumsTrack >= 0);
  29447. playlist.selectTrack (keysTrack);
  29448. offline.dispatchPendingMessages();
  29449. auto* dock = simple->dockForSnapshot();
  29450. if (dock == nullptr)
  29451. {
  29452. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  29453. return;
  29454. }
  29455. // the whole window and the dock alone, at 1x and 2x
  29456. const auto shots = [&] (const juce::String& name) {
  29457. offline.dispatchPendingMessages();
  29458. for (float scale : { 1.0f, 2.0f })
  29459. {
  29460. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  29461. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  29462. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  29463. }
  29464. };
  29465. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  29466. juce::StringArray names { title };
  29467. std::vector<juce::PopupMenu> menus { menu };
  29468. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  29469. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  29470. {
  29471. names.add (subTitle);
  29472. menus.push_back (*it.getItem().subMenu);
  29473. }
  29474. saveMenus (names, menus, prefix + "-" + name + ".png");
  29475. };
  29476. // --- the Instrument tab ---------------------------------------------------------------------------------------
  29477. check ("the dock shows the selected track", dock->shownTrack() == keysTrack && dock->isVisible() && dock->getParentComponent() != nullptr);
  29478. check ("an instrument track opens on its sound", dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::instrument);
  29479. const auto channel = dock->channelForCheck();
  29480. line ("sound at first: " + dock->soundNameForCheck() + ", rows in its category: " + juce::String (dock->soundRowsForCheck()));
  29481. shots ("instrument");
  29482. // a click on a row of another category: the track plays that sound, its own settings stay
  29483. const auto before = offline.getSong().channels[(std::size_t) channel];
  29484. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::pad);
  29485. offline.dispatchPendingMessages();
  29486. const auto padRows = dock->soundRowsForCheck();
  29487. dock->clickSoundForCheck (juce::jmin (2, padRows - 1));
  29488. offline.dispatchPendingMessages();
  29489. {
  29490. const auto& now = offline.getSong().channels[(std::size_t) channel];
  29491. const auto found = lynx::soundlib::find (lynx::soundlib::builtIn(), now);
  29492. check ("a click on a sound puts it on the track's channel (" + dock->soundNameForCheck() + ")",
  29493. padRows > 0 && found >= 0 && lynx::soundlib::builtIn()[(std::size_t) found].category == lynx::soundlib::Category::pad
  29494. && ! lynx::soundlib::sameSound (before, now));
  29495. check ("the channel keeps its name, level and insert", now.name == before.name && now.volume == before.volume && now.mixerTrack == before.mixerTrack);
  29496. double seconds = 0.0;
  29497. const auto heard = offline.auditionSound (now, { 60, 64, 67 }, &seconds);
  29498. check ("the sound's audition renders (" + juce::String (seconds, 2) + " s)", heard && seconds > 1.0);
  29499. }
  29500. shots ("instrument-pad");
  29501. const auto picked = dock->soundNameForCheck();
  29502. dock->stepSoundForCheck (1);
  29503. offline.dispatchPendingMessages();
  29504. const auto stepped = dock->soundNameForCheck();
  29505. dock->stepSoundForCheck (-1);
  29506. offline.dispatchPendingMessages();
  29507. check ("the arrows step through the category (" + picked + " -> " + stepped + " -> back)", stepped != picked && dock->soundNameForCheck() == picked);
  29508. check ("one undo step per sound", offline.canUndo());
  29509. // the user's SoundFont files (an index made here: no file is read)
  29510. {
  29511. std::vector<lynx::sf::IndexedFont> fonts (2);
  29512. fonts[0].path = "/home/me/SoundFonts/Concert Band.sf2";
  29513. fonts[0].name = "Concert Band";
  29514. int program = 0;
  29515. for (const char* name : { "Grand Piano", "Bright Piano", "Electric Piano", "Harpsichord", "Clavinet", "Celesta", "Music Box", "Vibraphone" })
  29516. fonts[0].presets.push_back ({ name, 0, program++ });
  29517. for (const auto& [name, p] : std::initializer_list<std::pair<const char*, int>> { { "Finger Bass", 33 }, { "Picked Bass", 34 }, { "Nylon Guitar", 24 }, { "Strings", 48 }, { "Choir Aahs", 52 }, { "Trumpet", 56 } })
  29518. fonts[0].presets.push_back ({ name, 0, p });
  29519. fonts[0].presets.push_back ({ "Standard Kit", 128, 0 });
  29520. fonts[1].path = "/home/me/SoundFonts/Old Upright.sf2";
  29521. fonts[1].name = "Old Upright";
  29522. fonts[1].presets.push_back ({ "Old Upright", 0, 0 });
  29523. fonts[1].presets.push_back ({ "Old Upright Soft", 0, 1 });
  29524. dock->setFontsForSnapshot (fonts);
  29525. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::keys);
  29526. offline.dispatchPendingMessages();
  29527. check ("My SoundFonts lists the presets of the user's files by category (Keys: " + juce::String (dock->soundRowsForCheck()) + " of 17)", dock->soundRowsForCheck() == 7);
  29528. dock->clickSoundForCheck (0);
  29529. offline.dispatchPendingMessages();
  29530. const auto& now = offline.getSong().channels[(std::size_t) channel];
  29531. check ("a SoundFont preset becomes the track's sound (" + dock->soundNameForCheck() + ")",
  29532. now.instrument == lynx::InstrumentKind::soundfont && juce::String (now.samplePath).endsWith (".sf2"));
  29533. shots ("instrument-soundfonts");
  29534. }
  29535. // --- the Effects tab ------------------------------------------------------------------------------------------
  29536. playlist.selectTrack (voiceTrack);
  29537. offline.dispatchPendingMessages();
  29538. const auto insert = dock->insertForCheck();
  29539. check ("an audio track has no Instrument tab and opens on its effects",
  29540. dock->shownTrack() == voiceTrack && ! dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::effects && insert > 0);
  29541. check ("no effects yet: no cards", dock->cardCountForCheck() == 0);
  29542. shots ("effects-empty");
  29543. menuShot (dock->addMenuForSnapshot(), lynx::tr ("Add an effect"), {}, "menu-add");
  29544. // + adds one-knob effects at the end of the chain
  29545. dock->addOneKnobForCheck (lynx::goals::brighter);
  29546. dock->addOneKnobForCheck (lynx::goals::room);
  29547. dock->addOneKnobForCheck (lynx::goals::level);
  29548. offline.dispatchPendingMessages();
  29549. const auto slotsText = [&offline] (int t) {
  29550. juce::String text;
  29551. const auto rows = lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) t].effects); // (the Mixer's slot of each)
  29552. std::size_t at = 0;
  29553. for (const auto& fx : offline.getSong().mixer[(std::size_t) t].effects)
  29554. text << "[slot " << rows[at++] + 1 << " " << lynx::effectInfo (fx.kind).name
  29555. << (lynx::goals::active (fx) ? " = " + juce::String (lynx::goals::name (fx.goal)) + " " + juce::String (juce::roundToInt (fx.goalAmount * 100.0f)) + "%" : juce::String())
  29556. << (fx.enabled ? "" : " off") << "] ";
  29557. return text.trimEnd();
  29558. };
  29559. line ("after + x3: " + slotsText (insert));
  29560. check ("three cards, three one-knob effects", dock->cardCountForCheck() == 3 && dock->oneKnobCardsForCheck() == 3);
  29561. // the knob writes the effect's own parameters
  29562. const auto roomBefore = offline.getSong().mixer[(std::size_t) insert].effects[1];
  29563. dock->turnKnobForCheck (1, 0.8f);
  29564. offline.dispatchPendingMessages();
  29565. {
  29566. const auto& room = offline.getSong().mixer[(std::size_t) insert].effects[1];
  29567. check ("the knob at 80 % writes the mapped parameters", std::abs (room.goalAmount - 0.8f) < 1.0e-6f && lynx::goals::active (room) && ! (room.params == roomBefore.params));
  29568. }
  29569. // ‹ › reorder, × removes
  29570. dock->moveCardForCheck (2, -1);
  29571. offline.dispatchPendingMessages();
  29572. line ("Level moved left: " + slotsText (insert));
  29573. {
  29574. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  29575. check ("the card moved one place earlier", fx.size() == 3 && fx[1].goal == lynx::goals::level && fx[2].goal == lynx::goals::room);
  29576. }
  29577. dock->removeCardForCheck (0);
  29578. offline.dispatchPendingMessages();
  29579. line ("Brighter removed: " + slotsText (insert));
  29580. check ("the card is gone", dock->cardCountForCheck() == 2 && offline.getSong().mixer[(std::size_t) insert].effects.size() == 2);
  29581. // a hand edit in the full editor: the slot is an ordinary effect again (its card shows Mix)
  29582. offline.editSong ([insert] (lynx::Song& s) {
  29583. auto& slot = s.mixer[(std::size_t) insert].effects[0];
  29584. const auto moved = (std::size_t) lynx::goals::mapping (slot.goal, slot.goalAmount).back().param;
  29585. slot.params[moved] = slot.params[moved] > 0.5f ? 0.2f : 0.9f;
  29586. });
  29587. offline.dispatchPendingMessages();
  29588. check ("a parameter moved by hand makes the card an ordinary effect", dock->cardCountForCheck() == 2 && dock->oneKnobCardsForCheck() == 1);
  29589. dock->turnKnobForCheck (0, 0.5f); // (its knob is the slot's Mix now)
  29590. offline.dispatchPendingMessages();
  29591. check ("an ordinary card's knob is the slot's Mix", std::abs (offline.getSong().mixer[(std::size_t) insert].effects[0].mix - 0.5f) < 1.0e-6f);
  29592. // a preset replaces the chain; Blend is the chain's dry/wet
  29593. if (const auto* preset = lynx::chains::find ("Clear Voice"))
  29594. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  29595. offline.dispatchPendingMessages();
  29596. line ("preset Clear Voice: " + slotsText (insert));
  29597. check ("the preset's chain is on the insert", offline.getSong().mixer[(std::size_t) insert].chainPreset == "Clear Voice" && lynx::chains::unchanged (offline.getSong(), insert)
  29598. && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size());
  29599. shots ("effects-preset");
  29600. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("Voice"), "menu-preset");
  29601. dock->setBlendForCheck (0.7f);
  29602. dock->addOneKnobForCheck (lynx::goals::echo);
  29603. offline.dispatchPendingMessages();
  29604. check ("Blend 70 % is the insert's chain blend; the preset shows as edited",
  29605. std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.7f) < 1.0e-6f && ! lynx::chains::unchanged (offline.getSong(), insert));
  29606. shots ("effects-edited");
  29607. // a user preset: saved to a file, loaded on another track (its slots and Blend; that track's level stays)
  29608. const auto mine = offline.getSong().mixer[(std::size_t) insert];
  29609. const auto saved = lynx::SimpleDock::saveUserPreset (offline, insert, "My voice");
  29610. const auto file = lynx::SimpleDock::userPresetFolder().getChildFile ("My voice.lynxtrack");
  29611. check ("the preset is saved as " + file.getFileName(), saved && file.existsAsFile() && offline.getSong().mixer[(std::size_t) insert].chainPreset == "My voice");
  29612. offline.editSong ([keysInsert] (lynx::Song& s) { s.mixer[(std::size_t) keysInsert].volume = 0.42f; });
  29613. const auto loaded = keysInsert > 0 && lynx::SimpleDock::loadUserPreset (offline, keysInsert, file);
  29614. offline.dispatchPendingMessages();
  29615. {
  29616. const auto& other = offline.getSong().mixer[(std::size_t) keysInsert];
  29617. auto same = loaded && other.effects.size() == mine.effects.size() && std::abs (other.chainBlend - mine.chainBlend) < 1.0e-6f && other.chainPreset == "My voice";
  29618. for (std::size_t i = 0; same && i < mine.effects.size(); ++i)
  29619. same = other.effects[i].kind == mine.effects[i].kind && other.effects[i].goal == mine.effects[i].goal
  29620. && lynx::mixerops::effectRows (other.effects)[i] == lynx::mixerops::effectRows (mine.effects)[i] && std::abs (other.effects[i].goalAmount - mine.effects[i].goalAmount) < 1.0e-6f && lynx::goals::active (other.effects[i]) == lynx::goals::active (mine.effects[i]);
  29621. check ("loaded on the Keys track: the same slots and Blend", same);
  29622. check ("the Keys track keeps its level", std::abs (other.volume - 0.42f) < 1.0e-6f);
  29623. line ("Keys after load: " + slotsText (keysInsert));
  29624. }
  29625. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("My presets"), "menu-preset-mine");
  29626. file.deleteFile();
  29627. // the drums: effects only (a kit has no single sound to pick)
  29628. playlist.selectTrack (drumsTrack);
  29629. offline.dispatchPendingMessages();
  29630. check ("the Drums track shows its insert's effects, no Instrument tab", dock->shownTrack() == drumsTrack && ! dock->hasInstrumentTabForCheck() && dock->insertForCheck() > 0);
  29631. if (const auto* preset = lynx::chains::find ("Smash Room"))
  29632. offline.editSongStructural ([t = dock->insertForCheck(), preset] (lynx::Song& s) { lynx::chains::apply (s, t, *preset); });
  29633. shots ("effects-drums");
  29634. // the project file keeps all of it
  29635. {
  29636. juce::String error;
  29637. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  29638. const auto back = lynx::ProjectFile::fromJson (json, error);
  29639. auto same = back && back->mixer.size() == offline.getSong().mixer.size();
  29640. for (std::size_t t = 0; same && t < back->mixer.size(); ++t)
  29641. {
  29642. const auto& a = offline.getSong().mixer[t];
  29643. const auto& b = back->mixer[t];
  29644. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  29645. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  29646. same = a.effects[i].kind == b.effects[i].kind && a.effects[i].goal == b.effects[i].goal && a.effects[i].row == b.effects[i].row
  29647. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f;
  29648. }
  29649. check ("saved and loaded as a project: the same chains, knobs, Blend and preset names", same);
  29650. }
  29651. // --- the same plugins in the same slots in FL's layout --------------------------------------------------------
  29652. const auto simpleSong = offline.getSong();
  29653. const auto inSimple = slotsText (insert);
  29654. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  29655. offline.dispatchPendingMessages();
  29656. check ("Pattern workflow: the dock is gone", dock->getParentComponent() == nullptr);
  29657. ui.selectTabForSnapshot (3);
  29658. ui.getMixerForSnapshot().selectTrack (insert);
  29659. offline.dispatchPendingMessages();
  29660. for (float scale : { 1.0f, 2.0f })
  29661. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), juce::String ("pattern-mixer") + (scale > 1.0f ? "@2x" : ""));
  29662. line ("Simple layout: " + inSimple);
  29663. line ("Pattern layout: " + slotsText (insert));
  29664. check ("the same effects in the same Mixer slots in the Pattern workflow", offline.getSong().mixer == simpleSong.mixer && offline.getSong().channels == simpleSong.channels);
  29665. // an effect added in the Mixer's way shows as a card when the Simple workflow comes back
  29666. offline.editSongStructural ([insert] (lynx::Song& s) { lynx::mixerops::insertEffectAtRow (s, insert, lynx::makeEffectSlot (lynx::EffectKind::chorus), 7); });
  29667. ui.selectTabForSnapshot (2);
  29668. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  29669. offline.dispatchPendingMessages();
  29670. simple->hideChooser();
  29671. playlist.selectTrack (voiceTrack);
  29672. offline.dispatchPendingMessages();
  29673. check ("back in Simple: the dock shows the insert as it is now, the Mixer's new effect too",
  29674. dock->getParentComponent() != nullptr && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size()
  29675. && lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) insert].effects).back() == 7);
  29676. line ("Simple again: " + slotsText (insert));
  29677. shots ("effects-back");
  29678. // hidden with its key, shown again by "+FX"
  29679. simple->toggleDock();
  29680. offline.dispatchPendingMessages();
  29681. check ("Ctrl+Alt+L hides the dock", ! simple->isDockShowing() && ! lynx::SimpleDock::shownSetting);
  29682. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "dock-hidden");
  29683. simple->showEffectsOfInsert (keysInsert);
  29684. offline.dispatchPendingMessages();
  29685. check ("+FX on a track header shows the dock on that track's effects",
  29686. simple->isDockShowing() && dock->shownTrack() == keysTrack && dock->getTab() == lynx::SimpleDock::Tab::effects && dock->insertForCheck() == keysInsert);
  29687. simple->cycleDockTab();
  29688. check ("Shift+Tab goes to the Instrument tab", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  29689. line ("Simple workflow objects: " + juce::String (madeBefore) + " before, " + juce::String (lynx::SimpleWorkflow::instances.load()) + " after");
  29690. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  29691. juce::File (prefix + "-report.txt").replaceWithText (report);
  29692. }
  29693. // --simpleclosetest (round 190fc, 0.1.27 RC blocker B1): every close in the Simple layout crashed (the Simple workflow
  29694. // was destroyed after the Workspace and its destructor called into it). Off-screen, no window: the main window in the
  29695. // Simple layout with everything of it open — Welcome, the first-song tour's card, Start from, a demo song, each dock
  29696. // tab (the Editor tab docks the Piano roll), Finish, Lyrics, the chooser — then destroyed as the app's shutdown does.
  29697. // A second main window goes Simple -> Pattern -> Simple and closes too. Checks: no Simple workflow outlives its main
  29698. // window's destructor body, none is left at all. (Under ASan on Linux the old order is a heap-use-after-free.)
  29699. bool runDonateShot (const juce::String& prefix)
  29700. {
  29701. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29702. juce::String report;
  29703. bool ok = true;
  29704. const auto line = [&report, &prefix] (const juce::String& text) {
  29705. report << text << "\n";
  29706. juce::File (prefix + "-report.txt").replaceWithText (report); // (written as it goes)
  29707. };
  29708. const auto check = [&line, &ok] (const juce::String& what, bool good) {
  29709. line ((good ? "ok " : "FAIL ") + what);
  29710. ok = ok && good;
  29711. };
  29712. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  29713. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29714. file.deleteFile();
  29715. juce::FileOutputStream out (file);
  29716. juce::PNGImageFormat().writeImageToStream (image, out);
  29717. };
  29718. // a window as the --snapshot route saves one (off the desktop, on the theme's panel colour), at 1x and 2x
  29719. const auto saveAlert = [&] (juce::AlertWindow& w, const juce::String& name) {
  29720. if (w.isOnDesktop())
  29721. w.removeFromDesktop();
  29722. w.setOpaque (true);
  29723. juce::Component frame;
  29724. frame.setSize (w.getWidth(), w.getHeight());
  29725. frame.setOpaque (true);
  29726. frame.addAndMakeVisible (w);
  29727. w.setTopLeftPosition (0, 0);
  29728. writeImage (lynx::shot::paint (frame, lynx::theme::panel), name);
  29729. writeImage (frame.createComponentSnapshot (frame.getLocalBounds(), true, 2.0f), name + "@2x");
  29730. frame.removeChildComponent (&w);
  29731. };
  29732. const auto buttonTexts = [] (juce::AlertWindow& w) {
  29733. if (auto* d = dynamic_cast<lynx::ui::dialog::Dialog*> (&w)) // (round 190jp: LYNX's dialog, its own buttons)
  29734. return d->dialogButtonTexts();
  29735. juce::StringArray texts;
  29736. for (int b = 0; b < w.getNumButtons(); ++b)
  29737. if (auto* button = w.getButton (b))
  29738. texts.add (button->getButtonText());
  29739. return texts;
  29740. };
  29741. check ("the donation page is one constant, on Ko-fi", juce::String (lynx::links::donate).startsWith ("https://ko-fi"));
  29742. line ("donate URL: " + juce::String (lynx::links::donate));
  29743. const auto stateFile = lynx::PluginHost::settingsFolder().getChildFile ("support-note.txt");
  29744. const auto hadState = stateFile.existsAsFile();
  29745. const auto oldState = stateFile.loadFileAsString();
  29746. line ("state file: " + stateFile.getFullPathName() + (hadState ? " (exists; put back at the end)" : ""));
  29747. {
  29748. lynx::AudioEngine offline (false);
  29749. lynx::MainComponent ui (offline, false);
  29750. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  29751. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29752. ui.setVisible (true);
  29753. const auto settle = [&] {
  29754. for (int k = 0; k < 3; ++k)
  29755. offline.dispatchPendingMessages();
  29756. };
  29757. // --- Help › Support LYNX SHARE..., right above About, in the three layouts ----------------------------------
  29758. for (auto [style, name] : { std::pair { lynx::layoutstyle::Style::pattern, "pattern" }, { lynx::layoutstyle::Style::clipLaunch, "cliplaunch" },
  29759. { lynx::layoutstyle::Style::simple, "simple" } })
  29760. {
  29761. ui.setLayoutStyle (style);
  29762. settle();
  29763. const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
  29764. juce::StringArray items;
  29765. for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
  29766. if (! it.getItem().isSeparator)
  29767. items.add (it.getItem().text);
  29768. const auto support = items.indexOf (lynx::tr ("Support LYNX SHARE..."));
  29769. const auto about = items.indexOf (lynx::tr ("About LYNX SHARE"));
  29770. check (juce::String ("Help has Support LYNX SHARE... right above About LYNX SHARE (") + name + " layout)",
  29771. support >= 0 && about == support + 1);
  29772. saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help-" + name + ".png");
  29773. }
  29774. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  29775. settle();
  29776. // --- the Support window -------------------------------------------------------------------------------------
  29777. {
  29778. auto w = lynx::support::makeSupportWindow();
  29779. const auto texts = buttonTexts (*w);
  29780. check ("Support window: Donate on Ko-fi, Close", texts == juce::StringArray { lynx::tr ("Donate on Ko-fi"), lynx::tr ("Close") });
  29781. check ("Support window: Donate on Ko-fi points at the constant",
  29782. dynamic_cast<lynx::ui::dialog::Dialog*> (w.get()) != nullptr
  29783. && static_cast<lynx::ui::dialog::Dialog*> (w.get())->dialogButton (0)->getTooltip() == juce::String (lynx::links::donate));
  29784. check ("Support window title", w->getName() == lynx::tr ("Support LYNX SHARE"));
  29785. saveAlert (*w, "support");
  29786. }
  29787. // --- the About window ---------------------------------------------------------------------------------------
  29788. {
  29789. auto w = lynx::MainComponent::makeAboutWindow();
  29790. const auto texts = buttonTexts (*w);
  29791. check ("About window: Support LYNX SHARE (result 2) and OK", texts == juce::StringArray { lynx::tr ("Support LYNX SHARE"), lynx::tr ("OK") });
  29792. saveAlert (*w, "about");
  29793. }
  29794. // --- Settings › General › Show the support note -------------------------------------------------------------
  29795. {
  29796. auto page = lynx::makeGeneralPage (offline, {}, false);
  29797. bool found = false;
  29798. std::function<void (juce::Component&)> walk = [&] (juce::Component& c) {
  29799. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Show the support note"))
  29800. found = t->getToggleState();
  29801. for (auto* child : c.getChildren())
  29802. walk (*child);
  29803. };
  29804. walk (*page);
  29805. check ("Settings > General: \"Show the support note\", ticked by default", found);
  29806. }
  29807. // --- the start-up note's rules, end to end on the saved state ----------------------------------------------
  29808. lynx::supportnote::Moment moment; // (the main window here is off-screen: the moment is set by hand)
  29809. lynx::support::StartupNote note (ui, [&moment] { return moment; }, [] { return 0; });
  29810. const auto state = [] { return lynx::support::loadState(); };
  29811. const auto setState = [] (int launches, int next, bool show) { lynx::support::saveState ({ launches, next, show }); };
  29812. stateFile.deleteFile();
  29813. for (int k = 0; k < 15; ++k)
  29814. note.begin (true);
  29815. note.pollForSnapshot();
  29816. check ("test mode / CI runs: 15 starts, nothing counted, no file, no card", ! stateFile.existsAsFile() && ! note.isCardShowing());
  29817. check ("a first start's defaults: next at start 10, shown", state() == lynx::supportnote::State { 0, 10, true });
  29818. for (int k = 1; k <= 9; ++k)
  29819. {
  29820. note.begin (false);
  29821. note.pollForSnapshot();
  29822. }
  29823. check ("starts 1 to 9: counted, no card", state().launches == 9 && ! note.isCardShowing());
  29824. moment.playing = true;
  29825. note.begin (false); // the 10th start
  29826. note.pollForSnapshot();
  29827. check ("10th start while playing: the card waits", state().launches == 10 && ! note.isCardShowing());
  29828. moment = {};
  29829. moment.dialogOpen = true;
  29830. note.pollForSnapshot();
  29831. check ("... and while a dialog is open", ! note.isCardShowing());
  29832. moment = {};
  29833. note.pollForSnapshot();
  29834. check ("10th start, a quiet moment: the card shows", note.isCardShowing());
  29835. check ("shown: left without an answer it comes back 30 starts later", state().nextAt == 40);
  29836. if (auto* card = note.cardForSnapshot())
  29837. {
  29838. const auto b = card->getBounds();
  29839. check ("the card sits in the bottom-right corner", b.getRight() <= ui.getWidth() - 8 && b.getRight() >= ui.getWidth() - 40
  29840. && b.getBottom() <= ui.getHeight() - 4 && b.getBottom() >= ui.getHeight() - 40);
  29841. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "note-in-window");
  29842. writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), "note@2x");
  29843. // the corner of the window around the card, at 2x
  29844. writeImage (ui.createComponentSnapshot (b.expanded (220, 120).getIntersection (ui.getLocalBounds()), true, 2.0f), "note-corner@2x");
  29845. }
  29846. moment.playing = true;
  29847. note.pollForSnapshot();
  29848. check ("playback starts: the card steps aside", ! note.isCardShowing());
  29849. moment = {};
  29850. // Not now: again after 30 more starts
  29851. setState (10, 10, true);
  29852. note.begin (false); // start 11
  29853. note.pollForSnapshot();
  29854. if (auto* card = note.cardForSnapshot(); card != nullptr && card->buttonForSnapshot (lynx::supportnote::Choice::notNow) != nullptr)
  29855. card->buttonForSnapshot (lynx::supportnote::Choice::notNow)->onClick();
  29856. note.closeCard(); // (the click closes it on the next message turn)
  29857. check ("Not now: next at start 41", state() == lynx::supportnote::State { 11, 41, true });
  29858. for (int k = 12; k <= 40; ++k)
  29859. {
  29860. note.begin (false);
  29861. note.pollForSnapshot();
  29862. if (note.isCardShowing())
  29863. break;
  29864. }
  29865. check ("Not now: starts 12 to 40 without the card", ! note.isCardShowing() && state().launches == 40);
  29866. note.begin (false);
  29867. note.pollForSnapshot();
  29868. check ("Not now: the card again at start 41", note.isCardShowing());
  29869. // Don't show again: never, and Settings shows the box unticked
  29870. if (auto* card = note.cardForSnapshot())
  29871. card->buttonForSnapshot (lynx::supportnote::Choice::never)->onClick();
  29872. note.closeCard();
  29873. check ("Don't show again: off", ! state().show && ! lynx::support::noteEnabled());
  29874. for (int k = 0; k < 200; ++k)
  29875. {
  29876. note.begin (false);
  29877. note.pollForSnapshot();
  29878. }
  29879. check ("Don't show again: 200 more starts, never", ! note.isCardShowing());
  29880. // Support: opens the Support window (on the next message turn) and the note doesn't come back
  29881. setState (20, 10, true);
  29882. note.begin (false);
  29883. note.pollForSnapshot();
  29884. if (auto* card = note.cardForSnapshot())
  29885. card->buttonForSnapshot (lynx::supportnote::Choice::support)->onClick();
  29886. note.closeCard();
  29887. check ("Support: the note has done its job", ! state().show);
  29888. // Settings off: never; on again: counts from now
  29889. setState (5, 10, true);
  29890. lynx::support::setNoteEnabled (false);
  29891. for (int k = 0; k < 100; ++k)
  29892. {
  29893. note.begin (false);
  29894. note.pollForSnapshot();
  29895. }
  29896. check ("Settings off: 100 starts, never", ! note.isCardShowing() && state().launches == 105);
  29897. lynx::support::setNoteEnabled (true);
  29898. check ("Settings on again: next 30 starts later", state() == lynx::supportnote::State { 105, 135, true });
  29899. note.closeCard();
  29900. }
  29901. stateFile.deleteFile();
  29902. if (hadState)
  29903. stateFile.replaceWithText (oldState);
  29904. line (ok ? "result=OK" : "result=FAILED");
  29905. return ok;
  29906. }
  29907. bool runSimpleCloseTest (const juce::String& reportPath)
  29908. {
  29909. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29910. juce::String report;
  29911. bool ok = true;
  29912. const auto line = [&report, &reportPath] (const juce::String& text) {
  29913. report << text << "\n";
  29914. juce::File (reportPath).replaceWithText (report); // (written as it goes: a crash still leaves the last step)
  29915. };
  29916. const auto check = [&line, &ok] (const juce::String& what, bool good) {
  29917. line ((good ? "ok " : "FAIL ") + what);
  29918. ok = ok && good;
  29919. };
  29920. const auto aliveBefore = lynx::SimpleWorkflow::alive.load();
  29921. {
  29922. lynx::AudioEngine offline (false);
  29923. {
  29924. lynx::MainComponent ui (offline, false);
  29925. ui.setSize (1600, 900);
  29926. ui.setVisible (true); // (no window: the docked editor and the tour only need their parents visible)
  29927. const auto settle = [&] {
  29928. for (int k = 0; k < 3; ++k)
  29929. offline.dispatchPendingMessages();
  29930. };
  29931. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  29932. settle();
  29933. auto* simple = ui.getSimpleWorkflowForSnapshot();
  29934. check ("the Simple workflow is up", simple != nullptr);
  29935. if (simple != nullptr)
  29936. {
  29937. const auto empty = lynx::builtInTemplateIndex ("Empty");
  29938. offline.setSong (empty >= 0 ? lynx::makeNewProject (empty) : lynx::makeNewProject());
  29939. settle();
  29940. simple->showWelcome();
  29941. settle();
  29942. auto* tour = simple->tourForSnapshot();
  29943. check ("Welcome screen shown", tour != nullptr && tour->isWelcomeShowing());
  29944. simple->startOrContinueTour();
  29945. settle();
  29946. simple->doTourStep (lynx::tour::beat);
  29947. settle();
  29948. check ("the tour runs with its card up", simple->tourRunning() && tour != nullptr && tour->cardForSnapshot() != nullptr);
  29949. // a demo song from Start from (the panel stays up over the Playlist)
  29950. if (auto* start = simple->startFromForSnapshot(); start != nullptr && lynx::demos::count > 1)
  29951. {
  29952. offline.setSong (lynx::demos::make (1));
  29953. settle();
  29954. check ("a demo song opened, Start from up", simple->isStartFromShowing() && ! offline.getSong().playlist.empty());
  29955. }
  29956. // the dock on a track, every tab (the Editor tab docks the Piano roll)
  29957. if (auto* dock = simple->dockForSnapshot())
  29958. {
  29959. simple->trackSelected ([] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  29960. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  29961. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  29962. return t;
  29963. return 0;
  29964. } (offline.getSong()));
  29965. for (auto tab : { lynx::SimpleDock::Tab::instrument, lynx::SimpleDock::Tab::keyboard, lynx::SimpleDock::Tab::editor,
  29966. lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::editor })
  29967. {
  29968. dock->setTab (tab);
  29969. settle();
  29970. }
  29971. check ("the dock shows", simple->isDockShowing());
  29972. line ("dock tab at the close: " + juce::String ((int) dock->getTab()) + " (2 = Editor, the docked Piano roll)");
  29973. }
  29974. ui.toggleLyrics(); // (Lyrics, then Finish: they share the dock on the right)
  29975. settle();
  29976. simple->showFinish();
  29977. settle();
  29978. check ("Finish open", simple->isFinishShowing());
  29979. simple->showChooser();
  29980. settle();
  29981. line ("Simple workflow objects alive before the close: " + juce::String (lynx::SimpleWorkflow::alive.load() - aliveBefore));
  29982. }
  29983. } // (the main window goes as at shutdown)
  29984. check ("no Simple workflow outlived its main window's destructor body (it reaches the Workspace)",
  29985. lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore);
  29986. check ("none left after the close", lynx::SimpleWorkflow::alive.load() == aliveBefore);
  29987. // Simple, then Pattern, then Simple again, and closed
  29988. {
  29989. lynx::MainComponent ui (offline, false);
  29990. ui.setSize (1600, 900);
  29991. ui.setVisible (true);
  29992. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  29993. offline.dispatchPendingMessages();
  29994. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  29995. offline.dispatchPendingMessages();
  29996. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  29997. offline.dispatchPendingMessages();
  29998. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  29999. simple->showWelcome();
  30000. offline.dispatchPendingMessages();
  30001. }
  30002. check ("Simple -> Pattern -> Simple, closed: none outlived the destructor body", lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore
  30003. && lynx::SimpleWorkflow::alive.load() == aliveBefore);
  30004. }
  30005. line (ok ? "result=OK" : "result=FAILED");
  30006. return ok;
  30007. }
  30008. void runTour190dvShot (const juce::String& prefix)
  30009. {
  30010. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30011. lynx::AudioEngine offline (false);
  30012. lynx::MainComponent ui (offline, false);
  30013. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  30014. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30015. ui.setVisible (true); // (no window: the docked editor and the ring's targets only need their parents visible)
  30016. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  30017. const auto file = juce::File (prefix + "-" + name + ".png");
  30018. file.deleteFile();
  30019. juce::FileOutputStream out (file);
  30020. juce::PNGImageFormat().writeImageToStream (image, out);
  30021. };
  30022. juce::String report;
  30023. // (written as it goes: a run that stops halfway still leaves its checks)
  30024. const auto line = [&report, &prefix] (const juce::String& text) {
  30025. report << text << "\n";
  30026. juce::File (prefix + "-report.txt").replaceWithText (report);
  30027. };
  30028. const auto check = [&line] (const juce::String& what, bool ok) { line ((ok ? "OK " : "ERROR ") + what); };
  30029. ui.selectTabForSnapshot (2);
  30030. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  30031. offline.dispatchPendingMessages();
  30032. auto* simple = ui.getSimpleWorkflowForSnapshot();
  30033. auto* tour = simple != nullptr ? simple->tourForSnapshot() : nullptr;
  30034. if (tour == nullptr)
  30035. {
  30036. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow / tour\n");
  30037. return;
  30038. }
  30039. check ("no Welcome screen by itself in a --snapshot route (not a real first start)", ! tour->isWelcomeShowing());
  30040. const auto settle = [&] {
  30041. for (int k = 0; k < 3; ++k)
  30042. offline.dispatchPendingMessages();
  30043. };
  30044. const auto window = [&] (const juce::String& name, bool twoX = false) {
  30045. settle();
  30046. tour->ringForSnapshot(); // (the ring follows the layout: resolved now, as its timer would)
  30047. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name);
  30048. if (twoX)
  30049. if (auto* card = tour->cardForSnapshot(); card != nullptr && card->getParentComponent() != nullptr)
  30050. writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), name + "-card@2x");
  30051. };
  30052. const auto stepIs = [&] (int step, const juce::String& target) {
  30053. settle();
  30054. const auto ring = tour->ringForSnapshot();
  30055. const auto id = tour->targetIdForSnapshot();
  30056. line ("step " + juce::String (tour->step() + 1) + " (" + lynx::tour::stepId (tour->step()) + "): ring on " + (id.isEmpty() ? juce::String ("-") : id) + " "
  30057. + ring.toString());
  30058. check (juce::String ("the card shows step ") + lynx::tour::stepId (step), tour->isRunning() && tour->step() == step);
  30059. if (target.isNotEmpty())
  30060. check ("the ring is on " + target, id == target && ! ring.isEmpty());
  30061. };
  30062. // --- the Welcome screen (on a new, empty project: the built-in "Empty" template, as File › New can give) -------------
  30063. const auto emptyProject = [] {
  30064. const auto index = lynx::builtInTemplateIndex ("Empty");
  30065. return index >= 0 ? lynx::makeNewProject (index) : lynx::makeNewProject();
  30066. };
  30067. offline.setSong (emptyProject());
  30068. settle();
  30069. check ("the new project is empty for the Simple workflow (it opens on the chooser)", lynx::simpletracks::isEmptySong (offline.getSong()));
  30070. simple->showWelcome();
  30071. settle();
  30072. check ("Help › Welcome screen shows it", tour->isWelcomeShowing());
  30073. window ("welcome");
  30074. if (auto* w = tour->welcomeForSnapshot())
  30075. writeImage (w->createComponentSnapshot (w->getLocalBounds(), true, 2.0f), "welcome@2x");
  30076. tour->clickForSnapshot ("welcome.tour");
  30077. settle();
  30078. check ("Make my first song: the Welcome screen closes, the tour starts, the chooser comes up for the beat",
  30079. ! tour->isWelcomeShowing() && tour->isRunning() && simple->isChooserShowing());
  30080. // --- step 1: the beat ---------------------------------------------------------------------------------------------
  30081. stepIs (lynx::tour::beat, "simple.tile.drums");
  30082. window ("step1-beat", true);
  30083. simple->showStarterPageForSnapshot();
  30084. stepIs (lynx::tour::beat, "simple.starters");
  30085. window ("step1-beat-starters");
  30086. tour->clickForSnapshot ("do");
  30087. settle();
  30088. check ("Do it for me added a starter beat", lynx::tour::hasBeat (offline.getSong()));
  30089. // --- step 2: the key ----------------------------------------------------------------------------------------------
  30090. stepIs (lynx::tour::key, "toolbar.key");
  30091. window ("step2-key", true);
  30092. tour->clickForSnapshot ("do");
  30093. settle();
  30094. check ("Do it for me set A minor", lynx::projectkey::get (offline.getSong()).has_value());
  30095. // --- step 3: an instrument (Add track opens the chooser: the ring moves to its tile) ------------------------------
  30096. stepIs (lynx::tour::instrument, "simple.addTrack");
  30097. window ("step3-instrument", true);
  30098. simple->showChooser();
  30099. stepIs (lynx::tour::instrument, "simple.tile.instrument");
  30100. window ("step3-instrument-chooser");
  30101. tour->clickForSnapshot ("do");
  30102. settle();
  30103. check ("Do it for me added an Instrument track (the chooser closed)", lynx::tour::firstInstrumentTrack (offline.getSong()) >= 0 && ! simple->isChooserShowing());
  30104. // --- step 4: chords -----------------------------------------------------------------------------------------------
  30105. stepIs (lynx::tour::chords, "keyboard.chordPad");
  30106. window ("step4-chords", true);
  30107. tour->clickForSnapshot ("do");
  30108. settle();
  30109. check ("Do it for me wrote four chords (12 notes) on the instrument's pattern", [&] {
  30110. const auto& song = offline.getSong();
  30111. const auto p = lynx::simpletracks::patternOf (song, lynx::tour::firstInstrumentTrack (song));
  30112. return p >= 0 && song.patterns[(std::size_t) p].notes.size() == 12;
  30113. }());
  30114. // --- step 5: a voice or a loop (no "Do it for me": a loop is dropped as a user would) ------------------------------
  30115. stepIs (lynx::tour::loop, "simple.dropLane"); // (round 190jc, SG-18: it rang "+ Add track")
  30116. window ("step5-loop", true);
  30117. {
  30118. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190dv-loops");
  30119. dir.deleteRecursively();
  30120. dir.createDirectory();
  30121. const auto wav = dir.getChildFile ("Warm Keys 120 Am.wav");
  30122. const int frames = 192000;
  30123. juce::AudioBuffer<float> audio (1, frames);
  30124. for (int i = 0; i < frames; ++i)
  30125. {
  30126. const auto t = (double) i / 48000.0;
  30127. double v = 0.0;
  30128. for (const auto key : { 57, 60, 64 })
  30129. v += std::sin (2.0 * juce::MathConstants<double>::pi * 440.0 * std::pow (2.0, (key - 69) / 12.0) * t);
  30130. audio.setSample (0, i, (float) (0.1 * v * (1.0 - std::exp (-std::fmod (t, 0.5) * 60.0))));
  30131. }
  30132. {
  30133. juce::WavAudioFormat format;
  30134. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  30135. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  30136. {
  30137. out.release();
  30138. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  30139. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  30140. }
  30141. }
  30142. simple->dropFiles ({ wav.getFullPathName() }, 0);
  30143. settle();
  30144. check ("a dropped loop (A minor in its name) follows the key", [&] {
  30145. for (const auto& c : offline.getSong().playlist)
  30146. if (c.kind == lynx::ClipKind::audio)
  30147. return c.followKey;
  30148. return false;
  30149. }());
  30150. }
  30151. // --- step 6: a one-knob effect --------------------------------------------------------------------------------------
  30152. stepIs (lynx::tour::effect, "simple.dock.addEffect");
  30153. window ("step6-effect", true);
  30154. tour->clickForSnapshot ("do");
  30155. settle();
  30156. check ("Do it for me put Room on the instrument track", lynx::tour::hasOneKnob (offline.getSong()));
  30157. // --- step 7: Finish -----------------------------------------------------------------------------------------------
  30158. stepIs (lynx::tour::finish, "simple.finish");
  30159. window ("step7-finish", true);
  30160. tour->clickForSnapshot ("do");
  30161. settle();
  30162. check ("Do it for me opened Finish and chose Balanced", simple->isFinishShowing() && lynx::looks::present (offline.getSong()));
  30163. // --- the end card, Back / Next, close -------------------------------------------------------------------------------
  30164. settle();
  30165. check ("the end card", tour->isRunning() && tour->step() == lynx::tour::stepCount);
  30166. window ("end", true);
  30167. tour->clickForSnapshot ("back");
  30168. settle();
  30169. check ("Back: the Finish step again, shown done (the tour waits for Next)", tour->step() == lynx::tour::finish
  30170. && tour->machineForCheck().shownDone (offline.getSong()));
  30171. window ("back-done", true);
  30172. tour->clickForSnapshot ("next");
  30173. settle();
  30174. check ("Next: the end card again", tour->step() == lynx::tour::stepCount);
  30175. check ("all seven steps done by the song", tour->machineForCheck().state().completed == 0x7fu);
  30176. tour->clickForSnapshot ("close");
  30177. settle();
  30178. check ("closing the end card ends the tour (not continued from Help)", ! tour->isRunning() && ! tour->canContinue()
  30179. && tour->machineForCheck().state().done);
  30180. line ("-- paused tour");
  30181. // --- a paused tour, the Help menu and the chooser's button ---------------------------------------------------------
  30182. offline.setSong (emptyProject());
  30183. settle();
  30184. tour->machineForCheck() = lynx::tour::Machine {};
  30185. simple->startOrContinueTour();
  30186. settle();
  30187. line ("-- do beat");
  30188. simple->doTourStep (lynx::tour::beat);
  30189. settle();
  30190. check ("a new tour on an empty project: the beat done moves it to the key", tour->step() == lynx::tour::key);
  30191. tour->clickForSnapshot ("close");
  30192. settle();
  30193. check ("closing the card pauses the tour (Help continues it)", ! tour->isRunning() && tour->canContinue());
  30194. line ("-- help menu");
  30195. {
  30196. const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
  30197. bool continueItem = false, welcomeItem = false;
  30198. for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
  30199. {
  30200. continueItem = continueItem || it.getItem().text.startsWith (lynx::tr ("Continue the first-song tour (step {0} of {1})", { "2", "7" }));
  30201. welcomeItem = welcomeItem || it.getItem().text == lynx::tr ("Welcome screen...");
  30202. }
  30203. check ("Help: Continue the first-song tour (step 2 of 7) and Welcome screen...", continueItem && welcomeItem);
  30204. saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help.png");
  30205. }
  30206. simple->startOrContinueTour();
  30207. settle();
  30208. check ("Help › Continue: back on the key step", tour->isRunning() && tour->step() == lynx::tour::key);
  30209. tour->clickForSnapshot ("skip");
  30210. settle();
  30211. check ("Skip tour ends it", ! tour->isRunning() && ! tour->canContinue());
  30212. offline.setSong (emptyProject());
  30213. settle();
  30214. simple->showChooser();
  30215. window ("chooser");
  30216. line ("-- start from");
  30217. // --- Start from: the three demo songs; a demo opened in Simple -------------------------------------------------------
  30218. if (auto* start = simple->startFromForSnapshot())
  30219. {
  30220. settle();
  30221. writeImage (start->createComponentSnapshot (start->getLocalBounds(), true, 1.0f), "startfrom");
  30222. const auto list = lynx::startfrom::entries();
  30223. int demos = 0;
  30224. for (const auto& e : list)
  30225. demos += e.kind == lynx::startfrom::Entry::Kind::demo && e.playable ? 1 : 0;
  30226. check ("Start from lists three playable demo songs first", demos == 3 && list.size() >= 3 && list[1].demo == 1 && list[2].demo == 2);
  30227. for (int d = 1; d < 3 && d < (int) list.size(); ++d)
  30228. line ("demo " + list[(std::size_t) d].name + ": " + juce::String (list[(std::size_t) d].bpm) + " BPM, " + juce::String (list[(std::size_t) d].bars) + " bars");
  30229. simple->hideStartFrom();
  30230. }
  30231. line ("-- demos");
  30232. for (int d = 1; d < lynx::demos::count; ++d)
  30233. {
  30234. offline.setSong (lynx::demos::make (d));
  30235. settle();
  30236. simple->hideChooser();
  30237. window (juce::String ("demo-") + (d == 1 ? "hiphop" : "pop"));
  30238. // the committed file is the generated song
  30239. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile ("resources/demos").getChildFile (lynx::demos::fileName (d));
  30240. juce::String error;
  30241. const auto loaded = lynx::ProjectFile::load (file, error);
  30242. check ("resources/demos/" + juce::String (lynx::demos::fileName (d)) + " loads and is the generated song",
  30243. loaded.has_value() && lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (lynx::demos::make (d), false));
  30244. }
  30245. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  30246. juce::File (prefix + "-report.txt").replaceWithText (report);
  30247. }
  30248. // --patterns190ea (round 190ea): FL keeps at least one pattern; the engine now does too (AudioEngine::publishSong,
  30249. // Song::keepOnePattern). Before, a Song without a pattern crashed the docked Piano roll's listener.
  30250. bool runPatterns190ea (const juce::String& reportPath)
  30251. {
  30252. namespace st = lynx::simpletracks;
  30253. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30254. lynx::AudioEngine offline (false);
  30255. lynx::MainComponent ui (offline, false);
  30256. ui.setSize (1600, 900);
  30257. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  30258. juce::String report;
  30259. bool ok = true;
  30260. const auto check = [&report, &ok] (const juce::String& what, bool good) {
  30261. report << (good ? "OK " : "ERROR ") << what << "\n";
  30262. ok = ok && good;
  30263. };
  30264. const auto save = [&report, &reportPath] { juce::File (reportPath).replaceWithText (report); };
  30265. const auto settle = [&] { offline.dispatchPendingMessages(); ui.getPianoRollForSnapshot().repaint(); };
  30266. const auto onePattern = [&offline] {
  30267. const auto& s = offline.getSong();
  30268. return s.patterns.size() >= 1 && s.currentPattern >= 0 && s.currentPattern < (int) s.patterns.size();
  30269. };
  30270. // the hand-built songs the engine can be given: none of them has a pattern
  30271. const auto bare = [] {
  30272. lynx::Song s;
  30273. s.mixer = lynx::Song::defaultMixer();
  30274. return s;
  30275. };
  30276. // every way to reach "no pattern" in the current layout
  30277. const auto paths = [&] (const juce::String& where) {
  30278. offline.setSong (bare());
  30279. settle();
  30280. check (where + ": a song without a pattern opens with one empty \"Pattern 1\"",
  30281. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].name == "Pattern 1"
  30282. && offline.getSong().patterns[0].notes.empty());
  30283. offline.editSong ([] (lynx::Song& s) { s.patterns.clear(); });
  30284. settle();
  30285. check (where + ": an edit that clears every pattern leaves one", onePattern());
  30286. offline.editSong ([] (lynx::Song& s) {
  30287. s.patterns.resize (2);
  30288. s.patterns[1].notes.push_back ({});
  30289. s.currentPattern = 1;
  30290. });
  30291. settle();
  30292. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  30293. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  30294. settle();
  30295. check (where + ": deleting the last pattern leaves an empty \"Pattern 1\" (FL's invariant)",
  30296. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].notes.empty());
  30297. for (int k = 0; k < 6; ++k)
  30298. {
  30299. offline.undo();
  30300. settle();
  30301. }
  30302. check (where + ": undo back over those steps keeps a pattern", onePattern());
  30303. for (int k = 0; k < 6; ++k)
  30304. {
  30305. offline.redo();
  30306. settle();
  30307. }
  30308. check (where + ": redo keeps a pattern", onePattern());
  30309. offline.applyRemote (bare());
  30310. settle();
  30311. check (where + ": a live session's remote song without a pattern gets one", onePattern());
  30312. offline.editSong ([] (lynx::Song& s) { s.currentPattern = 99; });
  30313. settle();
  30314. check (where + ": a current pattern out of range is put back in range", onePattern() && offline.getSong().currentPattern == 0);
  30315. };
  30316. // the Simple layout with the Piano roll docked in the Editor tab (round 190dv's crash)
  30317. ui.selectTabForSnapshot (2);
  30318. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  30319. settle();
  30320. auto* simple = ui.getSimpleWorkflowForSnapshot();
  30321. check ("the Simple workflow is up", simple != nullptr);
  30322. if (simple == nullptr)
  30323. {
  30324. save();
  30325. return false;
  30326. }
  30327. simple->hideChooser();
  30328. st::Request q;
  30329. q.kind = st::Kind::instrument;
  30330. q.name = "Keys";
  30331. lynx::ChannelDef synth;
  30332. synth.instrument = lynx::InstrumentKind::synth;
  30333. q.channel = synth;
  30334. q.emptyBars = 4;
  30335. st::Result r;
  30336. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  30337. settle();
  30338. ui.getPlaylistForSnapshot().selectTrack (r.track);
  30339. simple->trackSelected (r.track);
  30340. settle();
  30341. auto* dock = simple->dockForSnapshot();
  30342. check ("the instrument track's dock has the Editor tab", dock != nullptr && dock->hasPlayTabsForCheck());
  30343. if (dock != nullptr)
  30344. dock->setTab (lynx::SimpleDock::Tab::editor);
  30345. settle();
  30346. check ("the Piano roll is docked in the Editor tab", dock != nullptr && dock->isEditorDocked() && dock->isParentOf (&ui.getPianoRollForSnapshot()));
  30347. paths ("Simple, Editor tab");
  30348. // the Pattern layout with the Piano roll panel, then the Clip-launch layout
  30349. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  30350. settle();
  30351. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::pianoRoll });
  30352. settle();
  30353. paths ("Pattern layout, Piano roll");
  30354. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  30355. settle();
  30356. paths ("Clip-launch layout");
  30357. report << (ok ? "RESULT OK\n" : "RESULT FAILED\n");
  30358. save();
  30359. return ok;
  30360. }
  30361. // round 190fo: the Simple layout's Sampler track (16 pads) and a folder of stems and MIDI files, off-screen at 1x and
  30362. // 2x, with a text report of the checks (.lynx round trip, kits, typing keys, the folder import)
  30363. void runReabl190foShot (const juce::String& prefix)
  30364. {
  30365. namespace st = lynx::simpletracks;
  30366. namespace sp = lynx::simplepads;
  30367. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30368. lynx::AudioEngine offline (false);
  30369. lynx::MainComponent ui (offline, false);
  30370. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  30371. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30372. ui.setVisible (true);
  30373. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  30374. const auto file = juce::File (prefix + "-" + name + ".png");
  30375. file.deleteFile();
  30376. juce::FileOutputStream out (file);
  30377. juce::PNGImageFormat().writeImageToStream (image, out);
  30378. };
  30379. juce::String report;
  30380. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  30381. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  30382. ui.selectTabForSnapshot (2);
  30383. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  30384. offline.dispatchPendingMessages();
  30385. auto* simple = ui.getSimpleWorkflowForSnapshot();
  30386. if (simple == nullptr)
  30387. {
  30388. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  30389. return;
  30390. }
  30391. const auto whole = [&] (const juce::String& name) {
  30392. offline.dispatchPendingMessages();
  30393. for (float scale : { 1.0f, 2.0f })
  30394. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
  30395. };
  30396. // the chooser: the Sampler tile (16 pads, "On keys..." for one sample over the keys) and Import's "Folder..."
  30397. simple->showChooser();
  30398. whole ("chooser");
  30399. simple->hideChooser();
  30400. // --- test sounds -------------------------------------------------------------------------------------------------
  30401. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190fo");
  30402. dir.deleteRecursively();
  30403. dir.createDirectory();
  30404. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  30405. juce::AudioBuffer<float> audio (1, frames);
  30406. for (int i = 0; i < frames; ++i)
  30407. audio.setSample (0, i, f (i));
  30408. wav.getParentDirectory().createDirectory();
  30409. juce::WavAudioFormat format;
  30410. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  30411. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  30412. {
  30413. out.release();
  30414. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  30415. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  30416. }
  30417. return wav;
  30418. };
  30419. juce::Random rnd (190);
  30420. const auto pi = juce::MathConstants<double>::pi;
  30421. const auto kick = writeWav (dir.getChildFile ("pads/Kick.wav"), 24000, [pi] (int i) {
  30422. const auto t = i / 48000.0;
  30423. return (float) (0.9 * std::sin (2.0 * pi * (50.0 * t + 60.0 * (1.0 - std::exp (-t * 30.0)) / 30.0)) * std::exp (-t * 7.0));
  30424. });
  30425. const auto snare = writeWav (dir.getChildFile ("pads/Snare.wav"), 14400, [&rnd] (int i) { return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.6f * std::exp (-i / 4000.0f)); });
  30426. const auto hat = writeWav (dir.getChildFile ("pads/Hat.wav"), 4800, [&rnd] (int i) { return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.4f * std::exp (-i / 900.0f)); });
  30427. const auto chord = writeWav (dir.getChildFile ("pads/Chord stab.wav"), 48000, [pi] (int i) {
  30428. const auto t = i / 48000.0;
  30429. double v = 0.0;
  30430. for (int k : { 57, 60, 64 })
  30431. v += std::sin (2.0 * pi * 440.0 * std::pow (2.0, (k - 69) / 12.0) * t);
  30432. return (float) (0.2 * v * std::exp (-t * 2.5));
  30433. });
  30434. const auto vox = writeWav (dir.getChildFile ("pads/Vox hey.wav"), 30000, [pi] (int i) {
  30435. const auto t = i / 48000.0;
  30436. return (float) (0.5 * std::sin (2.0 * pi * 220.0 * t + 2.0 * std::sin (2.0 * pi * 660.0 * t)) * std::sin (pi * t / 0.625));
  30437. });
  30438. // --- the Sampler track ---------------------------------------------------------------------------------------------
  30439. check ("the Sampler tile's track was added", simple->addPads());
  30440. offline.dispatchPendingMessages();
  30441. const auto& song0 = offline.getSong();
  30442. int track = -1;
  30443. for (int t = 0; t < (int) song0.playlistTracks.size() && track < 0; ++t)
  30444. if (st::kindOf (song0, t) == st::Kind::pads)
  30445. track = t;
  30446. check ("a Sampler track with 16 pads", track >= 0 && [&] {
  30447. const auto c = sp::padChannels (song0, track);
  30448. return std::all_of (c.begin(), c.end(), [] (int i) { return i >= 0; });
  30449. }());
  30450. auto* dock = simple->dockForSnapshot();
  30451. if (dock == nullptr || track < 0)
  30452. {
  30453. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock / track\n");
  30454. return;
  30455. }
  30456. simple->trackSelected (track);
  30457. offline.dispatchPendingMessages();
  30458. check ("the dock opens on the Pads tab", dock->hasPadsTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::pads);
  30459. const auto shots = [&] (const juce::String& name) {
  30460. offline.dispatchPendingMessages();
  30461. for (float scale : { 1.0f, 2.0f })
  30462. {
  30463. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  30464. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  30465. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  30466. }
  30467. };
  30468. shots ("pads-empty");
  30469. const juce::File files[] { kick, snare, hat, hat, chord, vox };
  30470. for (int p = 0; p < 6; ++p)
  30471. dock->padsLoadForCheck (p, files[p]);
  30472. offline.dispatchPendingMessages();
  30473. check ("six pads hold a sound", [&] {
  30474. int n = 0;
  30475. for (int p = 0; p < sp::padCount; ++p)
  30476. n += sp::hasSample (offline.getSong(), track, p) ? 1 : 0;
  30477. return n == 6;
  30478. }());
  30479. // pad 3 = the open hat: one-shot, group 1 with pad 2 (closed hat), a colour; pad 4 = the chord, looped and darker
  30480. dock->padsSelectForCheck (2);
  30481. dock->padsModeForCheck (1);
  30482. dock->padsSelectForCheck (3);
  30483. dock->padsModeForCheck (1);
  30484. offline.editSong ([track] (lynx::Song& s) {
  30485. for (int p : { 2, 3 })
  30486. if (const auto c = sp::padChannel (s, track, p); c >= 0)
  30487. {
  30488. s.channels[(std::size_t) c].simplePad.group = 1;
  30489. s.channels[(std::size_t) c].simplePad.colour = 2;
  30490. sp::apply (s.channels[(std::size_t) c], 4800);
  30491. }
  30492. });
  30493. dock->padsSelectForCheck (4);
  30494. dock->padsModeForCheck (2);
  30495. dock->padsKnobForCheck (2, 0.3f); // tone: a low-pass
  30496. dock->padsKnobForCheck (1, 0.35f); // release
  30497. dock->padsRegionForCheck (0.05f, 0.7f);
  30498. dock->padsNormalizeForCheck();
  30499. dock->padsUpdateForCheck();
  30500. {
  30501. const auto& s = offline.getSong();
  30502. const auto& c = s.channels[(std::size_t) sp::padChannel (s, track, 4)];
  30503. line ("pad 5: mode " + juce::String ((int) c.simplePad.mode) + " tone " + juce::String (c.simplePad.tone, 2) + " cutoff " + juce::String (c.sampler.cutoff, 0)
  30504. + " release " + juce::String (c.sampler.release, 3) + " region " + juce::String (c.sampler.regionStart, 2) + "-" + juce::String (c.sampler.regionEnd, 2)
  30505. + " gain " + juce::String (c.sampler.gainDb, 2) + " dB zones " + juce::String ((int) c.zones.size()));
  30506. check ("pad 5 loops its region, darker, normalized", c.simplePad.mode == 2 && c.zones.size() == 1 && c.zones[0].loopMode == 2 && c.simplePad.tone < -0.3f
  30507. && c.sampler.filterType == 0 && c.sampler.cutoff < 5000.0f && c.sampler.gainDb > 0.5f);
  30508. const auto& h = s.channels[(std::size_t) sp::padChannel (s, track, 3)];
  30509. check ("the hats share a choke group of this insert", h.cutGroup > 1000 && h.cutGroup == s.channels[(std::size_t) sp::padChannel (s, track, 2)].cutGroup);
  30510. }
  30511. shots ("pads");
  30512. dock->padsHitForCheck (0);
  30513. dock->lightPad (2);
  30514. shots ("pads-hit");
  30515. // the typing keys: V plays pad 1, M pad 4, 7 pad 16; Z is not a pad key
  30516. check ("typing keys reach the pads", simple->padChannelForKey ('V') == sp::padChannel (offline.getSong(), track, 0)
  30517. && simple->padChannelForKey ('m') == sp::padChannel (offline.getSong(), track, 3)
  30518. && simple->padChannelForKey ('7') == sp::padChannel (offline.getSong(), track, 15)
  30519. && simple->padChannelForKey ('Z') == -1);
  30520. // drag pad 6 (vox) onto the empty pad 9: it moves; Alt-drag pad 1 onto pad 10: a copy
  30521. dock->padsDragForCheck (5, 8, false);
  30522. dock->padsDragForCheck (0, 9, true);
  30523. check ("a pad moved and a pad copied", ! sp::hasSample (offline.getSong(), track, 5) && sp::hasSample (offline.getSong(), track, 8)
  30524. && sp::hasSample (offline.getSong(), track, 9) && sp::hasSample (offline.getSong(), track, 0));
  30525. dock->padsSelectForCheck (4);
  30526. shots ("pads-moved");
  30527. saveMenus ({ "Pad menu", "Colour", "Copy a value to every pad" }, [&] {
  30528. const auto top = dock->padMenuForSnapshot (4);
  30529. std::vector<juce::PopupMenu> menus { top };
  30530. for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
  30531. if (it.getItem().subMenu != nullptr)
  30532. menus.push_back (*it.getItem().subMenu);
  30533. return menus;
  30534. }(), prefix + "-menu-pad.png");
  30535. // kits: saved, the pads cleared, opened again
  30536. const auto kitFile = lynx::platform::documentsFolder().getChildFile ("LYNX/Sampler kits/Test kit 190fo.lynxkit");
  30537. kitFile.deleteFile();
  30538. check ("the pads saved as a kit", dock->saveKitForCheck ("Test kit 190fo") && kitFile.existsAsFile());
  30539. saveMenus ({ "Kit", "My kits" }, [&] {
  30540. const auto top = dock->kitMenuForSnapshot();
  30541. std::vector<juce::PopupMenu> menus { top };
  30542. for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
  30543. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("My kits"))
  30544. menus.push_back (*it.getItem().subMenu);
  30545. return menus;
  30546. }(), prefix + "-menu-kit.png");
  30547. const auto before = offline.getSong().channels;
  30548. offline.editSong ([track] (lynx::Song& s) {
  30549. for (int p = 0; p < sp::padCount; ++p)
  30550. sp::clearPad (s, track, p);
  30551. });
  30552. check ("the kit opens the same pads again", dock->openKitForCheck (kitFile) && [&] {
  30553. const auto& now = offline.getSong().channels;
  30554. for (int p = 0; p < sp::padCount; ++p)
  30555. {
  30556. const auto c = sp::padChannel (offline.getSong(), track, p);
  30557. if (c < 0 || now[(std::size_t) c].samplePath != before[(std::size_t) c].samplePath || now[(std::size_t) c].simplePad != before[(std::size_t) c].simplePad
  30558. || now[(std::size_t) c].sampler.release != before[(std::size_t) c].sampler.release || now[(std::size_t) c].zones != before[(std::size_t) c].zones)
  30559. return false;
  30560. }
  30561. return true;
  30562. }());
  30563. {
  30564. const auto renamed = kitFile.getSiblingFile ("Renamed kit 190fo.lynxkit");
  30565. renamed.deleteFile();
  30566. check ("a kit renamed (and a one-letter name refused)", ! lynx::SimpleDock::renameKitForCheck (kitFile, "x")
  30567. && lynx::SimpleDock::renameKitForCheck (kitFile, "Renamed kit 190fo") && renamed.existsAsFile()
  30568. && ! kitFile.exists());
  30569. renamed.deleteFile();
  30570. }
  30571. kitFile.deleteFile();
  30572. // a beat on the pads (the track's pattern) and the .lynx round trip
  30573. offline.editSong ([track] (lynx::Song& s) {
  30574. const auto pattern = [&] {
  30575. for (const auto& c : s.playlist)
  30576. if (c.track == track && c.kind == lynx::ClipKind::pattern)
  30577. return c.pattern;
  30578. return -1;
  30579. }();
  30580. if (pattern < 0)
  30581. return;
  30582. for (int step = 0; step < 16; ++step)
  30583. {
  30584. const int pad = step % 4 == 0 ? 0 : step % 8 == 4 ? 1 : 2;
  30585. lynx::Note n;
  30586. n.channel = sp::padChannel (s, track, pad);
  30587. n.key = sp::padKey;
  30588. n.start = (std::int64_t) step * lynx::ticksPerStep;
  30589. n.length = lynx::ticksPerStep;
  30590. s.patterns[(std::size_t) pattern].notes.push_back (n);
  30591. }
  30592. });
  30593. {
  30594. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  30595. juce::String error;
  30596. const auto back = lynx::ProjectFile::fromJson (json, error);
  30597. bool same = back.has_value() && back->channels.size() == offline.getSong().channels.size() && st::kindOf (*back, track) == st::Kind::pads;
  30598. for (std::size_t c = 0; same && c < back->channels.size(); ++c)
  30599. {
  30600. const auto& a = back->channels[c];
  30601. const auto& b = offline.getSong().channels[c];
  30602. same = a.simplePad == b.simplePad && a.zones == b.zones && a.cutGroup == b.cutGroup && a.cutBy == b.cutBy && a.samplePath == b.samplePath
  30603. && a.sampler.regionStart == b.sampler.regionStart && a.sampler.release == b.sampler.release && a.sampler.cutoff == b.sampler.cutoff;
  30604. }
  30605. check ("pads, their modes, groups and loops survive .lynx", same);
  30606. lynx::Song plain = lynx::Song::makeDefault();
  30607. check ("a project without pads writes no pad field", ! lynx::ProjectFile::toJson (plain).contains ("simplePad"));
  30608. }
  30609. ui.getPlaylistForSnapshot().selectTrack (track);
  30610. // --- a folder of stems and MIDI files (the other app's "download stems" naming) --------------------------------------
  30611. const auto stems = dir.getChildFile ("My song stems");
  30612. writeWav (stems.getChildFile ("01_Drums.wav"), 96000, [&rnd] (int i) { return (i % 24000) < 2000 ? (rnd.nextFloat() - 0.5f) * 0.8f : 0.0f; });
  30613. writeWav (stems.getChildFile ("02_Bass.wav"), 96000, [pi] (int i) { return (float) (0.3 * std::sin (2.0 * pi * 55.0 * i / 48000.0)); });
  30614. writeWav (stems.getChildFile ("10_Lead Vox.wav"), 96000, [pi] (int i) { return (float) (0.2 * std::sin (2.0 * pi * 330.0 * i / 48000.0)); });
  30615. {
  30616. juce::MidiMessageSequence seq;
  30617. for (int k = 0; k < 8; ++k)
  30618. {
  30619. seq.addEvent (juce::MidiMessage::noteOn (1, 36 + (k % 4) * 3, (juce::uint8) 100), k * 480.0);
  30620. seq.addEvent (juce::MidiMessage::noteOff (1, 36 + (k % 4) * 3), k * 480.0 + 400.0);
  30621. }
  30622. seq.updateMatchedPairs();
  30623. juce::MidiFile midi;
  30624. midi.setTicksPerQuarterNote (960);
  30625. midi.addTrack (seq);
  30626. for (const auto& name : { "02_Bass.mid", "03_Keys.mid" })
  30627. {
  30628. juce::FileOutputStream out (stems.getChildFile (name));
  30629. midi.writeTo (out);
  30630. }
  30631. }
  30632. const auto tracksBefore = [&] {
  30633. int n = 0;
  30634. for (int t = 0; t < (int) offline.getSong().playlistTracks.size(); ++t)
  30635. n += st::kindOf (offline.getSong(), t).has_value() ? 1 : 0;
  30636. return n;
  30637. }();
  30638. simple->addFilesForCheck ({ stems });
  30639. offline.dispatchPendingMessages();
  30640. {
  30641. const auto& s = offline.getSong();
  30642. juce::StringArray names;
  30643. int muted = 0, count = 0;
  30644. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  30645. if (st::kindOf (s, t).has_value())
  30646. {
  30647. ++count;
  30648. if (count > tracksBefore)
  30649. {
  30650. names.add (juce::String::fromUTF8 (s.playlistTracks[(std::size_t) t].name.c_str()) + (s.playlistTracks[(std::size_t) t].muted ? " (muted)" : ""));
  30651. muted += s.playlistTracks[(std::size_t) t].muted ? 1 : 0;
  30652. }
  30653. }
  30654. line ("folder tracks: " + names.joinIntoString (", "));
  30655. check ("the folder gave 5 tracks in number order, named without numbers, the Bass notes muted (its stem plays)",
  30656. names == juce::StringArray { "Drums", "Bass", "Lead Vox", "Bass 2 (muted)", "Keys" } && muted == 1);
  30657. bool atZero = true;
  30658. for (const auto& c : s.playlist)
  30659. if (c.track >= 0 && st::kindOf (s, c.track) == st::Kind::audio)
  30660. atZero = atZero && c.start == 0;
  30661. check ("every stem starts at the song's start", atZero);
  30662. }
  30663. simple->hideChooser();
  30664. whole ("folder-import");
  30665. dir.deleteRecursively();
  30666. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  30667. juce::File (prefix + "-report.txt").replaceWithText (report);
  30668. }
  30669. void runSimple190dsShot (const juce::String& prefix)
  30670. {
  30671. namespace st = lynx::simpletracks;
  30672. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30673. lynx::AudioEngine offline (false);
  30674. lynx::MainComponent ui (offline, false);
  30675. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  30676. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30677. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  30678. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  30679. const auto file = juce::File (prefix + "-" + name + ".png");
  30680. file.deleteFile();
  30681. juce::FileOutputStream out (file);
  30682. juce::PNGImageFormat().writeImageToStream (image, out);
  30683. };
  30684. juce::String report;
  30685. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  30686. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  30687. ui.selectTabForSnapshot (2);
  30688. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  30689. offline.dispatchPendingMessages();
  30690. auto* simple = ui.getSimpleWorkflowForSnapshot();
  30691. if (simple == nullptr)
  30692. {
  30693. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  30694. return;
  30695. }
  30696. simple->hideChooser();
  30697. auto& playlist = ui.getPlaylistForSnapshot();
  30698. // --- three loops: two with their key in the name, one only in its sound ---------------------------------------
  30699. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190ds-loops");
  30700. dir.deleteRecursively();
  30701. dir.createDirectory();
  30702. // a chord loop (two bars at 120 BPM, 48 kHz): each chord's notes with six harmonics, a soft attack per beat
  30703. const auto writeLoop = [&dir] (const juce::String& name, std::vector<std::vector<int>> chords) {
  30704. const int frames = 192000;
  30705. juce::AudioBuffer<float> audio (1, frames);
  30706. audio.clear();
  30707. for (int i = 0; i < frames; ++i)
  30708. {
  30709. const auto& chord = chords[(std::size_t) (i / (frames / (int) chords.size()))];
  30710. const auto t = (double) i / 48000.0;
  30711. const auto beat = std::fmod (t, 0.5);
  30712. double v = 0.0;
  30713. for (const auto key : chord)
  30714. {
  30715. const auto f = 440.0 * std::pow (2.0, (key - 69) / 12.0);
  30716. for (int h = 1; h <= 6; ++h)
  30717. v += std::sin (2.0 * juce::MathConstants<double>::pi * f * h * t) / (h * h);
  30718. }
  30719. audio.setSample (0, i, (float) (0.08 * v * (1.0 - std::exp (-beat * 60.0)) * (0.6 + 0.4 * std::exp (-beat * 3.0))));
  30720. }
  30721. const auto wav = dir.getChildFile (name);
  30722. juce::WavAudioFormat format;
  30723. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  30724. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  30725. {
  30726. out.release();
  30727. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  30728. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  30729. }
  30730. return wav.getFullPathName();
  30731. };
  30732. const auto gMinor = writeLoop ("Night Pad 120 Gm.wav", { { 55, 58, 62 }, { 51, 55, 58 }, { 53, 57, 60 }, { 55, 58, 62 } });
  30733. const auto dMinor = writeLoop ("Pluck_120_D_minor.wav", { { 50, 53, 57 }, { 46, 50, 53 }, { 48, 52, 55 }, { 50, 53, 57 } });
  30734. const auto eMinor = writeLoop ("Warm Keys Loop 120 bpm.wav", { { 52, 55, 59, 64 }, { 48, 52, 55, 60 }, { 50, 54, 57, 62 }, { 52, 55, 59, 64 } });
  30735. lynx::SimpleWorkflow::answerForSnapshot = 1; // "Set the project key to G minor?" — yes
  30736. simple->dropFiles ({ gMinor, dMinor, eMinor }, 0);
  30737. lynx::SimpleWorkflow::answerForSnapshot = -1;
  30738. offline.dispatchPendingMessages();
  30739. simple->hideChooser();
  30740. line ("question: " + simple->lastKeyQuestionForCheck());
  30741. check ("the first keyed loop offered its key (G minor)", simple->lastKeyQuestionForCheck().contains ("G minor"));
  30742. {
  30743. const auto& song = offline.getSong();
  30744. const auto key = lynx::projectkey::get (song);
  30745. check ("the project key is G minor", key && key->root == 7 && lynx::projectkey::isMinor (*key));
  30746. std::vector<int> clips;
  30747. for (int i = 0; i < (int) song.playlist.size(); ++i)
  30748. if (song.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  30749. clips.push_back (i);
  30750. check ("three loop clips", clips.size() == 3);
  30751. const int expect[] { 0, 5, 3 }; // G minor, D minor (F -> Bb: +5), E minor detected (G -> Bb: +3)
  30752. const int roots[] { 7, 2, 4 };
  30753. const int sources[] { 1, 1, 2 };
  30754. for (std::size_t k = 0; k < clips.size() && k < 3; ++k)
  30755. {
  30756. const auto& c = song.playlist[(std::size_t) clips[k]];
  30757. const auto& sampler = song.channels[(std::size_t) c.channel].sampler;
  30758. line ("loop " + juce::String ((int) k + 1) + ": key " + juce::String (sampler.loopKeyRoot) + (sampler.loopKeyMinor ? "m" : "") + " source "
  30759. + juce::String ((int) sampler.loopKeySource) + " follow " + juce::String (c.followKey ? 1 : 0) + " shift " + juce::String ((int) c.keyShift)
  30760. + " pitch " + juce::String (c.pitch));
  30761. check ("loop " + juce::String ((int) k + 1) + " key, source and move", sampler.loopKeyRoot == roots[k] && sampler.loopKeyMinor
  30762. && sampler.loopKeySource == sources[k] && c.followKey
  30763. && c.keyShift == expect[k] && std::abs (c.pitch - (float) expect[k]) < 1.0e-4f);
  30764. }
  30765. }
  30766. // the key changes: every following loop moves with it (one undo step)
  30767. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, lynx::projectkey::Key { 9, lynx::projectkey::commonFirst()[1] }); });
  30768. offline.dispatchPendingMessages();
  30769. {
  30770. const auto& song = offline.getSong();
  30771. std::vector<int> shifts;
  30772. for (const auto& c : song.playlist)
  30773. if (c.kind == lynx::ClipKind::audio)
  30774. shifts.push_back (c.keyShift);
  30775. line ("after A minor: " + juce::String (shifts.size() > 2 ? shifts[0] : 99) + " " + juce::String (shifts.size() > 2 ? shifts[1] : 99) + " "
  30776. + juce::String (shifts.size() > 2 ? shifts[2] : 99));
  30777. check ("A minor: the loops move by +2, -5, +5", shifts == std::vector<int> { 2, -5, 5 });
  30778. }
  30779. // the loop tracks in the dock: the switch and what it does
  30780. int loopTrack = -1;
  30781. for (const auto& c : offline.getSong().playlist)
  30782. if (c.kind == lynx::ClipKind::audio && loopTrack < 0)
  30783. loopTrack = c.track;
  30784. playlist.selectTrack (loopTrack);
  30785. offline.dispatchPendingMessages();
  30786. auto* dock = simple->dockForSnapshot();
  30787. if (dock == nullptr)
  30788. {
  30789. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  30790. return;
  30791. }
  30792. simple->trackSelected (loopTrack);
  30793. offline.dispatchPendingMessages();
  30794. const auto shots = [&] (const juce::String& name) {
  30795. offline.dispatchPendingMessages();
  30796. for (float scale : { 1.0f, 2.0f })
  30797. {
  30798. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  30799. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  30800. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  30801. }
  30802. };
  30803. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  30804. juce::StringArray names { title };
  30805. std::vector<juce::PopupMenu> menus { menu };
  30806. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  30807. if (it.getItem().subMenu != nullptr && it.getItem().text.startsWith (subTitle))
  30808. {
  30809. names.add (subTitle);
  30810. menus.push_back (*it.getItem().subMenu);
  30811. }
  30812. saveMenus (names, menus, prefix + "-" + name + ".png");
  30813. };
  30814. check ("the dock shows the follow switch for the loop track", dock->followShownForCheck());
  30815. shots ("follow-on");
  30816. {
  30817. int clip = -1;
  30818. for (int i = 0; i < (int) offline.getSong().playlist.size() && clip < 0; ++i)
  30819. if (offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  30820. clip = i;
  30821. const auto menu = playlist.getClipMenuForSnapshot (clip);
  30822. bool follow = false, keyItem = false;
  30823. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  30824. {
  30825. follow = follow || (it.getItem().text.startsWith (lynx::tr ("Follow the project key")) && it.getItem().isTicked);
  30826. keyItem = keyItem || it.getItem().text.startsWith (lynx::tr ("Loop key"));
  30827. }
  30828. check ("the clip menu has Follow the project key (ticked) and Loop key", follow && keyItem);
  30829. menuShot (menu, lynx::tr ("Audio clip"), lynx::tr ("Loop key"), "menu-clip-key");
  30830. }
  30831. dock->clickFollowForCheck(); // off: back to its own key
  30832. offline.dispatchPendingMessages();
  30833. {
  30834. float pitch = 99.0f;
  30835. bool following = true;
  30836. for (const auto& c : offline.getSong().playlist)
  30837. if (c.kind == lynx::ClipKind::audio && c.track == loopTrack)
  30838. pitch = c.pitch, following = c.followKey;
  30839. check ("switched off: the loop plays in its own key (pitch 0)", ! following && std::abs (pitch) < 1.0e-6f);
  30840. }
  30841. shots ("follow-off");
  30842. dock->clickFollowForCheck();
  30843. offline.dispatchPendingMessages();
  30844. // --- an instrument track from the tile: a pattern to write into, the Editor tab ------------------------------
  30845. {
  30846. st::Request q;
  30847. q.kind = st::Kind::instrument;
  30848. q.name = "Keys";
  30849. lynx::ChannelDef synth;
  30850. synth.instrument = lynx::InstrumentKind::synth;
  30851. q.channel = synth;
  30852. q.emptyBars = 4;
  30853. st::Result r;
  30854. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  30855. offline.dispatchPendingMessages();
  30856. check ("the new Instrument track has an empty 4-bar pattern on it", r.ok() && r.pattern >= 0
  30857. && st::patternOf (offline.getSong(), r.track) == r.pattern
  30858. && offline.getSong().patterns[(std::size_t) r.pattern].notes.empty());
  30859. // a few notes, as the first clicks would write them (A minor: A C E, then G B D)
  30860. offline.editSong ([r] (lynx::Song& s) {
  30861. auto& p = s.patterns[(std::size_t) r.pattern];
  30862. const int keys[] { 57, 60, 64, 67, 71, 74, 69, 72 };
  30863. for (int i = 0; i < 8; ++i)
  30864. {
  30865. lynx::Note n;
  30866. n.channel = r.channels.front();
  30867. n.key = keys[i];
  30868. n.start = (std::int64_t) (i / 3) * lynx::ppq * 2 + (i % 3 == 0 ? 0 : 0);
  30869. n.length = lynx::ppq * 2;
  30870. n.velocity = 0.8f;
  30871. p.notes.push_back (n);
  30872. }
  30873. p.sortNotes();
  30874. });
  30875. offline.dispatchPendingMessages();
  30876. playlist.selectTrack (r.track);
  30877. simple->trackSelected (r.track);
  30878. offline.dispatchPendingMessages();
  30879. check ("the instrument track has the Keyboard and Editor tabs", dock->hasPlayTabsForCheck());
  30880. dock->setTab (lynx::SimpleDock::Tab::editor);
  30881. offline.dispatchPendingMessages();
  30882. check ("the Piano roll is docked in the Editor tab", dock->isEditorDocked());
  30883. check ("on the track's pattern", offline.getSong().currentPattern == r.pattern);
  30884. ui.getPianoRollForSnapshot().scrollToNotes(); // (done asynchronously when it docks)
  30885. shots ("editor");
  30886. dock->clickFoldForCheck (true); // "Only notes in key"
  30887. check ("Only notes in key folds the rows to A minor", ui.getPianoRollForSnapshot().isFoldedToScale());
  30888. ui.getPianoRollForSnapshot().scrollToNotes();
  30889. shots ("editor-in-key");
  30890. dock->clickFoldForCheck (false);
  30891. // --- the keyboard's modes ------------------------------------------------------------------------------
  30892. auto& keyboard = lynx::scalekeys::current();
  30893. const auto saved = keyboard;
  30894. keyboard = {};
  30895. keyboard.lockToKey = true;
  30896. dock->setTab (lynx::SimpleDock::Tab::keyboard);
  30897. if (auto* panel = dock->keyboardPanelForSnapshot())
  30898. {
  30899. lynx::refreshKeyboardPanel (*panel);
  30900. shots ("keys-locked");
  30901. keyboard.lockToKey = false;
  30902. keyboard.mode = lynx::scalekeys::Mode::scaleKeys;
  30903. lynx::refreshKeyboardPanel (*panel);
  30904. shots ("scale-keys");
  30905. keyboard.mode = lynx::scalekeys::Mode::chordPad;
  30906. keyboard.complexity = lynx::scalekeys::Complexity::seventh;
  30907. keyboard.strumMs = 40;
  30908. lynx::refreshKeyboardPanel (*panel);
  30909. shots ("chord-pad");
  30910. }
  30911. check ("the Keyboard tab shows the keyboard panel", dock->keyboardPanelForSnapshot() != nullptr);
  30912. // the same panel as the Touch keyboard window, each mode with a key / pad held
  30913. for (const auto& [mode, name, pressed] : { std::tuple { lynx::scalekeys::Mode::scaleKeys, juce::String ("window-scale-keys"), 4 },
  30914. std::tuple { lynx::scalekeys::Mode::chordPad, juce::String ("window-chord-pad"), 3 } })
  30915. {
  30916. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, mode, pressed, [ch = r.channels.front()] { return ch; });
  30917. panel->setSize (1100, 260);
  30918. for (float scale : { 1.0f, 2.0f })
  30919. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
  30920. if (mode == lynx::scalekeys::Mode::chordPad)
  30921. menuShot (lynx::chordPadMenuForSnapshot (*panel, 3), lynx::tr ("Edit chord"), lynx::tr ("Chord type"), "menu-chord-edit");
  30922. }
  30923. // the Chord pad on an FL Studio Mobile chord set (the default set's shape: C Dm Em F G Am B° C)
  30924. {
  30925. const auto set = lynx::scalekeys::parseFlmChordSet (R"({"chords":[{"baseNote":0,"extensions":[],"octave":3,"quality":0},{"baseNote":2,"extensions":[],"octave":3,"quality":1},{"baseNote":4,"extensions":[],"octave":3,"quality":1},{"baseNote":5,"extensions":[],"octave":3,"quality":0},{"baseNote":7,"extensions":[],"octave":3,"quality":0},{"baseNote":9,"extensions":[],"octave":3,"quality":1},{"baseNote":11,"extensions":[],"octave":3,"quality":3},{"baseNote":0,"extensions":[],"octave":4,"quality":0}],"rootNote":0})");
  30926. check ("an FLM chord set reads as 8 chords (B diminished)", set.size() == 8 && set[6].quality == 3);
  30927. offline.editSong ([set] (lynx::Song& s) { s.keyboardChords = set; });
  30928. keyboard.projectChords = true;
  30929. keyboard.complexity = lynx::scalekeys::Complexity::triad;
  30930. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, lynx::scalekeys::Mode::chordPad, 5, [ch = r.channels.front()] { return ch; });
  30931. panel->setSize (1100, 260);
  30932. for (float scale : { 1.0f, 2.0f })
  30933. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), juce::String ("window-chord-set") + (scale > 1.0f ? "@2x" : ""));
  30934. }
  30935. // the typing keys in each mode (A minor; Z = the root)
  30936. {
  30937. const auto& song = offline.getSong();
  30938. lynx::scalekeys::Settings s;
  30939. s.mode = lynx::scalekeys::Mode::scaleKeys;
  30940. juce::String z;
  30941. for (const int typed : { 60, 62, 64, 65, 67, 69, 71, 72, 61 })
  30942. {
  30943. const auto n = lynx::scalekeys::typedNotes (song, s, typed, 60);
  30944. z << (n.empty() ? juce::String ("-") : juce::String (n.front())) << " ";
  30945. }
  30946. line ("Scale keys, typing C D E F G A B C C#: " + z);
  30947. check ("Scale keys: the white typing keys play A minor from A", z.trim() == "69 71 72 74 76 77 79 81 -");
  30948. s.mode = lynx::scalekeys::Mode::chordPad;
  30949. s.projectChords = false;
  30950. const auto pad = lynx::scalekeys::typedNotes (song, s, 60, 60);
  30951. check ("Chord pad: Z plays A minor (A C E)", pad == std::vector<int> { 69, 72, 76 });
  30952. }
  30953. keyboard = saved;
  30954. }
  30955. // --- the project round trip --------------------------------------------------------------------------------
  30956. {
  30957. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  30958. juce::String error;
  30959. const auto back = lynx::ProjectFile::fromJson (json, error);
  30960. bool same = back.has_value() && back->keyboardChords == offline.getSong().keyboardChords && back->playlist.size() == offline.getSong().playlist.size();
  30961. for (std::size_t i = 0; same && i < back->playlist.size(); ++i)
  30962. same = back->playlist[i].followKey == offline.getSong().playlist[i].followKey && back->playlist[i].keyShift == offline.getSong().playlist[i].keyShift
  30963. && back->playlist[i].pitch == offline.getSong().playlist[i].pitch;
  30964. for (std::size_t c = 0; same && c < back->channels.size(); ++c)
  30965. same = back->channels[c].sampler.loopKeyRoot == offline.getSong().channels[c].sampler.loopKeyRoot
  30966. && back->channels[c].sampler.loopKeySource == offline.getSong().channels[c].sampler.loopKeySource;
  30967. check ("follow, key moves, loop keys and the chord set survive .lynx", same);
  30968. }
  30969. dir.deleteRecursively();
  30970. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  30971. juce::File (prefix + "-report.txt").replaceWithText (report);
  30972. }
  30973. void runSimple190dgShot (const juce::String& prefix)
  30974. {
  30975. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30976. lynx::AudioEngine offline (false);
  30977. lynx::MainComponent ui (offline, false);
  30978. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  30979. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30980. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  30981. const auto file = juce::File (prefix + "-" + name + ".png");
  30982. file.deleteFile();
  30983. juce::FileOutputStream out (file);
  30984. juce::PNGImageFormat().writeImageToStream (image, out);
  30985. };
  30986. juce::String report;
  30987. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  30988. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  30989. ui.selectTabForSnapshot (2);
  30990. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  30991. offline.dispatchPendingMessages();
  30992. auto* simple = ui.getSimpleWorkflowForSnapshot();
  30993. if (simple == nullptr)
  30994. {
  30995. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  30996. return;
  30997. }
  30998. simple->hideChooser();
  30999. offline.editSong ([] (lynx::Song& s) {
  31000. namespace st = lynx::simpletracks;
  31001. st::Request q;
  31002. q.kind = st::Kind::voice;
  31003. q.name = "Lead vocal";
  31004. st::addTrack (s, q);
  31005. q = {};
  31006. q.kind = st::Kind::instrument;
  31007. q.name = "Keys";
  31008. lynx::ChannelDef keys;
  31009. keys.instrument = lynx::InstrumentKind::synth;
  31010. q.channel = keys;
  31011. st::addTrack (s, q);
  31012. });
  31013. offline.dispatchPendingMessages();
  31014. simple->hideChooser();
  31015. auto& playlist = ui.getPlaylistForSnapshot();
  31016. int voiceTrack = -1, keysTrack = -1;
  31017. {
  31018. const auto& song = offline.getSong();
  31019. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  31020. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  31021. {
  31022. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  31023. voiceTrack = t;
  31024. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  31025. keysTrack = t;
  31026. }
  31027. }
  31028. check ("two Simple tracks (voice, keys)", voiceTrack >= 0 && keysTrack >= 0);
  31029. playlist.selectTrack (voiceTrack);
  31030. offline.dispatchPendingMessages();
  31031. auto* dock = simple->dockForSnapshot();
  31032. if (dock == nullptr)
  31033. {
  31034. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  31035. return;
  31036. }
  31037. const auto shots = [&] (const juce::String& name) {
  31038. offline.dispatchPendingMessages();
  31039. for (float scale : { 1.0f, 2.0f })
  31040. {
  31041. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  31042. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  31043. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  31044. }
  31045. };
  31046. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  31047. juce::StringArray names { title };
  31048. std::vector<juce::PopupMenu> menus { menu };
  31049. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  31050. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  31051. {
  31052. names.add (subTitle);
  31053. menus.push_back (*it.getItem().subMenu);
  31054. }
  31055. saveMenus (names, menus, prefix + "-" + name + ".png");
  31056. };
  31057. const auto insert = dock->insertForCheck();
  31058. // --- every one-knob effect as a card, each at a knob position of its own -------------------------------------
  31059. const float at[] { 0.0f, 0.55f, 0.40f, 0.70f, 0.30f, 0.60f, 0.45f, 0.35f, 0.80f };
  31060. for (int id = 1; id <= lynx::goals::count; ++id)
  31061. dock->addOneKnobForCheck (id);
  31062. offline.dispatchPendingMessages();
  31063. for (int id = 1; id <= lynx::goals::count; ++id)
  31064. dock->turnKnobForCheck (id - 1, at[id]);
  31065. offline.dispatchPendingMessages();
  31066. check ("eight one-knob cards on the insert", dock->cardCountForCheck() == 8 && dock->oneKnobCardsForCheck() == 8);
  31067. {
  31068. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  31069. bool turned = fx.size() == 8;
  31070. for (std::size_t i = 0; turned && i < fx.size(); ++i)
  31071. turned = lynx::goals::active (fx[i]) && std::abs (fx[i].goalAmount - at[i + 1]) < 1.0e-6f;
  31072. check ("each knob wrote its effect's parameters", turned);
  31073. }
  31074. shots ("effects-all");
  31075. offline.dispatchPendingMessages();
  31076. for (int card = 0; card < dock->cardCountForCheck(); ++card)
  31077. {
  31078. const auto area = dock->cardBoundsForSnapshot (card);
  31079. const auto name = juce::String (lynx::goals::name (card + 1)).toLowerCase();
  31080. check ("card " + juce::String (card + 1) + " (" + name + ") is on screen", ! area.isEmpty() && dock->getLocalBounds().contains (area));
  31081. for (float scale : { 1.0f, 2.0f })
  31082. writeImage (dock->createComponentSnapshot (area.expanded (4), true, scale), "card-" + name + (scale > 1.0f ? "@2x" : ""));
  31083. }
  31084. // --- a chain preset with Blend --------------------------------------------------------------------------------
  31085. if (const auto* preset = lynx::chains::find ("Canyon"))
  31086. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  31087. offline.dispatchPendingMessages();
  31088. dock->setBlendForCheck (0.6f);
  31089. offline.dispatchPendingMessages();
  31090. check ("preset Canyon with Blend 60 % (shown as edited)", offline.getSong().mixer[(std::size_t) insert].chainPreset == "Canyon"
  31091. && std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.6f) < 1.0e-6f
  31092. && ! lynx::chains::unchanged (offline.getSong(), insert));
  31093. shots ("effects-preset-blend");
  31094. // favourites: the track's preset starred; the menu lists it first
  31095. const auto favFile = lynx::SimpleDock::favouritesFile();
  31096. const auto hadFavourites = favFile.existsAsFile();
  31097. const auto oldFavourites = favFile.loadFileAsString();
  31098. lynx::SimpleDock::setFavouritePreset ("Canyon", true);
  31099. lynx::SimpleDock::setFavouritePreset ("Clear Voice", true);
  31100. lynx::SimpleDock::setFavouritePreset ("Canyon", true); // (twice: once in the list)
  31101. check ("two favourites kept, in order", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Canyon", "Clear Voice" });
  31102. {
  31103. bool first = false, toggle = false;
  31104. const auto menu = dock->presetMenuForSnapshot();
  31105. juce::PopupMenu::MenuItemIterator it (menu);
  31106. if (it.next())
  31107. first = it.getItem().subMenu != nullptr && it.getItem().text.contains (lynx::tr ("Favourites"));
  31108. for (juce::PopupMenu::MenuItemIterator all (menu); all.next();)
  31109. toggle = toggle || all.getItem().text == lynx::tr ("Remove \"{0}\" from favourites", { "Canyon" });
  31110. check ("the Preset menu starts with the favourites and offers to unstar the track's preset", first && toggle);
  31111. menuShot (menu, lynx::tr ("Preset"), juce::String::fromUTF8 ("\xe2\x98\x85 ") + lynx::tr ("Favourites"), "menu-preset-favourites");
  31112. }
  31113. lynx::SimpleDock::setFavouritePreset ("Canyon", false);
  31114. check ("unstarred", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Clear Voice" });
  31115. if (hadFavourites)
  31116. favFile.replaceWithText (oldFavourites);
  31117. else
  31118. favFile.deleteFile();
  31119. // --- the sound picker: a search, and the installed plugins -----------------------------------------------------
  31120. playlist.selectTrack (keysTrack);
  31121. offline.dispatchPendingMessages();
  31122. check ("the Keys track opens on its sound", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  31123. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::bass);
  31124. dock->setSearchForSnapshot ("sub");
  31125. offline.dispatchPendingMessages();
  31126. line ("search \"sub\" in Bass: " + juce::String (dock->soundRowsForCheck()) + " rows");
  31127. check ("a search narrows the category", dock->soundRowsForCheck() > 0 && dock->soundRowsForCheck() < (int) lynx::soundlib::filter (lynx::soundlib::builtIn(), lynx::soundlib::Category::bass).size());
  31128. shots ("picker-search");
  31129. dock->setSearchForSnapshot ({});
  31130. // a made-up list of installed plugins (nothing is scanned or loaded)
  31131. dock->setPluginsForSnapshot ({ { "VST3-demo-1", "Analog Mono", "Example Audio", "VST3", "Instrument|Synth" },
  31132. { "VST3-demo-2", "Grand Upright", "Example Audio", "VST3", "Instrument|Piano" },
  31133. { "VST3-demo-3", "Beat Kit 808", "Sample Lab", "VST3", "Instrument|Drum" },
  31134. { "CLAP-demo-4", "Orchestra Strings", "Sample Lab", "CLAP", "Instrument|Sampler" },
  31135. { "VST3-demo-5", "Wave Table One", "Example Audio", "VST3", "Instrument|Synth" },
  31136. { "VST-demo-6", "Sub Bass Machine", "Low End", "VST", "Synth" },
  31137. { "VST3-demo-7", "Sample Player", "Sample Lab", "VST3", "Instrument|Sampler" } });
  31138. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::synths);
  31139. offline.dispatchPendingMessages();
  31140. check ("My plugins: the generic synths and samplers in their own category (" + juce::String (dock->soundRowsForCheck()) + " of 7)", dock->soundRowsForCheck() == 3);
  31141. shots ("picker-plugins");
  31142. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  31143. juce::File (prefix + "-report.txt").replaceWithText (report);
  31144. }
  31145. // LYNX --simple190jcshot prefix (round 190jc, design190ia slices 5, 14, 15, 22, 24 + Large controls): the Simple
  31146. // layout's tracks (only real rows, the round "+", M S, type icons, the track-colour volume and clips; muted, soloed,
  31147. // selected), the drop lane idle and lit, the dock (close X, icon tabs, a lone tab, the sound picker, the keyboard's
  31148. // keycaps and octave capsule, effect cards), the pads in all 8 colours (label contrast measured), the chooser,
  31149. // starter beats, Finish, the tour card beside its ring with the beacon (Animations on / off), and Large controls;
  31150. // windows at 1x and 2x, and a text report of the checks
  31151. void runSimple190jcShot (const juce::String& prefix)
  31152. {
  31153. namespace st = lynx::simpletracks;
  31154. namespace sp = lynx::simplepads;
  31155. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31156. lynx::AudioEngine offline (false);
  31157. lynx::MainComponent ui (offline, false);
  31158. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  31159. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  31160. ui.setVisible (true);
  31161. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  31162. const auto file = juce::File (prefix + "-" + name + ".png");
  31163. file.deleteFile();
  31164. juce::FileOutputStream out (file);
  31165. juce::PNGImageFormat().writeImageToStream (image, out);
  31166. };
  31167. juce::String report;
  31168. const auto line = [&report, &prefix] (const juce::String& text) {
  31169. report << text << "\n";
  31170. juce::File (prefix + "-report.txt").replaceWithText (report);
  31171. };
  31172. const auto check = [&line] (const juce::String& what, bool ok) { line ((ok ? "OK " : "ERROR ") + what); };
  31173. const auto settle = [&] {
  31174. for (int k = 0; k < 3; ++k)
  31175. offline.dispatchPendingMessages();
  31176. };
  31177. const auto whole = [&] (const juce::String& name, bool twoX = true) {
  31178. settle();
  31179. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name);
  31180. if (twoX)
  31181. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 2.0f), name + "@2x");
  31182. };
  31183. ui.selectTabForSnapshot (2);
  31184. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  31185. settle();
  31186. auto* simple = ui.getSimpleWorkflowForSnapshot();
  31187. auto& playlist = ui.getPlaylistForSnapshot();
  31188. if (simple == nullptr)
  31189. {
  31190. line ("ERROR no Simple workflow");
  31191. return;
  31192. }
  31193. // an empty project: the drop lane alone, the round "+"
  31194. offline.setSong ([] {
  31195. lynx::Song s;
  31196. s.mixer = lynx::Song::defaultMixer();
  31197. return s;
  31198. }());
  31199. settle();
  31200. simple->hideChooser();
  31201. whole ("empty");
  31202. check ("an empty song shows one row (the drop lane), with the round +", st::rowsShown (offline.getSong(), 500) == 1 && ! playlist.simpleAddButtonForSnapshot().isEmpty());
  31203. // --- sounds ------------------------------------------------------------------------------------------------------
  31204. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190jc");
  31205. dir.deleteRecursively();
  31206. dir.createDirectory();
  31207. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  31208. wav.getParentDirectory().createDirectory();
  31209. juce::AudioBuffer<float> audio (1, frames);
  31210. for (int i = 0; i < frames; ++i)
  31211. audio.setSample (0, i, f (i));
  31212. juce::WavAudioFormat format;
  31213. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  31214. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  31215. {
  31216. out.release();
  31217. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  31218. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  31219. }
  31220. return wav;
  31221. };
  31222. const auto pi = juce::MathConstants<double>::pi;
  31223. juce::Random rnd (190);
  31224. const auto loop = writeWav (dir.getChildFile ("Vocal chop 100.wav"), 230400, [pi] (int i) {
  31225. const auto t = i / 48000.0, inBeat = std::fmod (t, 0.6);
  31226. return (float) (0.7 * std::exp (-inBeat * 5.0) * std::sin (2.0 * pi * 220.0 * t + 1.5 * std::sin (2.0 * pi * 440.0 * t)));
  31227. });
  31228. std::vector<juce::File> padSounds;
  31229. const char* padNames[] { "Kick", "Snare", "Hat", "Clap", "Chord stab", "Vox hey", "Perc", "Bass hit" };
  31230. for (int k = 0; k < 8; ++k)
  31231. padSounds.push_back (writeWav (dir.getChildFile (juce::String ("pads/") + padNames[k] + ".wav"), 12000 + 3000 * k, [&rnd, k] (int i) {
  31232. return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.6f * std::exp (-i / (600.0f + 500.0f * (float) k)));
  31233. }));
  31234. // --- tracks: a voice with a loop, keys with chords, drums, a bass take, a Sampler track --------------------------------
  31235. int vocal = -1, keys = -1, drums = -1, bass = -1;
  31236. offline.editSong ([&] (lynx::Song& s) {
  31237. st::Request q;
  31238. q.kind = st::Kind::audio;
  31239. q.name = "Vocal chop";
  31240. q.audioFile = loop.getFullPathName().toStdString();
  31241. q.audioLength = 8 * lynx::ppq;
  31242. q.audioBeats = 8.0f;
  31243. vocal = st::addTrack (s, q).track;
  31244. q = {};
  31245. q.kind = st::Kind::instrument;
  31246. q.name = "Keys";
  31247. lynx::ChannelDef synth;
  31248. synth.instrument = lynx::InstrumentKind::synth;
  31249. q.channel = synth;
  31250. lynx::Pattern chords;
  31251. for (int i = 0; i < 4; ++i)
  31252. for (int k : { 60, 64, 67 })
  31253. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  31254. q.pattern = chords;
  31255. const auto r = st::addTrack (s, q);
  31256. keys = r.track;
  31257. q = {};
  31258. q.kind = st::Kind::drums;
  31259. q.name = "Drums";
  31260. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  31261. {
  31262. lynx::ChannelDef c;
  31263. c.instrument = kind;
  31264. q.kit.push_back (c);
  31265. }
  31266. lynx::Pattern beat;
  31267. for (int step = 0; step < 16; step += 2)
  31268. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 2, 60 });
  31269. for (int step : { 0, 8 })
  31270. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 0, 60 });
  31271. q.pattern = beat;
  31272. q.fillBars = 4;
  31273. const auto d = st::addTrack (s, q);
  31274. drums = d.track;
  31275. q = {};
  31276. q.kind = st::Kind::bass;
  31277. q.name = "Bass";
  31278. bass = st::addTrack (s, q).track;
  31279. if (r.insert > 0)
  31280. {
  31281. s.mixer[(std::size_t) r.insert].volume = 0.55f;
  31282. s.mixer[(std::size_t) r.insert].pan = -0.4f;
  31283. s.mixer[(std::size_t) r.insert].solo = true;
  31284. }
  31285. if (d.insert > 0)
  31286. s.mixer[(std::size_t) d.insert].muted = true;
  31287. });
  31288. settle();
  31289. check ("the Sampler tile's track was added", simple->addPads());
  31290. settle();
  31291. const auto& song = offline.getSong();
  31292. int pads = -1;
  31293. for (int t = 0; t < (int) song.playlistTracks.size() && pads < 0; ++t)
  31294. if (st::kindOf (song, t) == st::Kind::pads)
  31295. pads = t;
  31296. lynx::ui::WaveformCache::getInstance()->find (loop.getFullPathName(), [&offline, &loop] { return offline.getSampleLibrary().load (loop.getFullPathName()); });
  31297. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  31298. simple->hideChooser();
  31299. playlist.selectTrack (keys);
  31300. settle();
  31301. const auto rows = st::rowsShown (song, 500);
  31302. line ("tracks: vocal " + juce::String (vocal) + " keys " + juce::String (keys) + " drums " + juce::String (drums) + " bass " + juce::String (bass)
  31303. + " pads " + juce::String (pads) + "; rows shown " + juce::String (rows));
  31304. check ("five tracks + the drop lane are the rows shown (no placeholder rows)", rows == 6);
  31305. whole ("tracks");
  31306. {
  31307. // the Simple Playlist's whole paint (its rows only, no placeholder rows): CPU ms per frame
  31308. juce::Image img (juce::Image::ARGB, juce::jmax (1, playlist.getWidth()), juce::jmax (1, playlist.getHeight()), true);
  31309. std::vector<double> ms;
  31310. for (int f = -3; f < 40; ++f)
  31311. {
  31312. const auto t0 = lynx::threadCpuSeconds();
  31313. {
  31314. juce::Graphics g (img);
  31315. playlist.paintEntireComponent (g, true);
  31316. }
  31317. if (f >= 0)
  31318. ms.push_back (1000.0 * (lynx::threadCpuSeconds() - t0));
  31319. }
  31320. std::sort (ms.begin(), ms.end());
  31321. line ("simple playlist " + juce::String (playlist.getWidth()) + "x" + juce::String (playlist.getHeight()) + " whole paint: median "
  31322. + juce::String (ms[ms.size() / 2], 3) + " ms, p90 " + juce::String (ms[ms.size() * 9 / 10], 3) + " ms");
  31323. }
  31324. playlist.setDropLaneHotForSnapshot (true);
  31325. whole ("droplane-hot", false);
  31326. playlist.setDropLaneHotForSnapshot (false);
  31327. // --- the dock ------------------------------------------------------------------------------------------------------
  31328. auto* dock = simple->dockForSnapshot();
  31329. if (dock == nullptr)
  31330. {
  31331. line ("ERROR no dock");
  31332. return;
  31333. }
  31334. const auto dockShots = [&] (const juce::String& name) {
  31335. settle();
  31336. for (float scale : { 1.0f, 2.0f })
  31337. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + (scale > 1.0f ? "@2x" : ""));
  31338. };
  31339. simple->trackSelected (keys);
  31340. dock->setTab (lynx::SimpleDock::Tab::instrument);
  31341. dockShots ("instrument");
  31342. whole ("window-dock-instrument", false);
  31343. dock->showKeyboard();
  31344. dockShots ("keyboard");
  31345. simple->trackSelected (vocal);
  31346. settle();
  31347. check ("an audio track's dock has one tab (drawn as a title)", dock->getTab() == lynx::SimpleDock::Tab::effects);
  31348. dockShots ("audio-lone-tab");
  31349. simple->showEffectsOfInsert (st::insertOf (offline.getSong(), keys));
  31350. dock->addOneKnobForCheck (1);
  31351. dock->addOneKnobForCheck (2);
  31352. dockShots ("effects");
  31353. // --- pads: 8 sounds in the 8 colours --------------------------------------------------------------------------------
  31354. if (pads >= 0)
  31355. {
  31356. simple->trackSelected (pads);
  31357. settle();
  31358. for (int p = 0; p < 8; ++p)
  31359. dock->padsLoadForCheck (p, padSounds[(std::size_t) p]);
  31360. offline.editSong ([pads] (lynx::Song& s) {
  31361. for (int p = 0; p < 8; ++p)
  31362. if (const auto c = sp::padChannel (s, pads, p); c >= 0)
  31363. s.channels[(std::size_t) c].simplePad.colour = (std::uint8_t) (p + 1);
  31364. });
  31365. dock->padsSelectForCheck (4);
  31366. dock->padsUpdateForCheck();
  31367. dockShots ("pads");
  31368. dock->padsHitForCheck (2);
  31369. dockShots ("pads-hit");
  31370. whole ("window-pads", false);
  31371. // the labels' contrast on the 8 colours, unlit and lit (the same colours the page draws)
  31372. static const juce::uint32 palette[] { 0xffe5383b, 0xffe8833a, 0xffe2c044, 0xff5fbf6a, 0xff3fb6b0, 0xff4f8ee0, 0xff9a6fe0, 0xffe06aa8 };
  31373. float worst = 99.0f;
  31374. for (auto argb : palette)
  31375. for (bool lit : { false, true })
  31376. {
  31377. const auto fill = juce::Colour (argb).withMultipliedBrightness (lit ? 1.0f : 0.55f).withMultipliedSaturation (lit ? 1.0f : 0.8f);
  31378. const auto ratio = lynx::ui::simplelook::contrast (lynx::ui::simplelook::inkOn (fill), fill);
  31379. worst = juce::jmin (worst, ratio);
  31380. line ("pad " + juce::String::toHexString ((int) argb).substring (2) + (lit ? " lit " : " unlit") + ": label " + juce::String (ratio, 2) + ":1");
  31381. }
  31382. check ("pad labels >= 4.5:1 on all 8 colours, lit and unlit (worst " + juce::String (worst, 2) + ":1)", worst >= 4.5f);
  31383. }
  31384. // --- chooser, starters, Finish ---------------------------------------------------------------------------------------
  31385. simple->showChooser();
  31386. whole ("chooser");
  31387. simple->showStarterPageForSnapshot();
  31388. whole ("starters");
  31389. simple->hideChooser();
  31390. simple->showFinish();
  31391. whole ("finish");
  31392. simple->hideFinish();
  31393. // --- the tour: the card beside its ring, the beacon with Animations on and off -----------------------------------------
  31394. if (auto* tour = simple->tourForSnapshot())
  31395. {
  31396. simple->showWelcome();
  31397. settle();
  31398. tour->clickForSnapshot ("welcome.tour");
  31399. settle();
  31400. const auto ring = tour->ringForSnapshot();
  31401. const auto card = tour->cardBoundsForSnapshot();
  31402. const auto distance = juce::jmax (0, juce::jmax (card.getY() - ring.getBottom(), ring.getY() - card.getBottom()))
  31403. + juce::jmax (0, juce::jmax (card.getX() - ring.getRight(), ring.getX() - card.getRight()));
  31404. line ("tour step 1: ring " + ring.toString() + " card " + card.toString() + " gap " + juce::String (distance) + " px");
  31405. check ("the card sits beside its ring (<= 24 px)", ! ring.isEmpty() && distance <= 24 && ! card.intersects (ring));
  31406. check ("the beacon pulses after a step change (Animations on)", tour->pulsingForCheck());
  31407. tour->setPulseForSnapshot (0.5f);
  31408. whole ("tour-pulse-on", false);
  31409. lynx::ui::motion::enabled() = false;
  31410. tour->clickForSnapshot ("next");
  31411. settle();
  31412. check ("no pulse timer with Animations off", ! tour->pulsingForCheck());
  31413. tour->setPulseForSnapshot (0.0f);
  31414. whole ("tour-pulse-off", false);
  31415. lynx::ui::motion::enabled() = true;
  31416. tour->clickForSnapshot ("skip");
  31417. settle();
  31418. }
  31419. // --- Large controls ---------------------------------------------------------------------------------------------------
  31420. ui.setSimpleLargeControls (true);
  31421. simple->hideChooser();
  31422. playlist.selectTrack (keys);
  31423. settle();
  31424. whole ("large-tracks", false);
  31425. if (pads >= 0)
  31426. {
  31427. simple->trackSelected (pads);
  31428. dockShots ("large-pads");
  31429. }
  31430. ui.setSimpleLargeControls (false);
  31431. line ("done");
  31432. }
  31433. void runSimpleShot (const juce::String& prefix)
  31434. {
  31435. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31436. lynx::AudioEngine offline (false);
  31437. lynx::MainComponent ui (offline, false);
  31438. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  31439. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  31440. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  31441. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  31442. file.deleteFile();
  31443. juce::FileOutputStream out (file);
  31444. juce::PNGImageFormat().writeImageToStream (image, out);
  31445. };
  31446. const auto write = [&ui, &writeImage] (const char* name) { writeImage (lynx::shot::snapshot (ui), name); };
  31447. // View › Layout style, with its submenu, as it is with `style` chosen
  31448. const auto viewMenu = [&ui] {
  31449. const auto names = ui.getMenuNamesForSnapshot();
  31450. const auto view = names.indexOf (lynx::tr ("View"));
  31451. return ui.getMenuForSnapshot (juce::jmax (0, view));
  31452. };
  31453. const auto saveStyleMenus = [&] (const juce::String& suffix) {
  31454. const auto view = viewMenu();
  31455. juce::StringArray names { lynx::tr ("View") };
  31456. std::vector<juce::PopupMenu> menus { view };
  31457. for (juce::PopupMenu::MenuItemIterator it (view); it.next();)
  31458. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Layout style"))
  31459. {
  31460. names.add (lynx::tr ("Layout style"));
  31461. menus.push_back (*it.getItem().subMenu);
  31462. }
  31463. saveMenus (names, menus, prefix + "-menu-" + suffix + ".png");
  31464. };
  31465. // Settings › General with `style` selected, and its style list
  31466. const auto saveSettings = [&] (lynx::layoutstyle::Style style, const char* name) {
  31467. lynx::SettingsHooks hooks;
  31468. hooks.getGeneral = [style] {
  31469. lynx::GeneralOptions o;
  31470. o.language = lynx::i18n::current();
  31471. o.layoutStyle = (int) style;
  31472. return o;
  31473. };
  31474. auto page = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general, false, hooks);
  31475. const auto image = lynx::shot::paint (*page, lynx::theme::panel, -1, juce::jmin (page->getHeight(), 420));
  31476. writeImage (image, name);
  31477. std::function<juce::ComboBox* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ComboBox* {
  31478. if (c.getComponentID() == "layoutStyle")
  31479. return dynamic_cast<juce::ComboBox*> (&c);
  31480. for (auto* child : c.getChildren())
  31481. if (auto* box = find (*child))
  31482. return box;
  31483. return nullptr;
  31484. };
  31485. if (auto* box = find (*page); box != nullptr && box->getRootMenu() != nullptr)
  31486. saveMenus (juce::StringArray { lynx::tr ("Layout style") }, std::vector<juce::PopupMenu> { *box->getRootMenu() },
  31487. prefix + "-" + name + "-list.png");
  31488. };
  31489. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  31490. ui.selectTabForSnapshot (2); // the Playlist panel, maximized (as --gridshot)
  31491. write ("pattern");
  31492. saveStyleMenus ("pattern");
  31493. saveSettings (lynx::layoutstyle::Style::pattern, "settings-pattern");
  31494. const auto madePattern = lynx::SimpleWorkflow::instances.load();
  31495. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  31496. saveStyleMenus ("cliplaunch");
  31497. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  31498. offline.dispatchPendingMessages();
  31499. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  31500. simple->showChooser(); // (an empty project opens on it by itself; the offline project may hold the default song)
  31501. write ("simple"); // the New track chooser (slice S3)
  31502. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  31503. {
  31504. simple->showStarterPageForSnapshot();
  31505. write ("simple-starter");
  31506. simple->hideChooser();
  31507. write ("simple-closed");
  31508. // round 190p: a loop keeps time. Two files with the same 4.8 s of audio dropped on the empty Simple timeline:
  31509. // "Guitar loop 100.wav" (2 bars at 100 BPM) lasts 2 bars at the project's tempo, "Guitar take.wav" plays at
  31510. // its own speed. Both are undone again, so the shots after this one are as they were.
  31511. {
  31512. const auto folder = juce::File (prefix + "-loops");
  31513. folder.createDirectory();
  31514. juce::StringArray files;
  31515. for (const auto* name : { "Guitar loop 100.wav", "Guitar take.wav" })
  31516. {
  31517. const auto file = folder.getChildFile (name);
  31518. file.deleteFile();
  31519. const auto rate = 44100.0;
  31520. const auto frames = (int) (4.8 * rate);
  31521. juce::AudioBuffer<float> audio (1, frames);
  31522. for (int i = 0; i < frames; ++i)
  31523. {
  31524. const auto t = (double) i / rate, inBeat = std::fmod (t, 0.6); // a plucked note on every beat at 100 BPM
  31525. audio.setSample (0, i, (float) (0.7 * std::exp (-inBeat * 7.0) * std::sin (juce::MathConstants<double>::twoPi * 196.0 * t)));
  31526. }
  31527. if (auto out = file.createOutputStream())
  31528. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0)))
  31529. {
  31530. out.release();
  31531. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  31532. }
  31533. files.add (file.getFullPathName());
  31534. }
  31535. simple->dropFiles (files, 0);
  31536. offline.dispatchPendingMessages();
  31537. // the clips' waveforms are analysed in the background and drawn once ready (a live window repaints by
  31538. // itself; one off-screen paint came too early and showed empty clips)
  31539. for (const auto& path : files)
  31540. lynx::ui::WaveformCache::getInstance()->find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  31541. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  31542. offline.dispatchPendingMessages();
  31543. write ("simple-loop");
  31544. const auto& song = offline.getSong();
  31545. juce::String report;
  31546. for (const auto& clip : song.playlist)
  31547. if (clip.kind == lynx::ClipKind::audio)
  31548. report << song.channels[(std::size_t) clip.channel].name << ": " << juce::String ((double) clip.length / lynx::ppq, 3) << " beats, stretch "
  31549. << juce::String (song.channels[(std::size_t) clip.channel].sampler.stretchBeats, 2) << "\n";
  31550. juce::File (prefix + "-loop.txt").replaceWithText ("tempo " + juce::String (song.bpm, 1) + "\n" + report);
  31551. for (int i = 0; i < files.size() && offline.canUndo(); ++i) // (one undo step per dropped file)
  31552. offline.undo();
  31553. offline.dispatchPendingMessages();
  31554. simple->hideChooser();
  31555. }
  31556. // round 190t, slice A: one click on a starter beat adds it, placed for four bars (undone again)
  31557. {
  31558. const auto clipsBefore = offline.getSong().playlist.size();
  31559. const auto tempoBefore = offline.getSong().bpm;
  31560. simple->clickStarterForSnapshot (1);
  31561. offline.dispatchPendingMessages();
  31562. write ("simple-starter-added");
  31563. const auto& song = offline.getSong();
  31564. juce::String report ("tempo " + juce::String (tempoBefore, 1) + " -> " + juce::String (song.bpm, 1) + "\n");
  31565. for (auto i = clipsBefore; i < song.playlist.size(); ++i)
  31566. report << "clip at beat " << juce::String ((double) song.playlist[i].start / lynx::ppq, 2) << ", " << juce::String ((double) song.playlist[i].length / lynx::ppq, 2)
  31567. << " beats, pattern " << song.playlist[i].pattern << ", track " << song.playlist[i].track << "\n";
  31568. juce::File (prefix + "-starter.txt").replaceWithText (report);
  31569. if (song.playlist.size() > clipsBefore && offline.canUndo())
  31570. offline.undo();
  31571. offline.dispatchPendingMessages();
  31572. simple->hideChooser();
  31573. }
  31574. // slice S4: the Simple headers with a few tracks (voice, instrument, drums, an audio file), some levels moved
  31575. offline.editSong ([] (lynx::Song& s) {
  31576. namespace st = lynx::simpletracks;
  31577. st::Request q;
  31578. q.kind = st::Kind::voice;
  31579. q.name = "Lead vocal";
  31580. st::addTrack (s, q);
  31581. q = {};
  31582. q.kind = st::Kind::instrument;
  31583. q.name = "Keys";
  31584. lynx::ChannelDef keys;
  31585. keys.instrument = lynx::InstrumentKind::synth;
  31586. q.channel = keys;
  31587. lynx::Pattern chords;
  31588. for (int i = 0; i < 4; ++i)
  31589. for (int k : { 60, 64, 67 })
  31590. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  31591. q.pattern = chords;
  31592. const auto r = st::addTrack (s, q);
  31593. q = {};
  31594. q.kind = st::Kind::drums;
  31595. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  31596. {
  31597. lynx::ChannelDef c;
  31598. c.instrument = kind;
  31599. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  31600. q.kit.push_back (c);
  31601. }
  31602. lynx::Pattern beat;
  31603. const auto hit = [&beat] (int step, int row) { beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, row, 60 }); };
  31604. for (int step = 0; step < 16; step += 2)
  31605. hit (step, 2); // hats on the 8ths, kick on 1 and 3, snare on 2 and 4
  31606. for (int step : { 0, 8 })
  31607. hit (step, 0);
  31608. for (int step : { 4, 12 })
  31609. hit (step, 1);
  31610. q.pattern = beat;
  31611. q.bpm = 96.0;
  31612. st::addTrack (s, q);
  31613. if (r.insert > 0)
  31614. {
  31615. s.mixer[(std::size_t) r.insert].volume = 0.55f;
  31616. s.mixer[(std::size_t) r.insert].pan = -0.4f;
  31617. s.mixer[(std::size_t) r.insert].solo = true;
  31618. }
  31619. });
  31620. offline.dispatchPendingMessages();
  31621. ui.getPlaylistForSnapshot().selectTrack (1);
  31622. write ("simple-tracks");
  31623. // round 190t, slice E: the backup status beside the title tools, in each of its states
  31624. {
  31625. const auto now = juce::Time::currentTimeMillis();
  31626. juce::String states;
  31627. int n = 0;
  31628. for (const auto& text : { lynx::MainComponent::simpleSaveStatusText (true, false, 0, now), lynx::MainComponent::simpleSaveStatusText (true, false, now - 5000, now),
  31629. lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now), lynx::MainComponent::simpleSaveStatusText (false, true, 0, now),
  31630. lynx::MainComponent::simpleSaveStatusText (false, false, 0, now) })
  31631. {
  31632. simple->setStatusForSnapshot (text);
  31633. offline.dispatchPendingMessages();
  31634. states << n << ": " << text << "\n";
  31635. // (round 190oo, CS-32: the status is the top bar's since round 190iv: its rows 0..74, not the title band)
  31636. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 74))),
  31637. ("status-" + juce::String (n++)).toRawUTF8());
  31638. }
  31639. juce::File (prefix + "-status.txt").replaceWithText (states);
  31640. simple->setStatusForSnapshot (lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now));
  31641. offline.dispatchPendingMessages();
  31642. write ("simple-status");
  31643. }
  31644. // round 190oo (design review 2): the top bar while the transport plays (CS-35: Play shows BandLab's Pause,
  31645. // Back-to-start becomes Stop; the offline engine does not play, so the main window's states are driven), and
  31646. // the LYNX extra O-4 (the project's name centred at the top, "Untitled" while it has none) at this size and at
  31647. // 1280 px, then off again
  31648. {
  31649. const auto topBar = [&ui] { return ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 80)); };
  31650. const auto nameWas = std::exchange (lynx::ui::simplelook::projectNameShown(), false); // (round 190qk: on by default)
  31651. ui.resized();
  31652. ui.transportForSnapshot (true, false);
  31653. writeImage (lynx::shot::snapshot (ui, topBar()), "topbar-playing");
  31654. ui.transportForSnapshot (false, false);
  31655. writeImage (lynx::shot::snapshot (ui, topBar()), "topbar-stopped");
  31656. lynx::ui::simplelook::projectNameShown() = true;
  31657. ui.resized();
  31658. writeImage (lynx::shot::snapshot (ui, topBar()), "topbar-project-name");
  31659. const auto wide = ui.getWidth(), tall = ui.getHeight();
  31660. ui.setSize (1280, tall);
  31661. offline.dispatchPendingMessages();
  31662. writeImage (lynx::shot::snapshot (ui, topBar()), "topbar-project-name-1280");
  31663. ui.setSize (wide, tall);
  31664. lynx::ui::simplelook::projectNameShown() = nameWas;
  31665. ui.resized();
  31666. offline.dispatchPendingMessages();
  31667. }
  31668. // slice S8: the Finish dock, empty, then with a look on the Master (Balanced, Normal, a little Tone)
  31669. simple->showFinish();
  31670. offline.dispatchPendingMessages();
  31671. write ("simple-finish-empty");
  31672. offline.editSongStructural ([] (lynx::Song& s) { lynx::looks::apply (s, lynx::MasterLookSettings { lynx::looks::balanced, 0.5f, { 1.5f, 0.0f, 1.0f }, -3.0f }); });
  31673. offline.dispatchPendingMessages();
  31674. simple->showFinish();
  31675. write ("simple-finish");
  31676. simple->hideFinish();
  31677. }
  31678. saveStyleMenus ("simple");
  31679. saveSettings (lynx::layoutstyle::Style::simple, "settings-simple");
  31680. // round 184a S11: the Key panel (no key, then an A minor riff and its guesses) and its menu
  31681. const auto toolbarShot = [&] (const char* name) {
  31682. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 80))), name);
  31683. };
  31684. toolbarShot ("key-none");
  31685. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-empty.png");
  31686. offline.editSong ([] (lynx::Song& s) {
  31687. if (s.channels.empty())
  31688. s.channels.resize (1);
  31689. if (s.patterns.empty())
  31690. s.patterns.emplace_back();
  31691. int t = 0;
  31692. for (int k : { 57, 60, 64, 67, 69, 67, 64, 60, 57, 59, 60, 62, 64, 62, 60, 59, 57, 57, 64, 45 })
  31693. {
  31694. lynx::Note n;
  31695. n.channel = 0;
  31696. n.key = k;
  31697. n.start = t * lynx::ppq / 2;
  31698. n.length = k == 57 || k == 45 ? lynx::ppq : lynx::ppq / 2;
  31699. s.patterns[0].notes.push_back (n);
  31700. ++t;
  31701. }
  31702. });
  31703. offline.dispatchPendingMessages();
  31704. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-guess.png");
  31705. const auto guesses = lynx::keyguess::guess (offline.getSong(), 3);
  31706. if (! guesses.empty())
  31707. offline.editSong ([k = guesses[0].key] (lynx::Song& s) { lynx::projectkey::set (s, k); });
  31708. offline.dispatchPendingMessages();
  31709. toolbarShot ("key-set");
  31710. write ("simple-key");
  31711. juce::String keyCounts;
  31712. for (const auto& g : guesses)
  31713. keyCounts << "guess " << lynx::projectkey::name (g.key) << " " << g.notesInScale << "/" << g.notes << " score " << g.score << "\n";
  31714. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, std::nullopt); });
  31715. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  31716. offline.dispatchPendingMessages();
  31717. toolbarShot ("key-pattern-toolbar");
  31718. write ("pattern-after");
  31719. // round 184a S17: the setup wizard with its Workflow choice — a first start (Pattern selected), then reopened in Simple
  31720. for (int style : { 0, 2 })
  31721. {
  31722. auto wizard = lynx::makeSetupWizardContent (offline, {}, {}, style, {});
  31723. auto image = lynx::shot::paint (*wizard);
  31724. writeImage (image, style == 0 ? "wizard-pattern" : "wizard-simple");
  31725. }
  31726. juce::File (prefix + "-counts.txt").replaceWithText ("simple workflows before " + juce::String (madeBefore) + ", in pattern workflow "
  31727. + juce::String (madePattern) + ", after " + juce::String (lynx::SimpleWorkflow::instances.load())
  31728. + "\nstyle after " + lynx::layoutstyle::id (ui.getLayoutStyle()) + "\n" + keyCounts);
  31729. }
  31730. void runLiveRackShot190hr (const juce::String& prefix)
  31731. {
  31732. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31733. lynx::AudioEngine offline (false);
  31734. lynx::MainComponent ui (offline, false);
  31735. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  31736. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  31737. const auto write = [&prefix, &ui, &offline] (const char* name) {
  31738. offline.dispatchPendingMessages();
  31739. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  31740. file.deleteFile();
  31741. juce::FileOutputStream out (file);
  31742. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  31743. };
  31744. const auto writeView = [&prefix] (juce::Component& c, const char* name) {
  31745. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  31746. file.deleteFile();
  31747. juce::FileOutputStream out (file);
  31748. juce::PNGImageFormat().writeImageToStream (lynx::shot::paint (c, lynx::theme::panel), out);
  31749. };
  31750. juce::String checks;
  31751. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  31752. const auto itemEnabled = [] (const juce::PopupMenu& menu, const juce::String& start) {
  31753. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  31754. if (it.getItem().text.startsWith (start))
  31755. return it.getItem().isEnabled ? 1 : 0;
  31756. return -1;
  31757. };
  31758. ui.setVisible (true);
  31759. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  31760. ui.setClipLaunchWorkflow (true);
  31761. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  31762. offline.editSong ([] (lynx::Song& s) {
  31763. if (s.channels.size() < 1)
  31764. s.channels.resize (1);
  31765. s.channels[0].name = "Lead";
  31766. s.channels[0].instrument = lynx::InstrumentKind::synth;
  31767. s.channels[0].mixerTrack = 2;
  31768. if (s.mixer.size() < 4)
  31769. s.mixer.resize (4);
  31770. s.mixer[2].name = "Lead";
  31771. s.mixer[2].effects.clear();
  31772. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::delay })
  31773. s.mixer[2].effects.push_back (lynx::makeEffectSlot (kind));
  31774. while (s.patterns.size() < 1)
  31775. s.patterns.emplace_back();
  31776. lynx::Note note;
  31777. note.channel = 0;
  31778. note.key = 60;
  31779. s.patterns[0].notes = { note };
  31780. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  31781. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  31782. s.playlistTracks[1].name = "Lead";
  31783. lynx::Clip clip;
  31784. clip.pattern = 0;
  31785. clip.length = 4 * lynx::ppq;
  31786. lynx::launcher::setClip (s, 1, 0, clip);
  31787. }, false);
  31788. offline.dispatchPendingMessages();
  31789. auto* detail = ui.getDetailViewForSnapshot();
  31790. if (detail == nullptr)
  31791. {
  31792. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  31793. return;
  31794. }
  31795. detail->showSelection (1, 0);
  31796. detail->setPage (lynx::DetailView::Page::devices);
  31797. detail->selectCardForCheck (0); // the instrument
  31798. write ("01-devices");
  31799. auto menu = detail->cardMenuForSnapshot (0);
  31800. saveMenus (juce::StringArray { "Instrument" }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-instrument-menu.png");
  31801. check ("instrument menu: Group on, Ungroup off", itemEnabled (menu, lynx::tr ("Group")) == 1 && itemEnabled (menu, lynx::tr ("Ungroup")) == 0);
  31802. // Ctrl+G: the synth into an Instrument Rack (the card becomes the rack's)
  31803. check ("Ctrl+G groups the instrument into an Instrument Rack", detail->groupCardForCheck (0, false));
  31804. const auto& grouped = offline.getSong().channels[0];
  31805. check ("the channel keeps its insert and the rack holds the synth",
  31806. grouped.mixerTrack == 2 && lynx::rack::isRack (grouped) && lynx::rack::rackOf (grouped.patcher)->kind == lynx::RackDoc::Kind::instrument
  31807. && lynx::rack::devices (*lynx::rack::rackOf (grouped.patcher), 0).size() == 1);
  31808. detail->selectCardForCheck (0);
  31809. write ("03-grouped");
  31810. menu = detail->cardMenuForSnapshot (0);
  31811. saveMenus (juce::StringArray { "Instrument Rack" }, std::vector<juce::PopupMenu> { menu }, prefix + "-04-rack-menu.png");
  31812. check ("rack menu: Ungroup on, Save as Live rack preset", itemEnabled (menu, lynx::tr ("Ungroup")) == 1
  31813. && itemEnabled (menu, lynx::tr ("Save as Live rack preset (.adg)...")) == 1);
  31814. check ("Ctrl+Shift+G ungroups it", detail->groupCardForCheck (0, true) && offline.getSong().channels[0].instrument == lynx::InstrumentKind::synth);
  31815. write ("05-ungrouped");
  31816. // a rack's view: Live's Save Preset button at the foot of the strip, the drop area
  31817. offline.editSong ([] (lynx::Song& s) {
  31818. auto rack = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  31819. lynx::rack::rackOf (rack.patcher)->showDevices = true;
  31820. s.mixer[3].effects = { rack };
  31821. }, false);
  31822. offline.dispatchPendingMessages();
  31823. {
  31824. auto view = lynx::RackWindows::makeSlotView (offline, 3, 0, true);
  31825. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  31826. writeView (*view, "06-rack-empty");
  31827. lynx::PatchNode fx;
  31828. fx.effect = lynx::makeEffectSlot (lynx::EffectKind::delay);
  31829. const juce::Point<int> inDevices { view->getWidth() - 30, view->getHeight() / 2 };
  31830. check ("an effect dropped on the chain goes in", view->dropNodeForCheck (fx, inDevices));
  31831. lynx::PatchNode synth;
  31832. synth.generator = true;
  31833. synth.channel.instrument = lynx::InstrumentKind::synth;
  31834. check ("an instrument dropped on an Audio Effect Rack is refused", ! view->dropNodeForCheck (synth, inDevices));
  31835. const auto* r = lynx::rack::rackOf (offline.getSong().mixer[3].effects[0].patcher);
  31836. check ("the chain holds one device", r != nullptr && lynx::rack::devices (*r, 0).size() == 1);
  31837. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  31838. writeView (*view, "07-rack-after-drop");
  31839. // the rack as a Live preset and back
  31840. const auto out = lynx::exportLiveRackPreset (offline.getSong().mixer[3].effects[0].patcher, "Shot Rack");
  31841. check ("Save as .adg writes Live's preset form", out.xml.find ("<GroupDevicePreset>") != std::string::npos
  31842. && out.xml.find ("<AudioEffectBranchPreset ") != std::string::npos);
  31843. const auto back = lynx::importLiveDevicePreset (out.bytes);
  31844. check ("the .adg reads back as the rack", back.has_value() && lynx::rack::isRack (back->slot)
  31845. && lynx::rack::rackOf (back->slot.patcher)->chains.size() == 1);
  31846. }
  31847. // Live's own .adg (Core Library, read-only): before round 190hr it opened without chains
  31848. const juce::File live ("C:/ProgramData/Ableton/Live 12 Trial/Resources/Core Library/Racks/Audio Effect Racks/Distortion/Smokey Water.adg");
  31849. const juce::File liveWsl ("/mnt/c/ProgramData/Ableton/Live 12 Trial/Resources/Core Library/Racks/Audio Effect Racks/Distortion/Smokey Water.adg");
  31850. const auto adg = live.existsAsFile() ? live : liveWsl;
  31851. if (adg.existsAsFile())
  31852. {
  31853. juce::MemoryBlock data;
  31854. adg.loadFileAsData (data);
  31855. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  31856. auto p = lynx::importLiveDevicePreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()));
  31857. check ("Live's Smokey Water.adg opens with its chain and devices", p.has_value() && lynx::rack::isRack (p->slot)
  31858. && ! lynx::rack::rackOf (p->slot.patcher)->chains.empty()
  31859. && lynx::rack::devices (*lynx::rack::rackOf (p->slot.patcher), 0).size() >= 3);
  31860. if (p)
  31861. {
  31862. lynx::rack::rackOf (p->slot.patcher)->showDevices = true;
  31863. lynx::rack::rackOf (p->slot.patcher)->showChains = true;
  31864. offline.editSong ([slot = p->slot] (lynx::Song& s) { s.mixer[3].effects = { slot }; }, false);
  31865. offline.dispatchPendingMessages();
  31866. auto view = lynx::RackWindows::makeSlotView (offline, 3, 0, true);
  31867. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  31868. writeView (*view, "08-live-adg-smokey-water");
  31869. }
  31870. }
  31871. else
  31872. checks << "skip Live's Core Library is not on this machine\n";
  31873. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  31874. }
  31875. void runHelixShot190ja (const juce::String& prefix, const juce::String& preset)
  31876. {
  31877. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31878. lynx::AudioEngine offline (false);
  31879. lynx::MainComponent ui (offline, false);
  31880. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  31881. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  31882. juce::String checks;
  31883. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  31884. const auto write = [&prefix, &ui, &offline] (const char* name) {
  31885. offline.dispatchPendingMessages();
  31886. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  31887. file.deleteFile();
  31888. juce::FileOutputStream out (file);
  31889. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  31890. };
  31891. // the Helix channel: Helix's defaults, or a Live Wavetable preset's values through the .als import's own mapping
  31892. lynx::ChannelDef helix;
  31893. helix.instrument = lynx::InstrumentKind::helix;
  31894. helix.name = "Helix";
  31895. if (preset.isNotEmpty())
  31896. {
  31897. juce::MemoryBlock raw;
  31898. juce::File (preset).loadFileAsData (raw);
  31899. juce::MemoryInputStream in (raw, false);
  31900. juce::GZIPDecompressorInputStream gz (&in, false, juce::GZIPDecompressorInputStream::gzipFormat);
  31901. const auto text = juce::File (preset).getFileExtension() == ".adv" ? gz.readEntireStreamAsString() : juce::String();
  31902. lynx::xml::Document doc;
  31903. lynx::alsdev::Notes notes;
  31904. const auto parsed = doc.parse (text.toStdString());
  31905. auto device = parsed ? doc.root().child ("InstrumentVector") : lynx::xml::Element();
  31906. check ("preset read: " + preset, parsed && (bool) device && lynx::alsdev::wavetableToHelix (device, helix, notes));
  31907. helix.name = juce::File (preset).getFileNameWithoutExtension().toStdString();
  31908. }
  31909. ui.setVisible (true);
  31910. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  31911. ui.setClipLaunchWorkflow (true);
  31912. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  31913. offline.editSong ([&helix] (lynx::Song& s) {
  31914. if (s.channels.empty())
  31915. s.channels.resize (1);
  31916. helix.mixerTrack = s.channels[0].mixerTrack;
  31917. s.channels[0] = helix;
  31918. while (s.patterns.empty())
  31919. s.patterns.emplace_back();
  31920. lynx::Note note;
  31921. note.channel = 0;
  31922. note.key = 60;
  31923. s.patterns[0].name = "Chords";
  31924. s.patterns[0].notes = { note };
  31925. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  31926. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  31927. s.playlistTracks[0].name = helix.name;
  31928. lynx::Clip clip;
  31929. clip.pattern = 0;
  31930. clip.length = 4 * lynx::ppq;
  31931. lynx::launcher::setClip (s, 0, 0, clip);
  31932. }, false);
  31933. offline.dispatchPendingMessages();
  31934. auto* detail = ui.getDetailViewForSnapshot();
  31935. check ("detail view", detail != nullptr);
  31936. if (detail != nullptr)
  31937. {
  31938. detail->showSelection (0, 0);
  31939. detail->setPage (lynx::DetailView::Page::devices);
  31940. offline.dispatchPendingMessages();
  31941. write ("01-device");
  31942. struct View
  31943. {
  31944. const char* name;
  31945. int modTab, source, osc;
  31946. };
  31947. for (const auto v : { View { "02-matrix", 1, 0, 0 }, View { "03-midi", 2, 0, 0 }, View { "04-mpe", 3, 0, 0 }, View { "05-env2", 0, 1, 0 },
  31948. View { "06-lfo1", 0, 3, 0 }, View { "07-osc2", 0, 0, 1 } })
  31949. {
  31950. check (juce::String ("Helix card shown for ") + v.name, lynx::helixcards::showView (*detail, v.modTab, v.source, v.osc) > 0);
  31951. write (v.name);
  31952. }
  31953. lynx::helixcards::showView (*detail, 0, 0, 0);
  31954. }
  31955. // the Pattern layout: the channel window's page alone
  31956. {
  31957. auto page = lynx::makeHelixEditor (offline, [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; }, 0);
  31958. const auto file = lynx::shot::file (juce::File (prefix + "-10-window.png"));
  31959. file.deleteFile();
  31960. juce::FileOutputStream out (file);
  31961. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*page), out);
  31962. check ("channel window page", page->getWidth() > 0);
  31963. }
  31964. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  31965. }
  31966. void runHelixShot190oc (const juce::String& prefix)
  31967. {
  31968. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31969. lynx::AudioEngine offline (false);
  31970. juce::String checks;
  31971. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  31972. const auto& bank = lynx::banks::bankOf (lynx::InstrumentKind::helix);
  31973. const auto load = [&] (const juce::String& name) {
  31974. int index = -1;
  31975. for (int b = 0; b < (int) bank.size(); ++b)
  31976. if (juce::String (bank[(std::size_t) b].name) == name)
  31977. index = b;
  31978. check ("preset " + name, index >= 0);
  31979. offline.editSong ([index] (lynx::Song& s) {
  31980. if (s.channels.empty())
  31981. s.channels.resize (1);
  31982. lynx::ChannelDef c;
  31983. c.instrument = lynx::InstrumentKind::helix;
  31984. c.name = "Helix";
  31985. c.mixerTrack = s.channels[0].mixerTrack;
  31986. if (auto loaded = lynx::banks::withPreset (c, std::max (index, 0)))
  31987. c = *loaded;
  31988. s.channels[0] = c;
  31989. }, false);
  31990. offline.dispatchPendingMessages();
  31991. };
  31992. const auto locate = [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; };
  31993. const auto save = [&prefix, &offline] (juce::Component& c, const char* name) {
  31994. offline.dispatchPendingMessages();
  31995. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  31996. file.deleteFile();
  31997. juce::FileOutputStream out (file);
  31998. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  31999. };
  32000. const auto paintCost = [&checks] (juce::Component& c, const char* what) {
  32001. double best = 1.0e9;
  32002. for (int run = 0; run < 3; ++run)
  32003. {
  32004. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  32005. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  32006. for (int f = 0; f < 30; ++f)
  32007. {
  32008. juce::Graphics g (image);
  32009. c.paintEntireComponent (g, false);
  32010. }
  32011. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 30.0);
  32012. }
  32013. checks << "paint " << what << " " << juce::String (best, 3) << " ms per frame (" << c.getWidth() << " x " << c.getHeight() << ")\n";
  32014. };
  32015. // each part of a window alone (the strip, the device), its paint cost
  32016. const auto parts = [&checks] (juce::Component& page) {
  32017. for (int i = 0; i < page.getNumChildComponents(); ++i)
  32018. {
  32019. auto* child = page.getChildComponent (i);
  32020. juce::Image image (juce::Image::ARGB, std::max (1, child->getWidth()), std::max (1, child->getHeight()), true);
  32021. double best = 1.0e9;
  32022. for (int run = 0; run < 3; ++run)
  32023. {
  32024. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  32025. for (int f = 0; f < 10; ++f)
  32026. {
  32027. juce::Graphics g (image);
  32028. child->paintEntireComponent (g, false);
  32029. }
  32030. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 10.0);
  32031. }
  32032. checks << " part " << juce::String (best, 3) << " ms " << typeid (*child).name() << " " << child->getBounds().toString() << "\n";
  32033. }
  32034. };
  32035. // the channel window (Pattern layout, LYNX's look): Helix+'s strip with round 4's row
  32036. load ("Grain Swarm");
  32037. {
  32038. auto page = lynx::makeHelixEditor (offline, locate, 0);
  32039. check ("window page holds the six strip rows", page->getHeight() >= lynx::helixDeviceHeight + 16 + 446);
  32040. save (*page, "01-window-grain-swarm");
  32041. paintCost (*page, "window (Grain Swarm)");
  32042. }
  32043. load ("Spectral Ensemble");
  32044. {
  32045. auto page = lynx::makeHelixEditor (offline, locate, 0);
  32046. save (*page, "02-window-spectral-ensemble");
  32047. paintCost (*page, "window (Spectral Ensemble)");
  32048. parts (*page);
  32049. }
  32050. load ("Frozen Choir");
  32051. {
  32052. auto page = lynx::makeHelixEditor (offline, locate, 0);
  32053. save (*page, "03-window-frozen-choir");
  32054. }
  32055. load ("Triple Stack");
  32056. {
  32057. auto page = lynx::makeHelixEditor (offline, locate, 0);
  32058. save (*page, "04-window-triple");
  32059. paintCost (*page, "window (Triple Stack)");
  32060. parts (*page);
  32061. }
  32062. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  32063. }
  32064. void runHelixShot190mt (const juce::String& prefix)
  32065. {
  32066. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32067. lynx::AudioEngine offline (false);
  32068. juce::String checks;
  32069. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  32070. const auto& bank = lynx::banks::bankOf (lynx::InstrumentKind::helix);
  32071. const auto load = [&] (const juce::String& name) {
  32072. int index = -1;
  32073. for (int b = 0; b < (int) bank.size(); ++b)
  32074. if (juce::String (bank[(std::size_t) b].name) == name)
  32075. index = b;
  32076. check ("preset " + name, index >= 0);
  32077. offline.editSong ([index] (lynx::Song& s) {
  32078. if (s.channels.empty())
  32079. s.channels.resize (1);
  32080. lynx::ChannelDef c;
  32081. c.instrument = lynx::InstrumentKind::helix;
  32082. c.name = "Helix";
  32083. c.mixerTrack = s.channels[0].mixerTrack;
  32084. if (auto loaded = lynx::banks::withPreset (c, std::max (index, 0)))
  32085. c = *loaded;
  32086. s.channels[0] = c;
  32087. }, false);
  32088. offline.dispatchPendingMessages();
  32089. };
  32090. const auto locate = [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; };
  32091. const auto save = [&prefix, &offline] (juce::Component& c, const char* name) {
  32092. offline.dispatchPendingMessages();
  32093. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  32094. file.deleteFile();
  32095. juce::FileOutputStream out (file);
  32096. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  32097. };
  32098. const auto paintCost = [&checks] (juce::Component& c, const char* what) {
  32099. double best = 1.0e9;
  32100. for (int run = 0; run < 3; ++run)
  32101. {
  32102. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  32103. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  32104. for (int f = 0; f < 30; ++f)
  32105. {
  32106. juce::Graphics g (image);
  32107. c.paintEntireComponent (g, false);
  32108. }
  32109. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 30.0);
  32110. }
  32111. checks << "paint " << what << " " << juce::String (best, 3) << " ms per frame (" << c.getWidth() << " x " << c.getHeight() << ")\n";
  32112. };
  32113. // the channel window (Pattern layout, LYNX's look): Helix+'s strip with round 3's row
  32114. load ("Grain Cloud");
  32115. {
  32116. auto page = lynx::makeHelixEditor (offline, locate, 0);
  32117. check ("window page holds the five strip rows", page->getHeight() >= lynx::helixDeviceHeight + 16 + 370);
  32118. save (*page, "01-window-granular");
  32119. paintCost (*page, "window (Grain Cloud)");
  32120. check ("Matrix tab", lynx::helixcards::showView (*page, 1, 0, 0) == 1);
  32121. save (*page, "04-matrix-granular");
  32122. }
  32123. load ("Frozen Choir");
  32124. {
  32125. auto page = lynx::makeHelixEditor (offline, locate, 0);
  32126. save (*page, "02-window-spectral");
  32127. }
  32128. load ("Spectral Glass");
  32129. {
  32130. auto page = lynx::makeHelixEditor (offline, locate, 0);
  32131. save (*page, "03-window-glass");
  32132. }
  32133. // the same preset as 190ml's first picture (the side by side)
  32134. load ("Triple Stack");
  32135. {
  32136. auto page = lynx::makeHelixEditor (offline, locate, 0);
  32137. save (*page, "05-window-triple");
  32138. paintCost (*page, "window (Triple Stack)");
  32139. for (int i = 0; i < page->getNumChildComponents(); ++i) // (each part alone)
  32140. {
  32141. auto* child = page->getChildComponent (i);
  32142. juce::Image image (juce::Image::ARGB, std::max (1, child->getWidth()), std::max (1, child->getHeight()), true);
  32143. double best = 1.0e9;
  32144. for (int run = 0; run < 3; ++run)
  32145. {
  32146. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  32147. for (int f = 0; f < 10; ++f)
  32148. {
  32149. juce::Graphics g (image);
  32150. child->paintEntireComponent (g, false);
  32151. }
  32152. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 10.0);
  32153. }
  32154. checks << " part " << juce::String (best, 3) << " ms " << typeid (*child).name() << " " << child->getBounds().toString() << "\n";
  32155. }
  32156. }
  32157. // the Clip-launch layout's Device View card (Live's look) with its Helix+ panel (Granular / Spectral discs)
  32158. load ("Frozen Choir");
  32159. {
  32160. lynx::MainComponent ui (offline, false);
  32161. ui.setSize (2560, 1080);
  32162. ui.setVisible (true);
  32163. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  32164. ui.setClipLaunchWorkflow (true);
  32165. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  32166. offline.editSong ([] (lynx::Song& s) {
  32167. while (s.patterns.empty())
  32168. s.patterns.emplace_back();
  32169. lynx::Note note;
  32170. note.channel = 0;
  32171. note.key = 60;
  32172. s.patterns[0].name = "Choir";
  32173. s.patterns[0].notes = { note };
  32174. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  32175. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  32176. s.playlistTracks[0].name = "Helix";
  32177. lynx::Clip clip;
  32178. clip.pattern = 0;
  32179. clip.length = 4 * lynx::ppq;
  32180. lynx::launcher::setClip (s, 0, 0, clip);
  32181. }, false);
  32182. offline.dispatchPendingMessages();
  32183. auto* detail = ui.getDetailViewForSnapshot();
  32184. check ("detail view", detail != nullptr);
  32185. if (detail != nullptr)
  32186. {
  32187. detail->showSelection (0, 0);
  32188. detail->setPage (lynx::DetailView::Page::devices);
  32189. offline.dispatchPendingMessages();
  32190. check ("card's Helix+ panel", lynx::helixcards::showPlusInCard (*detail, true) == 1);
  32191. offline.dispatchPendingMessages();
  32192. save (ui, "06-card-plus");
  32193. checks << "detail " << detail->getScreenBounds().translated (-ui.getScreenX(), -ui.getScreenY()).toString() << "\n";
  32194. lynx::helixcards::showPlusInCard (*detail, false);
  32195. }
  32196. }
  32197. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  32198. }
  32199. void runHelixShot190ml (const juce::String& prefix)
  32200. {
  32201. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32202. lynx::AudioEngine offline (false);
  32203. juce::String checks;
  32204. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  32205. const auto& bank = lynx::banks::bankOf (lynx::InstrumentKind::helix);
  32206. const auto load = [&] (const juce::String& name) {
  32207. int index = -1;
  32208. for (int b = 0; b < (int) bank.size(); ++b)
  32209. if (juce::String (bank[(std::size_t) b].name) == name)
  32210. index = b;
  32211. check ("preset " + name, index >= 0);
  32212. offline.editSong ([index] (lynx::Song& s) {
  32213. if (s.channels.empty())
  32214. s.channels.resize (1);
  32215. lynx::ChannelDef c;
  32216. c.instrument = lynx::InstrumentKind::helix;
  32217. c.name = "Helix";
  32218. c.mixerTrack = s.channels[0].mixerTrack;
  32219. if (auto loaded = lynx::banks::withPreset (c, std::max (index, 0)))
  32220. c = *loaded;
  32221. s.channels[0] = c;
  32222. }, false);
  32223. offline.dispatchPendingMessages();
  32224. };
  32225. const auto locate = [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; };
  32226. const auto save = [&prefix, &offline] (juce::Component& c, const char* name) {
  32227. offline.dispatchPendingMessages();
  32228. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  32229. file.deleteFile();
  32230. juce::FileOutputStream out (file);
  32231. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  32232. };
  32233. const auto paintCost = [&checks] (juce::Component& c, const char* what) {
  32234. double best = 1.0e9;
  32235. for (int run = 0; run < 3; ++run)
  32236. {
  32237. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  32238. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  32239. for (int f = 0; f < 30; ++f)
  32240. {
  32241. juce::Graphics g (image);
  32242. c.paintEntireComponent (g, false);
  32243. }
  32244. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 30.0);
  32245. }
  32246. checks << "paint " << what << " " << juce::String (best, 3) << " ms per frame (" << c.getWidth() << " x " << c.getHeight() << ")\n";
  32247. };
  32248. // the channel window (Pattern layout, LYNX's look): Helix+'s strip with Helix+ 2's two rows
  32249. load ("Triple Stack");
  32250. {
  32251. auto page = lynx::makeHelixEditor (offline, locate, 0);
  32252. check ("window page holds the four strip rows", page->getHeight() >= lynx::helixDeviceHeight + 16 + 300);
  32253. save (*page, "01-window");
  32254. paintCost (*page, "window");
  32255. // (the slowest parts: each child of the page and of its children, alone)
  32256. std::vector<std::pair<double, juce::String>> parts;
  32257. std::function<void (juce::Component&, int)> walk = [&] (juce::Component& c, int depth) {
  32258. for (auto* child : c.getChildren())
  32259. {
  32260. if (child->getWidth() <= 0 || child->getHeight() <= 0)
  32261. continue;
  32262. juce::Image image (juce::Image::ARGB, child->getWidth(), child->getHeight(), true);
  32263. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  32264. for (int f = 0; f < 10; ++f)
  32265. {
  32266. juce::Graphics g (image);
  32267. child->paintEntireComponent (g, false);
  32268. }
  32269. parts.push_back ({ (juce::Time::getMillisecondCounterHiRes() - t0) / 10.0,
  32270. juce::String (depth) + " " + typeid (*child).name() + " " + child->getBounds().toString() });
  32271. if (depth < 2)
  32272. walk (*child, depth + 1);
  32273. }
  32274. };
  32275. walk (*page, 0);
  32276. for (int i = 0; i < page->getNumChildComponents(); ++i) // (the page with one child hidden)
  32277. {
  32278. auto* child = page->getChildComponent (i);
  32279. child->setVisible (false);
  32280. paintCost (*page, (juce::String ("window without child ") + juce::String (i)).toRawUTF8());
  32281. child->setVisible (true);
  32282. }
  32283. paintCost (*page, "window again");
  32284. std::sort (parts.begin(), parts.end(), [] (const auto& x, const auto& y) { return x.first > y.first; });
  32285. for (std::size_t i = 0; i < parts.size() && i < 12; ++i)
  32286. checks << " part " << juce::String (parts[i].first, 3) << " ms " << parts[i].second << "\n";
  32287. check ("Macros tab", lynx::helixcards::showView (*page, 4, 0, 0) == 1);
  32288. save (*page, "02-matrix-macros");
  32289. }
  32290. load ("Vowel Sync");
  32291. {
  32292. auto page = lynx::makeHelixEditor (offline, locate, 0);
  32293. save (*page, "03-window-sample");
  32294. }
  32295. // the table editor on a formula preset's table
  32296. load ("Formula Bell");
  32297. {
  32298. auto editor = lynx::helixcards::makeTableEditor (offline, locate, 0, 0, 0, 20);
  32299. save (*editor, "04-table-draw");
  32300. paintCost (*editor, "table editor (draw)");
  32301. auto harmonics = lynx::helixcards::makeTableEditor (offline, locate, 0, 0, 1, 20);
  32302. save (*harmonics, "05-table-harmonics");
  32303. }
  32304. // the Clip-launch layout's Device View card (Live's look), without and with its Helix+ panel
  32305. load ("Triple Stack");
  32306. {
  32307. lynx::MainComponent ui (offline, false);
  32308. ui.setSize (2560, 1080); // (wide: the card with its panel whole)
  32309. ui.setVisible (true);
  32310. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  32311. ui.setClipLaunchWorkflow (true);
  32312. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  32313. offline.editSong ([] (lynx::Song& s) {
  32314. while (s.patterns.empty())
  32315. s.patterns.emplace_back();
  32316. lynx::Note note;
  32317. note.channel = 0;
  32318. note.key = 60;
  32319. s.patterns[0].name = "Lead";
  32320. s.patterns[0].notes = { note };
  32321. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  32322. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  32323. s.playlistTracks[0].name = "Helix";
  32324. lynx::Clip clip;
  32325. clip.pattern = 0;
  32326. clip.length = 4 * lynx::ppq;
  32327. lynx::launcher::setClip (s, 0, 0, clip);
  32328. }, false);
  32329. offline.dispatchPendingMessages();
  32330. auto* detail = ui.getDetailViewForSnapshot();
  32331. check ("detail view", detail != nullptr);
  32332. if (detail != nullptr)
  32333. {
  32334. detail->showSelection (0, 0);
  32335. detail->setPage (lynx::DetailView::Page::devices);
  32336. offline.dispatchPendingMessages();
  32337. lynx::helixcards::showPlusInCard (*detail, false);
  32338. save (ui, "06-card");
  32339. check ("card's Helix+ panel", lynx::helixcards::showPlusInCard (*detail, true) == 1);
  32340. offline.dispatchPendingMessages();
  32341. save (ui, "07-card-plus");
  32342. // (where the Device View sits in the picture, for the crops)
  32343. checks << "detail " << detail->getScreenBounds().translated (-ui.getScreenX(), -ui.getScreenY()).toString() << "\n";
  32344. lynx::helixcards::showPlusInCard (*detail, false);
  32345. }
  32346. }
  32347. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  32348. }
  32349. void runHelixShot190mi (const juce::String& prefix, const juce::String& presetName)
  32350. {
  32351. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32352. lynx::AudioEngine offline (false);
  32353. juce::String checks;
  32354. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  32355. const auto& bank = lynx::banks::bankOf (lynx::InstrumentKind::helix);
  32356. int index = -1;
  32357. for (int b = 0; b < (int) bank.size(); ++b)
  32358. if (juce::String (bank[(std::size_t) b].name) == presetName)
  32359. index = b;
  32360. check ("preset " + presetName, index >= 0);
  32361. offline.editSong ([index] (lynx::Song& s) {
  32362. if (s.channels.empty())
  32363. s.channels.resize (1);
  32364. lynx::ChannelDef c;
  32365. c.instrument = lynx::InstrumentKind::helix;
  32366. c.mixerTrack = s.channels[0].mixerTrack;
  32367. if (auto loaded = lynx::banks::withPreset (c, std::max (index, 0)))
  32368. c = *loaded;
  32369. s.channels[0] = c;
  32370. }, false);
  32371. offline.dispatchPendingMessages();
  32372. auto page = lynx::makeHelixEditor (offline, [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; }, 0);
  32373. const auto write = [&prefix, &page, &offline] (const char* name) {
  32374. offline.dispatchPendingMessages();
  32375. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  32376. file.deleteFile();
  32377. juce::FileOutputStream out (file);
  32378. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*page), out);
  32379. };
  32380. check ("window page", page->getWidth() > 0 && page->getHeight() > lynx::helixDeviceHeight + 100);
  32381. check ("Helix panel inside", lynx::helixcards::showView (*page, 0, 0, 0) == 1);
  32382. write ("01-window");
  32383. lynx::helixcards::showView (*page, 0, 3, 0);
  32384. write ("02-lfo1-drawn");
  32385. lynx::helixcards::showView (*page, 1, 0, 0);
  32386. write ("03-matrix");
  32387. // the window's paint cost (device + strip, the Mod Sources page): 60 whole frames off screen, the best of 3 runs
  32388. lynx::helixcards::showView (*page, 0, 0, 0);
  32389. double best = 1.0e9;
  32390. for (int run = 0; run < 3; ++run)
  32391. {
  32392. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  32393. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  32394. for (int f = 0; f < 60; ++f)
  32395. {
  32396. juce::Graphics g (image);
  32397. page->paintEntireComponent (g, false);
  32398. }
  32399. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 60.0);
  32400. }
  32401. checks << "paint " << juce::String (best, 3) << " ms per frame (" << page->getWidth() << " x " << page->getHeight() << ")\n";
  32402. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  32403. }
  32404. void runLiveShot190ce (const juce::String& prefix)
  32405. {
  32406. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32407. lynx::AudioEngine offline (false);
  32408. lynx::MainComponent ui (offline, false);
  32409. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  32410. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  32411. const auto write = [&prefix, &ui, &offline] (const char* name) {
  32412. offline.dispatchPendingMessages();
  32413. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  32414. file.deleteFile();
  32415. juce::FileOutputStream out (file);
  32416. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  32417. };
  32418. juce::String checks;
  32419. const auto check = [&checks] (const char* what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  32420. // a small library of its own (empty files: only names are shown)
  32421. const auto lib = juce::File (prefix + "-library");
  32422. lib.deleteRecursively();
  32423. for (const auto* path : { "Drums/Kicks/Kick Hard.wav", "Drums/Kicks/Kick Soft.wav", "Drums/Snare Tight.wav", "Drums/Hat Closed.wav",
  32424. "Loops/Break 120.wav", "Loops/Shaker 98.wav", "Textures/Vinyl Noise.wav", "Textures/Rain.wav" })
  32425. lib.getChildFile (path).create();
  32426. auto& browser = ui.getBrowserForSnapshot();
  32427. auto& store = lynx::BrowserComponent::collectionStore();
  32428. store = {};
  32429. const auto item = [&lib] (const char* path) { return lib.getChildFile (path).getFullPathName().toStdString(); };
  32430. ui.setVisible (true);
  32431. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  32432. ui.setClipLaunchWorkflow (true);
  32433. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  32434. offline.editSong ([] (lynx::Song& s) {
  32435. if (s.channels.size() < 2)
  32436. s.channels.resize (2);
  32437. s.channels[0].name = "Bass synth";
  32438. s.channels[0].mixerTrack = 2;
  32439. s.channels[1].mixerTrack = 3;
  32440. if (s.mixer.size() < 4)
  32441. s.mixer.resize (4);
  32442. s.mixer[2].name = "Bass";
  32443. s.mixer[2].effects.clear();
  32444. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  32445. {
  32446. lynx::EffectSlot fx;
  32447. fx.kind = kind;
  32448. const auto& info = lynx::effectInfo (kind);
  32449. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  32450. fx.params[k] = info.params[k].defaultValue;
  32451. s.mixer[2].effects.push_back (fx);
  32452. }
  32453. s.mixer[2].effects[1].enabled = false; // the compressor: off, at half mix
  32454. s.mixer[2].effects[1].mix = 0.5f;
  32455. while (s.patterns.size() < 2)
  32456. s.patterns.emplace_back();
  32457. s.patterns[0].name = "Bass line";
  32458. lynx::Note note;
  32459. note.channel = 0;
  32460. note.key = 36;
  32461. s.patterns[0].notes = { note };
  32462. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  32463. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  32464. s.playlistTracks[1].name = "Bass";
  32465. lynx::Clip clip;
  32466. clip.pattern = 0;
  32467. clip.length = 4 * lynx::ppq;
  32468. lynx::launcher::setClip (s, 1, 0, clip);
  32469. }, false);
  32470. offline.dispatchPendingMessages();
  32471. auto* detail = ui.getDetailViewForSnapshot();
  32472. if (detail == nullptr)
  32473. {
  32474. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  32475. return;
  32476. }
  32477. detail->showSelection (1, 0);
  32478. detail->setPage (lynx::DetailView::Page::devices);
  32479. detail->selectCardForCheck (2); // the compressor (card 0 is the instrument)
  32480. write ("01-devices"); // the cards' title buttons: hot-swap, save, fold
  32481. saveMenus (juce::StringArray { "Device (effect card)" }, std::vector<juce::PopupMenu> { detail->cardMenuForSnapshot (2) }, prefix + "-02-device-menu.png");
  32482. // hot-swap on for the compressor: the Browser's bar, the Plugin database's effects, the card's button lit
  32483. const auto compressor = lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1);
  32484. browser.beginHotSwap (compressor);
  32485. write ("03-hotswap-effect");
  32486. check ("hot-swap links the compressor", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  32487. // a swap through the Browser itself (the row of LYNX's Reverb, then Enter): the slot keeps its place, its off
  32488. // state and its Mix; the link moves to the new device
  32489. {
  32490. browser.showPluginDatabase ("LYNX SHARE", 0); // (the folder of LYNX's own effects, opened as a click would)
  32491. browser.selectRowForSnapshot (lynx::tr (lynx::effectInfo (lynx::EffectKind::reverb).name));
  32492. write ("03a-hotswap-row"); // the candidate's row selected
  32493. check ("swap: Enter on the Reverb row is taken by hot-swap", browser.hotSwapLoadSelected());
  32494. offline.dispatchPendingMessages();
  32495. const auto& slot = offline.getSong().mixer[2].effects[1];
  32496. // (round 190cy: the device comes in with its own on / off state, on, as in Live 12.4.16; the Mix stays)
  32497. check ("swap: reverb in the compressor's place, on (its own state), at 50 % mix", slot.kind == lynx::EffectKind::reverb && slot.enabled && slot.mix == 0.5f);
  32498. check ("swap: three effects as before", offline.getSong().mixer[2].effects.size() == 3);
  32499. check ("swap: the Browser is linked to the new device", browser.isHotSwapping() && browser.hotSwapTarget() == lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1)
  32500. && ! (browser.hotSwapTarget() == compressor));
  32501. write ("03b-hotswap-swapped");
  32502. offline.undo();
  32503. offline.dispatchPendingMessages();
  32504. const auto& back = offline.getSong().mixer[2].effects[1];
  32505. check ("undo: the compressor is back with its instance", back.kind == lynx::EffectKind::compressor && back.instance.id == compressor.instance);
  32506. check ("undo: the Browser is still linked to it", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  32507. }
  32508. // round 190cy (Live 12.4.16 live check 190cw shot 02a): hot-swap starts on the device's current preset. The
  32509. // compressor got its settings from a saved preset of LYNX's ("Glue bus", in this run's own settings folder)
  32510. {
  32511. browser.endHotSwap();
  32512. const auto folder = lynx::pluginheader::userFolder (lynx::EffectKind::compressor);
  32513. folder.createDirectory();
  32514. const auto& fx = offline.getSong().mixer[2].effects[1];
  32515. for (const auto* name : { "Glue bus", "Gentle", "Parallel smash" })
  32516. folder.getChildFile (juce::String (name) + ".lynxpreset").replaceWithText (lynx::presets::toText (lynx::EffectKind::compressor, name, fx.params));
  32517. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects[1].presetName = "Glue bus"; }, false);
  32518. offline.dispatchPendingMessages();
  32519. browser.beginHotSwap (compressor);
  32520. write ("03c-hotswap-current-preset");
  32521. check ("hot-swap starts on the current preset", browser.getSelectedFile() == folder.getChildFile ("Glue bus.lynxpreset"));
  32522. // a preset of the same effect swapped in comes in on (the compressor was off)
  32523. browser.selectRowForSnapshot ("Gentle.lynxpreset");
  32524. check ("swap: the preset row is taken by hot-swap", browser.hotSwapLoadSelected());
  32525. offline.dispatchPendingMessages();
  32526. const auto& now = offline.getSong().mixer[2].effects[1];
  32527. check ("swap: the preset's settings, the device on", now.kind == lynx::EffectKind::compressor && now.presetName == "Gentle" && now.enabled);
  32528. write ("03d-hotswap-preset-swapped");
  32529. offline.undo();
  32530. offline.dispatchPendingMessages();
  32531. check ("undo: the compressor off again", ! offline.getSong().mixer[2].effects[1].enabled);
  32532. browser.endHotSwap();
  32533. check ("hot-swap ended: the preset list goes", ! browser.isHotSwapping());
  32534. browser.beginHotSwap (compressor);
  32535. }
  32536. // linked to the instrument instead
  32537. const auto bass = lynx::hotswap::targetOfChannel (offline.getSong(), 0);
  32538. browser.beginHotSwap (bass);
  32539. detail->selectCardForCheck (0);
  32540. write ("04-hotswap-instrument");
  32541. check ("re-link to the instrument", browser.hotSwapTarget() == bass);
  32542. browser.endHotSwap();
  32543. check ("hot-swap ended", ! browser.isHotSwapping());
  32544. write ("05-hotswap-ended"); // the Browser as it was before
  32545. // the device is deleted while linked: the mode ends by itself
  32546. browser.beginHotSwap (lynx::hotswap::targetOfEffect (offline.getSong(), 2, 2));
  32547. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.pop_back(); });
  32548. offline.dispatchPendingMessages();
  32549. check ("deleting the linked device ends hot-swap", ! browser.isHotSwapping());
  32550. offline.undo();
  32551. offline.dispatchPendingMessages();
  32552. // Duplicate (Ctrl+D) of the EQ
  32553. check ("duplicate", detail->duplicateCardForCheck (1));
  32554. offline.dispatchPendingMessages();
  32555. check ("duplicate: four effects, EQ twice", offline.getSong().mixer[2].effects.size() == 4 && offline.getSong().mixer[2].effects[1].kind == lynx::EffectKind::eq
  32556. && offline.getSong().mixer[2].effects[0].instance.id != offline.getSong().mixer[2].effects[1].instance.id);
  32557. write ("06-duplicated");
  32558. // --- collections ---
  32559. browser.showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  32560. ui.waitForBrowserForSnapshot();
  32561. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 0, true);
  32562. browser.setInCollection (item ("Drums/Snare Tight.wav"), 0, true);
  32563. browser.setInCollection (item ("Loops"), 0, true);
  32564. browser.setTab (lynx::BrowserComponent::starredTab);
  32565. write ("07-starred-only"); // only Starred shown: the tab as it always was
  32566. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 4, true); // also Blue
  32567. browser.setInCollection (item ("Loops/Break 120.wav"), 4, true);
  32568. browser.setInCollection (item ("Textures/Vinyl Noise.wav"), 3, true);
  32569. browser.setInCollection (item ("Textures/Rain.wav"), 3, true);
  32570. browser.setInCollection (item ("Drums/Hat Closed.wav"), 1, true);
  32571. store.rename (3, "Textures");
  32572. browser.setCollectionShown (1, true);
  32573. browser.setCollectionShown (3, true);
  32574. browser.setCollectionShown (4, true);
  32575. write ("08-collections"); // a heading per collection shown
  32576. check ("collections: four shown", store.shown().size() == 4);
  32577. check ("collections: an item in two", store.mask (item ("Drums/Kicks/Kick Hard.wav")) == 0b10001);
  32578. // round 190cy: the Clip-launch workflow's row menu lists the collections flat, as Live's item menu (shot 05);
  32579. // the Pattern workflow keeps the "Collections" sub-menu
  32580. browser.setLiveItemMenus (false);
  32581. saveMenus (juce::StringArray { "Collections (Pattern workflow: a row's sub-menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  32582. prefix + "-09-collections-menu.png");
  32583. browser.setLiveItemMenus (true);
  32584. saveMenus (juce::StringArray { "Collections (Clip-launch workflow: a row's menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  32585. prefix + "-09b-collections-flat.png");
  32586. // the key of a hidden collection (6, Purple) labels the row and the collection appears
  32587. check ("hidden collection: not shown before", ! store.isShown (5));
  32588. browser.setInCollection (item ("Textures/Rain.wav"), 5, true);
  32589. check ("hidden collection: its key shows it", store.isShown (5) && store.has (item ("Textures/Rain.wav"), 5));
  32590. write ("08b-hidden-collection-shown");
  32591. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { browser.buildViewMenu() }, prefix + "-10-browser-options.png");
  32592. browser.setTab (lynx::BrowserComponent::allTab);
  32593. write ("11-all-tab-chips"); // the colour chips on the rows of the ALL tab
  32594. browser.setSearchForSnapshot ("textures");
  32595. ui.waitForBrowserForSnapshot();
  32596. write ("12-search-collection-name"); // found by the collection's name
  32597. browser.setSearchForSnapshot ({});
  32598. // the file round trip
  32599. {
  32600. const auto text = store.toText();
  32601. check ("collections: text round trip", lynx::collections::Store::fromText (text) == store);
  32602. }
  32603. store = {};
  32604. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  32605. lib.deleteRecursively();
  32606. }
  32607. void runLinkShot190gl (const juce::String& prefix)
  32608. {
  32609. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32610. lynx::AudioEngine offline (false);
  32611. lynx::MainComponent ui (offline, false);
  32612. ui.setSize (1600, 900);
  32613. ui.setVisible (true);
  32614. juce::String checks;
  32615. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  32616. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  32617. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  32618. file.deleteFile();
  32619. juce::FileOutputStream out (file);
  32620. juce::PNGImageFormat().writeImageToStream (image, out);
  32621. };
  32622. const auto toolbarShot = [&] (const char* name) {
  32623. ui.tickLinkForSnapshot();
  32624. writeImage (lynx::shot::snapshot (ui, ui.getToolbarBoundsForSnapshot()), name);
  32625. };
  32626. auto& link = offline.getLink();
  32627. auto& transport = offline.getTransport();
  32628. link.deviceStarted (44100.0);
  32629. // the audio callbacks the offline engine has none of: Link's per-block step, in real time
  32630. const auto pump = [&] (double seconds, std::function<bool()> until = {}) {
  32631. const auto end = juce::Time::getMillisecondCounterHiRes() + seconds * 1000.0;
  32632. while (juce::Time::getMillisecondCounterHiRes() < end)
  32633. {
  32634. const auto start = link.beginBlock (transport, 256, 0.0);
  32635. if (start >= 0)
  32636. transport.playing.store (true);
  32637. if (transport.playing.load())
  32638. transport.positionTicks.store (transport.positionTicks.load() + 256 * transport.ticksPerSample());
  32639. juce::Thread::sleep (6);
  32640. if (until && until())
  32641. return true;
  32642. }
  32643. return ! until || until();
  32644. };
  32645. auto peer = lynx::AbletonLink::makeTestPeer (97.0); // the other app in the session (it was there first)
  32646. juce::Thread::sleep (1500); // (a session that started at the same moment as LYNX's could take either tempo)
  32647. using lynx::toolbarlayout::Group;
  32648. // FL's Pattern layout: no Link toggle on a new install
  32649. check ("Pattern layout: the Link toggle is hidden by default", ! ui.getToolbarLayoutForSnapshot().isShown (Group::link));
  32650. toolbarShot ("toolbar-fl-default");
  32651. // shown by hand (Settings › Ableton Link › Show Link Toggle): "Link", off
  32652. auto layout = ui.getToolbarLayoutForSnapshot();
  32653. layout.setShown (Group::link, true);
  32654. ui.setToolbarLayoutForSnapshot (layout);
  32655. toolbarShot ("toolbar-fl-link-off");
  32656. check ("off: the toggle says Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: Link"));
  32657. // on: the session the other peer runs (its tempo, 97 BPM, wins over the project's)
  32658. link.setEnabled (true, offline.getSong().bpm);
  32659. // (a new peer is counted at once; its session's tempo is taken after Link measured it, a moment later)
  32660. const auto joined = pump (8.0, [&] { return link.peers() > 0 && link.startProgress() >= 0.0 && std::abs (link.sessionTempo() - 97.0) < 1e-3; });
  32661. check ("Link on: one peer found", joined && link.peers() == 1);
  32662. check ("Link on: the session's tempo (97 BPM, the first peer's) is the one shown", std::abs (offline.shownTempo() - 97.0) < 1e-3);
  32663. toolbarShot ("toolbar-fl-link-on");
  32664. check ("on with one peer: the toggle says 1 Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: {0} Link").replace ("{0}", "1"));
  32665. check ("stopped with a peer: the position display shows the session's progress", link.startProgress() >= 0.0);
  32666. // the Clip-launch layout: the toggle is shown by default (the reference DAW's "Show Link Toggle": Show)
  32667. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  32668. ui.setClipLaunchWorkflow (true);
  32669. check ("Clip-launch layout: the Link toggle is shown by default", ui.getToolbarLayoutForSnapshot().isShown (Group::link));
  32670. pump (0.4);
  32671. toolbarShot ("toolbar-cliplaunch-1link");
  32672. writeImage (lynx::shot::snapshot (ui), "window-cliplaunch");
  32673. // Play: it waits for the session's phase (the play button lit, the progress bar running), then starts
  32674. transport.playing.store (true);
  32675. pump (0.05);
  32676. const auto waited = offline.isLinkWaiting();
  32677. check ("Play with a peer waits for the session's phase", waited);
  32678. toolbarShot ("toolbar-cliplaunch-waiting");
  32679. const auto started = pump (4.0, [&] { return transport.playing.load() && ! offline.isLinkWaiting(); });
  32680. check ("then playback starts on the session's phase", started);
  32681. pump (0.5);
  32682. toolbarShot ("toolbar-cliplaunch-playing");
  32683. check ("playing: no progress bar", link.startProgress() < 0.0);
  32684. // the toggle's drop-down and the Options menu
  32685. saveMenus (juce::StringArray { lynx::trc ("@Ableton Link: Link") }, std::vector<juce::PopupMenu> { ui.getLinkToggleForSnapshot().makeMenu() },
  32686. prefix + "-menu-link.png");
  32687. {
  32688. const auto names = ui.getMenuNamesForSnapshot();
  32689. for (int m = 0; m < names.size(); ++m)
  32690. if (names[m] == lynx::tr ("Options"))
  32691. saveMenus (juce::StringArray { names[m] }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (m) }, prefix + "-menu-options.png");
  32692. }
  32693. // Settings › Ableton Link
  32694. {
  32695. lynx::SettingsHooks hooks;
  32696. hooks.linkToggleShown = [] { return true; };
  32697. auto panel = lynx::makeSettingsPanel (offline, lynx::SettingsPage::link, false, hooks);
  32698. panel->setSize (680, 620);
  32699. writeImage (lynx::shot::snapshot (*panel), "settings-link");
  32700. }
  32701. // off: the project's own tempo comes back on the display
  32702. transport.playing.store (false);
  32703. pump (0.1);
  32704. link.setEnabled (false, offline.getSong().bpm);
  32705. pump (0.1);
  32706. toolbarShot ("toolbar-cliplaunch-link-off");
  32707. check ("off: the tempo display shows the project's tempo again", std::abs (offline.shownTempo() - offline.getSong().bpm) < 1e-9);
  32708. const auto stats = link.stats();
  32709. checks << "audio-thread cost of the Link step: mean " << juce::String (stats.meanUs, 2) << " us, max " << juce::String (stats.maxUs, 1)
  32710. << " us over " << (juce::int64) stats.blocks << " blocks\n";
  32711. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  32712. }
  32713. // LYNX --communityshot190hp <prefix> (round 190hp): the three community slices off-screen, with checks in
  32714. // prefix-checks.txt — B9 the MIDI Map Mode's "In every project (LYNX)" (the row menu, the Mapping Browser with the
  32715. // global rows, a new project still playing on the mapped CC, Settings' list), B16 the Mixer menu's Mix snapshots
  32716. // (take, recall, Compare A/B, the .lynx round trip), B18 the audio clip menu's "Split at silence..." (the dialog and
  32717. // the Playlist before / after).
  32718. void runCommunityShot190hp (const juce::String& prefix)
  32719. {
  32720. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32721. lynx::AudioEngine offline (false);
  32722. lynx::MainComponent ui (offline, false);
  32723. ui.setSize (1600, 900);
  32724. const auto write = [&prefix] (juce::Component& c, const char* name) {
  32725. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  32726. file.deleteFile();
  32727. juce::FileOutputStream out (file);
  32728. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  32729. };
  32730. juce::String checks;
  32731. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  32732. const auto plain = [] (juce::String t) { return t.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&"); };
  32733. const auto find = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  32734. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  32735. if (plain (it.getItem().text) == plain (text))
  32736. return &it.getItem();
  32737. return nullptr;
  32738. };
  32739. const auto click = [&find] (const juce::PopupMenu& menu, const juce::String& text) {
  32740. const auto* item = find (menu, text);
  32741. if (item == nullptr || ! item->isEnabled || item->action == nullptr)
  32742. return false;
  32743. item->action();
  32744. return true;
  32745. };
  32746. using namespace lynx::remotemap;
  32747. ui.setVisible (true);
  32748. // ---- B9: the MIDI Map Mode's mappings for every project ---------------------------------------------------------
  32749. ui.setClipLaunchWorkflow (true);
  32750. offline.editSong ([] (lynx::Song& s) {
  32751. auto& grid = lynx::launcher::ensureGrid (s);
  32752. grid.scenes.resize (4);
  32753. assignMidi (s, Target::of (lynx::RemoteAction::play), { 0, 118, -1 });
  32754. assignMidi (s, Target::of (lynx::RemoteAction::stop), { 0, 117, -1 });
  32755. assignMidi (s, Target::sceneLaunch (0), { 0, lynx::linkNoteBase + 44, -1 });
  32756. assignMidi (s, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, -1 });
  32757. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }), { 0, 7, -1 });
  32758. }, false);
  32759. offline.dispatchPendingMessages();
  32760. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist, lynx::workspace::Panel::browser });
  32761. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  32762. ui.setMapMode (Mode::midi);
  32763. auto* list = ui.mappingBrowserForSnapshot();
  32764. if (list == nullptr)
  32765. {
  32766. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no Mapping Browser\n");
  32767. return;
  32768. }
  32769. list->setMode (Mode::midi);
  32770. ui.resized();
  32771. const auto rowOf = [&] (const Target& t) {
  32772. const auto rows = list->rowsShown();
  32773. for (int r = 0; r < (int) rows.size(); ++r)
  32774. if (rows[(std::size_t) r].target == t)
  32775. return r;
  32776. return -1;
  32777. };
  32778. const auto everyProject = lynx::tr ("In every project (LYNX)");
  32779. {
  32780. const auto slotMenu = list->rowMenu (rowOf (Target::slot (0, 0)));
  32781. const auto* item = find (slotMenu, everyProject);
  32782. check ("row menu: a clip slot cannot be for every project (greyed)", item != nullptr && ! item->isEnabled);
  32783. const auto playRow = rowOf (Target::of (lynx::RemoteAction::play));
  32784. list->selectRow (playRow);
  32785. const auto playMenu = list->rowMenu (playRow);
  32786. const auto* p = find (playMenu, everyProject);
  32787. check ("row menu: Play can, unticked", p != nullptr && p->isEnabled && ! p->isTicked);
  32788. saveMenus (juce::StringArray { "Row" }, std::vector<juce::PopupMenu> { playMenu }, prefix + "-b9-01-row-menu.png");
  32789. check ("Play goes to every project", click (playMenu, everyProject) && offline.getMidiPrefs().globalMappings.size() == 1);
  32790. }
  32791. check ("Stop goes too", click (list->rowMenu (rowOf (Target::of (lynx::RemoteAction::stop))), everyProject));
  32792. check ("the Master volume link goes too (FL's global links)",
  32793. click (list->rowMenu (rowOf (Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }))), everyProject)
  32794. && offline.getMidiPrefs().globalLinks.size() == 1 && offline.getSong().midiLinks.empty());
  32795. list->setMode (Mode::midi);
  32796. const auto shown = list->rowsShown();
  32797. check ("Mapping Browser: 2 project rows, then 3 global ones (" + juce::String ((int) shown.size()) + ")",
  32798. shown.size() == 5 && ! shown[0].global && ! shown[1].global && shown[2].global && shown[4].global);
  32799. {
  32800. const auto rowMenu = list->rowMenu (2); // (round 190rf: kept while its item is read; ASan, heap-use-after-free)
  32801. const auto* ticked = find (rowMenu, everyProject);
  32802. check ("a global row's item is ticked", ticked != nullptr && ticked->isTicked);
  32803. }
  32804. write (*list, "b9-02-mapping-browser-global");
  32805. // a new project: the global mappings are there and act (CC 118 plays, CC 117 stops)
  32806. offline.setSong (lynx::Song::makeDefault());
  32807. offline.dispatchPendingMessages();
  32808. list->setMode (Mode::midi);
  32809. const auto fresh = list->rowsShown();
  32810. check ("new project: the 3 global rows (" + juce::String ((int) fresh.size()) + ")", fresh.size() == 3 && fresh[0].global);
  32811. write (*list, "b9-03-new-project-browser");
  32812. ui.setMapMode (Mode::off);
  32813. offline.injectControllerForTest (118, 0, 127);
  32814. offline.dispatchPendingMessages();
  32815. check ("new project: CC 118 plays", offline.getTransport().playing.load());
  32816. offline.injectControllerForTest (118, 0, 0);
  32817. offline.injectControllerForTest (117, 0, 127);
  32818. offline.dispatchPendingMessages();
  32819. check ("new project: CC 117 stops", ! offline.getTransport().playing.load());
  32820. offline.injectControllerForTest (7, 0, 0);
  32821. offline.dispatchPendingMessages();
  32822. check ("new project: CC 7 moves the Master", offline.currentTargetValue ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }) < 0.01f);
  32823. // the Pattern layout: they act there too, and Settings › MIDI lists them
  32824. ui.setClipLaunchWorkflow (false);
  32825. offline.injectControllerForTest (117, 0, 0);
  32826. offline.injectControllerForTest (118, 0, 127);
  32827. offline.dispatchPendingMessages();
  32828. check ("Pattern layout: CC 118 plays", offline.getTransport().playing.load());
  32829. offline.stop();
  32830. // back into one project, then cleared (the settings of this test engine are never written)
  32831. ui.setClipLaunchWorkflow (true);
  32832. ui.setMapMode (Mode::midi);
  32833. list->setMode (Mode::midi);
  32834. check ("back into this project", click (list->rowMenu (rowOf (Target::of (lynx::RemoteAction::play))), everyProject)
  32835. && offline.getMidiPrefs().globalMappings.size() == 1 && offline.getSong().remoteMappings.size() == 1);
  32836. ui.setMapMode (Mode::off);
  32837. ui.setClipLaunchWorkflow (false);
  32838. // ---- B16: Mix snapshots ----------------------------------------------------------------------------------------
  32839. offline.setSong (lynx::Song::makeDefault());
  32840. offline.dispatchPendingMessages();
  32841. offline.editSong ([] (lynx::Song& s) {
  32842. const char* names[] { "Master", "Drums", "Bass", "Keys", "Vox", "Reverb" };
  32843. for (int i = 1; i < 6 && i < (int) s.mixer.size(); ++i)
  32844. s.mixer[(std::size_t) i].name = names[i];
  32845. s.mixer[1].volume = 0.7f;
  32846. s.mixer[4].pan = -0.3f;
  32847. s.setRoute (4, 5, true, 0.5f);
  32848. });
  32849. juce::PopupMenu mixerMenu;
  32850. lynx::mixeroptions::addItems (mixerMenu, offline, false);
  32851. const auto* snaps = find (mixerMenu, lynx::tr ("Mix snapshots (LYNX)"));
  32852. check ("Mixer menu: Mix snapshots (LYNX)", snaps != nullptr && snaps->subMenu != nullptr);
  32853. check ("Take snapshot", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Take snapshot")) && offline.getSong().mixSnapshots.size() == 1);
  32854. offline.editSong ([] (lynx::Song& s) {
  32855. s.mixer[1].volume = 0.4f;
  32856. s.mixer[4].pan = 0.6f;
  32857. s.mixer[3].muted = true;
  32858. s.setRoute (4, 5, false);
  32859. });
  32860. check ("Take snapshot again", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Take snapshot")) && offline.getSong().mixSnapshots.size() == 2);
  32861. {
  32862. const auto menu = lynx::mixeroptions::snapshotsMenu (offline);
  32863. const auto* first = find (menu, juce::String ("Snapshot 1 (B)"));
  32864. check ("snapshot 1 listed as B", first != nullptr && first->subMenu != nullptr && ! first->isTicked);
  32865. const auto* second = find (menu, juce::String ("Snapshot 2 (A)"));
  32866. check ("snapshot 2 ticked: the mix is it", second != nullptr && second->isTicked);
  32867. saveMenus (juce::StringArray { "Mixer", "Mix snapshots (LYNX)", "Snapshot 1" },
  32868. std::vector<juce::PopupMenu> { mixerMenu, menu, first != nullptr ? *first->subMenu : juce::PopupMenu() }, prefix + "-b16-01-menus.png");
  32869. check ("Recall snapshot 1", first != nullptr && click (*first->subMenu, lynx::tr ("Recall")));
  32870. }
  32871. const auto& m = offline.getSong().mixer;
  32872. check ("recalled: fader, pan, mute, send", m[1].volume == 0.7f && m[4].pan == -0.3f && ! m[3].muted && offline.getSong().routes (4, 5));
  32873. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  32874. ui.resized();
  32875. offline.dispatchPendingMessages();
  32876. write (ui, "b16-02-mixer-recalled");
  32877. check ("Compare A/B", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Compare A/B: back to \"{0}\"", { "Snapshot 2" }))
  32878. && m[1].volume == 0.4f && m[3].muted);
  32879. offline.undo();
  32880. check ("one undo step: back to snapshot 1", m[1].volume == 0.7f);
  32881. {
  32882. const auto file = juce::File (prefix + "-b16-snapshots.lynx");
  32883. juce::String error;
  32884. const auto saved = lynx::ProjectFile::save (offline.getSong(), file, error);
  32885. const auto back = lynx::ProjectFile::load (file, error);
  32886. check ("saved and loaded: the snapshots and A/B", saved && back && back->mixSnapshots == offline.getSong().mixSnapshots
  32887. && back->mixSnapshotCurrent == offline.getSong().mixSnapshotCurrent
  32888. && back->mixSnapshotPrevious == offline.getSong().mixSnapshotPrevious);
  32889. file.deleteFile();
  32890. }
  32891. // ---- B18: Split at silence -------------------------------------------------------------------------------------
  32892. {
  32893. // a "vocal take": 0.5 s silence, three phrases with pauses of 0.6 s and 0.15 s, quiet hiss in the gaps
  32894. const double rate = 44100.0;
  32895. juce::AudioBuffer<float> buffer (1, (int) (rate * 4.0));
  32896. buffer.clear();
  32897. juce::Random noise (190);
  32898. for (int i = 0; i < buffer.getNumSamples(); ++i)
  32899. {
  32900. const auto t = i / rate;
  32901. const auto phrase = (t >= 0.5 && t < 1.4) || (t >= 2.0 && t < 2.6) || (t >= 2.75 && t < 3.3);
  32902. buffer.setSample (0, i, phrase ? (float) (0.4 * std::sin (juce::MathConstants<double>::twoPi * 180.0 * t) * (0.6 + 0.4 * std::sin (6.0 * t)))
  32903. : (noise.nextFloat() - 0.5f) * 0.0004f);
  32904. }
  32905. const auto wav = juce::File (prefix + "-b18-take.wav");
  32906. wav.deleteFile();
  32907. juce::WavAudioFormat format;
  32908. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (format.createWriterFor (wav.createOutputStream().release(), rate, 1, 16, {}, 0)))
  32909. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  32910. auto song = lynx::Song::makeDefault();
  32911. song.channels.push_back ({});
  32912. song.channels.back().name = "Vocal take";
  32913. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  32914. song.channels.back().samplePath = wav.getFullPathName().toStdString();
  32915. lynx::Clip c;
  32916. c.kind = lynx::ClipKind::audio;
  32917. c.channel = (int) song.channels.size() - 1;
  32918. c.track = 1;
  32919. c.start = 4 * lynx::ppq;
  32920. c.length = (std::int64_t) std::llround (4.0 * song.bpm / 60.0 * lynx::ppq); // (the whole file at the song tempo)
  32921. song.playlist.push_back (c);
  32922. offline.setSong (std::move (song));
  32923. offline.dispatchPendingMessages();
  32924. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  32925. ui.resized();
  32926. auto& playlist = ui.getPlaylistForSnapshot();
  32927. const auto index = (int) offline.getSong().playlist.size() - 1;
  32928. const auto menu = playlist.getClipMenuForSnapshot (index);
  32929. const auto* item = find (menu, lynx::tr ("Split at silence..."));
  32930. const auto* splitHere = find (menu, lynx::tr ("Split here"));
  32931. check ("clip menu: Split at silence... in LYNX extras, enabled", item != nullptr && item->isEnabled && splitHere != nullptr);
  32932. savePng (columnMenuImage (menu), prefix + "-b18-01-clip-menu.png");
  32933. {
  32934. auto dialog = playlist.makeSplitSilenceDialogForSnapshot (index);
  32935. write (*dialog, "b18-02-dialog");
  32936. }
  32937. offline.dispatchPendingMessages();
  32938. write (ui, "b18-03-playlist-before");
  32939. juce::String why;
  32940. const auto made = playlist.splitClipsAtSilence ({ index }, lynx::PlaylistComponent::splitSilenceOptions(), &why);
  32941. offline.dispatchPendingMessages();
  32942. const auto& clips = offline.getSong().playlist;
  32943. std::vector<const lynx::Clip*> audio;
  32944. for (const auto& x : clips)
  32945. if (x.kind == lynx::ClipKind::audio)
  32946. audio.push_back (&x);
  32947. std::sort (audio.begin(), audio.end(), [] (const lynx::Clip* a, const lynx::Clip* b) { return a->start < b->start; });
  32948. const auto secondsAt = [&] (std::int64_t ticks) { return (double) (ticks - 4 * lynx::ppq) / lynx::ppq * 60.0 / offline.getSong().bpm; };
  32949. check ("split into 2 clips (the 0.15 s pause stays inside): " + juce::String (made) + ", " + why, made == 2 && audio.size() == 2);
  32950. if (audio.size() == 2)
  32951. check ("the clips start at the phrases less the pre-roll, end after them: " + juce::String (secondsAt (audio[0]->start), 3) + "-"
  32952. + juce::String (secondsAt (audio[0]->end()), 3) + ", " + juce::String (secondsAt (audio[1]->start), 3) + "-" + juce::String (secondsAt (audio[1]->end()), 3),
  32953. std::abs (secondsAt (audio[0]->start) - 0.49) < 0.02 && std::abs (secondsAt (audio[0]->end()) - 1.45) < 0.02
  32954. && std::abs (secondsAt (audio[1]->start) - 1.99) < 0.02 && std::abs (secondsAt (audio[1]->end()) - 3.35) < 0.02
  32955. && audio[1]->offset - audio[0]->offset == audio[1]->start - audio[0]->start);
  32956. write (ui, "b18-04-playlist-after");
  32957. offline.undo();
  32958. check ("one undo step", offline.getSong().playlist.size() == clips.size() && std::count_if (offline.getSong().playlist.begin(), offline.getSong().playlist.end(),
  32959. [] (const lynx::Clip& x) { return x.kind == lynx::ClipKind::audio; }) == 1);
  32960. lynx::stripsilence::Options loud;
  32961. loud.thresholdDb = -1.0f;
  32962. check ("all below the threshold: nothing split", playlist.splitClipsAtSilence ({ index }, loud, &why) == 0);
  32963. wav.deleteFile();
  32964. }
  32965. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  32966. }
  32967. void runMapShot190ef (const juce::String& prefix)
  32968. {
  32969. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32970. lynx::AudioEngine offline (false);
  32971. lynx::MainComponent ui (offline, false);
  32972. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  32973. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  32974. const auto write = [&prefix] (juce::Component& c, const char* name) {
  32975. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  32976. file.deleteFile();
  32977. juce::FileOutputStream out (file);
  32978. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  32979. };
  32980. juce::String checks;
  32981. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  32982. using namespace lynx::remotemap;
  32983. ui.setVisible (true);
  32984. // the Pattern layout first: Ctrl+M stays FL's metronome there and no map mode starts
  32985. {
  32986. const auto before = offline.getTransport().metronome.load();
  32987. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  32988. check ("Pattern layout: Ctrl+M is the metronome, no map mode", ui.getMapMode() == Mode::off && offline.getTransport().metronome.load() != before);
  32989. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  32990. ui.setMapMode (Mode::midi);
  32991. check ("Pattern layout: setMapMode stays off", ui.getMapMode() == Mode::off);
  32992. }
  32993. ui.setClipLaunchWorkflow (true);
  32994. offline.editSong ([] (lynx::Song& s) {
  32995. if (s.mixer.size() < 6)
  32996. s.mixer.resize (6);
  32997. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Reverb" };
  32998. for (int i = 1; i < 6; ++i)
  32999. s.mixer[(std::size_t) i].name = inserts[i];
  33000. const int channels = (int) s.channels.size();
  33001. s.channels.resize ((std::size_t) channels + 3);
  33002. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  33003. for (int k = 0; k < 3; ++k)
  33004. {
  33005. auto& ch = s.channels[(std::size_t) (channels + k)];
  33006. ch.name = names[k];
  33007. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  33008. ch.mixerTrack = k + 1;
  33009. }
  33010. s.mixer[2].effects.clear();
  33011. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  33012. {
  33013. lynx::EffectSlot fx;
  33014. fx.kind = kind;
  33015. const auto& info = lynx::effectInfo (kind);
  33016. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  33017. fx.params[k] = info.params[k].defaultValue;
  33018. s.mixer[2].effects.push_back (fx);
  33019. }
  33020. while (s.patterns.size() < 3)
  33021. s.patterns.emplace_back();
  33022. const char* patterns[] { "Beat", "Bassline", "Chords" };
  33023. for (int p = 0; p < 3; ++p)
  33024. {
  33025. auto& pattern = s.patterns[(std::size_t) p];
  33026. pattern.name = patterns[p];
  33027. lynx::Note n;
  33028. n.channel = channels + p;
  33029. n.key = 48 + p * 5;
  33030. pattern.notes = { n };
  33031. pattern.lengthTicks = 4 * lynx::ppq;
  33032. }
  33033. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  33034. const char* tracks[] { "Drums", "Bass", "Keys", "Vox" };
  33035. for (int t = 0; t < 4; ++t)
  33036. s.playlistTracks[(std::size_t) t].name = tracks[t];
  33037. for (int t = 0; t < 3; ++t)
  33038. for (int r = 0; r < 3; ++r)
  33039. {
  33040. lynx::Clip clip;
  33041. clip.pattern = t;
  33042. clip.length = 4 * lynx::ppq;
  33043. lynx::launcher::setClip (s, t, r, clip);
  33044. }
  33045. auto& grid = lynx::launcher::ensureGrid (s);
  33046. const char* scenes[] { "Intro", "Verse", "Drop" };
  33047. grid.scenes.resize (4);
  33048. for (int r = 0; r < 3; ++r)
  33049. grid.scenes[(std::size_t) r].name = scenes[r];
  33050. // some mappings, as the lesson's pictures show them (pads on slots and scenes, knobs on volume and pan)
  33051. assignMidi (s, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, -1 });
  33052. assignMidi (s, Target::slot (1, 0), { 0, lynx::linkNoteBase + 37, -1 });
  33053. assignMidi (s, Target::sceneLaunch (1), { 0, lynx::linkNoteBase + 44, -1 });
  33054. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }), { 0, 17, -1 });
  33055. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }), { 0, 16, -1 });
  33056. assignMidi (s, Target::of (lynx::RemoteAction::play), { 0, 118, -1 });
  33057. setRange (s, rows (s, Mode::midi)[0], 0.0f, 0.85f);
  33058. assignKey (s, Target::slot (0, 1), 'A');
  33059. assignKey (s, Target::slot (1, 1), 'S');
  33060. assignKey (s, Target::sceneLaunch (2), '3');
  33061. assignKey (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 }), 'V');
  33062. }, false);
  33063. offline.dispatchPendingMessages();
  33064. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist, lynx::workspace::Panel::browser }); // (no floating Channel Rack over the grid)
  33065. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  33066. offline.dispatchPendingMessages();
  33067. ui.resized();
  33068. if (auto* detail = ui.getDetailViewForSnapshot())
  33069. {
  33070. detail->showSelection (1, 0);
  33071. detail->setPage (lynx::DetailView::Page::devices);
  33072. }
  33073. ui.resized();
  33074. offline.dispatchPendingMessages();
  33075. write (ui, "00-clip-launch-before");
  33076. // Ctrl+M in the Clip-launch layout: MIDI Map Mode (the metronome stays as it was)
  33077. const auto metronome = offline.getTransport().metronome.load();
  33078. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  33079. check ("Clip-launch layout: Ctrl+M starts MIDI Map Mode", ui.getMapMode() == Mode::midi && offline.getTransport().metronome.load() == metronome);
  33080. auto* overlay = ui.mapOverlayForSnapshot();
  33081. auto* list = ui.mappingBrowserForSnapshot();
  33082. if (overlay == nullptr || list == nullptr)
  33083. {
  33084. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no overlay\n");
  33085. return;
  33086. }
  33087. overlay->refresh();
  33088. const auto& spots = overlay->spots();
  33089. const auto count = [&] (lynx::RemoteAction a) { return (int) std::count_if (spots.begin(), spots.end(), [a] (const lynx::mapmode::Spot& p) { return p.target.action == a; }); };
  33090. const auto params = [&] (lynx::AutomationTargetKind k) {
  33091. return (int) std::count_if (spots.begin(), spots.end(), [k] (const lynx::mapmode::Spot& p) { return p.target.action == lynx::RemoteAction::parameter && p.target.param.kind == k; });
  33092. };
  33093. check ("overlay: clip slots (" + juce::String (count (lynx::RemoteAction::clipSlot)) + ")", count (lynx::RemoteAction::clipSlot) >= 12);
  33094. check ("overlay: scene launch buttons (" + juce::String (count (lynx::RemoteAction::sceneLaunch)) + ")", count (lynx::RemoteAction::sceneLaunch) >= 4);
  33095. check ("overlay: track stop buttons", count (lynx::RemoteAction::trackStop) >= 4);
  33096. check ("overlay: Stop all clips, Session Record", count (lynx::RemoteAction::stopAllClips) == 1 && count (lynx::RemoteAction::sessionRecord) == 1);
  33097. check ("overlay: transport play / stop / record / metronome", count (lynx::RemoteAction::play) == 1 && count (lynx::RemoteAction::stop) == 1
  33098. && count (lynx::RemoteAction::record) == 1 && count (lynx::RemoteAction::metronome) == 1);
  33099. check ("overlay: tempo", params (lynx::AutomationTargetKind::tempo) == 1);
  33100. check ("overlay: mixer volume / pan (" + juce::String (params (lynx::AutomationTargetKind::mixerVolume)) + " / " + juce::String (params (lynx::AutomationTargetKind::mixerPan)) + ")",
  33101. params (lynx::AutomationTargetKind::mixerVolume) >= 3 && params (lynx::AutomationTargetKind::mixerPan) >= 3);
  33102. check ("overlay: device knobs (" + juce::String (params (lynx::AutomationTargetKind::effectParam)) + ")", params (lynx::AutomationTargetKind::effectParam) >= 2);
  33103. // a click on Keys' first slot selects it; a MIDI control assigns it (as the engine's catch would)
  33104. for (const auto& spot : spots)
  33105. if (spot.target == Target::slot (2, 0))
  33106. {
  33107. auto source = juce::Desktop::getInstance().getMainMouseSource();
  33108. const auto now = juce::Time::getCurrentTime();
  33109. const auto at = spot.area.getCentre().toFloat();
  33110. overlay->mouseDown (juce::MouseEvent (source, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
  33111. overlay, overlay, now, at, now, 1, false));
  33112. break;
  33113. }
  33114. if (spots.empty())
  33115. {
  33116. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no spots\n");
  33117. return;
  33118. }
  33119. check ("a click selects the slot", overlay->selection() == std::optional<Target> (Target::slot (2, 0)));
  33120. check ("the overlay takes clicks only on elements", overlay->hitTest (spots.front().area.getCentreX(), spots.front().area.getCentreY()) && ! overlay->hitTest (2, ui.getHeight() - 2));
  33121. check ("a pad assigns it", overlay->assignMidi ({ 0, lynx::linkNoteBase + 38, -1 }) && midiOf (offline.getSong(), Target::slot (2, 0)).number == lynx::linkNoteBase + 38);
  33122. check ("the same pad again on track 0 is refused", ! (overlay->select (Target::slot (0, 2)), overlay->assignMidi ({ 0, lynx::linkNoteBase + 36, -1 })));
  33123. overlay->select (Target::slot (2, 0));
  33124. list->setMode (Mode::midi);
  33125. list->selectRow (0);
  33126. ui.resized();
  33127. overlay->refresh();
  33128. write (ui, "01-midi-map-mode");
  33129. check ("Mapping Browser rows (MIDI): " + juce::String ((int) list->rowsShown().size()), list->rowsShown().size() == 7);
  33130. write (*list, "02-mapping-browser-midi");
  33131. saveMenus (juce::StringArray { "Row" }, std::vector<juce::PopupMenu> { list->rowMenu (0) }, prefix + "-03-row-menu.png");
  33132. // Ctrl+K: Key Map Mode; a key assigns the selected element
  33133. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  33134. check ("Ctrl+K switches to Key Map Mode", ui.getMapMode() == Mode::key && offline.getMapMode() == Mode::key);
  33135. overlay->select (Target::sceneLaunch (0));
  33136. ui.keyPressed (juce::KeyPress ('1', {}, '1'));
  33137. check ("a key assigns the selected scene", keyOf (offline.getSong(), Target::sceneLaunch (0)).key == '1');
  33138. overlay->select (Target::sceneLaunch (1));
  33139. ui.keyPressed (juce::KeyPress ('A', {}, 'a'));
  33140. check ("a key already on a slot is refused for a scene", ! keyOf (offline.getSong(), Target::sceneLaunch (1)).found);
  33141. overlay->refresh();
  33142. write (ui, "04-key-map-mode");
  33143. write (*list, "05-mapping-browser-key");
  33144. {
  33145. // round 190em: Min / Max in the parameter's unit, Path "<track> | Mixer", Name "Track Volume" / "Slot n"
  33146. const lynx::remotemap::Target volume = Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 });
  33147. const auto [path, name] = lynx::mapmode::describe (offline, volume);
  33148. check ("browser: volume row Path / Name = " + path + " / " + name, path == "Bass | Mixer" && name == "Track Volume");
  33149. check ("browser: volume Min / Max = " + lynx::mapmode::rangeText (offline, volume, 0.0f) + " / " + lynx::mapmode::rangeText (offline, volume, 1.0f),
  33150. lynx::mapmode::rangeText (offline, volume, 0.0f) == juce::String::fromUTF8 ("\xe2\x88\x92\xe2\x88\x9e dB")
  33151. && lynx::mapmode::rangeText (offline, volume, 1.0f).endsWith (" dB"));
  33152. const lynx::remotemap::Target pan = Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 });
  33153. check ("browser: pan Min / Max = " + lynx::mapmode::rangeText (offline, pan, 0.25f) + " / " + lynx::mapmode::rangeText (offline, pan, 0.5f),
  33154. lynx::mapmode::rangeText (offline, pan, 0.25f) == "50L" && lynx::mapmode::rangeText (offline, pan, 0.5f) == "C"
  33155. && lynx::mapmode::rangeText (offline, pan, 1.0f) == "100R");
  33156. const auto typed = lynx::mapmode::rangeValueOf (offline, volume, "0 dB");
  33157. check ("browser: typing 0 dB", typed.has_value() && std::abs (lynx::mapmode::rangeText (offline, volume, *typed).getDoubleValue()) < 0.15);
  33158. check ("browser: typing 50L", lynx::mapmode::rangeValueOf (offline, pan, "50L") == std::optional<float> (0.25f));
  33159. check ("browser: Key column = " + lynx::mapmode::listKeyText ('V') + ", " + lynx::mapmode::listKeyText ('3'),
  33160. lynx::mapmode::listKeyText ('V') == "Key v" && lynx::mapmode::listKeyText ('3') == "Key 3");
  33161. check ("browser: slot row Name = " + lynx::mapmode::describe (offline, Target::slot (0, 2)).second,
  33162. lynx::mapmode::describe (offline, Target::slot (0, 2)) == std::pair<juce::String, juce::String> ("Drums", "Slot 3"));
  33163. }
  33164. // off again: the key mapping on a parameter toggles it between Min and Max
  33165. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  33166. check ("Ctrl+K again ends it", ui.getMapMode() == Mode::off && ! overlay->isVisible() && ! list->isVisible());
  33167. const lynx::AutomationTarget keysVolume { lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 };
  33168. // (round 190em, Live 12.4.16: the first press goes to Min, then Max, then Min)
  33169. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  33170. check ("the mapped key V moves Bass's volume to Min first", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  33171. ui.keyStateChanged (false); // (V is not down any more: its release)
  33172. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  33173. check ("again: to Max", std::abs (offline.currentTargetValue (keysVolume) - 1.0f) < 0.01f);
  33174. ui.keyStateChanged (false);
  33175. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  33176. check ("again: to Min", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  33177. ui.keyStateChanged (false);
  33178. // the title bar switches
  33179. ui.setMapMode (Mode::midi);
  33180. write (ui, "06-switches-midi-on");
  33181. ui.setMapMode (Mode::off);
  33182. ui.setClipLaunchWorkflow (false);
  33183. check ("leaving the Clip-launch layout ends the map mode", ui.getMapMode() == Mode::off);
  33184. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33185. }
  33186. void runSceneShot190ef (const juce::String& prefix)
  33187. {
  33188. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33189. lynx::AudioEngine offline (false);
  33190. lynx::MainComponent ui (offline, false);
  33191. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  33192. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  33193. const auto write = [&prefix] (juce::Component& c, const char* name) {
  33194. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33195. file.deleteFile();
  33196. juce::FileOutputStream out (file);
  33197. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  33198. };
  33199. juce::String checks;
  33200. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  33201. ui.setVisible (true);
  33202. lynx::DetailView::shownSetting = false;
  33203. ui.setClipLaunchWorkflow (true);
  33204. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  33205. offline.editSong ([] (lynx::Song& s) {
  33206. const int channels = (int) s.channels.size();
  33207. s.channels.resize ((std::size_t) channels + 3);
  33208. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  33209. for (int k = 0; k < 3; ++k)
  33210. {
  33211. auto& ch = s.channels[(std::size_t) (channels + k)];
  33212. ch.name = names[k];
  33213. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  33214. }
  33215. while (s.patterns.size() < 3)
  33216. s.patterns.emplace_back();
  33217. const char* patterns[] { "Beat", "Bassline", "Chords" };
  33218. for (int p = 0; p < 3; ++p)
  33219. {
  33220. auto& pattern = s.patterns[(std::size_t) p];
  33221. pattern.name = patterns[p];
  33222. lynx::Note n;
  33223. n.channel = channels + p;
  33224. n.key = 48 + p * 5;
  33225. pattern.notes = { n };
  33226. pattern.lengthTicks = 4 * lynx::ppq;
  33227. }
  33228. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  33229. const char* tracks[] { "Drums", "Bass", "Keys" };
  33230. const std::uint32_t colours[] { 0xFFE0533Bu, 0xFF3B8BE0u, 0xFF46C27Au };
  33231. for (int t = 0; t < 3; ++t)
  33232. {
  33233. s.playlistTracks[(std::size_t) t].name = tracks[t];
  33234. s.playlistTracks[(std::size_t) t].colour = colours[t];
  33235. }
  33236. for (int t = 0; t < 3; ++t)
  33237. for (int r = 0; r < 3; ++r)
  33238. if (! (t == 2 && r == 0))
  33239. {
  33240. lynx::Clip clip;
  33241. clip.pattern = t;
  33242. clip.length = 4 * lynx::ppq;
  33243. lynx::launcher::setClip (s, t, r, clip);
  33244. }
  33245. auto& grid = lynx::launcher::ensureGrid (s);
  33246. grid.scenes.resize (4);
  33247. const char* scenes[] { "Intro", "Verse", "Drop" };
  33248. for (int r = 0; r < 3; ++r)
  33249. grid.scenes[(std::size_t) r].name = scenes[r];
  33250. lynx::session::setSceneTempo (s, 1, 128.0);
  33251. lynx::session::setSceneSignature (s, 1, 3, 4); // (as the live check's "Verse": 3 / 4)
  33252. lynx::session::setSceneSignature (s, 2, 6, 8); // (round 190em: a denominator of its own)
  33253. grid.scenes[2].colour = 0xFF8E5BD6u;
  33254. }, false);
  33255. offline.dispatchPendingMessages();
  33256. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  33257. offline.dispatchPendingMessages();
  33258. ui.resized();
  33259. auto* gridView = ui.getClipGridForSnapshot();
  33260. if (gridView == nullptr)
  33261. {
  33262. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid\n");
  33263. return;
  33264. }
  33265. lynx::clipGridSceneTempoShown() = true;
  33266. lynx::refreshClipGrid (*gridView);
  33267. lynx::selectClipGridScene (*gridView, 1);
  33268. write (*gridView, "01-scene-fields");
  33269. {
  33270. // round 190em: a plain scene's launch triangle in Live's dark grey (#1E1E1E), scene 4 (row 3)
  33271. const auto image = lynx::shot::snapshot (*gridView);
  33272. int dark = 0;
  33273. for (int y = 0; y < image.getHeight(); ++y)
  33274. for (int x = image.getWidth() - 240; x < image.getWidth() - 180; ++x)
  33275. if (const auto p = image.getPixelAt (x, y); y > 3 * 24 + 26 && y < 4 * 24 + 26 && std::abs (p.getRed() - 0x1e) <= 2
  33276. && std::abs (p.getGreen() - 0x1e) <= 2 && std::abs (p.getBlue() - 0x1e) <= 2)
  33277. ++dark;
  33278. check ("plain scene triangle in Live's #1E1E1E (" + juce::String (dark) + " px)", dark >= 20);
  33279. }
  33280. saveMenus (juce::StringArray { "Scene menu (Verse)" }, std::vector<juce::PopupMenu> { lynx::clipGridSceneMenu (*gridView, 1) }, prefix + "-02-scene-menu.png");
  33281. saveMenus (juce::StringArray { "Scene tempo field", "Scene time signature field" },
  33282. std::vector<juce::PopupMenu> { lynx::clipGridSceneFieldMenu (*gridView, 1, 1), lynx::clipGridSceneFieldMenu (*gridView, 2, 2) },
  33283. prefix + "-03-field-menus.png");
  33284. saveMenus (juce::StringArray { "Column title (Bass)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*gridView, 1) }, prefix + "-04-title-menu.png");
  33285. const auto clipsIn = [&offline] (int row) {
  33286. int n = 0;
  33287. if (const auto& g = offline.getSong().clipGrid)
  33288. for (int t = 0; t < 8; ++t)
  33289. n += lynx::launcher::clipAt (*g, t, row) != nullptr ? 1 : 0;
  33290. return n;
  33291. };
  33292. const auto before = clipsIn (1);
  33293. const auto dup = lynx::duplicateClipGridScene (*gridView, 1);
  33294. offline.dispatchPendingMessages();
  33295. const auto& scenesNow = offline.getSong().clipGrid->scenes;
  33296. check ("duplicate: Verse's copy is row 2, with its clips and tempo", dup == 2 && clipsIn (2) == before && scenesNow.size() > 2
  33297. && scenesNow[2].name == "Verse" && scenesNow[2].tempo == 128.0);
  33298. write (*gridView, "05-scene-duplicated");
  33299. const auto cap = lynx::captureClipGridScene (*gridView, 3, { 0, 2, 1 }); // Drums row 0, Bass row 2, Keys row 1
  33300. offline.dispatchPendingMessages();
  33301. check ("capture: a new row 4 with the three playing clips", cap == 4 && clipsIn (4) == 3);
  33302. {
  33303. const auto& sc = offline.getSong().clipGrid->scenes;
  33304. check ("capture while playing: the new scene is plain (no name, fields off)", sc.size() > 4 && sc[4] == lynx::ClipGridScene {});
  33305. }
  33306. write (*gridView, "06-scene-captured");
  33307. // round 190em: nothing plays: an empty scene like the selected one (name, tempo, signature), selected
  33308. const auto empty = lynx::captureClipGridScene (*gridView, 1, { -1, -1 });
  33309. offline.dispatchPendingMessages();
  33310. {
  33311. const auto& sc = offline.getSong().clipGrid->scenes;
  33312. check ("capture with nothing playing: an empty row 2 named Verse, 128 BPM, 3 / 4", empty == 2 && clipsIn (2) == 0 && sc[2].name == "Verse"
  33313. && sc[2].tempo == 128.0 && sc[2].beatsPerBar == 3 && sc[2].beatUnit == 4);
  33314. }
  33315. write (*gridView, "06b-scene-captured-stopped");
  33316. // round 190em: Capture and Insert while clips play: playback moves to the new row (the runtime view shows what
  33317. // the player reports once the published song holds the moved slots)
  33318. {
  33319. const auto rowsBefore = offline.getSong().clipGrid->scenes.size();
  33320. lynx::selectClipGridScene (*gridView, 0);
  33321. const auto at = lynx::captureClipGridScene (*gridView, 0, { 0, 0, -1 });
  33322. offline.dispatchPendingMessages();
  33323. const auto& g = *offline.getSong().clipGrid;
  33324. check ("capture while playing: row 1 holds the moved playing slots", at == 1 && g.scenes.size() == rowsBefore + 1
  33325. && clipsIn (1) == 2 && clipsIn (0) == 2 && g.scenes[1] == lynx::ClipGridScene {});
  33326. if (auto* runtime = offline.launcherStateForSnapshot())
  33327. for (int t = 0; t < 2; ++t)
  33328. runtime->tracks[(std::size_t) t].playing.store (1);
  33329. lynx::refreshClipGrid (*gridView);
  33330. write (*gridView, "09-capture-playing-moves");
  33331. if (auto* runtime = offline.launcherStateForSnapshot())
  33332. for (int t = 0; t < 2; ++t)
  33333. runtime->tracks[(std::size_t) t].playing.store (-1);
  33334. }
  33335. // round 190em: the fields as "n / d", a selected field, Del = Return to Default
  33336. lynx::clipGridSceneTempoShown() = true;
  33337. lynx::refreshClipGrid (*gridView);
  33338. {
  33339. const auto& sc = offline.getSong().clipGrid->scenes;
  33340. int verse = -1;
  33341. for (int r = 0; r < (int) sc.size() && verse < 0; ++r)
  33342. if (sc[(std::size_t) r].name == "Verse" && sc[(std::size_t) r].tempo > 0.0)
  33343. verse = r;
  33344. lynx::selectClipGridSceneField (*gridView, verse, 1);
  33345. write (*gridView, "10-field-selected");
  33346. gridView->keyPressed (juce::KeyPress (juce::KeyPress::deleteKey));
  33347. offline.dispatchPendingMessages();
  33348. const auto& after = offline.getSong().clipGrid->scenes;
  33349. check ("Del on a selected tempo field returns it to default (scene kept)", verse >= 0 && after.size() == sc.size()
  33350. && after[(std::size_t) verse].tempo == 0.0 && after[(std::size_t) verse].beatsPerBar == 3);
  33351. write (*gridView, "11-field-returned-to-default");
  33352. }
  33353. // round 190em: Capture MIDI to the armed track (Bass), the selected scene's slot, the tempo from the phrase
  33354. {
  33355. offline.stop();
  33356. offline.setGridTrackArmed (1, true, true);
  33357. lynx::selectClipGridScene (*gridView, 0);
  33358. int empty = 0;
  33359. while (lynx::launcher::clipAt (*offline.getSong().clipGrid, 1, empty) != nullptr)
  33360. ++empty;
  33361. const auto now = juce::Time::getMillisecondCounterHiRes();
  33362. const auto beat = 60000.0 / 148.0;
  33363. for (int i = 0; i < 8; ++i)
  33364. {
  33365. const auto at = now - 9.0 * beat + i * beat;
  33366. offline.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  33367. offline.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  33368. }
  33369. int placed = -1;
  33370. bool into = true;
  33371. const auto r = offline.captureMidiToSlot (1, empty, placed, into);
  33372. offline.dispatchPendingMessages();
  33373. check ("Capture MIDI: 8 notes into Bass row " + juce::String (placed) + ", tempo " + juce::String (offline.getSong().bpm, 2),
  33374. r.notes == 8 && placed == empty && ! into && std::abs (offline.getSong().bpm - 148.0) < 0.5 && offline.getTransport().playing.load());
  33375. const auto& capturedGrid = *offline.getSong().clipGrid;
  33376. const auto* capturedClip = lynx::launcher::clipAt (capturedGrid, 1, placed);
  33377. const auto* slot = capturedClip != nullptr ? &capturedGrid.slots[(std::size_t) capturedClip->gridSlot] : nullptr;
  33378. check ("Capture MIDI: the clip has no name of its own (blank label, as Live)", slot != nullptr && slot->name.empty() && slot->blankName);
  33379. if (auto* runtime = offline.launcherStateForSnapshot())
  33380. runtime->tracks[1].playing.store (placed);
  33381. lynx::refreshClipGrid (*gridView);
  33382. write (*gridView, "12-capture-midi");
  33383. if (auto* runtime = offline.launcherStateForSnapshot())
  33384. runtime->tracks[1].playing.store (-1);
  33385. offline.stop();
  33386. }
  33387. write (ui, "07-window");
  33388. lynx::clipGridSceneTempoShown() = false;
  33389. lynx::refreshClipGrid (*gridView);
  33390. write (*gridView, "08-fields-off");
  33391. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33392. }
  33393. void runDrawShot190ef (const juce::String& prefix)
  33394. {
  33395. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33396. lynx::AudioEngine offline (false);
  33397. lynx::MainComponent ui (offline, false);
  33398. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  33399. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  33400. const auto write = [&prefix] (juce::Component& c, const char* name) {
  33401. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33402. file.deleteFile();
  33403. juce::FileOutputStream out (file);
  33404. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  33405. };
  33406. juce::String checks;
  33407. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  33408. ui.setVisible (true);
  33409. ui.setClipLaunchWorkflow (true);
  33410. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  33411. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  33412. lynx::autolanes::setShown (true);
  33413. offline.editSong ([] (lynx::Song& s) {
  33414. if (s.mixer.size() < 4)
  33415. s.mixer.resize (4);
  33416. s.mixer[1].name = "Bass";
  33417. s.mixer[2].name = "Pad";
  33418. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  33419. s.playlistTracks[0].name = "Bass";
  33420. s.playlistTracks[0].mode = lynx::PlaylistTrackMode::audio;
  33421. s.playlistTracks[0].mixerTrack = 1;
  33422. s.playlistTracks[1].name = "Pad";
  33423. s.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  33424. s.playlistTracks[1].mixerTrack = 2;
  33425. }, false);
  33426. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0);
  33427. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerPan, 2, 0, 0 }, 1);
  33428. offline.editSong ([] (lynx::Song& s) {
  33429. for (int t = 0; t < 2; ++t)
  33430. if (! s.playlistTracks[(std::size_t) t].lanes.empty())
  33431. s.playlistTracks[(std::size_t) t].lanes[0].height = 110;
  33432. }, false);
  33433. offline.dispatchPendingMessages();
  33434. auto& playlist = ui.getPlaylistForSnapshot();
  33435. playlist.setViewForSnapshot (180.0, 0, 0);
  33436. ui.resized();
  33437. offline.dispatchPendingMessages();
  33438. const auto& song = offline.getSong();
  33439. const auto laneA = song.playlistTracks[0].lanes.empty() ? -1 : song.playlistTracks[0].lanes[0].automation;
  33440. const auto laneB = song.playlistTracks[1].lanes.empty() ? -1 : song.playlistTracks[1].lanes[0].automation;
  33441. check ("two lanes made", laneA >= 0 && laneB >= 0);
  33442. if (laneA < 0 || laneB < 0)
  33443. {
  33444. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33445. return;
  33446. }
  33447. write (ui, "00-lanes-before");
  33448. const auto before = song.automations[(std::size_t) laneA].points;
  33449. // a drag through the Playlist's own handlers (the events a real mouse sends)
  33450. auto source = juce::Desktop::getInstance().getMainMouseSource();
  33451. const auto now = juce::Time::getCurrentTime();
  33452. const auto stroke = [&] (int track, const std::vector<juce::Point<float>>& path, juce::ModifierKeys extra) {
  33453. const juce::ModifierKeys mods (juce::ModifierKeys::leftButtonModifier | extra.getRawFlags());
  33454. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
  33455. return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, path.front(), now, 1, dragged);
  33456. };
  33457. juce::ignoreUnused (track);
  33458. // (the engine joins the edits of one press into one undo step while a button is down)
  33459. const auto held = juce::ModifierKeys::currentModifiers;
  33460. juce::ModifierKeys::currentModifiers = mods;
  33461. playlist.mouseDown (event (path.front(), mods, false));
  33462. for (std::size_t i = 1; i < path.size(); ++i)
  33463. playlist.mouseDrag (event (path[i], mods, true));
  33464. juce::ModifierKeys::currentModifiers = held;
  33465. playlist.mouseUp (event (path.back(), extra, true));
  33466. };
  33467. const auto bodyA = playlist.laneBodyForSnapshot (0, 0), bodyB = playlist.laneBodyForSnapshot (1, 0);
  33468. const auto bar = (double) (4 * lynx::ppq);
  33469. const auto x = [&] (double bars) { return (float) playlist.xOfTickForSnapshot (bars * bar); };
  33470. const auto y = [] (juce::Rectangle<float> body, float v) { return body.getBottom() - v * body.getHeight(); };
  33471. lynx::drawmode::set (true);
  33472. // steps: a rise over bar 1 and a fall over bar 2, at the Playlist's grid (Line, at this zoom)
  33473. std::vector<juce::Point<float>> steps;
  33474. for (int k = 0; k <= 16; ++k)
  33475. steps.push_back ({ x (1.0 + k / 16.0) + 2.0f, y (bodyA, 0.15f + 0.05f * (float) k) });
  33476. for (int k = 0; k <= 16; ++k)
  33477. steps.push_back ({ x (2.0 + k / 16.0) + 2.0f, y (bodyA, 0.95f - 0.05f * (float) k) });
  33478. stroke (0, steps, {});
  33479. const auto& afterSteps = offline.getSong().automations[(std::size_t) laneA].points;
  33480. check ("Draw Mode drag made steps (" + juce::String ((int) afterSteps.size()) + " points)", afterSteps.size() > before.size() + 4);
  33481. bool unchangedOutside = true;
  33482. for (double t = 0.0; t < 6.0 * bar; t += 37.0)
  33483. if ((t < bar - 1.0 || t > 3.1 * bar) && std::abs (lynx::automationCurveAt (before, t) - lynx::automationCurveAt (afterSteps, t)) > 1.0e-4f)
  33484. unchangedOutside = false;
  33485. check ("the curve outside the drawn bars is unchanged", unchangedOutside);
  33486. {
  33487. // flat inside each drawn cell: the values in a cell's first and last tick are the same
  33488. int flatCells = 0, cells = 0;
  33489. for (double t = bar; t < 3.0 * bar; t += lynx::ppq / 4.0)
  33490. {
  33491. ++cells;
  33492. if (std::abs (lynx::automationCurveAt (afterSteps, t + 1.0) - lynx::automationCurveAt (afterSteps, t + lynx::ppq / 4.0 - 1.0)) < 1.0e-5f)
  33493. ++flatCells;
  33494. }
  33495. check ("each sixteenth inside bars 2-3 is flat (" + juce::String (flatCells) + " / " + juce::String (cells) + ")", flatCells == cells);
  33496. }
  33497. // freehand: Alt (no grid) on the pad's pan lane, a wave over bars 1-4
  33498. const auto panBefore = offline.getSong().automations[(std::size_t) laneB].points;
  33499. // (off-screen every press has the same mouse-down time, which the undo history uses to join one press's edits:
  33500. // an edit with no button down in between separates the two strokes, as a real second press does)
  33501. offline.editSong ([] (lynx::Song&) {});
  33502. std::vector<juce::Point<float>> wave;
  33503. for (int k = 0; k <= 60; ++k)
  33504. wave.push_back ({ x (1.0 + 3.0 * k / 60.0), y (bodyB, 0.5f + 0.4f * std::sin ((float) k * 0.3f)) });
  33505. stroke (1, wave, juce::ModifierKeys (juce::ModifierKeys::altModifier));
  33506. const auto& pan = offline.getSong().automations[(std::size_t) laneB].points;
  33507. check ("Alt drag drew freehand (" + juce::String ((int) pan.size()) + " points)", pan.size() > 30);
  33508. playlist.repaint();
  33509. write (ui, "01-draw-mode-steps-and-freehand");
  33510. if (auto* parent = playlist.getParentComponent())
  33511. write (*parent, "01b-playlist");
  33512. // one stroke is one undo step
  33513. offline.undo();
  33514. check ("one undo takes the whole freehand stroke back", offline.getSong().automations[(std::size_t) laneB].points == panBefore);
  33515. // Draw Mode off: the same press adds one point, as before
  33516. lynx::drawmode::set (false);
  33517. const auto countOff = offline.getSong().automations[(std::size_t) laneA].points.size();
  33518. stroke (0, { { x (4.5), y (bodyA, 0.8f) } }, {});
  33519. check ("Draw Mode off: a press adds one point", offline.getSong().automations[(std::size_t) laneA].points.size() == countOff + 1);
  33520. // the Options menu (Clip-launch layout) with the switch
  33521. lynx::drawmode::set (true);
  33522. {
  33523. const auto names = ui.getMenuNamesForSnapshot();
  33524. const auto index = names.indexOf (TRANS ("Options"));
  33525. if (index >= 0)
  33526. saveMenus (juce::StringArray { "Options" }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-02-options-menu.png");
  33527. check ("Options menu found", index >= 0);
  33528. }
  33529. lynx::drawmode::set (false);
  33530. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33531. }
  33532. void runClipEnvShot190gi (const juce::String& prefix)
  33533. {
  33534. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33535. lynx::AudioEngine offline (false);
  33536. lynx::MainComponent ui (offline, false);
  33537. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  33538. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  33539. const auto write = [&prefix] (juce::Component& c, const char* name) {
  33540. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33541. file.deleteFile();
  33542. juce::FileOutputStream out (file);
  33543. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  33544. };
  33545. juce::String checks;
  33546. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  33547. // two files: a sustained pad (4 s, a slow swell, for the envelope over its waveform) and a one-bar loop of clicks
  33548. const auto writeWav = [] (const juce::File& file, int seconds, const std::function<float (int, double)>& fn) {
  33549. const double rate = 48000.0;
  33550. juce::AudioBuffer<float> buffer (2, (int) (rate * seconds));
  33551. for (int ch = 0; ch < 2; ++ch)
  33552. for (int i = 0; i < buffer.getNumSamples(); ++i)
  33553. buffer.setSample (ch, i, fn (i, rate));
  33554. file.deleteFile();
  33555. if (auto out = std::unique_ptr<juce::FileOutputStream> (file.createOutputStream()))
  33556. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  33557. {
  33558. out.release();
  33559. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  33560. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  33561. }
  33562. return file;
  33563. };
  33564. const auto pad = writeWav (juce::File (prefix + "-pad.wav"), 4, [] (int i, double rate) {
  33565. const auto t = i / rate;
  33566. return (float) (0.45 * (std::sin (juce::MathConstants<double>::twoPi * 220.0 * t) + 0.5 * std::sin (juce::MathConstants<double>::twoPi * 331.0 * t))
  33567. * (0.7 + 0.3 * std::sin (juce::MathConstants<double>::twoPi * 1.5 * t)));
  33568. });
  33569. const auto loop = writeWav (juce::File (prefix + "-loop.wav"), 2, [] (int i, double) {
  33570. const auto k = i % 12000;
  33571. const auto hit = i / 12000;
  33572. return k < 3000 ? (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8) : 0.0f;
  33573. });
  33574. ui.setVisible (true);
  33575. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  33576. offline.editSong ([&] (lynx::Song& s) {
  33577. const auto add = [&s] (const char* name, const juce::File& file) {
  33578. lynx::ChannelDef ch;
  33579. ch.name = name;
  33580. ch.instrument = lynx::InstrumentKind::audioClip;
  33581. ch.samplePath = file.getFullPathName().toStdString();
  33582. s.channels.push_back (ch);
  33583. return (int) s.channels.size() - 1;
  33584. };
  33585. const auto padChannel = add ("Pad", pad), loopChannel = add ("Loop", loop);
  33586. s.playlist.clear();
  33587. lynx::Clip a;
  33588. a.kind = lynx::ClipKind::audio;
  33589. a.channel = padChannel;
  33590. a.length = 8 * lynx::ppq;
  33591. a.track = 0;
  33592. s.playlist.push_back (a);
  33593. a.track = 1;
  33594. s.playlist.push_back (a);
  33595. lynx::Clip b = a;
  33596. b.channel = loopChannel;
  33597. b.track = 2;
  33598. b.length = 4 * lynx::ppq;
  33599. s.playlist.push_back (b);
  33600. // the first clip: a volume envelope (a swell, a dip, FL's curve modes on two segments)
  33601. auto& e = lynx::clipenv::own (s, s.playlist[0]);
  33602. e.shown = lynx::clipenv::volumeLane;
  33603. e.volume = { { 0, 0.15f, 0.0f, 0 }, { lynx::ppq * 2, 1.0f, -0.6f, 0 }, { lynx::ppq * 4, 1.0f, 0.0f, 0 },
  33604. { lynx::ppq * 5, 0.45f, 0.0f, 2 }, { lynx::ppq * 6, 0.9f, 0.0f, 0 }, { lynx::ppq * 8, 0.9f, 0.0f, 0 } };
  33605. // the second: its pan lane shown (only pan made)
  33606. lynx::clipenv::show (s, s.playlist[1], lynx::clipenv::panLane);
  33607. auto& p = lynx::clipenv::own (s, s.playlist[1]);
  33608. p.pan = { { 0, 0.5f, 0.0f, 0 }, { lynx::ppq * 2, 0.1f, 0.0f, 0 }, { lynx::ppq * 4, 0.9f, 0.0f, 0 }, { lynx::ppq * 6, 0.5f, 0.0f, 0 } };
  33609. if (s.playlistTracks.size() < 3)
  33610. s.playlistTracks.resize (3);
  33611. for (int t = 0; t < 3; ++t)
  33612. s.playlistTracks[(std::size_t) t].height = 96;
  33613. }, false);
  33614. offline.dispatchPendingMessages();
  33615. auto& playlist = ui.getPlaylistForSnapshot();
  33616. playlist.setViewForSnapshot (360.0, 0, 0);
  33617. ui.resized();
  33618. offline.dispatchPendingMessages();
  33619. (void) lynx::shot::snapshot (ui); // (a paint starts the waveform analyses; the shot waits for them)
  33620. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  33621. offline.dispatchPendingMessages();
  33622. write (ui, "01-playlist-envelopes");
  33623. // the clip menu: LYNX's extras with Clip envelope ›, Auto-warp, Quantize audio (Auto-warp run from it on the loop)
  33624. {
  33625. const auto menu = playlist.getClipMenuForSnapshot (2);
  33626. const juce::PopupMenu* envelopeMenu = nullptr;
  33627. bool autoWarp = false, quantize = false;
  33628. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  33629. {
  33630. if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
  33631. envelopeMenu = it.getItem().subMenu.get();
  33632. autoWarp = autoWarp || (it.getItem().text == lynx::tr ("Auto-warp") && it.getItem().isEnabled);
  33633. quantize = quantize || (it.getItem().text == lynx::tr ("Quantize audio") && it.getItem().isEnabled);
  33634. }
  33635. check ("clip menu: Clip envelope submenu, Auto-warp, Quantize audio", envelopeMenu != nullptr && autoWarp && quantize);
  33636. saveMenus (juce::StringArray { lynx::tr ("Audio clip"), lynx::tr ("Clip envelope") },
  33637. std::vector<juce::PopupMenu> { menu, envelopeMenu != nullptr ? *envelopeMenu : juce::PopupMenu() }, prefix + "-02-clip-menu.png");
  33638. check ("Auto-warp from the clip menu places markers", clickMenuItem (menu, lynx::tr ("Auto-warp")));
  33639. offline.dispatchPendingMessages();
  33640. const auto& s = offline.getSong();
  33641. const auto& loopClip = s.playlist[2];
  33642. check ("the loop's channel is warped", s.channels[(std::size_t) loopClip.channel].sampler.warp.size() >= 2
  33643. && s.channels[(std::size_t) loopClip.channel].sampler.keepPitch);
  33644. // the first clip's menu: Show volume envelope ticked
  33645. const auto first = playlist.getClipMenuForSnapshot (0);
  33646. bool ticked = false;
  33647. for (juce::PopupMenu::MenuItemIterator it (first); it.next();)
  33648. if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
  33649. for (juce::PopupMenu::MenuItemIterator sub (*it.getItem().subMenu); sub.next();)
  33650. ticked = ticked || (sub.getItem().text == lynx::tr ("Show volume envelope") && sub.getItem().isTicked);
  33651. check ("Show volume envelope is ticked on the first clip", ticked);
  33652. }
  33653. // gestures through the Playlist's own handlers
  33654. auto source = juce::Desktop::getInstance().getMainMouseSource();
  33655. const auto now = juce::Time::getCurrentTime();
  33656. const auto press = [&] (juce::Point<float> from, juce::Point<float> to, juce::ModifierKeys button, juce::ModifierKeys extra) {
  33657. const juce::ModifierKeys mods (button.getRawFlags() | extra.getRawFlags());
  33658. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
  33659. return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, from, now, 1, dragged);
  33660. };
  33661. const auto held = juce::ModifierKeys::currentModifiers;
  33662. juce::ModifierKeys::currentModifiers = mods;
  33663. playlist.mouseDown (event (from, mods, false));
  33664. if (to != from)
  33665. playlist.mouseDrag (event (to, mods, true));
  33666. juce::ModifierKeys::currentModifiers = held;
  33667. playlist.mouseUp (event (to, extra, to != from));
  33668. };
  33669. const auto x = [&] (double beats) { return (float) playlist.xOfTickForSnapshot (beats * lynx::ppq); };
  33670. {
  33671. const auto body = playlist.curveBodyForSnapshot (0);
  33672. const auto points = offline.getSong().clipEnvelopes[(std::size_t) offline.getSong().playlist[0].envelope].volume.size();
  33673. // [RMB] in the curve's area adds a point there (FL's in-Playlist automation editing, round 165)
  33674. press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.3f * body.getHeight() },
  33675. juce::ModifierKeys::rightButtonModifier, {});
  33676. offline.dispatchPendingMessages();
  33677. const auto& s = offline.getSong();
  33678. const auto* e = lynx::clipenv::of (s, s.playlist[0]);
  33679. check ("[RMB] on the clip's volume lane adds a point", e != nullptr && e->volume.size() == points + 1
  33680. && std::abs (lynx::automationCurveAt (e->volume, 7.0 * lynx::ppq) - 0.3f) < 0.05f);
  33681. // drag that point up with the Pencil
  33682. press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.7f * body.getHeight() },
  33683. juce::ModifierKeys::leftButtonModifier, {});
  33684. offline.dispatchPendingMessages();
  33685. const auto* moved = lynx::clipenv::of (offline.getSong(), offline.getSong().playlist[0]);
  33686. check ("dragging the point moves it", moved != nullptr && std::abs (lynx::automationCurveAt (moved->volume, 7.0 * lynx::ppq) - 0.7f) < 0.05f);
  33687. check ("the edits are undoable", offline.canUndo());
  33688. }
  33689. write (ui, "03-playlist-edited");
  33690. {
  33691. // warp: a double-click on the loop clip's flag strip adds a marker; Alt + drag on its line (mid clip) moves it
  33692. const auto bounds = playlist.clipBoundsForSnapshot (2);
  33693. const auto channelOf = [&] { return offline.getSong().playlist[2].channel; };
  33694. const auto markers = [&] { return offline.getSong().channels[(std::size_t) channelOf()].sampler.warp; };
  33695. const auto before = markers().size();
  33696. const juce::Point<float> strip { x (1.5), (float) bounds.getY() + 13.0f + 3.0f };
  33697. playlist.mouseDoubleClick (juce::MouseEvent (source, strip, juce::ModifierKeys::leftButtonModifier, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist,
  33698. now, strip, now, 2, false));
  33699. offline.dispatchPendingMessages();
  33700. check ("a double-click on the flag strip adds a warp marker", markers().size() == before + 1);
  33701. if (markers().size() != before + 1)
  33702. checks << " (strip seconds " << playlist.warpStripSecondsForSnapshot (2, strip.toInt()) << ", played markers "
  33703. << (int) playlist.warpMarkerCountForSnapshot (2) << ", file seconds " << playlist.clipFileSecondsForSnapshot (2)
  33704. << ", channel markers " << (int) before << ", clip at " << bounds.toString() << ", strip " << strip.toString() << ")\n";
  33705. int added = -1;
  33706. for (int k = 0; k < (int) markers().size(); ++k)
  33707. if (std::abs (markers()[(std::size_t) k].beats - 1.5) < 0.05)
  33708. added = k;
  33709. check ("the marker sits on the beat it was added on", added > 0);
  33710. if (added > 0)
  33711. {
  33712. const juce::Point<float> line { x (1.5), (float) bounds.getCentreY() + 10.0f };
  33713. press (line, line.translated (x (1.75) - x (1.5), 0.0f), juce::ModifierKeys::leftButtonModifier, juce::ModifierKeys::altModifier);
  33714. offline.dispatchPendingMessages();
  33715. check ("Alt + drag on a marker's line moves it", added < (int) markers().size() && std::abs (markers()[(std::size_t) added].beats - 1.75) < 0.05);
  33716. }
  33717. }
  33718. write (ui, "04-playlist-warp");
  33719. // the Clip-launch layout: the Clip View's Envelopes tab of a grid audio clip
  33720. offline.editSong ([&] (lynx::Song& s) {
  33721. auto clip = s.playlist[0];
  33722. clip.start = 0;
  33723. lynx::launcher::setClip (s, 0, 0, clip);
  33724. lynx::launcher::ensureGrid (s).scenes.resize (std::max<std::size_t> (1, lynx::launcher::ensureGrid (s).scenes.size()));
  33725. }, false);
  33726. offline.dispatchPendingMessages();
  33727. const auto shootPanel = [&] (const char* name, bool envelopes, std::uint8_t lane) {
  33728. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  33729. if (panel == nullptr)
  33730. return false;
  33731. panel->setSize (1100, 300);
  33732. for (auto* child : panel->getChildren())
  33733. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (envelopes ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
  33734. if (b->onClick)
  33735. b->onClick();
  33736. if (lane != 0)
  33737. offline.editSong ([lane] (lynx::Song& s) {
  33738. if (s.clipGrid)
  33739. if (auto* c = const_cast<lynx::Clip*> (lynx::launcher::clipAt (*s.clipGrid, 0, 0)); c != nullptr)
  33740. lynx::clipenv::show (s, *c, lane);
  33741. }, false);
  33742. offline.dispatchPendingMessages();
  33743. write (*panel, name);
  33744. return true;
  33745. };
  33746. check ("Clip View: Sample tab", shootPanel ("05-clipview-sample", false, 0));
  33747. check ("Clip View: Envelopes tab, Clip > Gain", shootPanel ("06-clipview-envelopes-gain", true, lynx::clipenv::volumeLane));
  33748. check ("Clip View: Envelopes tab, Mixer > Track Panning", shootPanel ("07-clipview-envelopes-pan", true, lynx::clipenv::panLane));
  33749. {
  33750. const auto* c = offline.getSong().clipGrid ? lynx::launcher::clipAt (*offline.getSong().clipGrid, 0, 0) : nullptr;
  33751. check ("the grid clip keeps the volume envelope", c != nullptr && lynx::clipenv::activeOf (offline.getSong(), *c) != nullptr);
  33752. }
  33753. shootPanel ("08-clipview-sample-again", false, 0); // (the tab choice back to Sample for the next run)
  33754. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33755. }
  33756. void runGapsShot190kf (const juce::String& prefix, const juce::String& wavPath)
  33757. {
  33758. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33759. lynx::AudioEngine offline (false);
  33760. juce::String checks;
  33761. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  33762. // the probe's file, else a LYNX-made stand-in (8.42 s of a decaying 220 Hz tone every half second, 44.1 kHz)
  33763. auto wav = juce::File (wavPath);
  33764. if (! wav.existsAsFile())
  33765. {
  33766. wav = juce::File (prefix + "-probe.wav");
  33767. wav.deleteFile();
  33768. const double rate = 44100.0;
  33769. juce::AudioBuffer<float> buffer (1, (int) (rate * 8.421));
  33770. for (int k = 0; k < buffer.getNumSamples(); ++k)
  33771. {
  33772. const auto t = std::fmod (k / rate, 0.5);
  33773. buffer.setSample (0, k, (float) (0.5 * std::exp (-t * 6.0) * std::sin (2.0 * juce::MathConstants<double>::pi * 220.0 * k / rate)));
  33774. }
  33775. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  33776. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  33777. {
  33778. out.release();
  33779. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  33780. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  33781. }
  33782. }
  33783. double seconds = 0.0;
  33784. {
  33785. juce::AudioFormatManager formats;
  33786. formats.registerBasicFormats();
  33787. if (std::unique_ptr<juce::AudioFormatReader> r (formats.createReaderFor (wav)); r != nullptr && r->sampleRate > 0.0)
  33788. seconds = (double) r->lengthInSamples / r->sampleRate;
  33789. }
  33790. check ("probe file " + wav.getFileName() + " " + juce::String (seconds, 3) + " s", seconds > 1.0);
  33791. const auto beats = seconds * 2.0; // (warped at 120 BPM, its own tempo)
  33792. offline.editSong ([&] (lynx::Song& s) {
  33793. s.bpm = 120.0;
  33794. lynx::ChannelDef ch;
  33795. ch.name = "warped";
  33796. ch.instrument = lynx::InstrumentKind::audioClip;
  33797. ch.samplePath = wav.getFullPathName().toStdString();
  33798. ch.sampler.keepPitch = true;
  33799. ch.sampler.stretchMethod = lynx::StretchMethod::complex;
  33800. ch.sampler.stretchBeats = (float) beats;
  33801. ch.sampler.warp = { { 0.0, 0.0 }, { seconds * 0.3, beats * 0.25 }, { seconds * 0.55, beats * 0.5 }, { seconds, beats } };
  33802. s.channels.push_back (ch);
  33803. const auto c = (int) s.channels.size() - 1;
  33804. lynx::Clip audio;
  33805. audio.kind = lynx::ClipKind::audio;
  33806. audio.channel = c;
  33807. audio.offset = 2 * lynx::ppq; // (Loop Position 1.3, Length 2.0.0 → 3.3, Start 1.4: the probe set's)
  33808. audio.length = 8 * lynx::ppq;
  33809. lynx::launcher::setClip (s, 0, 0, audio);
  33810. lynx::launcher::ensureGrid (s).scenes.resize (1);
  33811. auto& grid = *s.clipGrid;
  33812. for (auto& g : grid.clips)
  33813. if (g.gridSlot >= 0)
  33814. {
  33815. grid.slots[(std::size_t) g.gridSlot].loop = true;
  33816. grid.slots[(std::size_t) g.gridSlot].startMarker = lynx::ppq;
  33817. }
  33818. }, false);
  33819. offline.dispatchPendingMessages();
  33820. const auto editorOf = [] (juce::Component& panel) -> juce::Component* {
  33821. for (auto* child : panel.getChildren())
  33822. if (child->isVisible() && child->getWidth() > 400 && dynamic_cast<juce::Button*> (child) == nullptr)
  33823. return child;
  33824. return nullptr;
  33825. };
  33826. const auto write = [&] (juce::Component& panel, const char* name) {
  33827. offline.dispatchPendingMessages();
  33828. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33829. file.deleteFile();
  33830. juce::FileOutputStream out (file);
  33831. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (panel), out);
  33832. };
  33833. const auto slotOf = [&] (auto&& fn) {
  33834. offline.editSong ([&] (lynx::Song& s) {
  33835. for (auto& g : s.clipGrid->clips)
  33836. if (g.gridSlot >= 0)
  33837. fn (g, s.clipGrid->slots[(std::size_t) g.gridSlot]);
  33838. }, false);
  33839. offline.dispatchPendingMessages();
  33840. };
  33841. {
  33842. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  33843. check ("the Clip View panel", panel != nullptr);
  33844. if (panel == nullptr)
  33845. return;
  33846. panel->setSize (1390, 670);
  33847. if (auto* e = editorOf (*panel)) // (the Clip-launch layout's beat-time view; off-screen there is no layout)
  33848. lynx::setAudioEditorBeatTimeForSnapshot (*e, 1);
  33849. write (*panel, "01-loop-on-start-marker");
  33850. // perf (round gaps190kf): the sample editor painted 40 times with the warp time line (a grid clip's editor)
  33851. // and without it (the same channel's editor panel, no grid clip) — ms per full paint
  33852. {
  33853. const auto timeIt = [] (juce::Component& c) {
  33854. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  33855. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  33856. for (int k = 0; k < 40; ++k)
  33857. {
  33858. juce::Graphics g (image);
  33859. c.paintEntireComponent (g, false);
  33860. }
  33861. return (juce::Time::getMillisecondCounterHiRes() - t0) / 40.0;
  33862. };
  33863. if (auto* withLane = editorOf (*panel))
  33864. {
  33865. auto plain = lynx::makeAudioEditorPanel (offline, (int) offline.getSong().channels.size() - 1, -1, true);
  33866. plain->setSize (withLane->getWidth(), withLane->getHeight());
  33867. lynx::setAudioEditorBeatTimeForSnapshot (*plain, 1);
  33868. offline.dispatchPendingMessages();
  33869. timeIt (*withLane);
  33870. timeIt (*plain);
  33871. double a = 0.0, b = 0.0;
  33872. for (int round = 0; round < 3; ++round)
  33873. {
  33874. a += timeIt (*withLane) / 3.0;
  33875. b += timeIt (*plain) / 3.0;
  33876. }
  33877. check ("paint ms: with the warp time line " + juce::String (a, 3) + ", without " + juce::String (b, 3), true);
  33878. }
  33879. }
  33880. auto* editor = editorOf (*panel);
  33881. check ("its sample editor", editor != nullptr);
  33882. if (editor != nullptr)
  33883. {
  33884. lynx::selectAudioEditorBraceForSnapshot (*editor, true);
  33885. write (*panel, "02-brace-selected");
  33886. lynx::selectAudioEditorBraceForSnapshot (*editor, false);
  33887. lynx::holdAudioEditorBraceForSnapshot (*editor, 2, 12 * lynx::ppq); // (the loop's end dragged to 4.1)
  33888. write (*panel, "03-loop-end-held-at-4.1");
  33889. lynx::holdAudioEditorBraceForSnapshot (*editor, 0, 0);
  33890. }
  33891. }
  33892. slotOf ([] (lynx::Clip& c, lynx::ClipGridSlot& slot) {
  33893. slot.loop = false;
  33894. slot.startMarker = 0;
  33895. c.offset = 0;
  33896. c.length = (std::int64_t) std::llround (10.0 * lynx::ppq);
  33897. });
  33898. {
  33899. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  33900. if (panel != nullptr)
  33901. {
  33902. panel->setSize (1390, 670);
  33903. if (auto* e = editorOf (*panel))
  33904. lynx::setAudioEditorBeatTimeForSnapshot (*e, 1);
  33905. write (*panel, "04-loop-off-start-end");
  33906. }
  33907. }
  33908. offline.editSong ([&] (lynx::Song& s) { lynx::clipsample::setWarp (s, (int) s.channels.size() - 1, false, seconds); }, false);
  33909. offline.dispatchPendingMessages();
  33910. {
  33911. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  33912. if (panel != nullptr)
  33913. {
  33914. panel->setSize (1390, 670);
  33915. if (auto* e = editorOf (*panel))
  33916. lynx::setAudioEditorBeatTimeForSnapshot (*e, 1);
  33917. write (*panel, "05-unwarped-seconds");
  33918. }
  33919. }
  33920. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33921. }
  33922. void runLiveFactsShot190gx (const juce::String& prefix)
  33923. {
  33924. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33925. lynx::AudioEngine offline (false);
  33926. juce::String checks;
  33927. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  33928. // a 1 kHz sine, 20 s at 48 kHz (Live's 190gu clip-envelope stimulus), −9 dBFS
  33929. const auto wav = juce::File (prefix + "-sine1k.wav");
  33930. wav.deleteFile();
  33931. {
  33932. const double rate = 48000.0;
  33933. juce::AudioBuffer<float> buffer (2, (int) (rate * 20.0));
  33934. for (int k = 0; k < buffer.getNumSamples(); ++k)
  33935. for (int ch = 0; ch < 2; ++ch)
  33936. buffer.setSample (ch, k, (float) (0.3535 * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * k / rate)));
  33937. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  33938. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  33939. {
  33940. out.release();
  33941. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  33942. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  33943. }
  33944. }
  33945. offline.editSong ([&wav] (lynx::Song& s) {
  33946. s.bpm = 120.0;
  33947. lynx::ChannelDef ch;
  33948. ch.name = "sine1k";
  33949. ch.instrument = lynx::InstrumentKind::audioClip;
  33950. ch.samplePath = wav.getFullPathName().toStdString();
  33951. s.channels.push_back (ch);
  33952. const auto c = (int) s.channels.size() - 1;
  33953. lynx::clipsample::setWarp (s, c, true, 20.0);
  33954. lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats);
  33955. lynx::Clip audio;
  33956. audio.kind = lynx::ClipKind::audio;
  33957. audio.channel = c;
  33958. audio.length = 40 * lynx::ppq;
  33959. // Live's Clip Gain staircase of the 190gu render (−1 … 1 in 0.1 steps, 2 beats each), as LYNX lane values
  33960. lynx::ClipEnvelope e;
  33961. for (int k = 0; k <= 20; ++k)
  33962. {
  33963. const auto v = lynx::clipenv::fromLive (lynx::clipenv::volumeLane, -1.0 + 0.1 * k);
  33964. for (const auto at : { 2 * k, 2 * k + 2 })
  33965. {
  33966. lynx::AutomationPoint p;
  33967. p.tick = (std::int64_t) at * lynx::ppq;
  33968. p.value = v;
  33969. e.volume.push_back (p);
  33970. }
  33971. }
  33972. e.shown = lynx::clipenv::volumeLane;
  33973. s.clipEnvelopes.push_back (e);
  33974. audio.envelope = (int) s.clipEnvelopes.size() - 1;
  33975. lynx::launcher::setClip (s, 0, 0, audio);
  33976. lynx::launcher::ensureGrid (s).scenes.resize (1);
  33977. }, false);
  33978. offline.dispatchPendingMessages();
  33979. const auto channelOf = [&] {
  33980. const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, 0);
  33981. return c != nullptr ? c->channel : -1;
  33982. };
  33983. const auto shoot = [&] (const char* name, int w, int h, int tab) {
  33984. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  33985. if (panel == nullptr)
  33986. return std::unique_ptr<juce::Component>();
  33987. panel->setSize (w, h);
  33988. if (tab != 0)
  33989. for (auto* child : panel->getChildren())
  33990. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (tab == 2 ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
  33991. if (b->onClick)
  33992. b->onClick();
  33993. offline.dispatchPendingMessages();
  33994. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33995. file.deleteFile();
  33996. juce::FileOutputStream out (file);
  33997. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
  33998. return panel;
  33999. };
  34000. const auto visibleText = [] (juce::Component& panel, const juce::String& text) {
  34001. for (auto* child : panel.getChildren())
  34002. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == text)
  34003. return b->isVisible();
  34004. return false;
  34005. };
  34006. const auto setMode = [&] (int method) {
  34007. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf(), method); }, false);
  34008. offline.dispatchPendingMessages();
  34009. };
  34010. check ("01 Beats (Preserve label + chooser, loop icon + Transient Envelope)", shoot ("01-audio-beats", 900, 250, 1) != nullptr);
  34011. setMode ((int) lynx::StretchMethod::tones);
  34012. check ("02 Tones (Grain Size 30.00)", shoot ("02-audio-tones", 900, 250, 1) != nullptr);
  34013. setMode ((int) lynx::StretchMethod::texture);
  34014. check ("03 Texture (Grain Size 65.00, Flux only when it plays)", shoot ("03-audio-texture", 900, 250, 1) != nullptr);
  34015. { // (round 190ik: Complex Pro plays, its Formants and Envelope show)
  34016. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setComplexPro (s, channelOf()); }, false);
  34017. offline.dispatchPendingMessages();
  34018. check ("04 Complex Pro (Formants 100.00, Envelope 128)", shoot ("04-audio-complex-pro", 900, 250, 1) != nullptr);
  34019. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setWarpLaw (s, channelOf(), 0); }, false);
  34020. offline.dispatchPendingMessages();
  34021. check ("04b Complex Pro of a project saved before 0.1.30 (law chooser, no Formants / Envelope)",
  34022. shoot ("04b-audio-complex-pro-classic", 900, 250, 1) != nullptr);
  34023. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setWarpLaw (s, channelOf(), 1); }, false);
  34024. offline.dispatchPendingMessages();
  34025. }
  34026. setMode ((int) lynx::StretchMethod::beats);
  34027. {
  34028. auto panel = shoot ("05-envelopes-clip-gain-staircase", 1390, 420, 2);
  34029. check ("05 Envelopes tab shown on a warped clip", panel != nullptr && visibleText (*panel, lynx::tr ("Envelopes")));
  34030. }
  34031. offline.editSong ([&] (lynx::Song& s) { lynx::clipsample::setWarp (s, channelOf(), false, 20.0); }, false);
  34032. offline.dispatchPendingMessages();
  34033. {
  34034. auto panel = shoot ("06-unwarped-sample-only", 1390, 420, 2);
  34035. check ("06 an unwarped clip has no Envelopes tab (Live)", panel != nullptr && ! visibleText (*panel, lynx::tr ("Envelopes"))
  34036. && visibleText (*panel, lynx::tr ("Sample")));
  34037. }
  34038. // the law: Live's staircase values round trip through the lane values
  34039. bool law = true;
  34040. for (int k = 0; k <= 20; ++k)
  34041. {
  34042. const auto L = -1.0 + 0.1 * k;
  34043. law = law && std::abs (lynx::clipenv::toLive (lynx::clipenv::volumeLane, lynx::clipenv::fromLive (lynx::clipenv::volumeLane, L)) - L) < 2.0e-3;
  34044. }
  34045. check ("Clip Gain values round trip (Live → lane → Live)", law);
  34046. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  34047. }
  34048. void runDvShot190hr (const juce::String& prefix)
  34049. {
  34050. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34051. lynx::AudioEngine offline (false);
  34052. lynx::MainComponent ui (offline, false);
  34053. ui.setSize (1600, 900);
  34054. juce::String checks;
  34055. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  34056. const auto write = [&prefix] (juce::Component& c, const char* name) {
  34057. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  34058. file.deleteFile();
  34059. juce::FileOutputStream out (file);
  34060. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  34061. };
  34062. ui.setVisible (true);
  34063. lynx::DetailView::shownSetting = true;
  34064. ui.selectTabForSnapshot (2);
  34065. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  34066. offline.editSong ([] (lynx::Song& s) {
  34067. const int ch = (int) s.channels.size();
  34068. s.channels.resize ((std::size_t) ch + 1);
  34069. s.channels[(std::size_t) ch].name = "Keys";
  34070. s.channels[(std::size_t) ch].instrument = lynx::InstrumentKind::synth;
  34071. while (s.patterns.empty())
  34072. s.patterns.emplace_back();
  34073. auto& p = s.patterns[0];
  34074. p.name = "Riff";
  34075. p.notes.clear();
  34076. const int keys[] { 62, 65, 69, 72, 64, 67 };
  34077. for (int i = 0; i < 6; ++i)
  34078. {
  34079. lynx::Note n;
  34080. n.channel = ch;
  34081. n.key = keys[i];
  34082. n.start = i * lynx::ppq / 2 + (i % 2 ? 37 : -0) + 11; // a little off the 1/16 grid
  34083. n.length = lynx::ppq / 3;
  34084. p.notes.push_back (n);
  34085. }
  34086. p.lengthTicks = 4 * lynx::ppq;
  34087. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  34088. s.playlistTracks[0].name = "Keys";
  34089. lynx::Clip clip;
  34090. clip.pattern = 0;
  34091. clip.length = 4 * lynx::ppq;
  34092. const auto id = lynx::launcher::setClip (s, 0, 0, clip);
  34093. lynx::launcher::setClip (s, 0, 1, clip);
  34094. auto& grid = lynx::launcher::ensureGrid (s);
  34095. grid.scenes.resize (3);
  34096. if (id >= 0)
  34097. {
  34098. auto& slot = grid.slots[(std::size_t) id];
  34099. slot.name = "Riff";
  34100. slot.startMarker = 2 * lynx::ppq; // Start 1. 3. 1 inside the loop 1. 1. 1 + 1 bar
  34101. slot.ownScale = true;
  34102. slot.scaleRoot = 2; // D, the scale list's first (Major)
  34103. slot.scaleIndex = (std::int16_t) lynx::projectkey::commonFirst().front();
  34104. slot.follow.enabled = true;
  34105. slot.follow.a = lynx::FollowKind::next;
  34106. slot.follow.b = lynx::FollowKind::jump;
  34107. slot.follow.jumpB = 1;
  34108. slot.follow.chanceA = 70;
  34109. slot.follow.chanceB = 30;
  34110. slot.follow.linked = true;
  34111. slot.follow.iterations = 2;
  34112. }
  34113. }, false);
  34114. offline.dispatchPendingMessages();
  34115. ui.resized();
  34116. auto* detail = ui.getDetailViewForSnapshot();
  34117. if (detail == nullptr)
  34118. {
  34119. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  34120. return;
  34121. }
  34122. detail->showSelection (0, 0);
  34123. detail->setPage (lynx::DetailView::Page::clip);
  34124. offline.dispatchPendingMessages();
  34125. ui.resized();
  34126. write (ui, "01-clip-view-midi");
  34127. write (*detail, "01b-detail-alone");
  34128. auto& roll = ui.getPianoRollForSnapshot();
  34129. check ("the docked editor uses the reference's grid (" + roll.liveGridTextForCheck() + ")", roll.liveGridOn() && roll.liveGridTextForCheck().isNotEmpty());
  34130. check ("Start marker inside the loop kept by the launcher (lead 2 beats)", lynx::launcher::startLead (offline.getSong().clipGrid->slots[0], 4 * lynx::ppq) == 2.0 * lynx::ppq);
  34131. {
  34132. std::vector<juce::PopupMenu> menus { roll.liveGridMenu() };
  34133. saveMenus (juce::StringArray { "Grid" }, menus, prefix + "-02-grid-menu.png");
  34134. }
  34135. roll.liveGrid.fixed = true;
  34136. roll.liveGrid.fixedIndex = lynx::livegrid::defaultFixed;
  34137. roll.resized();
  34138. const auto sixteenth = roll.gridStepForCheck();
  34139. roll.runAction ("pianoRoll.liveGridNarrower");
  34140. const auto narrower = roll.gridStepForCheck();
  34141. roll.runAction ("pianoRoll.liveGridTriplet");
  34142. const auto triplet = roll.gridStepForCheck();
  34143. check ("fixed 1/16 = 240 ticks, Ctrl+1 -> 1/32 = 120, Ctrl+3 -> 1/32T = 80 (" + juce::String (sixteenth) + ", " + juce::String (narrower) + ", " + juce::String (triplet) + ")",
  34144. sixteenth == lynx::ppq / 4 && narrower == lynx::ppq / 8 && triplet == lynx::ppq / 12);
  34145. write (roll, "03-editor-grid-1-32T");
  34146. roll.runAction ("pianoRoll.liveGridTriplet");
  34147. roll.runAction ("pianoRoll.liveGridWider");
  34148. const auto before = offline.getSong().patterns[0].notes;
  34149. roll.runAction ("pianoRoll.liveQuantize"); // (Live 12: Edit › Quantize, the Quantize tool's settings: Grid = 1/16 here)
  34150. offline.dispatchPendingMessages();
  34151. {
  34152. const auto& after = offline.getSong().patterns[0].notes;
  34153. bool onGrid = ! after.empty();
  34154. for (const auto& n : after)
  34155. onGrid = onGrid && n.start % (lynx::ppq / 4) == 0;
  34156. check ("Ctrl+U quantized every note start onto the editor's 1/16 grid", onGrid && after.size() == before.size() && after != before);
  34157. }
  34158. roll.runAction ("pianoRoll.liveQuantizeSettings"); // (Live 12: Quantize Settings… opens the MIDI Tools' Quantize tool)
  34159. offline.dispatchPendingMessages();
  34160. check ("Ctrl+Shift+U shows the MIDI Tools' Quantize tool", detail->midiToolsForSnapshot().getTool() == lynx::MidiToolsPanel::quantize
  34161. && detail->midiToolsForSnapshot().isVisible());
  34162. ui.resized();
  34163. write (*detail, "04-after-quantize-tool");
  34164. // an audio clip transposed +30 st 25 ct (Live's ±48 st)
  34165. const auto wav = juce::File (prefix + "-tone.wav");
  34166. wav.deleteFile();
  34167. {
  34168. const double rate = 48000.0;
  34169. juce::AudioBuffer<float> buffer (1, (int) (rate * 2.0));
  34170. for (int k = 0; k < buffer.getNumSamples(); ++k)
  34171. buffer.setSample (0, k, (float) (0.5 * std::sin (k * 0.05)));
  34172. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  34173. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  34174. {
  34175. out.release();
  34176. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  34177. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  34178. }
  34179. }
  34180. offline.editSong ([&wav] (lynx::Song& s) {
  34181. lynx::ChannelDef ch;
  34182. ch.name = "Tone";
  34183. ch.instrument = lynx::InstrumentKind::audioClip;
  34184. ch.samplePath = wav.getFullPathName().toStdString();
  34185. s.channels.push_back (ch);
  34186. lynx::Clip audio;
  34187. audio.kind = lynx::ClipKind::audio;
  34188. audio.channel = (int) s.channels.size() - 1;
  34189. audio.length = 4 * lynx::ppq;
  34190. audio.pitch = 30.25f;
  34191. lynx::launcher::setClip (s, 1, 0, audio);
  34192. }, false);
  34193. offline.dispatchPendingMessages();
  34194. if (auto panel = lynx::makeClipAudioPanel (offline, 1, 0))
  34195. {
  34196. panel->setSize (900, 250);
  34197. write (*panel, "06-audio-transpose-30");
  34198. check ("audio clip transpose +30.25 st kept", std::abs (lynx::launcher::clipAt (*offline.getSong().clipGrid, 1, 0)->pitch - 30.25f) < 1e-4f);
  34199. }
  34200. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  34201. }
  34202. void runWarpShot190fm (const juce::String& prefix)
  34203. {
  34204. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34205. lynx::AudioEngine offline (false);
  34206. juce::String checks;
  34207. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  34208. // a one-bar loop of clicks (2 s at 48 kHz) for the audio clips
  34209. const auto wav = juce::File (prefix + "-loop.wav");
  34210. wav.deleteFile();
  34211. {
  34212. const double rate = 48000.0;
  34213. juce::AudioBuffer<float> buffer (2, (int) (rate * 2.0));
  34214. buffer.clear();
  34215. for (int hit = 0; hit < 8; ++hit)
  34216. for (int k = 0; k < 3000; ++k)
  34217. for (int ch = 0; ch < 2; ++ch)
  34218. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
  34219. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  34220. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  34221. {
  34222. out.release();
  34223. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  34224. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  34225. }
  34226. }
  34227. offline.editSong ([&wav] (lynx::Song& s) {
  34228. lynx::ChannelDef ch;
  34229. ch.name = "Loop";
  34230. ch.instrument = lynx::InstrumentKind::audioClip;
  34231. ch.samplePath = wav.getFullPathName().toStdString();
  34232. s.channels.push_back (ch);
  34233. const auto c = (int) s.channels.size() - 1;
  34234. lynx::clipsample::setWarp (s, c, true, 2.0);
  34235. lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats); // (keeps the pitch: Beats, not Re-Pitch)
  34236. lynx::Clip audio;
  34237. audio.kind = lynx::ClipKind::audio;
  34238. audio.channel = c;
  34239. audio.length = 4 * lynx::ppq;
  34240. lynx::launcher::setClip (s, 0, 0, audio);
  34241. lynx::launcher::setClip (s, 0, 1, audio); // (a second clip on the same channel: O16)
  34242. lynx::launcher::ensureGrid (s).scenes.resize (2);
  34243. }, false);
  34244. offline.dispatchPendingMessages();
  34245. const auto shoot = [&] (const char* name) {
  34246. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  34247. if (panel == nullptr)
  34248. return false;
  34249. panel->setSize (900, 250);
  34250. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  34251. file.deleteFile();
  34252. juce::FileOutputStream out (file);
  34253. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
  34254. return true;
  34255. };
  34256. const auto channelOf = [&] (int scene) {
  34257. const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, scene);
  34258. return c != nullptr ? c->channel : -1;
  34259. };
  34260. const auto beatsOn = [&] { const auto& sm = offline.getSong().channels[(std::size_t) channelOf (0)].sampler; return sm.keepPitch && sm.stretchMethod == lynx::StretchMethod::beats; };
  34261. check ("01 Beats panel (defaults: Transients, Back-and-Forth, 100)", beatsOn() && shoot ("01-beats-defaults"));
  34262. offline.editSong ([&] (lynx::Song& s) {
  34263. const auto c = lynx::warpmodes::ownChannelForGridClip (s, 0, 0);
  34264. lynx::warpmodes::setPreserve (s, c, 3);
  34265. lynx::warpmodes::setLoopMode (s, c, 0);
  34266. lynx::warpmodes::setEnvelope (s, c, 40.0);
  34267. }, false);
  34268. offline.dispatchPendingMessages();
  34269. check ("O16: the first clip moved to its own channel, the second kept the old one", channelOf (0) != channelOf (1) && channelOf (0) >= 0 && channelOf (1) >= 0);
  34270. check ("02 Beats panel (1/8, Loop Off, 40)", beatsOn() && shoot ("02-beats-set"));
  34271. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::tones); }, false);
  34272. offline.dispatchPendingMessages();
  34273. check ("03 Tones panel (Grain Size 30)", shoot ("03-tones"));
  34274. offline.editSong ([&] (lynx::Song& s) {
  34275. lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::texture);
  34276. lynx::warpmodes::setGrain (s, channelOf (0), 120.0);
  34277. }, false);
  34278. offline.dispatchPendingMessages();
  34279. check ("04 Texture panel (Grain Size 120)", shoot ("04-texture"));
  34280. check ("Texture grain kept 120, Tones grain still 30", offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.textureGrain == 120.0f
  34281. && offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.tonesGrain == 30.0f);
  34282. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::complex); }, false);
  34283. offline.dispatchPendingMessages();
  34284. check ("05 Complex panel (no settings row)", shoot ("05-complex"));
  34285. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  34286. }
  34287. // LYNX --livelook190jnshot prefix [set.als]: round 190jn off screen (design190ia slices 13 CL-D, 17 CL-E, 18 CL-H,
  34288. // 19 CL-F, 25 CL-I: the Clip-launch layout in Ableton Live's look) — the Session mixer (selected, armed, muted,
  34289. // soloed, I/O on and off, peak pills), the Device View (cards, a card off and one folded, the hot-swap link, a Drum
  34290. // Rack's pads, an Instrument Rack's macros), the Clip View (MIDI and audio, three detail heights), the Info View with a
  34291. // hovered control and the status strip; with a Live set: its Arrangement in 19 px lanes, the 38 px option and a tall
  34292. // audio lane; every view once more in the classic LYNX look (View › Classic LYNX look). prefix-checks.txt
  34293. void runLiveLook190jnShot (const juce::String& prefix, const juce::String& set)
  34294. {
  34295. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34296. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  34297. juce::String checks;
  34298. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  34299. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  34300. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  34301. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  34302. const auto area = [&prefix] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) { saveArea (c, r, prefix + "-" + name + ".png"); };
  34303. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  34304. const auto w = juce::jlimit (800, 3840, size[0].getIntValue()), h = juce::jlimit (450, 2160, size[1].getIntValue());
  34305. const auto classicBefore = lynx::clipGridClassicLook();
  34306. const auto tallBefore = lynx::playlistTallLiveLanes();
  34307. lynx::clipGridClassicLook() = false;
  34308. lynx::playlistTallLiveLanes() = false;
  34309. lynx::DetailView::infoViewShown = true;
  34310. // ---- A. a synthetic set (round 190dr's, with a Drum Rack and an audio loop) -----------------------------------
  34311. const auto wav = juce::File (prefix + "-loop.wav");
  34312. wav.deleteFile();
  34313. {
  34314. const double rate = 48000.0;
  34315. juce::AudioBuffer<float> buffer (2, (int) (rate * 4.0));
  34316. buffer.clear();
  34317. for (int hit = 0; hit < 16; ++hit)
  34318. for (int k = 0; k < 9000 && hit * 12000 + k < buffer.getNumSamples(); ++k)
  34319. for (int ch = 0; ch < 2; ++ch)
  34320. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 2500.0) * 0.8));
  34321. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  34322. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  34323. {
  34324. out.release();
  34325. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  34326. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  34327. }
  34328. }
  34329. {
  34330. lynx::AudioEngine offline (false);
  34331. lynx::MainComponent ui (offline, false);
  34332. ui.setSize (w, h);
  34333. const auto settle = [&] {
  34334. for (int k = 0; k < 3; ++k)
  34335. offline.dispatchPendingMessages();
  34336. };
  34337. ui.setVisible (true);
  34338. lynx::DetailView::shownSetting = true;
  34339. lynx::DetailView::devicesPage = true;
  34340. lynx::DetailView::preferredHeight = 228;
  34341. ui.setClipLaunchWorkflow (true);
  34342. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  34343. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  34344. settle();
  34345. int audioChannel = -1;
  34346. const auto selectedChannel = offline.getSelectedChannel();
  34347. offline.editSong ([&audioChannel, selectedChannel] (lynx::Song& s) {
  34348. lynx::Clip audio;
  34349. if (! s.playlist.empty())
  34350. {
  34351. audio = s.playlist.front();
  34352. audioChannel = audio.channel;
  34353. s.playlist.clear();
  34354. }
  34355. const int channels = (int) s.channels.size();
  34356. s.channels.resize ((std::size_t) channels + 3);
  34357. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  34358. for (int k = 0; k < 3; ++k)
  34359. {
  34360. auto& ch = s.channels[(std::size_t) (channels + k)];
  34361. ch.name = names[k];
  34362. ch.instrument = k == 0 ? lynx::InstrumentKind::patcher : lynx::InstrumentKind::synth;
  34363. ch.mixerTrack = k + 1;
  34364. }
  34365. // the Drum kit: a Drum Rack with Live's 909 pad names, its two first macros mapped
  34366. {
  34367. auto& kit = s.channels[(std::size_t) channels].patcher;
  34368. kit = lynx::rack::makeDrumRack();
  34369. const char* pads[] { "Bass Drum", "Rim Shot", "Snare Drum", "Hand Clap", "Snare Drum", "Closed Hi Hat", "Snare Drum", "Bass Drum",
  34370. "Low Tom", "Mid Tom", "Open Hi Hat", "Hi Tom", "Crash", "Crash", "Ride", "Ride" };
  34371. for (int p = 0; p < 16; ++p)
  34372. {
  34373. lynx::PatchNode n;
  34374. n.generator = true;
  34375. n.channel.instrument = lynx::InstrumentKind::sampler;
  34376. n.channel.name = pads[p];
  34377. lynx::rack::addPad (kit, 36 + p, pads[p], n);
  34378. }
  34379. if (auto* r = lynx::rack::rackOf (kit))
  34380. {
  34381. r->name = "909 Core Kit";
  34382. r->showMacros = true;
  34383. r->showPads = true;
  34384. r->shownMacros = 8;
  34385. r->macros[0].name = "Low Gain";
  34386. r->macros[1].name = "Mid Gain";
  34387. }
  34388. for (int m = 0; m < 2; ++m)
  34389. {
  34390. lynx::RackMapping map;
  34391. map.target = lynx::RackMapping::Target::chainVolume;
  34392. map.chain = m;
  34393. lynx::rack::map (kit, m, map);
  34394. }
  34395. lynx::rack::compile (kit);
  34396. }
  34397. if (audioChannel >= 0)
  34398. s.channels[(std::size_t) audioChannel].mixerTrack = 5;
  34399. if (s.mixer.size() < 8)
  34400. s.mixer.resize (8);
  34401. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Loop", "Reverb", "Delay" };
  34402. for (int i = 1; i < 8; ++i)
  34403. s.mixer[(std::size_t) i].name = inserts[i];
  34404. s.mixer[1].volume = lynx::sessionmixer::positionForDb (-3.0);
  34405. s.mixer[2].pan = 0.3f;
  34406. s.mixer[2].effects.clear();
  34407. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay, lynx::EffectKind::reverb })
  34408. {
  34409. lynx::EffectSlot fx;
  34410. fx.kind = kind;
  34411. const auto& info = lynx::effectInfo (kind);
  34412. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  34413. fx.params[k] = info.params[k].defaultValue;
  34414. s.mixer[2].effects.push_back (fx);
  34415. }
  34416. s.mixer[2].effects[2].enabled = false; // (the Delay off: Live dims a device that is off)
  34417. s.mixer[3].muted = true; // the Keys' activator off
  34418. s.mixer[4].inputChannel = 0;
  34419. s.mixer[4].inputStereo = true;
  34420. s.mixer[4].monitor = lynx::InputMonitor::automatic;
  34421. s.mixer[5].solo = false; // (soloed later: Live greys every activator while a track is soloed)
  34422. for (auto [from, to, level] : std::initializer_list<std::tuple<int, int, float>> { { 1, 6, 0.35f }, { 2, 6, 0.6f }, { 3, 6, 0.8f }, { 2, 7, 0.25f }, { 4, 7, 0.5f } })
  34423. {
  34424. lynx::MixerSend send;
  34425. send.target = to;
  34426. send.level = lynx::faderGain (level);
  34427. s.mixer[(std::size_t) from].sends.push_back (send);
  34428. }
  34429. while (s.patterns.size() < 3)
  34430. s.patterns.emplace_back();
  34431. const char* patterns[] { "Beat", "Bassline", "Chords" };
  34432. for (int p = 0; p < 3; ++p)
  34433. {
  34434. auto& pattern = s.patterns[(std::size_t) p];
  34435. pattern.name = patterns[p];
  34436. pattern.notes.clear();
  34437. for (int k = 0; k < 6; ++k)
  34438. {
  34439. lynx::Note n;
  34440. n.channel = channels + p;
  34441. n.key = (p == 0 ? 36 : 48) + (k * 5) % 12 + p * 2;
  34442. n.start = (std::int64_t) k * lynx::ppq / 2;
  34443. n.length = lynx::ppq / 2;
  34444. n.velocity = 0.55f + 0.07f * (float) k;
  34445. pattern.notes.push_back (n);
  34446. }
  34447. pattern.lengthTicks = 4 * lynx::ppq;
  34448. }
  34449. // a "Lead" clip on the FX track for the Clip View's MIDI shot: notes of the rack's selected channel (the docked
  34450. // Piano roll edits its notes) in the Piano roll's opening rows
  34451. {
  34452. const auto kick = juce::jlimit (0, channels - 1, selectedChannel); // (the docked Piano roll edits the selected channel's notes)
  34453. lynx::Pattern lead;
  34454. lead.name = "Lead";
  34455. for (int k = 0; k < 6; ++k)
  34456. {
  34457. lynx::Note n;
  34458. n.channel = kick;
  34459. n.key = 79 + (k * 5) % 6; // (G6 .. C7 in FL's names, C5 = 60: the rows the docked Piano roll opens on)
  34460. n.start = (std::int64_t) k * lynx::ppq / 2;
  34461. n.length = lynx::ppq / 2;
  34462. n.velocity = 0.55f + 0.07f * (float) k;
  34463. lead.notes.push_back (n);
  34464. }
  34465. lead.lengthTicks = 4 * lynx::ppq;
  34466. s.patterns.push_back (lead);
  34467. }
  34468. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  34469. const char* tracks[] { "Drums", "Bass", "Keys", "Vox", "Loop", "FX" };
  34470. const std::uint32_t colours[] { 0xff9bc48d, 0xffd2e498, 0xffa595b5, 0xffcdf1f8, 0xfff7f47c, 0xffc6928b }; // (Live's palette)
  34471. for (int t = 0; t < 6; ++t)
  34472. {
  34473. s.playlistTracks[(std::size_t) t].name = tracks[t];
  34474. s.playlistTracks[(std::size_t) t].colour = colours[t];
  34475. }
  34476. s.playlistTracks[3].mode = lynx::PlaylistTrackMode::audio;
  34477. s.playlistTracks[3].mixerTrack = 4;
  34478. for (int t = 0; t < 3; ++t)
  34479. for (int r = 0; r < 3; ++r)
  34480. if (! (t == 2 && r == 0))
  34481. {
  34482. lynx::Clip clip;
  34483. clip.pattern = t;
  34484. clip.length = 4 * lynx::ppq;
  34485. lynx::launcher::setClip (s, t, r, clip);
  34486. }
  34487. {
  34488. lynx::Clip lead;
  34489. lead.pattern = (int) s.patterns.size() - 1;
  34490. lead.length = 4 * lynx::ppq;
  34491. lynx::launcher::setClip (s, 5, 0, lead);
  34492. }
  34493. if (audioChannel >= 0)
  34494. {
  34495. lynx::clipsample::setWarp (s, audioChannel, true, 4.0);
  34496. audio.track = 4;
  34497. audio.start = 0;
  34498. lynx::launcher::setClip (s, 4, 0, audio);
  34499. lynx::launcher::setClip (s, 4, 1, audio);
  34500. }
  34501. auto& grid = lynx::launcher::ensureGrid (s);
  34502. const char* scenes[] { "Intro", "Verse", "Drop" };
  34503. grid.scenes.resize (5);
  34504. for (int r = 0; r < 3; ++r)
  34505. grid.scenes[(std::size_t) r].name = scenes[r];
  34506. }, false);
  34507. settle();
  34508. offline.setGridTrackArmed (3, true);
  34509. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  34510. settle();
  34511. ui.resized();
  34512. auto* gridView = ui.getClipGridForSnapshot();
  34513. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  34514. auto* detail = ui.getDetailViewForSnapshot();
  34515. if (gridView == nullptr || mixer == nullptr || detail == nullptr)
  34516. {
  34517. check ("a grid, a Session mixer and a detail view", false);
  34518. return;
  34519. }
  34520. check ("the Live look is on (Clip-launch, classic off)", lynx::theme::livelook::active());
  34521. const auto meters = [&] {
  34522. mixer->tick();
  34523. const float peaks[] { 0.9f, 0.5f, 0.7f, 0.0f, 0.3f, 0.45f, 0.2f, 0.12f };
  34524. for (int i = 0; i < 8; ++i)
  34525. mixer->setMeterForSnapshot (i, peaks[i], peaks[i] * 0.85f, peaks[i] * 1.1f, peaks[i], i == 1 ? 1.2f : peaks[i] * 1.15f);
  34526. };
  34527. if (auto* runtime = offline.launcherStateForSnapshot())
  34528. {
  34529. runtime->tracks[0].playing.store (1);
  34530. runtime->tracks[0].progress.store (0.3f);
  34531. runtime->tracks[1].playing.store (1);
  34532. runtime->tracks[1].progress.store (0.3f);
  34533. runtime->tracks[4].playing.store (0);
  34534. runtime->tracks[4].progress.store (0.5f);
  34535. runtime->running.store (true);
  34536. }
  34537. lynx::selectClipGridSlotForSnapshot (*gridView, 1, 1); // (the Bass track selected: its strip #464646)
  34538. settle();
  34539. meters();
  34540. gridView->resized();
  34541. write (ui, "13-window");
  34542. write (*gridView, "13-grid-mixer");
  34543. area (*gridView, mixer->getBoundsInParent(), "13-mixer");
  34544. using Part = lynx::SessionMixerComponent::Part;
  34545. check ("mixer: the Drums strip has a peak pill in Live's look", ! mixer->partBounds (0, Part::peak).isEmpty());
  34546. check ("mixer: the Drums peak pill reads the clipped peak", mixer->loudestPeak (1) >= 1.0f);
  34547. line ("mixer: activator " + mixer->partBounds (0, Part::activator).toString() + ", solo " + mixer->partBounds (0, Part::solo).toString()
  34548. + ", arm " + mixer->partBounds (0, Part::arm).toString() + ", pan " + mixer->partBounds (0, Part::pan).toString()
  34549. + ", volume " + mixer->partBounds (0, Part::volume).toString() + ", peak " + mixer->partBounds (0, Part::peak).toString());
  34550. check ("mixer: the activator is Live's 21-23 px square", juce::jlimit (21, 23, mixer->partBounds (0, Part::activator).getWidth()) == mixer->partBounds (0, Part::activator).getWidth());
  34551. mixer->setHoverForSnapshot ({ 1, Part::solo, 0 });
  34552. area (*gridView, mixer->getBoundsInParent(), "13-mixer-hover-solo");
  34553. mixer->setHoverForSnapshot ({});
  34554. // the I/O section off (View › Mixer › I/O)
  34555. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.io = false; }, false);
  34556. settle();
  34557. gridView->resized();
  34558. meters();
  34559. area (*gridView, mixer->getBoundsInParent(), "13-mixer-io-off");
  34560. // a track soloed: Live greys every active activator (#757575, captured in shots/ref/live-mixer-solo-deactivated.png)
  34561. offline.editSong ([] (lynx::Song& s) { s.mixer[5].solo = true; }, false);
  34562. settle();
  34563. meters();
  34564. area (*gridView, mixer->getBoundsInParent(), "13-mixer-soloing");
  34565. offline.editSong ([] (lynx::Song& s) { s.mixer[5].solo = false; }, false);
  34566. settle();
  34567. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.io = true; }, false);
  34568. settle();
  34569. gridView->resized();
  34570. // ---- 19 + 25: the Device View of the Bass track (EQ, Compressor, Delay off, Reverb folded), the Info View ----
  34571. detail->showSelection (1, 1);
  34572. detail->setPage (lynx::DetailView::Page::devices);
  34573. settle();
  34574. ui.resized();
  34575. settle();
  34576. const auto cards = detail->cardCountForCheck();
  34577. line ("device view: " + juce::String (cards) + " cards, insert " + juce::String (detail->chainInsertForCheck()));
  34578. if (cards >= 5)
  34579. detail->toggleFoldForCheck (4);
  34580. detail->selectCardForCheck (1);
  34581. meters();
  34582. // the Info View with a hovered control: the Bass strip's activator, as the hint timer would give it
  34583. {
  34584. lynx::ui::Hint hint; // (the mixer's hint is its tooltip, read at the mouse: off screen its text for the part)
  34585. hint.text = mixer->tipForSnapshot ({ 1, Part::activator, 0 });
  34586. detail->setInfoHint (hint);
  34587. line ("info view: title '" + detail->infoViewForSnapshot().getTitleText() + "', body '" + detail->infoViewForSnapshot().getBodyText() + "'");
  34588. check ("info view: the hovered activator's hint shows", detail->infoViewForSnapshot().getBodyText().isNotEmpty());
  34589. }
  34590. write (ui, "19-window-devices");
  34591. write (*detail, "19-detail-devices");
  34592. area (*detail, detail->getLocalBounds().withTrimmedTop (detail->getHeight() - lynx::DetailView::stripHeight), "25-status-strip");
  34593. area (*detail, detail->getLocalBounds().withWidth (260), "25-info-view");
  34594. check ("device view: four effect cards and the instrument", cards >= 5);
  34595. check ("device view: the folded card stays folded", cards < 5 || detail->isFoldedForCheck (4));
  34596. // the hot-swap link on the selected card (Q)
  34597. ui.runActionForSnapshot ("view.hotSwap");
  34598. settle();
  34599. write (*detail, "19-detail-hotswap");
  34600. ui.runActionForSnapshot ("view.hotSwap");
  34601. settle();
  34602. // the Drum Rack (the Drums track's instrument)
  34603. detail->showSelection (0, 1);
  34604. settle();
  34605. detail->selectCardForCheck (0);
  34606. write (*detail, "19-detail-drumrack");
  34607. // an Instrument Rack (Keys grouped: Ctrl+G on the instrument card)
  34608. detail->showSelection (2, 1);
  34609. settle();
  34610. check ("device view: the Keys instrument grouped into an Instrument Rack", detail->groupCardForCheck (0, false));
  34611. settle();
  34612. write (*detail, "19-detail-instrumentrack");
  34613. // the Info View off (its (i) button), then back
  34614. detail->toggleInfoView();
  34615. write (*detail, "25-detail-info-off");
  34616. detail->toggleInfoView();
  34617. // ---- 17: the Clip View: a MIDI clip, then the audio clip at three detail heights --------------------------
  34618. detail->showSelection (5, 0); // (the FX track's Lead clip)
  34619. detail->setPage (lynx::DetailView::Page::clip);
  34620. settle();
  34621. ui.resized();
  34622. settle();
  34623. write (ui, "17-window-clip-midi");
  34624. write (*detail, "17-detail-clip-midi");
  34625. // Launch (folded at first, as Live shows it) and Pitch & Time open, the column scrolled to them
  34626. detail->clipSectionsForSnapshot (true, true, true, 0);
  34627. write (*detail, "17-detail-clip-midi-launch-open");
  34628. detail->clipSectionsForSnapshot (true, true, true, 160);
  34629. write (*detail, "17-detail-clip-midi-scrolled");
  34630. detail->clipSectionsForSnapshot (true, false, true, 0);
  34631. detail->showSelection (4, 0);
  34632. settle();
  34633. for (const auto height : { 190, 260, 350 })
  34634. {
  34635. lynx::DetailView::preferredHeight = height;
  34636. ui.resized();
  34637. if (auto* parent = detail->getParentComponent()) // (the Playlist area lays its docked detail view out)
  34638. parent->resized();
  34639. settle();
  34640. write (*detail, "17-detail-clip-audio-" + juce::String (height));
  34641. check ("audio box at " + juce::String (height) + " px: the detail view is that high", detail->getHeight() == height);
  34642. }
  34643. lynx::DetailView::preferredHeight = 228;
  34644. ui.resized();
  34645. if (auto* parent = detail->getParentComponent())
  34646. parent->resized();
  34647. settle();
  34648. write (ui, "17-window-clip-audio");
  34649. // ---- the same views in the classic LYNX look (View › Classic LYNX look in the Clip-launch layout) --------
  34650. lynx::clipGridClassicLook() = true;
  34651. lynx::refreshClipGrid (*gridView);
  34652. ui.getPlaylistForSnapshot().liveLanesChanged();
  34653. ui.resized();
  34654. detail->resized();
  34655. settle();
  34656. check ("classic look: the Live look is off", ! lynx::theme::livelook::active());
  34657. write (ui, "classic-window-clip-audio");
  34658. detail->setPage (lynx::DetailView::Page::devices);
  34659. detail->showSelection (1, 1);
  34660. settle();
  34661. meters();
  34662. write (ui, "classic-window-devices");
  34663. lynx::clipGridClassicLook() = false;
  34664. lynx::refreshClipGrid (*gridView);
  34665. ui.getPlaylistForSnapshot().liveLanesChanged();
  34666. ui.resized();
  34667. settle();
  34668. // ---- 18: the synthetic set's Arrangement (Song view) ------------------------------------------------------
  34669. offline.editSong ([audioChannel] (lynx::Song& s) {
  34670. for (int t = 0; t < 3; ++t)
  34671. for (int bar = 0; bar < 8; bar += 2)
  34672. {
  34673. lynx::Clip clip;
  34674. clip.pattern = t;
  34675. clip.track = t;
  34676. clip.start = (std::int64_t) bar * 4 * lynx::ppq + (t == 2 ? 4 * lynx::ppq : 0);
  34677. clip.length = 4 * lynx::ppq * (t == 1 ? 2 : 1);
  34678. if (! (t == 1 && bar % 4 != 0))
  34679. s.playlist.push_back (clip);
  34680. }
  34681. if (audioChannel >= 0)
  34682. for (int bar = 0; bar < 8; bar += 2)
  34683. {
  34684. lynx::Clip audio;
  34685. audio.channel = audioChannel;
  34686. audio.track = 4;
  34687. audio.start = (std::int64_t) bar * 4 * lynx::ppq;
  34688. audio.length = 8 * lynx::ppq;
  34689. audio.kind = lynx::ClipKind::audio;
  34690. s.playlist.push_back (audio);
  34691. }
  34692. }, false);
  34693. settle();
  34694. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  34695. settle();
  34696. ui.resized();
  34697. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  34698. settle();
  34699. ui.getPlaylistForSnapshot().repaint();
  34700. write (ui, "18-synthetic-arrangement-19");
  34701. lynx::playlistTallLiveLanes() = true;
  34702. ui.getPlaylistForSnapshot().liveLanesChanged();
  34703. settle();
  34704. write (ui, "18-synthetic-arrangement-38");
  34705. lynx::playlistTallLiveLanes() = false;
  34706. ui.getPlaylistForSnapshot().liveLanesChanged();
  34707. settle();
  34708. }
  34709. // ---- B. the Live set (its Arrangement with real audio) ----------------------------------------------------------
  34710. if (set.isNotEmpty() && juce::File (set).existsAsFile())
  34711. {
  34712. lynx::AudioEngine offline (false);
  34713. lynx::MainComponent ui (offline, false);
  34714. ui.setSize (w, h);
  34715. const auto settle = [&] {
  34716. for (int k = 0; k < 3; ++k)
  34717. offline.dispatchPendingMessages();
  34718. };
  34719. ui.setVisible (true);
  34720. lynx::DetailView::shownSetting = true;
  34721. lynx::DetailView::devicesPage = true;
  34722. ui.selectTabForSnapshot (2);
  34723. ui.setClipLaunchWorkflow (true); // (first: the import takes Live's colour table in this layout, CL-6)
  34724. settle();
  34725. ui.openFile (juce::File (set));
  34726. settle();
  34727. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  34728. settle();
  34729. ui.resized();
  34730. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  34731. settle();
  34732. const auto& song = offline.getSong();
  34733. line ("set: " + juce::String ((int) song.playlist.size()) + " Arrangement clips, " + juce::String ((int) song.playlistTracks.size()) + " tracks");
  34734. int drums = -1;
  34735. for (int t = 0; t < (int) song.playlistTracks.size() && drums < 0; ++t)
  34736. if (juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str()).containsIgnoreCase ("drum"))
  34737. drums = t;
  34738. if (drums >= 0)
  34739. line ("set: Drums track colour #" + juce::String::toHexString ((int) (song.playlistTracks[(std::size_t) drums].colour & 0xffffff)).paddedLeft ('0', 6));
  34740. check ("set: the Drums track has Live's colour #9BC48D (CL-6)", drums >= 0 && (song.playlistTracks[(std::size_t) drums].colour & 0xffffff) == 0x9bc48d);
  34741. write (ui, "18-als-arrangement-19");
  34742. // the set's Session mixer (the coordinator's 190jn follow-up: every Patience track has its strip)
  34743. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  34744. settle();
  34745. ui.resized();
  34746. settle();
  34747. if (auto* gridView = ui.getClipGridForSnapshot())
  34748. if (auto* mixer = lynx::clipGridMixer (*gridView))
  34749. {
  34750. int strips = 0;
  34751. for (int t = 0; t < 64; ++t)
  34752. strips += mixer->partBounds (t, lynx::SessionMixerComponent::Part::volume).isEmpty() ? 0 : 1;
  34753. line ("set: Session mixer strips with a volume: " + juce::String (strips) + ", mixer " + mixer->getBounds().toString()
  34754. + ", grid " + gridView->getBounds().toString());
  34755. write (ui, "13-als-window");
  34756. area (*gridView, mixer->getBoundsInParent(), "13-als-mixer");
  34757. }
  34758. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  34759. settle();
  34760. write (ui.getPlaylistForSnapshot(), "18-als-playlist-19");
  34761. lynx::playlistTallLiveLanes() = true;
  34762. ui.getPlaylistForSnapshot().liveLanesChanged();
  34763. settle();
  34764. write (ui, "18-als-arrangement-38");
  34765. // a tall audio lane (live-arrangement-audiolane.png: Vocal Main at ~250 px)
  34766. int vocal = -1;
  34767. for (int t = 0; t < (int) song.playlistTracks.size() && vocal < 0; ++t)
  34768. if (juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str()).containsIgnoreCase ("vocal"))
  34769. vocal = t;
  34770. if (vocal >= 0)
  34771. {
  34772. offline.editSong ([vocal] (lynx::Song& s) { s.playlistTracks[(std::size_t) vocal].height = 250; }, false);
  34773. lynx::playlistTallLiveLanes() = false;
  34774. ui.getPlaylistForSnapshot().liveLanesChanged();
  34775. settle();
  34776. write (ui, "18-als-audiolane");
  34777. }
  34778. line ("set: Vocal track " + juce::String (vocal));
  34779. lynx::clipGridClassicLook() = true;
  34780. ui.getPlaylistForSnapshot().liveLanesChanged();
  34781. settle();
  34782. write (ui, "classic-als-arrangement");
  34783. lynx::clipGridClassicLook() = false;
  34784. }
  34785. lynx::clipGridClassicLook() = classicBefore;
  34786. lynx::playlistTallLiveLanes() = tallBefore;
  34787. wav.deleteFile();
  34788. line ("done");
  34789. }
  34790. // LYNX --fllook190joshot prefix project.flp: round 190jo off screen (design190ia slices 12 FM-S6, 21 FM-S4, 23 FW-S4)
  34791. void runFllook190joShot (const juce::String& prefix, const juce::String& project)
  34792. {
  34793. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34794. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  34795. lynx::ui::motion::enabled() = false; // (hover states drawn at once, no fade)
  34796. juce::String checks;
  34797. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  34798. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  34799. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  34800. lynx::AudioEngine offline (false);
  34801. lynx::MainComponent ui (offline, false);
  34802. ui.setSize (1920, 1080);
  34803. const auto settle = [&] {
  34804. for (int k = 0; k < 3; ++k)
  34805. offline.dispatchPendingMessages();
  34806. };
  34807. const auto area = [&] (juce::Rectangle<int> r, const juce::String& name) { saveArea (ui, r, prefix + "-" + name + ".png"); };
  34808. ui.selectTabForSnapshot (2);
  34809. if (project.isNotEmpty())
  34810. {
  34811. ui.openFile (juce::File (project));
  34812. settle();
  34813. }
  34814. check ("the project opened", ! offline.getSong().channels.empty());
  34815. const auto bar = [&ui] { return ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 90)); };
  34816. const std::pair<int, int> sizes[] { { 1920, 1080 }, { 1600, 900 }, { 1366, 768 }, { 1280, 800 } };
  34817. // ---- slice 12: the Pattern toolbar ------------------------------------------------------------------------------
  34818. for (const auto& [w, h] : sizes)
  34819. {
  34820. ui.setSize (w, h);
  34821. settle();
  34822. area (bar(), "tb-" + juce::String (w));
  34823. int tiles = 0;
  34824. for (auto* c : ui.getChildren())
  34825. if (auto* b = dynamic_cast<lynx::IconButton*> (c); b != nullptr && b->isVisible() && b->getLook() == lynx::IconButton::Look::flTile)
  34826. ++tiles;
  34827. line ("toolbar " + juce::String (w) + ": " + juce::String (tiles) + " tiled buttons");
  34828. }
  34829. ui.setSize (1920, 1080);
  34830. settle();
  34831. std::vector<lynx::IconButton*> tiled;
  34832. for (auto* c : ui.getChildren())
  34833. if (auto* b = dynamic_cast<lynx::IconButton*> (c); b != nullptr && b->isVisible() && b->getLook() == lynx::IconButton::Look::flTile)
  34834. tiled.push_back (b);
  34835. check ("the Pattern toolbar's buttons are FL tiles (" + juce::String ((int) tiled.size()) + ")", tiled.size() >= 25);
  34836. std::vector<bool> lit;
  34837. for (auto* b : tiled)
  34838. lit.push_back (b->getToggleState());
  34839. area (bar(), "tb-states-idle");
  34840. for (const auto& [state, name] : { std::pair<juce::Button::ButtonState, const char*> { juce::Button::buttonOver, "hover" }, { juce::Button::buttonDown, "pressed" } })
  34841. {
  34842. for (auto* b : tiled)
  34843. b->setState (state);
  34844. area (bar(), juce::String ("tb-states-") + name);
  34845. for (auto* b : tiled)
  34846. b->setState (juce::Button::buttonNormal);
  34847. }
  34848. for (auto* b : tiled)
  34849. b->setToggleState (true, juce::dontSendNotification);
  34850. area (bar(), "tb-states-on");
  34851. for (auto* b : tiled)
  34852. b->setState (juce::Button::buttonOver);
  34853. area (bar(), "tb-states-on-hover");
  34854. for (std::size_t k = 0; k < tiled.size(); ++k)
  34855. {
  34856. tiled[k]->setState (juce::Button::buttonNormal);
  34857. tiled[k]->setToggleState (lit[k], juce::dontSendNotification);
  34858. tiled[k]->setEnabled (false);
  34859. }
  34860. area (bar(), "tb-states-disabled");
  34861. for (auto* b : tiled)
  34862. b->setEnabled (true);
  34863. // one switch and one plain button under the mouse, as FL's capture (its audio editor button lit)
  34864. if (auto* metronome = dynamic_cast<lynx::IconButton*> (ui.toolbarPartForSnapshot ("metronome")))
  34865. {
  34866. metronome->setState (juce::Button::buttonOver);
  34867. area (bar(), "tb-hover-switch");
  34868. metronome->setState (juce::Button::buttonNormal);
  34869. }
  34870. // the time panel in B:S:T at bar 3, step 05, tick 12 (FL: "3:05:12"), the tempo, and the hint bar
  34871. {
  34872. auto& transport = offline.getTransport();
  34873. const auto& song = offline.getSong();
  34874. transport.positionTicks.store ((double) (2 * song.barTicks()) + 4.0 * lynx::ticksPerStep + lynx::ticksPerStep / 2.0);
  34875. ui.transportTickForSnapshot();
  34876. auto* time = ui.toolbarPartForSnapshot ("position");
  34877. auto* tempo = ui.toolbarPartForSnapshot ("tempo");
  34878. if (time != nullptr && tempo != nullptr)
  34879. {
  34880. area (time->getBounds().getUnion (tempo->getBounds()).expanded (8, 6), "tb-time");
  34881. if (auto* hs = dynamic_cast<lynx::ui::HintSource*> (time))
  34882. line ("time panel: " + hs->hintAt ({}).value);
  34883. check ("the time panel reads FL's B:S:T (3:05:12)", dynamic_cast<lynx::ui::HintSource*> (time) != nullptr
  34884. && dynamic_cast<lynx::ui::HintSource*> (time)->hintAt ({}).value == "3:05:12");
  34885. }
  34886. transport.positionTicks.store (0.0);
  34887. ui.transportTickForSnapshot();
  34888. }
  34889. const auto hintColumn = juce::Rectangle<int> (0, 0, 360, 80);
  34890. if (auto* knob = dynamic_cast<lynx::ui::HintSource*> (ui.toolbarPartForSnapshot ("masterVolume")))
  34891. {
  34892. ui.setHintForSnapshot (knob->hintAt ({}));
  34893. area (hintColumn, "tb-hint-knob");
  34894. }
  34895. if (auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record")))
  34896. {
  34897. ui.setHintForSnapshot ({ rec->getTooltip().upToFirstOccurrenceOf ("\n", false, false), {}, false, true });
  34898. area (hintColumn, "tb-hint-button");
  34899. }
  34900. ui.setHintForSnapshot ({});
  34901. area (hintColumn, "tb-menu");
  34902. // ---- slice 21: the Piano roll ----------------------------------------------------------------------------------
  34903. ui.selectTabForSnapshot (1);
  34904. settle();
  34905. saveSnapshot (ui, prefix + "-pr.png");
  34906. auto& roll = ui.getPianoRollForSnapshot();
  34907. line ("piano roll rows: " + juce::String (roll.rowHeight) + " px");
  34908. check ("FL's 18 px rows by default", roll.rowHeight == 18);
  34909. const auto keysBefore = lynx::PianoRollComponent::keyStyle; // (round 190oo: FL's keys are the default)
  34910. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::piano;
  34911. roll.repaint();
  34912. saveSnapshot (ui, prefix + "-pr-pianokeys.png");
  34913. lynx::PianoRollComponent::keyStyle = keysBefore;
  34914. lynx::notenames::everyKey.store (true);
  34915. roll.repaint();
  34916. saveSnapshot (ui, prefix + "-pr-allnames.png");
  34917. lynx::notenames::everyKey.store (false);
  34918. roll.repaint();
  34919. ui.setHintForSnapshot (roll.hoverForSnapshot());
  34920. saveSnapshot (ui, prefix + "-pr-hover.png");
  34921. ui.setHintForSnapshot ({});
  34922. {
  34923. // FL's ghost capture: "Synth Bass" (no notes of its own in this pattern) over the other channels' notes
  34924. const auto& song = offline.getSong();
  34925. int bass = -1;
  34926. for (int c = 0; c < (int) song.channels.size() && bass < 0; ++c)
  34927. if (juce::String (song.channels[(std::size_t) c].name).equalsIgnoreCase ("Synth Bass"))
  34928. bass = c;
  34929. const auto kept = offline.getSelectedChannel();
  34930. if (bass >= 0)
  34931. {
  34932. offline.setSelectedChannel (bass);
  34933. settle();
  34934. roll.rowHeight = 18;
  34935. roll.repaint();
  34936. saveSnapshot (ui, prefix + "-pr-ghosts.png");
  34937. offline.setSelectedChannel (kept);
  34938. settle();
  34939. }
  34940. check ("Synth Bass found for the ghosts", bass >= 0);
  34941. }
  34942. {
  34943. // the note label against the note over the velocity range of each note colour group (WCAG)
  34944. float worst = 99.0f;
  34945. for (int group = 0; group < 16; ++group)
  34946. for (float v = 0.0f; v <= 1.0001f; v += 0.05f)
  34947. {
  34948. const auto fill = lynx::theme::noteGroupColour (group, v);
  34949. const auto label = fill.getPerceivedBrightness() > 0.5f ? lynx::theme::colour::bg0 : lynx::theme::colour::textPrimary;
  34950. worst = juce::jmin (worst, lynx::theme::contrast (label, fill));
  34951. }
  34952. line ("note label contrast, worst of 16 colour groups x velocity 0..1: " + juce::String (worst, 2) + ":1");
  34953. const auto red = lynx::theme::noteGroupColour (0, 0.78f);
  34954. line ("default note " + red.toDisplayString (false) + " label " + juce::String (lynx::theme::contrast (lynx::theme::colour::bg0, red), 2) + ":1");
  34955. check ("note labels >= 4.5:1 on the default red notes", lynx::theme::contrast (lynx::theme::colour::bg0, red) >= 4.5f);
  34956. }
  34957. ui.selectTabForSnapshot (2);
  34958. settle();
  34959. // ---- slice 23: the audio editor in Edison's layout -------------------------------------------------------------
  34960. {
  34961. const juce::File breaker ("C:\\Program Files\\Image-Line\\FL Studio 2026\\Data\\Patches\\Packs\\Loops\\DL Breaker.wav");
  34962. const auto wav = breaker.existsAsFile() ? breaker : juce::File (juce::SystemStats::getEnvironmentVariable ("LYNX_190JO_WAV", ""));
  34963. check ("FL's DL Breaker.wav", wav.existsAsFile());
  34964. if (wav.existsAsFile())
  34965. if (auto editor = lynx::makeAudioEditorForFileSnapshot (offline, wav))
  34966. {
  34967. for (const auto& [w, h] : { std::pair { 1120, 600 }, std::pair { 960, 520 } })
  34968. {
  34969. editor->setSize (w, h);
  34970. saveSnapshot (*editor, prefix + "-ed-breaker-" + juce::String (w) + ".png");
  34971. }
  34972. editor->setSize (760, 320); // (the compact form: a short dock)
  34973. saveSnapshot (*editor, prefix + "-ed-compact.png");
  34974. }
  34975. const auto at = lynx::addEdisonSlot (offline, 1);
  34976. settle();
  34977. if (at >= 0)
  34978. if (auto slot = lynx::makeEdisonSlotEditor (offline, 1, at))
  34979. {
  34980. slot->setSize (1120, 630);
  34981. saveSnapshot (*slot, prefix + "-ed-slot.png");
  34982. }
  34983. check ("an Edison slot editor", at >= 0);
  34984. const auto& song = offline.getSong();
  34985. int sampled = -1;
  34986. for (int c = 0; c < (int) song.channels.size() && sampled < 0; ++c)
  34987. if (! song.channels[(std::size_t) c].samplePath.empty())
  34988. sampled = c;
  34989. if (sampled >= 0)
  34990. if (auto panel = lynx::makeAudioEditorPanel (offline, sampled, -1))
  34991. {
  34992. panel->setSize (1100, 300);
  34993. saveSnapshot (*panel, prefix + "-ed-panel.png");
  34994. }
  34995. }
  34996. lynx::ui::motion::enabled() = true;
  34997. }
  34998. // Round 190kc (see --cliplaunch190kcshot above): the Patience set in the Clip-launch layout
  34999. void runClipLaunch190kcShot (const juce::String& prefix, const juce::String& set)
  35000. {
  35001. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  35002. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  35003. juce::String checks;
  35004. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  35005. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  35006. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  35007. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  35008. const auto area = [&prefix] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) { saveArea (c, r, prefix + "-" + name + ".png"); };
  35009. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  35010. const auto w = juce::jlimit (800, 3840, size[0].getIntValue()), h = juce::jlimit (450, 2160, size[1].getIntValue());
  35011. const auto classicBefore = lynx::clipGridClassicLook();
  35012. lynx::clipGridClassicLook() = false;
  35013. if (set.isEmpty() || ! juce::File (set).existsAsFile())
  35014. {
  35015. check ("the Live set given", false);
  35016. return;
  35017. }
  35018. using Part = lynx::SessionMixerComponent::Part;
  35019. lynx::AudioEngine offline (false);
  35020. lynx::MainComponent ui (offline, false);
  35021. ui.setSize (w, h);
  35022. const auto settle = [&] {
  35023. for (int k = 0; k < 3; ++k)
  35024. offline.dispatchPendingMessages();
  35025. };
  35026. ui.setVisible (true);
  35027. lynx::DetailView::shownSetting = true;
  35028. lynx::DetailView::devicesPage = true;
  35029. ui.selectTabForSnapshot (2);
  35030. ui.setClipLaunchWorkflow (true);
  35031. settle();
  35032. ui.openFile (juce::File (set));
  35033. settle();
  35034. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  35035. settle();
  35036. ui.resized();
  35037. settle();
  35038. auto* gridView = ui.getClipGridForSnapshot();
  35039. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  35040. if (gridView == nullptr || mixer == nullptr)
  35041. {
  35042. check ("a clip grid with its Session mixer", false);
  35043. return;
  35044. }
  35045. const auto& song = offline.getSong();
  35046. const auto returns = lynx::sessionmixer::returnsOf (song);
  35047. line ("returns: " + juce::String ((int) returns.size()) + ", return strips " + juce::String (mixer->returnColumnCount()));
  35048. check ("the set's two returns are Live return tracks (A Reverb, B Delay)",
  35049. returns.size() == 2 && lynx::sessionmixer::returnTitle (song, returns[0]) == "A Reverb" && lynx::sessionmixer::returnTitle (song, returns[1]) == "B Delay");
  35050. check ("two return strips beside the tracks", mixer->returnColumnCount() == 2);
  35051. check ("every track shows a Sends row per return (the sends at -inf)",
  35052. mixer->sendTargets() == returns && ! mixer->partBounds (0, Part::send, 1).isEmpty());
  35053. const auto retA = lynx::SessionMixerComponent::returnColumn (0);
  35054. check ("a return strip: Sends, volume, activator, Solo, no Arm",
  35055. ! mixer->partBounds (retA, Part::send, 1).isEmpty() && ! mixer->partBounds (retA, Part::activator).isEmpty()
  35056. && ! mixer->partBounds (retA, Part::solo).isEmpty() && mixer->partBounds (retA, Part::arm).isEmpty());
  35057. check ("the Main strip: a Pre / Post toggle per return", ! mixer->partBounds (-2, Part::post, 0).isEmpty() && ! mixer->partBounds (-2, Part::post, 1).isEmpty());
  35058. line ("Post A " + mixer->partBounds (-2, Part::post, 0).toString() + ", Post B " + mixer->partBounds (-2, Part::post, 1).toString()
  35059. + ", return A activator " + mixer->partBounds (retA, Part::activator).toString());
  35060. write (ui, "window");
  35061. area (*gridView, mixer->getBoundsInParent(), "mixer");
  35062. area (*gridView, { 0, 0, gridView->getWidth(), 240 }, "grid-top");
  35063. area (*gridView, mixer->getBoundsInParent().withTrimmedLeft (mixer->getWidth() - 260), "mixer-returns");
  35064. // a return's send to the other one, switched on; Pre on return B
  35065. offline.editSong ([&returns] (lynx::Song& s) {
  35066. lynx::sessionmixer::setSendEnabled (s, returns[0], returns[1], true);
  35067. lynx::sessionmixer::setPre (s, returns[1], true);
  35068. });
  35069. settle();
  35070. area (*gridView, mixer->getBoundsInParent(), "mixer-sendon-pre");
  35071. area (*gridView, mixer->getBoundsInParent().withTrimmedLeft (mixer->getWidth() - 260), "mixer-returns-sendon-pre");
  35072. check ("return A's send to B switched on, B Pre", lynx::sessionmixer::sendEnabled (song, returns[0], returns[1]) && lynx::sessionmixer::isPre (song, returns[1]));
  35073. saveMenus (juce::StringArray { "Return send" }, std::vector<juce::PopupMenu> { mixer->sendMenu ({ lynx::SessionMixerComponent::returnColumn (1), Part::send, 0 }) },
  35074. prefix + "-menu-send.png");
  35075. offline.editSong ([&returns] (lynx::Song& s) {
  35076. lynx::sessionmixer::setSendEnabled (s, returns[0], returns[1], false);
  35077. lynx::sessionmixer::setPre (s, returns[1], false);
  35078. });
  35079. // the crossfader section: track 1 on A, track 2 on B, the crossfader a little towards A
  35080. const auto i0 = lynx::sessionmixer::stripOf (song, 0).insert, i1 = lynx::sessionmixer::stripOf (song, 1).insert;
  35081. offline.editSong ([i0, i1] (lynx::Song& s) {
  35082. lynx::launcher::ensureGrid (s).mixerView.crossfader = true;
  35083. if (i0 > 0)
  35084. s.mixer[(std::size_t) i0].crossfade = lynx::CrossfadeAssign::a;
  35085. if (i1 > 0)
  35086. s.mixer[(std::size_t) i1].crossfade = lynx::CrossfadeAssign::b;
  35087. s.crossfader = -0.3f;
  35088. });
  35089. settle();
  35090. gridView->resized(); // (the menu item does this: the grid gives the mixer its new height)
  35091. settle();
  35092. check ("the Crossfader section: A / B on a track, the crossfader on Main",
  35093. ! mixer->partBounds (0, Part::xfadeA).isEmpty() && ! mixer->partBounds (0, Part::xfadeB).isEmpty() && ! mixer->partBounds (-2, Part::crossfader).isEmpty());
  35094. line ("A " + mixer->partBounds (0, Part::xfadeA).toString() + ", B " + mixer->partBounds (0, Part::xfadeB).toString() + ", crossfader "
  35095. + mixer->partBounds (-2, Part::crossfader).toString());
  35096. area (*gridView, mixer->getBoundsInParent(), "mixer-crossfader");
  35097. area (*gridView, mixer->getBoundsInParent().withTrimmedLeft (mixer->getWidth() - 260), "mixer-returns-crossfader");
  35098. saveMenus (juce::StringArray { "Crossfader" }, std::vector<juce::PopupMenu> { mixer->crossfaderMenu() }, prefix + "-menu-curve.png");
  35099. lynx::clipGridClassicLook() = true;
  35100. lynx::refreshClipGrid (*gridView);
  35101. ui.resized();
  35102. settle();
  35103. area (*gridView, mixer->getBoundsInParent(), "classic-mixer-crossfader");
  35104. write (ui, "classic-window");
  35105. lynx::clipGridClassicLook() = false;
  35106. lynx::refreshClipGrid (*gridView);
  35107. ui.resized();
  35108. settle();
  35109. // the map modes: a key on a slot, a scene, Scene Down, the crossfader's left position
  35110. using namespace lynx::remotemap;
  35111. offline.editSong ([] (lynx::Song& s) {
  35112. assignKey (s, Target::slot (0, 0), 'Q');
  35113. assignKey (s, Target::sceneLaunch (0), 'W');
  35114. assignKey (s, Target::of (lynx::RemoteAction::sceneDown), 'J');
  35115. assignKey (s, Target::of (lynx::RemoteAction::crossfaderLeft), 'Z');
  35116. });
  35117. for (const auto mode : { Mode::key, Mode::midi })
  35118. {
  35119. ui.setMapMode (mode);
  35120. settle();
  35121. if (auto* overlay = ui.mapOverlayForSnapshot())
  35122. {
  35123. overlay->refresh();
  35124. const auto& spots = overlay->spots();
  35125. const auto count = [&spots] (lynx::RemoteAction a) { return (int) std::count_if (spots.begin(), spots.end(), [a] (const auto& sp) { return sp.target.action == a; }); };
  35126. line (juce::String (mode == Mode::key ? "key" : "midi") + " map: " + juce::String ((int) spots.size()) + " spots; relative strip "
  35127. + juce::String (count (lynx::RemoteAction::sceneUp) + count (lynx::RemoteAction::sceneDown) + count (lynx::RemoteAction::launchSelectedScene)
  35128. + count (lynx::RemoteAction::cancelLaunch))
  35129. + ", per-track launch " + juce::String (count (lynx::RemoteAction::launchSelectedClip)) + ", crossfader positions "
  35130. + juce::String (count (lynx::RemoteAction::crossfaderLeft) + count (lynx::RemoteAction::crossfaderCentre) + count (lynx::RemoteAction::crossfaderRight)));
  35131. check (juce::String (mode == Mode::key ? "Key" : "MIDI") + " Map Mode: the relative strip and the crossfader's three positions are mappable",
  35132. count (lynx::RemoteAction::sceneUp) == 1 && count (lynx::RemoteAction::sceneDown) == 1 && count (lynx::RemoteAction::launchSelectedScene) == 1
  35133. && count (lynx::RemoteAction::cancelLaunch) == 1 && count (lynx::RemoteAction::launchSelectedClip) >= 4
  35134. && count (lynx::RemoteAction::crossfaderLeft) == 1 && count (lynx::RemoteAction::crossfaderRight) == 1);
  35135. }
  35136. write (ui, mode == Mode::key ? "keymap" : "midimap");
  35137. }
  35138. ui.setMapMode (Mode::off);
  35139. settle();
  35140. // grooves on clips: a groove of LYNX's bank on the first MIDI clip and on an audio clip; the Clip View's Commit
  35141. int midiTrack = -1, midiScene = -1, audioTrack = -1, audioScene = -1;
  35142. if (song.clipGrid)
  35143. for (const auto& c : song.clipGrid->clips)
  35144. {
  35145. const auto scene = c.gridSlot >= 0 && c.gridSlot < (int) song.clipGrid->slots.size() ? song.clipGrid->slots[(std::size_t) c.gridSlot].scene : -1;
  35146. if (c.kind == lynx::ClipKind::pattern && midiTrack < 0)
  35147. midiTrack = c.track, midiScene = scene;
  35148. if (c.kind == lynx::ClipKind::audio && audioTrack < 0)
  35149. audioTrack = c.track, audioScene = scene;
  35150. }
  35151. line ("MIDI clip " + juce::String (midiTrack) + "/" + juce::String (midiScene) + ", audio clip " + juce::String (audioTrack) + "/" + juce::String (audioScene));
  35152. std::uint32_t grooveId = 0;
  35153. offline.editSong ([&grooveId, midiTrack, midiScene, audioTrack, audioScene] (lynx::Song& s) {
  35154. auto g = lynx::groove::factoryBank().front().groove;
  35155. g.timing = 1.0f;
  35156. grooveId = lynx::groove::add (s.grooves, g);
  35157. lynx::groove::setClipGroove (s, midiTrack, midiScene, grooveId);
  35158. lynx::groove::setClipGroove (s, audioTrack, audioScene, grooveId);
  35159. });
  35160. settle();
  35161. if (auto* detail = ui.getDetailViewForSnapshot(); detail != nullptr && midiTrack >= 0 && audioTrack >= 0)
  35162. {
  35163. detail->showSelection (midiTrack, midiScene);
  35164. detail->setPage (lynx::DetailView::Page::clip);
  35165. settle();
  35166. write (*detail, "clip-midi-groove");
  35167. detail->showSelection (audioTrack, audioScene);
  35168. detail->setPage (lynx::DetailView::Page::clip);
  35169. settle();
  35170. write (*detail, "clip-audio-groove");
  35171. const auto* audio = lynx::launcher::clipAt (*song.clipGrid, audioTrack, audioScene);
  35172. const auto sample = audio != nullptr && audio->channel >= 0 ? offline.getSampleLibrary().load (juce::String::fromUTF8 (song.channels[(std::size_t) audio->channel].samplePath.c_str()))
  35173. : nullptr;
  35174. check ("the audio clip's file loads", sample != nullptr);
  35175. if (sample != nullptr && audio != nullptr)
  35176. {
  35177. const auto hits = lynx::grooveaudio::hitsOf (song, *audio, *sample);
  35178. {
  35179. const auto all = lynx::clipwarp::attacks (*sample);
  35180. const auto& sm = song.channels[(std::size_t) audio->channel].sampler;
  35181. line ("audio file: " + juce::String ((int) sample->frames()) + " frames at " + juce::String (sample->sampleRate) + " Hz, "
  35182. + juce::String ((int) all.size()) + " attacks (first " + juce::String (all.empty() ? -1.0 : all.front(), 3) + " s); clip offset "
  35183. + juce::String (audio->offset) + " length " + juce::String (audio->length) + " stretch " + juce::String (audio->stretch, 3)
  35184. + "; warp " + juce::String ((int) sm.warp.size()) + " markers, keepPitch " + juce::String ((int) sm.keepPitch)
  35185. + ", first content beat " + juce::String (all.empty() ? 0.0 : lynx::grooveaudio::contentBeat (sm, all.front(), song.bpm), 3));
  35186. }
  35187. const auto pool = song.grooves.grooves.size();
  35188. offline.editSong ([&] (lynx::Song& s) {
  35189. if (const auto* c = lynx::launcher::clipAt (*s.clipGrid, audioTrack, audioScene))
  35190. if (auto g = lynx::grooveaudio::extract (s, *c, *sample, lynx::GrooveBase::sixteenth, "Vocal groove"); ! g.points.empty())
  35191. lynx::groove::add (s.grooves, std::move (g));
  35192. });
  35193. line ("audio clip: " + juce::String ((int) hits.size()) + " attacks; pool " + juce::String ((int) pool) + " -> " + juce::String ((int) song.grooves.grooves.size()));
  35194. check ("Extract Groove from the audio clip adds a groove", song.grooves.grooves.size() == pool + 1);
  35195. int placed = -1;
  35196. offline.editSong ([&] (lynx::Song& s) { placed = lynx::grooveaudio::commit (s, audioTrack, audioScene, *sample); });
  35197. auto gridCopy = *song.clipGrid;
  35198. const auto* slot = lynx::launcher::settingsAt (gridCopy, audioTrack, audioScene);
  35199. line ("commit on audio: " + juce::String (placed) + " warp markers");
  35200. check ("Commit on the audio clip writes warp markers and sets its groove to None", placed > 0 && slot != nullptr && slot->groove == 0);
  35201. }
  35202. }
  35203. lynx::clipGridClassicLook() = classicBefore;
  35204. line ("done");
  35205. }
  35206. // LYNX --capfix190jjshot prefix project.flp set.als: round 190jj off screen (capture190ji's "Change in LYNX" lines) —
  35207. // the Simple capsule idle / playing / count-in / recording with the master meter, the pads at rest and pressed, the
  35208. // keys held in the track's colour, the drop lane's ghosts; Live's control bar idle / playing / recording / punch;
  35209. // FL's C-11 picker drop ghost with the drag image, the drop, and the picker's playing mark; prefix-checks.txt
  35210. void runCapfix190jjShot (const juce::String& prefix, const juce::String& project, const juce::String& set)
  35211. {
  35212. namespace st = lynx::simpletracks;
  35213. namespace sp = lynx::simplepads;
  35214. using Look = lynx::toolbarlayout::Look;
  35215. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  35216. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  35217. juce::String checks;
  35218. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  35219. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  35220. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  35221. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  35222. const auto area = [&prefix] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) { saveArea (c, r, prefix + "-" + name + ".png"); };
  35223. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  35224. const auto w = juce::jlimit (800, 3840, size[0].getIntValue()), h = juce::jlimit (450, 2160, size[1].getIntValue());
  35225. // ---- A. Simple ----------------------------------------------------------------------------------------------------
  35226. {
  35227. lynx::AudioEngine offline (false);
  35228. lynx::MainComponent ui (offline, false);
  35229. ui.setSize (w, h);
  35230. const auto settle = [&] {
  35231. for (int k = 0; k < 3; ++k)
  35232. offline.dispatchPendingMessages();
  35233. };
  35234. ui.selectTabForSnapshot (2);
  35235. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  35236. settle();
  35237. auto* simple = ui.getSimpleWorkflowForSnapshot();
  35238. auto& playlist = ui.getPlaylistForSnapshot();
  35239. if (simple == nullptr)
  35240. {
  35241. check ("a Simple workflow", false);
  35242. return;
  35243. }
  35244. offline.setSong ([] {
  35245. lynx::Song s;
  35246. s.mixer = lynx::Song::defaultMixer();
  35247. s.bpm = 120.0;
  35248. return s;
  35249. }());
  35250. settle();
  35251. simple->hideChooser();
  35252. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190jj");
  35253. dir.deleteRecursively();
  35254. dir.createDirectory();
  35255. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  35256. wav.getParentDirectory().createDirectory();
  35257. juce::AudioBuffer<float> audio (1, frames);
  35258. for (int i = 0; i < frames; ++i)
  35259. audio.setSample (0, i, f (i));
  35260. juce::WavAudioFormat format;
  35261. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  35262. if (auto* wr = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  35263. {
  35264. out.release();
  35265. std::unique_ptr<juce::AudioFormatWriter> writer (wr);
  35266. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  35267. }
  35268. return wav;
  35269. };
  35270. const auto pi = juce::MathConstants<double>::pi;
  35271. juce::Random rnd (190);
  35272. // a 4-bar loop at 120 bpm (8 s), as BandLab's "TRAP_160_Piano1_Bm_4bars" is four bars
  35273. const auto loop = writeWav (dir.getChildFile ("TRAP_120_Piano1_Bm_4bars.wav"), 384000, [pi] (int i) {
  35274. const auto t = i / 48000.0, inBeat = std::fmod (t, 0.5);
  35275. return (float) (0.6 * std::exp (-inBeat * 6.0) * std::sin (2.0 * pi * 247.0 * t));
  35276. });
  35277. std::vector<juce::File> padSounds;
  35278. const char* padNames[] { "Kick", "Snare", "Hat", "Clap", "Stab", "Vox", "Perc", "Bass" };
  35279. for (int k = 0; k < 8; ++k)
  35280. padSounds.push_back (writeWav (dir.getChildFile (juce::String ("pads/") + padNames[k] + ".wav"), 12000 + 3000 * k, [&rnd, k] (int i) {
  35281. return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.6f * std::exp (-i / (600.0f + 500.0f * (float) k)));
  35282. }));
  35283. int vocal = -1, keys = -1;
  35284. offline.editSong ([&] (lynx::Song& s) {
  35285. st::Request q;
  35286. q.kind = st::Kind::audio;
  35287. q.name = "Piano loop";
  35288. q.audioFile = loop.getFullPathName().toStdString();
  35289. q.audioLength = 16 * lynx::ppq;
  35290. q.audioBeats = 16.0f;
  35291. vocal = st::addTrack (s, q).track;
  35292. q = {};
  35293. q.kind = st::Kind::instrument;
  35294. q.name = "Instrument";
  35295. lynx::ChannelDef synth;
  35296. synth.instrument = lynx::InstrumentKind::synth;
  35297. q.channel = synth;
  35298. keys = st::addTrack (s, q).track;
  35299. });
  35300. settle();
  35301. check ("the Sampler (pads) track was added", simple->addPads());
  35302. settle();
  35303. const auto& song = offline.getSong();
  35304. int pads = -1;
  35305. for (int t = 0; t < (int) song.playlistTracks.size() && pads < 0; ++t)
  35306. if (st::kindOf (song, t) == st::Kind::pads)
  35307. pads = t;
  35308. simple->hideChooser();
  35309. playlist.selectTrack (keys);
  35310. settle();
  35311. // 1. the transport capsule (+ tempo, key, master) in its four states
  35312. const auto bar = [&ui] {
  35313. juce::Rectangle<int> r;
  35314. for (const auto* name : { "play", "stop", "record", "position", "metronome", "tempo", "signature", "key", "masterVolume", "masterPitch" })
  35315. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible())
  35316. r = r.isEmpty() ? c->getBounds() : r.getUnion (c->getBounds());
  35317. return r.expanded (8, 6);
  35318. };
  35319. auto& transport = offline.getTransport();
  35320. auto* tempo = ui.toolbarPartForSnapshot ("tempo");
  35321. auto* stopButton = dynamic_cast<lynx::IconButton*> (ui.toolbarPartForSnapshot ("stop"));
  35322. auto* playButton = dynamic_cast<lynx::IconButton*> (ui.toolbarPartForSnapshot ("play"));
  35323. auto* master = dynamic_cast<lynx::toolbar::MasterKnob*> (ui.toolbarPartForSnapshot ("masterVolume"));
  35324. ui.transportTickForSnapshot();
  35325. area (ui, bar(), "simple-bar-idle");
  35326. check ("idle: Play shows Play, the second button Back-to-start", playButton != nullptr && playButton->getIcon() == lynx::Icon::play
  35327. && stopButton != nullptr && stopButton->getIcon() == lynx::Icon::toStart);
  35328. transport.positionTicks.store ((double) (2 * song.barTicks()) + 0.3 * lynx::ppq);
  35329. transport.playing.store (true);
  35330. if (master != nullptr)
  35331. master->meterForSnapshot ({ 0.62f, 0.57f });
  35332. ui.transportTickForSnapshot();
  35333. area (ui, bar(), "simple-bar-playing");
  35334. check ("playing: Pause and Stop (BandLab)", playButton != nullptr && playButton->getIcon() == lynx::Icon::pause && stopButton->getIcon() == lynx::Icon::stop);
  35335. transport.playing.store (false);
  35336. transport.positionTicks.store (0.0);
  35337. offline.setRecording (true);
  35338. transport.countIn.store (0.85 * (double) song.barTicks()); // (-1.7 s of a 2 s bar at 120 bpm)
  35339. ui.transportTickForSnapshot();
  35340. area (ui, bar(), "simple-bar-countin");
  35341. check ("count-in: tempo greyed, Pause shown", tempo != nullptr && ! tempo->isEnabled() && playButton->getIcon() == lynx::Icon::pause);
  35342. transport.countIn.store (0.0);
  35343. transport.playing.store (true);
  35344. transport.positionTicks.store (0.45 * (double) song.barTicks());
  35345. ui.transportTickForSnapshot();
  35346. area (ui, bar(), "simple-bar-recording");
  35347. line ("record start kept: " + juce::String (ui.simpleRecordStartForCheck(), 1) + " ticks");
  35348. check ("recording: the take's start is kept (the count-in's target, 0)", ui.simpleRecordStartForCheck() == 0.0);
  35349. auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record"));
  35350. const auto litA = rec != nullptr && rec->getToggleState();
  35351. juce::Thread::sleep (260);
  35352. ui.transportTickForSnapshot();
  35353. const auto litB = rec != nullptr && rec->getToggleState();
  35354. check ("recording: Record steady (lit 260 ms apart, no blink in Simple)", litA && litB);
  35355. transport.seekRequest.store (-1.0);
  35356. ui.stopForCheck();
  35357. line ("seek after Stop: " + juce::String (transport.seekRequest.load(), 1));
  35358. check ("Stop after a take goes back to where it started", transport.seekRequest.load() == 0.0);
  35359. offline.setRecording (false);
  35360. transport.playing.store (false);
  35361. ui.transportTickForSnapshot();
  35362. check ("stopped: tempo enabled again", tempo != nullptr && tempo->isEnabled());
  35363. if (master != nullptr)
  35364. {
  35365. area (ui, master->getBounds().expanded (6, 4), "simple-master-idle");
  35366. master->meterForSnapshot ({ 0.62f, 0.57f });
  35367. area (ui, master->getBounds().expanded (6, 4), "simple-master-playing");
  35368. master->meterForSnapshot ({ 0.0f, 0.0f });
  35369. }
  35370. // 2. the dock: pads at rest and pressed, keys held
  35371. if (auto* dock = simple->dockForSnapshot(); dock != nullptr && pads >= 0)
  35372. {
  35373. simple->trackSelected (pads);
  35374. settle();
  35375. for (int p = 0; p < 8; ++p)
  35376. dock->padsLoadForCheck (p, padSounds[(std::size_t) p]);
  35377. offline.editSong ([pads] (lynx::Song& s) {
  35378. for (int p = 0; p < 8; ++p)
  35379. if (const auto c = sp::padChannel (s, pads, p); c >= 0)
  35380. s.channels[(std::size_t) c].simplePad.colour = (std::uint8_t) (p + 1);
  35381. });
  35382. dock->padsSelectForCheck (0);
  35383. dock->padsUpdateForCheck();
  35384. settle();
  35385. write (*dock, "dock-pads-rest");
  35386. dock->padsPressForSnapshot (3, 1.0f);
  35387. dock->padsPressForSnapshot (5, 0.5f);
  35388. write (*dock, "dock-pads-pressed");
  35389. dock->padsPressForSnapshot (3, 0.0f);
  35390. dock->padsPressForSnapshot (5, 0.0f);
  35391. simple->trackSelected (keys);
  35392. settle();
  35393. dock->showKeyboard();
  35394. settle();
  35395. if (auto* kb = dock->keyboardForSnapshot())
  35396. {
  35397. lynx::keyboardPressForSnapshot (*kb);
  35398. write (*dock, "dock-keys-held");
  35399. }
  35400. }
  35401. // 3. the drop lane while the loop is dragged (the Browser's file drag)
  35402. simple->hideChooser();
  35403. playlist.selectTrack (vocal);
  35404. settle();
  35405. const auto lane = st::nextEmptyTrack (offline.getSong());
  35406. const juce::var drag (juce::String ("lynx-arquivo|") + loop.getFullPathName());
  35407. const auto x = (int) playlist.xOfTickForSnapshot (9.0 * (double) song.barTicks()) + 6;
  35408. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (lane).getCentreY() });
  35409. write (playlist, "simple-drop-lane");
  35410. check ("over the lane: a ghost, no reason", ! playlist.dropGhostAreaForCheck().isEmpty() && playlist.dropGhostReasonForCheck().isEmpty());
  35411. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (vocal).getCentreY() });
  35412. write (playlist, "simple-drop-audio-track");
  35413. check ("over an audio track: no reason", playlist.dropGhostReasonForCheck().isEmpty());
  35414. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (pads).getCentreY() });
  35415. write (playlist, "simple-drop-refused");
  35416. check ("over the Sampler track: red, with the reason", playlist.dropGhostReasonForCheck().isNotEmpty());
  35417. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (keys).getCentreY() });
  35418. check ("over an instrument track: red, with the reason", playlist.dropGhostReasonForCheck().isNotEmpty());
  35419. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (lane).getBottom() + 60 });
  35420. write (playlist, "simple-drop-below");
  35421. check ("below the lane: only the tag", playlist.dropGhostTagOnlyForCheck());
  35422. playlist.dragOverForSnapshot ({}, {});
  35423. check ("after the drag: nothing left to paint", playlist.dropGhostAreaForCheck().isEmpty());
  35424. const auto clipsBefore = offline.getSong().playlist.size();
  35425. playlist.filesDropped ({ loop.getFullPathName() }, x, playlist.trackRowForSnapshot (pads).getCentreY());
  35426. settle();
  35427. check ("a loop dropped on the Sampler track is refused", offline.getSong().playlist.size() == clipsBefore);
  35428. write (ui, "simple-window");
  35429. dir.deleteRecursively();
  35430. }
  35431. // ---- B. Clip-launch: Live's control bar ----------------------------------------------------------------------------
  35432. if (set.isNotEmpty())
  35433. {
  35434. lynx::AudioEngine offline (false);
  35435. lynx::MainComponent ui (offline, false);
  35436. ui.setSize (w, h);
  35437. ui.openFile (juce::File (set));
  35438. offline.dispatchPendingMessages();
  35439. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch, false);
  35440. offline.dispatchPendingMessages();
  35441. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  35442. offline.dispatchPendingMessages();
  35443. const auto centre = [&ui] {
  35444. juce::Rectangle<int> r;
  35445. for (const auto* name : { "backToArrangement", "position", "play", "stop", "record", "overdub", "capture", "sessionRecord", "punch" })
  35446. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible())
  35447. r = r.isEmpty() ? c->getBounds() : r.getUnion (c->getBounds());
  35448. return r.expanded (8, 8);
  35449. };
  35450. auto& transport = offline.getTransport();
  35451. ui.transportTickForSnapshot();
  35452. area (ui, centre(), "live-bar-idle");
  35453. transport.playing.store (true);
  35454. ui.transportTickForSnapshot();
  35455. area (ui, centre(), "live-bar-playing");
  35456. offline.setRecording (true);
  35457. ui.transportTickForSnapshot();
  35458. area (ui, centre(), "live-bar-recording");
  35459. auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record"));
  35460. const auto litA = rec != nullptr && rec->getToggleState();
  35461. juce::Thread::sleep (260);
  35462. ui.transportTickForSnapshot();
  35463. check ("Live look: Record steady while recording (no blink)", litA && rec->getToggleState());
  35464. if (auto* punch = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("punch")))
  35465. {
  35466. punch->setToggleState (true, juce::dontSendNotification);
  35467. area (ui, centre(), "live-bar-punch-lit");
  35468. punch->setToggleState (false, juce::dontSendNotification);
  35469. }
  35470. offline.setRecording (false);
  35471. transport.playing.store (false);
  35472. ui.transportTickForSnapshot();
  35473. }
  35474. // ---- C. Pattern (FL): C-11 drop ghost + drag image, the drop, the picker's playing mark ----------------------------------
  35475. if (project.isNotEmpty())
  35476. {
  35477. lynx::layoutstyle::setCurrent (lynx::layoutstyle::Style::pattern); // (the style is global: A and B changed it)
  35478. lynx::AudioEngine offline (false);
  35479. lynx::MainComponent ui (offline, false);
  35480. ui.setSize (w, h);
  35481. ui.openFile (juce::File (project));
  35482. offline.dispatchPendingMessages();
  35483. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern, false);
  35484. ui.selectTabForSnapshot (2);
  35485. offline.dispatchPendingMessages();
  35486. auto& playlist = ui.getPlaylistForSnapshot();
  35487. auto& picker = ui.getPickerForSnapshot();
  35488. const auto& song = offline.getSong();
  35489. write (playlist, "warmup");
  35490. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  35491. offline.dispatchPendingMessages();
  35492. juce::File (lynx::shot::file (juce::File (prefix + "-warmup.png"))).deleteFile();
  35493. int synthBass = 0;
  35494. for (int p = 0; p < (int) song.patterns.size(); ++p)
  35495. if (juce::String::fromUTF8 (song.patterns[(std::size_t) p].name.c_str()).equalsIgnoreCase ("Synth Bass"))
  35496. {
  35497. synthBass = p;
  35498. break;
  35499. }
  35500. // an empty track low in the view (FL's capture: Track 43 / 47, past the song's tracks)
  35501. // (an unnamed track past the song's own, as FL's Track 43 / 47)
  35502. const auto target = (int) song.playlistTracks.size() + 2;
  35503. for (int first = juce::jmax (0, target - 30); first <= target; ++first) // (the row in the lower part of the view)
  35504. {
  35505. playlist.setViewForSnapshot (15.6, 0, first);
  35506. if (playlist.trackRowForSnapshot (target).getBottom() < playlist.getHeight() - 40)
  35507. break;
  35508. }
  35509. offline.dispatchPendingMessages();
  35510. const auto row = playlist.trackRowForSnapshot (target);
  35511. const auto mouse = juce::Point<int> ((int) playlist.xOfTickForSnapshot (9.1 * (double) song.barTicks()), row.getCentreY());
  35512. const juce::var drag (lynx::PlaylistComponent::pickerDragDescription (lynx::ClipKind::pattern, { synthBass }));
  35513. playlist.dragOverForSnapshot (drag, mouse);
  35514. {
  35515. // the window as the drag shows it: the ghost in the row, the entry's picture below right of the mouse
  35516. auto image = lynx::shot::snapshot (ui);
  35517. const auto scale = (float) image.getWidth() / (float) juce::jmax (1, ui.getWidth());
  35518. const auto listRow = picker.listRowOfPattern (synthBass);
  35519. if (listRow >= 0)
  35520. {
  35521. const auto entry = picker.dragImageOf (listRow);
  35522. const auto at = ui.getLocalPoint (&playlist, mouse) + lynx::PatternPicker::dragImageOffset();
  35523. juce::Graphics g (image);
  35524. g.addTransform (juce::AffineTransform::scale (scale));
  35525. g.drawImageAt (entry, at.x, at.y);
  35526. g.setColour (juce::Colours::white);
  35527. juce::Path arrow; // (the mouse pointer, so the pair reads as FL's film still)
  35528. arrow.startNewSubPath ((float) ui.getLocalPoint (&playlist, mouse).x, (float) ui.getLocalPoint (&playlist, mouse).y);
  35529. arrow.lineTo (arrow.getCurrentPosition() + juce::Point<float> (0.0f, 16.0f));
  35530. arrow.lineTo (arrow.getCurrentPosition() + juce::Point<float> (4.0f, -4.0f));
  35531. arrow.lineTo (arrow.getCurrentPosition() + juce::Point<float> (7.0f, 0.0f));
  35532. arrow.closeSubPath();
  35533. g.fillPath (arrow);
  35534. g.setColour (juce::Colours::black);
  35535. g.strokePath (arrow, juce::PathStrokeType (1.0f));
  35536. }
  35537. savePng (image, prefix + "-fl-c11-drag.png");
  35538. }
  35539. const auto ghost = playlist.dropGhostAreaForCheck();
  35540. line ("ghost " + ghost.toString() + ", row " + row.toString() + ", mouse " + mouse.toString());
  35541. check ("C-11: the ghost lies in the row under the mouse", ! ghost.isEmpty() && ghost.getY() >= row.getY() - 2 && ghost.getBottom() <= row.getBottom() + 2);
  35542. const auto first = (int) offline.getSong().playlist.size();
  35543. playlist.dropForSnapshot (drag, mouse);
  35544. offline.dispatchPendingMessages();
  35545. const auto& dropped = offline.getSong(); // (an edit publishes a new Song: read it again; the Playlist sorts its clips)
  35546. int onRow = 0, at = -1;
  35547. for (int c = 0; c < (int) dropped.playlist.size(); ++c)
  35548. if (dropped.playlist[(std::size_t) c].track == target)
  35549. {
  35550. ++onRow;
  35551. at = c;
  35552. }
  35553. line ("clips " + juce::String (first) + " -> " + juce::String ((int) dropped.playlist.size()) + ", on the row " + juce::String (onRow));
  35554. check ("C-11: the drop places one clip on the row", (int) dropped.playlist.size() == first + 1 && onRow == 1);
  35555. check ("C-11: the dropped clip is selected", at >= 0 && playlist.isClipSelectedForCheck (at));
  35556. check ("C-11: nothing of the ghost is left", playlist.dropGhostAreaForCheck().isEmpty());
  35557. write (ui, "fl-c11-dropped");
  35558. // the picker's playing mark: Synth Bass plays in the first bars; then another pattern selected
  35559. offline.getTransport().positionTicks.store (0.5 * (double) offline.getSong().barTicks());
  35560. offline.getTransport().playing.store (true);
  35561. offline.getTransport().songMode = true;
  35562. playlist.frameStepForSnapshot();
  35563. playlist.frameStepForSnapshot();
  35564. write (picker, "fl-picker-playing");
  35565. line ("playing patterns: " + juce::String ((int) picker.playingForCheck().size()));
  35566. const auto other = juce::jmin ((int) offline.getSong().patterns.size() - 1, 7);
  35567. offline.editSong ([other] (lynx::Song& s) { s.currentPattern = other; }, false);
  35568. offline.dispatchPendingMessages();
  35569. playlist.frameStepForSnapshot();
  35570. write (picker, "fl-picker-playing-other-selected");
  35571. check ("DC-3: the mark follows what plays, not the selection",
  35572. std::find (picker.playingForCheck().begin(), picker.playingForCheck().end(), other) == picker.playingForCheck().end()
  35573. || std::count_if (offline.getSong().playlist.begin(), offline.getSong().playlist.end(), [&] (const lynx::Clip& c) {
  35574. return c.kind == lynx::ClipKind::pattern && c.pattern == other && (double) c.start <= 0.5 * (double) offline.getSong().barTicks()
  35575. && (double) c.end() > 0.5 * (double) offline.getSong().barTicks();
  35576. }) > 0);
  35577. offline.getTransport().playing.store (false);
  35578. playlist.frameStepForSnapshot();
  35579. write (picker, "fl-picker-stopped");
  35580. check ("DC-3: no mark once stopped", picker.playingForCheck().empty());
  35581. }
  35582. line ("done");
  35583. }
  35584. void runDetails190imShot (const juce::String& prefix, const juce::String& project, const juce::String& set)
  35585. {
  35586. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  35587. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true); // (the live frame steps run off-screen)
  35588. juce::String checks;
  35589. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  35590. const auto line = [&checks] (const juce::String& what) { checks << " " << what << "\n"; };
  35591. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  35592. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  35593. {
  35594. // ---- Pattern layout, the FL demo
  35595. lynx::AudioEngine offline (false);
  35596. lynx::MainComponent ui (offline, false);
  35597. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  35598. if (project.isNotEmpty())
  35599. ui.openFile (juce::File (project));
  35600. offline.dispatchPendingMessages();
  35601. ui.selectTabForSnapshot (2);
  35602. auto& playlist = ui.getPlaylistForSnapshot();
  35603. offline.dispatchPendingMessages();
  35604. const auto settle = [&] {
  35605. write (playlist, "warmup");
  35606. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  35607. offline.dispatchPendingMessages();
  35608. juce::File (prefix + "-warmup.png").deleteFile();
  35609. };
  35610. const auto& song = offline.getSong();
  35611. offline.editSong ([] (lynx::Song& s) { for (auto& t : s.playlistTracks) t.height = 50; }, false);
  35612. offline.dispatchPendingMessages();
  35613. const auto toolbar = ui.getToolbarBoundsForSnapshot();
  35614. // R1: the automation clip with the most points in view, its second point dragged, its first segment bent
  35615. int autoClip = -1;
  35616. for (int c = 0; c < (int) song.playlist.size(); ++c)
  35617. if (const auto& clip = song.playlist[(std::size_t) c]; clip.kind == lynx::ClipKind::automation && clip.automation >= 0
  35618. && clip.automation < (int) song.automations.size() && song.automations[(std::size_t) clip.automation].points.size() >= 3
  35619. && (autoClip < 0 || song.automations[(std::size_t) clip.automation].points.size() > song.automations[(std::size_t) song.playlist[(std::size_t) autoClip].automation].points.size()))
  35620. autoClip = c;
  35621. check ("R1: an automation clip with points in the project", autoClip >= 0);
  35622. if (autoClip >= 0)
  35623. {
  35624. const auto& clip = song.playlist[(std::size_t) autoClip];
  35625. const auto bar = (int) (clip.start / song.barTicks());
  35626. playlist.setViewForSnapshot (39.75, juce::jmax (0, bar - 2), juce::jmax (0, clip.track - 3));
  35627. settle();
  35628. const auto point = playlist.dragHintForSnapshot (autoClip, 1, false);
  35629. line ("point drag hint: " + point.text + " | " + point.value);
  35630. check ("R1: a dragged automation-clip point shows its value (DE-117)", point.value.isNotEmpty());
  35631. ui.setHintForSnapshot (point);
  35632. saveArea (ui, toolbar, prefix + "-r1-hint-point.png");
  35633. write (ui, "r1-window-point");
  35634. int bent = 0; // (a segment that is bent, when the clip has one)
  35635. const auto& points = song.automations[(std::size_t) clip.automation].points;
  35636. for (int k = 0; k + 1 < (int) points.size(); ++k)
  35637. if (points[(std::size_t) k].tension != 0.0f)
  35638. {
  35639. bent = k;
  35640. break;
  35641. }
  35642. const auto tension = playlist.dragHintForSnapshot (autoClip, bent, true);
  35643. line ("tension drag hint: " + tension.text + " | " + tension.value);
  35644. check ("R1: a bent segment shows its tension (DE-118)", tension.value.startsWith (lynx::tr ("Tension: {0}", { "" }).upToFirstOccurrenceOf (" ", false, false).trimEnd()));
  35645. ui.setHintForSnapshot (tension);
  35646. saveArea (ui, toolbar, prefix + "-r1-hint-tension.png");
  35647. const auto body = playlist.curveBodyForSnapshot (autoClip);
  35648. const auto hoverX = juce::jlimit (playlist.headerWidthForSnapshot() + 20, playlist.getWidth() - 40, (int) body.getX() + 80);
  35649. const auto hover = playlist.hintAt ({ hoverX, (int) body.getCentreY() });
  35650. line ("hover hint: " + hover.text + " | " + hover.value);
  35651. check ("R1: hovering the curve shows the value at the mouse (DE-119)", hover.value.contains (" "));
  35652. ui.setHintForSnapshot (hover);
  35653. saveArea (ui, toolbar, prefix + "-r1-hint-hover.png");
  35654. }
  35655. // R5: playing at bar 33 (FL's fl-playing.png), the meters fed so the activity strips show their steps
  35656. playlist.setViewForSnapshot (39.75, 20, 24);
  35657. settle();
  35658. offline.getTransport().positionTicks.store ((double) (32 * song.barTicks()));
  35659. offline.getTransport().playing.store (true);
  35660. const auto feed = [&offline] {
  35661. const float levels[] { 1.0f, 0.3f, 0.08f, 0.02f };
  35662. for (int k = 1; k < lynx::maxMixerTracks; ++k)
  35663. offline.getMeters().accumulate (k, levels[k % 4], levels[k % 4]);
  35664. };
  35665. feed();
  35666. playlist.frameStepForSnapshot();
  35667. feed();
  35668. playlist.frameStepForSnapshot();
  35669. write (ui, "r5-playing");
  35670. write (ui.getPickerForSnapshot(), "r5-picker-playing");
  35671. const auto px = (int) playlist.xOfTickForSnapshot (32.0 * (double) song.barTicks());
  35672. saveArea (playlist, { px - 40, lynx::PlaylistComponent::headerHeight, 60, 120 }, prefix + "-r5-playhead.png");
  35673. saveArea (playlist, { 0, lynx::PlaylistComponent::toolbarHeight, playlist.getWidth(), lynx::PlaylistComponent::overviewHeight }, prefix + "-r5-overview.png");
  35674. saveArea (playlist, { 0, lynx::PlaylistComponent::headerHeight, playlist.headerWidthForSnapshot() + 4, playlist.getHeight() - lynx::PlaylistComponent::headerHeight }, prefix + "-r5-headers.png");
  35675. lynx::ui::motion::enabled() = false;
  35676. playlist.frameStepForSnapshot();
  35677. saveArea (playlist, { px - 40, lynx::PlaylistComponent::headerHeight, 60, 120 }, prefix + "-r5-playhead-noanim.png");
  35678. lynx::ui::motion::enabled() = true;
  35679. playlist.frameStepForSnapshot();
  35680. // a drop preview: two patterns dragged from the Picker (issue #177's description) over track 4, bar 36
  35681. const auto row = playlist.trackRowForSnapshot (27);
  35682. playlist.dragOverForSnapshot (juce::var ("lynx-picker|0|0,1"), { (int) playlist.xOfTickForSnapshot (35.6 * (double) song.barTicks()), row.getCentreY() });
  35683. write (ui, "r5-drop-preview");
  35684. playlist.dragOverForSnapshot ({}, {});
  35685. offline.getTransport().playing.store (false);
  35686. playlist.frameStepForSnapshot();
  35687. write (ui, "r5-stopped");
  35688. write (ui.getPickerForSnapshot(), "r5-picker-stopped");
  35689. saveArea (playlist, { 0, lynx::PlaylistComponent::toolbarHeight, playlist.getWidth(), lynx::PlaylistComponent::overviewHeight }, prefix + "-r5-overview-stopped.png");
  35690. // R15: a scroll by hand while playing — Pattern layout: Follow goes on (off by default); the option on: it pauses
  35691. auto& globals = lynx::EditorGlobals::get();
  35692. const auto scrollWhilePlaying = [&] {
  35693. offline.getTransport().playing.store (true);
  35694. playlist.frameStepForSnapshot();
  35695. playlist.setScrollTickForSnapshot (playlist.scrollTicksForSnapshot() + 4.0 * (double) song.barTicks());
  35696. playlist.frameStepForSnapshot();
  35697. const auto paused = playlist.followPausedForSnapshot();
  35698. offline.getTransport().playing.store (false);
  35699. playlist.frameStepForSnapshot();
  35700. return paused;
  35701. };
  35702. check ("R15: Pattern layout (option off by default): no pause", ! globals.followPausing() && ! scrollWhilePlaying());
  35703. globals.followPausesOnEdit = 1;
  35704. check ("R15: option on: a scroll while playing pauses Follow", scrollWhilePlaying());
  35705. check ("R15: a stop lifts the pause", ! playlist.followPausedForSnapshot());
  35706. globals.followPausesOnEdit = -1;
  35707. }
  35708. {
  35709. // ---- R11: the Sampler's handles (a 1 s tone, loop points on)
  35710. lynx::AudioEngine engine (false);
  35711. const auto tone = juce::File (prefix).getParentDirectory().getChildFile ("details190im-tone.wav");
  35712. {
  35713. juce::AudioBuffer<float> buffer (1, 44100);
  35714. for (int i = 0; i < buffer.getNumSamples(); ++i)
  35715. buffer.setSample (0, i, (float) (0.6 * std::sin (juce::MathConstants<double>::twoPi * 110.0 * i / 44100.0) * (1.0 - i / 44100.0)));
  35716. tone.deleteFile();
  35717. juce::WavAudioFormat wav;
  35718. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (tone.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  35719. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  35720. }
  35721. engine.editSong ([&] (lynx::Song& s) {
  35722. if (s.channels.empty())
  35723. s.channels.resize (1);
  35724. lynx::audioclips::loadSampleInto (s.channels[0], tone.getFullPathName().toStdString(), "Tone");
  35725. });
  35726. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  35727. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  35728. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  35729. frame->createComponentSnapshot (frame->getLocalBounds());
  35730. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  35731. auto& f = *frame;
  35732. lynx::samplerPageTurn (f, "useLoops", 1.0);
  35733. lynx::samplerPageTurn (f, "loopStart", 11025.0);
  35734. lynx::samplerPageTurn (f, "loopEnd", 22050.0);
  35735. lynx::samplerPageTurn (f, "smpStart", 0.0);
  35736. savePng (f.createComponentSnapshot (f.getLocalBounds()), prefix + "-r11-sampler-before.png");
  35737. for (const auto* h : { "Start", "LoopStart", "LoopEnd" })
  35738. line (juce::String ("press on the drawn ") + h + " handle takes: " + lynx::samplerPageQuery (f, juce::String ("handleAt") + h));
  35739. check ("R11: a press on the loop start line takes the loop start", lynx::samplerPageQuery (f, "handleAtLoopStart") == "loopStart");
  35740. check ("R11: a press on the loop end line takes the loop end", lynx::samplerPageQuery (f, "handleAtLoopEnd") == "loopEnd");
  35741. check ("R11: a press on the Start marker takes the start", lynx::samplerPageQuery (f, "handleAtStart") == "start");
  35742. lynx::samplerPageTurn (f, "dragLoopEnd", 0.75);
  35743. check ("R11: the loop end dragged to 3/4", std::abs ((double) sampler().loopEnd - 0.75 * 44099.0) < 2.0);
  35744. lynx::samplerPageTurn (f, "dragLoopStart", 0.375, true);
  35745. check ("R11: Shift drags the whole loop", sampler().loopStart > 16000 && sampler().loopEnd - sampler().loopStart > 22000);
  35746. line ("loop after the drags: " + juce::String (sampler().loopStart) + " - " + juce::String (sampler().loopEnd));
  35747. lynx::samplerPageTurn (f, "dragStart", 0.2);
  35748. check ("R11: the Start marker dragged to 20 %", std::abs (sampler().startOffset - 0.2f) < 0.01f);
  35749. savePng (f.createComponentSnapshot (f.getLocalBounds()), prefix + "-r11-sampler-after.png");
  35750. tone.deleteFile();
  35751. }
  35752. if (set.isNotEmpty())
  35753. {
  35754. // ---- Clip-launch layout, the Live set
  35755. lynx::AudioEngine offline (false);
  35756. lynx::MainComponent ui (offline, false);
  35757. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  35758. ui.setVisible (true);
  35759. ui.selectTabForSnapshot (2);
  35760. ui.setClipLaunchWorkflow (true);
  35761. offline.dispatchPendingMessages();
  35762. ui.openFile (juce::File (set));
  35763. offline.dispatchPendingMessages();
  35764. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  35765. offline.dispatchPendingMessages();
  35766. ui.resized();
  35767. auto* gridView = ui.getClipGridForSnapshot();
  35768. auto* runtime = offline.launcherStateForSnapshot();
  35769. const auto& song = offline.getSong();
  35770. check ("grid and launcher", gridView != nullptr && runtime != nullptr && song.clipGrid.has_value());
  35771. if (gridView == nullptr || runtime == nullptr || ! song.clipGrid.has_value())
  35772. {
  35773. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  35774. return;
  35775. }
  35776. auto& grid = *gridView;
  35777. gridView->resized();
  35778. const auto firstClip = [&song] (int track, lynx::ClipKind kind) {
  35779. for (int r = 0; r < 64; ++r)
  35780. if (const auto* c = lynx::launcher::clipAt (*song.clipGrid, track, r); c != nullptr && c->kind == kind)
  35781. return r;
  35782. return -1;
  35783. };
  35784. const auto bigCrop = [&] (const juce::String& name, juce::Rectangle<int> area) { saveArea (grid, area, prefix + "-" + name + ".png"); };
  35785. // R6: track 0 plays a one-shot (Loop off), track 1 loops in its 2nd pass, track 2's clip has a follow action
  35786. int rows[3] { -1, -1, -1 };
  35787. for (int t = 0; t < 3; ++t)
  35788. for (const auto kind : { lynx::ClipKind::audio, lynx::ClipKind::pattern })
  35789. if (rows[t] < 0)
  35790. rows[t] = firstClip (t, kind);
  35791. offline.editSong ([&rows] (lynx::Song& s) {
  35792. if (rows[0] >= 0)
  35793. lynx::launcher::settingsAt (*s.clipGrid, 0, rows[0])->loop = false;
  35794. if (rows[2] >= 0)
  35795. {
  35796. auto& f = lynx::launcher::settingsAt (*s.clipGrid, 2, rows[2])->follow;
  35797. f.enabled = true;
  35798. f.a = lynx::FollowKind::next;
  35799. }
  35800. }, false);
  35801. offline.dispatchPendingMessages();
  35802. runtime->running.store (true);
  35803. for (int t = 0; t < 2; ++t)
  35804. if (rows[t] >= 0)
  35805. {
  35806. const auto length = (double) lynx::launcher::clipAt (*song.clipGrid, t, rows[t])->length;
  35807. runtime->tracks[(std::size_t) t].playing.store (rows[t]);
  35808. runtime->tracks[(std::size_t) t].progress.store (0.4f);
  35809. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  35810. runtime->clockNow.store (length * 1.4);
  35811. }
  35812. lynx::tickClipGridForSnapshot (grid);
  35813. grid.repaint();
  35814. write (grid, "r6-grid-playing");
  35815. bigCrop ("r6-status-oneshot", lynx::clipGridCellForSnapshot (grid, 1, 0, 0).getUnion (lynx::clipGridCellForSnapshot (grid, 1, 1, 0)));
  35816. if (rows[2] >= 0)
  35817. {
  35818. const auto cell = lynx::clipGridCellForSnapshot (grid, 0, 2, rows[2]);
  35819. bigCrop ("r6-follow-stripes", cell);
  35820. }
  35821. // the queued scene's pulse, both phases, then the next scene selected
  35822. const auto scene = juce::jmax (0, rows[1]);
  35823. lynx::setClipGridBlinkPhaseForSnapshot (1);
  35824. lynx::launchClipGridSceneForSnapshot (grid, scene);
  35825. grid.repaint();
  35826. bigCrop ("r6-scene-queued-lit", lynx::clipGridCellForSnapshot (grid, 2, 0, scene));
  35827. lynx::setClipGridBlinkPhaseForSnapshot (0);
  35828. grid.repaint();
  35829. bigCrop ("r6-scene-queued-dark", lynx::clipGridCellForSnapshot (grid, 2, 0, scene));
  35830. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  35831. const auto [selected, sceneSelected] = lynx::clipGridSceneSelectionForSnapshot (grid);
  35832. check ("R6: after a scene launch the scene below is selected (DL-6)", selected == juce::jmin (scene + 1, (int) song.clipGrid->scenes.size() - 1) && sceneSelected);
  35833. write (grid, "r6-grid-scene-launched");
  35834. // the hints of each part
  35835. const auto hintAt = [&] (const juce::String& what, juce::Point<int> p) {
  35836. const auto [text, value] = lynx::clipGridHintForSnapshot (grid, p);
  35837. line ("hint " + what + ": " + text + " | " + value);
  35838. return text;
  35839. };
  35840. const auto slot = lynx::clipGridCellForSnapshot (grid, 0, 1, juce::jmax (0, rows[1]));
  35841. const auto launchHint = hintAt ("clip launch button", { slot.getX() + 7, slot.getCentreY() });
  35842. hintAt ("clip", { slot.getCentreX(), slot.getCentreY() });
  35843. hintAt ("stop button", { lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getX() + 7, lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getCentreY() });
  35844. hintAt ("status", { lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getCentreX(), lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getCentreY() });
  35845. const auto sceneCell = lynx::clipGridCellForSnapshot (grid, 2, 0, 0);
  35846. hintAt ("scene launch button", { sceneCell.getX() + 6, sceneCell.getCentreY() });
  35847. hintAt ("scene", { sceneCell.getCentreX(), sceneCell.getCentreY() });
  35848. check ("R6: the grid's parts have hints (DL-21)", launchHint.isNotEmpty());
  35849. ui.setHintForSnapshot ({ launchHint, {}, false, false });
  35850. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-r6-hint-launch.png");
  35851. // R12: 0 on the selected clip deactivates it (greyed), again activates it; the scene column's font
  35852. lynx::selectClipGridSlotForSnapshot (grid, 1, juce::jmax (0, rows[1]));
  35853. grid.grabKeyboardFocus();
  35854. const auto activeNow = [&] { const auto* s = lynx::launcher::settingsAt (*const_cast<lynx::Song&> (song).clipGrid, 1, juce::jmax (0, rows[1])); return s == nullptr || s->active; };
  35855. check ("R12: 0 is taken by the grid", lynx::clipGridKeyForSnapshot (grid, juce::KeyPress ('0')));
  35856. offline.dispatchPendingMessages();
  35857. check ("R12: 0 deactivates the selected clip", ! activeNow());
  35858. for (auto& v : runtime->tracks)
  35859. v.playing.store (-1);
  35860. grid.repaint();
  35861. write (grid, "r12-clip-deactivated");
  35862. bigCrop ("r12-clip-deactivated-cell", slot);
  35863. lynx::clipGridKeyForSnapshot (grid, juce::KeyPress ('0'));
  35864. offline.dispatchPendingMessages();
  35865. check ("R12: 0 again activates it", activeNow());
  35866. bigCrop ("r12-scene-column", lynx::clipGridCellForSnapshot (grid, 2, 0, 0).getUnion (lynx::clipGridCellForSnapshot (grid, 2, 0, juce::jmin (7, (int) song.clipGrid->scenes.size() - 1))));
  35867. // R13: the Clip View of a launched MIDI clip: the Piano roll's playhead at the clip's position
  35868. int midiTrack = -1, midiRow = -1;
  35869. for (int t = 0; t < 16 && midiTrack < 0; ++t)
  35870. if (const auto r = firstClip (t, lynx::ClipKind::pattern); r >= 0)
  35871. {
  35872. midiTrack = t;
  35873. midiRow = r;
  35874. }
  35875. check ("R13: the set has a MIDI clip", midiTrack >= 0);
  35876. if (auto* detail = ui.getDetailViewForSnapshot(); detail != nullptr && midiTrack >= 0)
  35877. {
  35878. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  35879. lynx::DetailView::shownSetting = true;
  35880. detail->showSelection (midiTrack, midiRow);
  35881. detail->setPage (lynx::DetailView::Page::clip);
  35882. offline.dispatchPendingMessages();
  35883. ui.resized();
  35884. const auto& clip = *lynx::launcher::clipAt (*song.clipGrid, midiTrack, midiRow);
  35885. runtime->running.store (true);
  35886. runtime->tracks[(std::size_t) midiTrack].playing.store (midiRow);
  35887. runtime->tracks[(std::size_t) midiTrack].anchor.store (0.0);
  35888. runtime->clockNow.store ((double) clip.length * 2.3);
  35889. offline.getTransport().playing.store (true);
  35890. auto& roll = ui.getPianoRollForSnapshot();
  35891. roll.frameStepForSnapshot();
  35892. const auto expect = (double) clip.offset + 0.3 * (double) clip.length;
  35893. line ("piano roll playhead " + juce::String (roll.playheadForSnapshot(), 1) + ", the launched clip at " + juce::String (expect, 1));
  35894. check ("R13: the docked Piano roll shows the launched clip's position (DL-74)", std::abs (roll.playheadForSnapshot() - expect) < (double) lynx::ppq);
  35895. write (ui, "r13-clipview-midi");
  35896. offline.getTransport().playing.store (false);
  35897. runtime->tracks[(std::size_t) midiTrack].playing.store (-1);
  35898. roll.frameStepForSnapshot();
  35899. }
  35900. }
  35901. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  35902. }
  35903. void runDesign190igShot (const juce::String& prefix, const juce::String& project)
  35904. {
  35905. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  35906. lynx::AudioEngine offline (false);
  35907. lynx::MainComponent ui (offline, false);
  35908. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  35909. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  35910. const auto write = [&prefix] (juce::Component& c, const char* name) {
  35911. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  35912. };
  35913. if (project.isNotEmpty())
  35914. ui.openFile (juce::File (project));
  35915. offline.dispatchPendingMessages();
  35916. ui.selectTabForSnapshot (2); // the Playlist, maximized
  35917. auto& playlist = ui.getPlaylistForSnapshot();
  35918. offline.dispatchPendingMessages();
  35919. const auto settle = [&] { // (the waveforms are analysed in the background on the first paint)
  35920. write (playlist, "warmup");
  35921. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  35922. offline.dispatchPendingMessages();
  35923. juce::File (prefix + "-warmup.png").deleteFile();
  35924. };
  35925. const auto heights = [&] (int h) {
  35926. offline.editSong ([h] (lynx::Song& s) {
  35927. for (auto& t : s.playlistTracks)
  35928. t.height = h;
  35929. }, false);
  35930. offline.dispatchPendingMessages();
  35931. };
  35932. // FL's default view (shots/ref/fl-playlist.png): 26 px tracks, bar 21 at the left, 15.6 px a bar, CUTS at the top
  35933. heights (26);
  35934. playlist.setViewForSnapshot (15.6, 20, 0);
  35935. playlist.setScrollYForSnapshot (19 * 26);
  35936. settle();
  35937. write (ui, "01-default");
  35938. write (playlist, "01-default-playlist");
  35939. // FL's "Zoom level 17" (shots/ref/fl-playlist-zoom-audioclips.png): 50 px tracks, 39.75 px a bar, Saw Bass at the top
  35940. heights (50);
  35941. playlist.setViewForSnapshot (39.75, 20, 0);
  35942. playlist.setScrollYForSnapshot (24 * 50 + 4);
  35943. settle();
  35944. write (ui, "02-zoom17");
  35945. write (playlist, "02-zoom17-playlist");
  35946. // playing (shots/ref/fl-playing.png): the playhead at bar 33, the activity column lit for the tracks that sound
  35947. offline.getTransport().positionTicks.store ((double) (32 * offline.getSong().barTicks()));
  35948. offline.getTransport().playing.store (true);
  35949. playlist.frameStepForSnapshot();
  35950. playlist.frameStepForSnapshot();
  35951. write (ui, "03-playing");
  35952. offline.getTransport().playing.store (false);
  35953. playlist.frameStepForSnapshot();
  35954. heights (26);
  35955. playlist.setViewForSnapshot (15.6, 0, 0);
  35956. playlist.setScrollYForSnapshot (0);
  35957. write (ui, "04-default-start");
  35958. // round 190jd (live check 190iw Q4): FL's grid levels at its Ctrl+wheel steps — bars only at 9.9 px a beat, beat
  35959. // lines from 11.5, half-beat lines from 21.5 (shots/q4-fl-zoom-levels-ruler-grid.png), at bar 9 like FL's shot
  35960. heights (32);
  35961. for (const auto beat : { 9.9, 11.5, 18.4, 21.5 })
  35962. {
  35963. playlist.setViewForSnapshot (beat * 4.0, 8, 0);
  35964. playlist.setScrollYForSnapshot (0);
  35965. write (playlist, ("05-grid-" + juce::String (beat, 1) + "px-beat").toRawUTF8());
  35966. }
  35967. // round 190jd: NEW automation clips from the first channel's volume and pan knobs take FL's colours by parameter
  35968. // (#8C5F5F, #7F8C5E; shots/q4-fl-new-automation-clip-zoom2.png); the editor windows they open are closed again
  35969. if (! offline.getSong().channels.empty())
  35970. {
  35971. // (the channels of FL's capture: Synth Bass pan + volume, Grv Kick 27 volume + pan; else the first channel)
  35972. const auto channelNamed = [&offline] (const char* name) {
  35973. const auto& channels = offline.getSong().channels;
  35974. for (int c = 0; c < (int) channels.size(); ++c)
  35975. if (juce::String (channels[(std::size_t) c].name).startsWithIgnoreCase (name))
  35976. return c;
  35977. return 0;
  35978. };
  35979. juce::String report;
  35980. offline.editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  35981. offline.getTransport().positionTicks.store (0.0);
  35982. const auto before = offline.getSong().automations.size();
  35983. for (const auto& [name, kind] : { std::pair { "Synth Bass", lynx::AutomationTargetKind::channelPan },
  35984. std::pair { "Grv Kick", lynx::AutomationTargetKind::channelVolume },
  35985. std::pair { "Synth Bass", lynx::AutomationTargetKind::channelVolume },
  35986. std::pair { "Grv Kick", lynx::AutomationTargetKind::channelPan } })
  35987. {
  35988. lynx::AutomationTarget t;
  35989. t.kind = kind;
  35990. t.index = channelNamed (name);
  35991. lynx::createAutomationClip (offline, t);
  35992. offline.dispatchPendingMessages();
  35993. }
  35994. lynx::closeAutomationEditors();
  35995. offline.dispatchPendingMessages();
  35996. int first = -1;
  35997. for (std::size_t a = before; a < offline.getSong().automations.size(); ++a)
  35998. {
  35999. const auto& au = offline.getSong().automations[a];
  36000. for (const auto& c : offline.getSong().playlist)
  36001. if (c.kind == lynx::ClipKind::automation && c.automation == (int) a)
  36002. {
  36003. first = first < 0 ? c.track : std::min (first, c.track);
  36004. report << "new clip '" << au.name << "' track " << (c.track + 1) << " colour #"
  36005. << juce::String::toHexString ((int) (au.colour & 0xFFFFFF)).paddedLeft ('0', 6).toUpperCase() << "\n";
  36006. }
  36007. }
  36008. report << "automations " << (int) before << " -> " << (int) offline.getSong().automations.size() << "\n";
  36009. juce::File (prefix + "-190jd-automation.txt").replaceWithText (report);
  36010. heights (50);
  36011. playlist.setViewForSnapshot (39.75, 0, 0);
  36012. playlist.setScrollYForSnapshot (std::max (0, first - 1) * 50);
  36013. write (playlist, "06-new-automation-clips");
  36014. }
  36015. // round 190jd (live check 190iw Q7, shots/q7-fl-countin-sheet.png): a 1-bar count-in — the time display reads
  36016. // "REC IN 4" on its first beat and "REC IN 1" on its last, Play shows its Pause glyph, Record stays lit
  36017. for (const auto beatsLeft : { 4, 1 })
  36018. {
  36019. offline.getTransport().countIn.store ((double) beatsLeft * lynx::ppq - 1.0);
  36020. ui.tickLinkForSnapshot();
  36021. ui.transportForSnapshot (true, true);
  36022. write (ui, ("07-countin-" + juce::String (beatsLeft)).toRawUTF8());
  36023. }
  36024. offline.getTransport().countIn.store (0.0);
  36025. }
  36026. void runDesign190igS4Shot (const juce::String& prefix, const juce::String& projectPath)
  36027. {
  36028. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  36029. lynx::AudioEngine offline (false);
  36030. lynx::MainComponent ui (offline, false);
  36031. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  36032. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  36033. juce::String checks;
  36034. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  36035. const auto write = [&prefix] (juce::Component& c, const juce::String& name) {
  36036. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  36037. file.deleteFile();
  36038. juce::FileOutputStream out (file);
  36039. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  36040. };
  36041. ui.setVisible (true);
  36042. ui.selectTabForSnapshot (2);
  36043. ui.setClipLaunchWorkflow (true); // (first: an .als opened in the Clip-launch layout takes Live's own colours)
  36044. offline.dispatchPendingMessages();
  36045. if (projectPath.isNotEmpty())
  36046. {
  36047. ui.openFile (juce::File (projectPath));
  36048. offline.dispatchPendingMessages();
  36049. }
  36050. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  36051. offline.dispatchPendingMessages();
  36052. ui.resized();
  36053. auto* gridView = ui.getClipGridForSnapshot();
  36054. auto* runtime = offline.launcherStateForSnapshot();
  36055. const auto& song = offline.getSong();
  36056. if (gridView == nullptr || ! song.clipGrid)
  36057. {
  36058. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid\n");
  36059. return;
  36060. }
  36061. if (! song.mixer.empty())
  36062. checks << "first mixer colours:";
  36063. for (std::size_t m = 1; m < std::min<std::size_t> (song.mixer.size(), 6); ++m)
  36064. checks << " " << juce::String::toHexString ((int) (song.mixer[m].colour & 0xffffff)).paddedLeft ('0', 6);
  36065. checks << "\n";
  36066. gridView->resized();
  36067. write (ui, "01-window-idle");
  36068. write (*gridView, "02-grid-idle");
  36069. if (runtime == nullptr)
  36070. {
  36071. check ("a launcher runtime exists", false);
  36072. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  36073. return;
  36074. }
  36075. // the frame strip: the first five tracks; the scene each plays or waits for, by the clips the set has
  36076. const auto& grid = *song.clipGrid;
  36077. const auto rowWithClip = [&grid] (int track, int from) {
  36078. for (int r = from; r < 64; ++r)
  36079. if (lynx::launcher::clipAt (grid, track, r) != nullptr)
  36080. return r;
  36081. return -1;
  36082. };
  36083. const auto reset = [&] {
  36084. for (auto& v : runtime->tracks)
  36085. {
  36086. v.playing.store (-1);
  36087. v.pending.store (-1);
  36088. v.stopping.store (false);
  36089. v.recording.store (-1);
  36090. v.recordPending.store (-1);
  36091. v.progress.store (0.0f);
  36092. }
  36093. runtime->running.store (true);
  36094. };
  36095. const auto bar = (double) song.barTicks();
  36096. const auto state = [&] (const juce::String& name) {
  36097. gridView->repaint();
  36098. write (*gridView, name);
  36099. };
  36100. // playing (Live frame 1): tracks 0..3 play their first clip, a third of the way into its second loop
  36101. reset();
  36102. for (int t = 0; t < 4; ++t)
  36103. if (const auto r = rowWithClip (t, 0); r >= 0)
  36104. {
  36105. runtime->tracks[(std::size_t) t].playing.store (r);
  36106. runtime->tracks[(std::size_t) t].progress.store (0.33f);
  36107. const auto length = (double) lynx::launcher::clipAt (grid, t, r)->length;
  36108. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  36109. runtime->clockNow.store (length * 1.33);
  36110. }
  36111. state ("10-playing");
  36112. // queued (Live frames 2 and 3): the same, and each track's next clip waits for its start; both blink phases
  36113. for (int t = 0; t < 4; ++t)
  36114. if (const auto r = runtime->tracks[(std::size_t) t].playing.load(); r >= 0)
  36115. if (const auto next = rowWithClip (t, r + 1); next >= 0)
  36116. runtime->tracks[(std::size_t) t].pending.store (next);
  36117. lynx::setClipGridBlinkPhaseForSnapshot (0);
  36118. state ("11-queued-dark");
  36119. lynx::setClipGridBlinkPhaseForSnapshot (1);
  36120. state ("12-queued-lit");
  36121. // Animations off: the lit green, steady
  36122. lynx::ui::motion::enabled() = false;
  36123. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  36124. state ("13-queued-animations-off");
  36125. lynx::ui::motion::enabled() = true;
  36126. // a stop waiting (both phases)
  36127. reset();
  36128. for (int t = 0; t < 4; ++t)
  36129. if (const auto r = rowWithClip (t, 0); r >= 0)
  36130. {
  36131. runtime->tracks[(std::size_t) t].playing.store (r);
  36132. runtime->tracks[(std::size_t) t].progress.store (0.5f);
  36133. runtime->tracks[(std::size_t) t].stopping.store (t % 2 == 0);
  36134. }
  36135. lynx::setClipGridBlinkPhaseForSnapshot (0);
  36136. state ("14-stopping-dark");
  36137. lynx::setClipGridBlinkPhaseForSnapshot (1);
  36138. state ("15-stopping-lit");
  36139. // recording into an empty slot of track 1 (the counter one beat in) and a launch waiting on an empty slot (a stop)
  36140. reset();
  36141. {
  36142. int empty = -1;
  36143. for (int r = 0; r < 16 && empty < 0; ++r)
  36144. if (lynx::launcher::clipAt (grid, 1, r) == nullptr)
  36145. empty = r;
  36146. if (empty >= 0)
  36147. {
  36148. runtime->tracks[1].recording.store (empty);
  36149. runtime->tracks[1].recordFrom.store (0.0);
  36150. runtime->clockNow.store ((double) lynx::ppq);
  36151. }
  36152. check ("recording: an empty slot on track 2", empty >= 0);
  36153. }
  36154. state ("16-recording");
  36155. // the status pie at 25 / 50 / 75 % in the second loop
  36156. for (const auto [name, p] : { std::pair ("17-pie-25", 0.25f), std::pair ("18-pie-50", 0.5f), std::pair ("19-pie-75", 0.75f) })
  36157. {
  36158. reset();
  36159. for (int t = 0; t < 4; ++t)
  36160. if (const auto r = rowWithClip (t, 0); r >= 0)
  36161. {
  36162. const auto length = (double) lynx::launcher::clipAt (grid, t, r)->length;
  36163. runtime->tracks[(std::size_t) t].playing.store (r);
  36164. runtime->tracks[(std::size_t) t].progress.store (p);
  36165. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  36166. runtime->clockNow.store (length * (1.0 + (double) p));
  36167. }
  36168. state (name);
  36169. }
  36170. juce::ignoreUnused (bar);
  36171. // round 181a's look, the option (View › Classic LYNX look for the clip grid)
  36172. reset();
  36173. for (int t = 0; t < 4; ++t)
  36174. if (const auto r = rowWithClip (t, 0); r >= 0)
  36175. runtime->tracks[(std::size_t) t].playing.store (r);
  36176. lynx::clipGridClassicLook() = true;
  36177. lynx::refreshClipGrid (*gridView);
  36178. state ("20-classic-look-option");
  36179. lynx::clipGridClassicLook() = false;
  36180. lynx::refreshClipGrid (*gridView);
  36181. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  36182. reset();
  36183. runtime->running.store (false);
  36184. write (ui, "21-window-after");
  36185. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  36186. ui.setClipLaunchWorkflow (false);
  36187. }
  36188. void runLiveShot190dr (const juce::String& prefix)
  36189. {
  36190. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  36191. lynx::AudioEngine offline (false);
  36192. lynx::MainComponent ui (offline, false);
  36193. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  36194. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  36195. const auto write = [&prefix] (juce::Component& c, const char* name) {
  36196. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  36197. file.deleteFile();
  36198. juce::FileOutputStream out (file);
  36199. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  36200. };
  36201. juce::String checks;
  36202. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  36203. // a two-bar loop of clicks for the audio clip
  36204. const auto wav = juce::File (prefix + "-loop.wav");
  36205. wav.deleteFile();
  36206. {
  36207. const double rate = 48000.0;
  36208. juce::AudioBuffer<float> buffer (2, (int) (rate * 4.0));
  36209. buffer.clear();
  36210. for (int hit = 0; hit < 16; ++hit)
  36211. for (int k = 0; k < 3000 && hit * 12000 + k < buffer.getNumSamples(); ++k)
  36212. for (int ch = 0; ch < 2; ++ch)
  36213. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
  36214. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  36215. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  36216. {
  36217. out.release();
  36218. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  36219. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  36220. }
  36221. }
  36222. ui.setVisible (true);
  36223. lynx::DetailView::shownSetting = true;
  36224. lynx::DetailView::devicesPage = false;
  36225. ui.setClipLaunchWorkflow (true);
  36226. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  36227. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  36228. offline.dispatchPendingMessages();
  36229. int audioChannel = -1;
  36230. offline.editSong ([&audioChannel] (lynx::Song& s) {
  36231. lynx::Clip audio;
  36232. if (! s.playlist.empty())
  36233. {
  36234. audio = s.playlist.front();
  36235. audioChannel = audio.channel;
  36236. s.playlist.clear();
  36237. }
  36238. const int channels = (int) s.channels.size();
  36239. s.channels.resize ((std::size_t) channels + 3);
  36240. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  36241. for (int k = 0; k < 3; ++k)
  36242. {
  36243. auto& ch = s.channels[(std::size_t) (channels + k)];
  36244. ch.name = names[k];
  36245. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  36246. ch.mixerTrack = k + 1;
  36247. }
  36248. if (audioChannel >= 0)
  36249. s.channels[(std::size_t) audioChannel].mixerTrack = 5;
  36250. if (s.mixer.size() < 8)
  36251. s.mixer.resize (8);
  36252. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Loop", "Reverb", "Delay" };
  36253. for (int i = 1; i < 8; ++i)
  36254. s.mixer[(std::size_t) i].name = inserts[i];
  36255. s.mixer[1].volume = lynx::sessionmixer::positionForDb (-3.0);
  36256. s.mixer[2].pan = 0.3f;
  36257. s.mixer[2].effects.clear();
  36258. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  36259. {
  36260. lynx::EffectSlot fx;
  36261. fx.kind = kind;
  36262. const auto& info = lynx::effectInfo (kind);
  36263. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  36264. fx.params[k] = info.params[k].defaultValue;
  36265. s.mixer[2].effects.push_back (fx);
  36266. }
  36267. s.mixer[3].muted = true; // the Keys' activator off
  36268. s.mixer[4].inputChannel = 0;
  36269. s.mixer[4].inputStereo = true;
  36270. s.mixer[4].monitor = lynx::InputMonitor::automatic;
  36271. s.mixer[4].effects.clear();
  36272. {
  36273. lynx::EffectSlot fx;
  36274. fx.kind = lynx::EffectKind::reverb;
  36275. s.mixer[4].effects.push_back (fx);
  36276. }
  36277. s.mixer[5].solo = true;
  36278. for (auto [from, to, level] : std::initializer_list<std::tuple<int, int, float>> { { 1, 6, 0.35f }, { 2, 6, 0.6f }, { 3, 6, 0.8f }, { 2, 7, 0.25f }, { 4, 7, 0.5f } })
  36279. {
  36280. lynx::MixerSend send;
  36281. send.target = to;
  36282. send.level = lynx::faderGain (level);
  36283. s.mixer[(std::size_t) from].sends.push_back (send);
  36284. }
  36285. while (s.patterns.size() < 3)
  36286. s.patterns.emplace_back();
  36287. const char* patterns[] { "Beat", "Bassline", "Chords" };
  36288. for (int p = 0; p < 3; ++p)
  36289. {
  36290. auto& pattern = s.patterns[(std::size_t) p];
  36291. pattern.name = patterns[p];
  36292. lynx::Note n;
  36293. n.channel = channels + p;
  36294. n.key = 48 + p * 5;
  36295. pattern.notes = { n };
  36296. pattern.lengthTicks = 4 * lynx::ppq;
  36297. }
  36298. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  36299. const char* tracks[] { "Drums", "Bass", "Keys", "Vox", "Loop", "FX" };
  36300. for (int t = 0; t < 6; ++t)
  36301. s.playlistTracks[(std::size_t) t].name = tracks[t];
  36302. s.playlistTracks[3].mode = lynx::PlaylistTrackMode::audio;
  36303. s.playlistTracks[3].mixerTrack = 4;
  36304. for (int t = 0; t < 3; ++t)
  36305. for (int r = 0; r < 3; ++r)
  36306. if (! (t == 2 && r == 0))
  36307. {
  36308. lynx::Clip clip;
  36309. clip.pattern = t;
  36310. clip.length = 4 * lynx::ppq;
  36311. lynx::launcher::setClip (s, t, r, clip);
  36312. }
  36313. if (audioChannel >= 0)
  36314. {
  36315. lynx::clipsample::setWarp (s, audioChannel, true, 4.0); // (Warp on, as a dropped loop in Live)
  36316. audio.track = 4;
  36317. audio.start = 0;
  36318. lynx::launcher::setClip (s, 4, 0, audio);
  36319. lynx::launcher::setClip (s, 4, 1, audio);
  36320. }
  36321. auto& grid = lynx::launcher::ensureGrid (s);
  36322. const char* scenes[] { "Intro", "Verse", "Drop" };
  36323. grid.scenes.resize (5);
  36324. for (int r = 0; r < 3; ++r)
  36325. grid.scenes[(std::size_t) r].name = scenes[r];
  36326. }, false);
  36327. offline.dispatchPendingMessages();
  36328. offline.setGridTrackArmed (3, true);
  36329. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  36330. offline.dispatchPendingMessages();
  36331. ui.resized();
  36332. auto* gridView = ui.getClipGridForSnapshot();
  36333. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  36334. auto* detail = ui.getDetailViewForSnapshot();
  36335. if (gridView == nullptr || mixer == nullptr || detail == nullptr)
  36336. {
  36337. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid, mixer or detail view\n");
  36338. return;
  36339. }
  36340. // the meters: a level per insert, as a playing song leaves them (offscreen nothing plays), two ticks
  36341. const auto levels = [&] {
  36342. for (int k = 0; k < 2; ++k)
  36343. {
  36344. const float peaks[] { 0.9f, 0.5f, 0.7f, 0.0f, 0.3f, 0.45f, 0.2f, 0.12f };
  36345. for (int i = 0; i < 8; ++i)
  36346. offline.getMeters().accumulate (i, peaks[i], peaks[i] * 0.85f);
  36347. mixer->tick();
  36348. }
  36349. };
  36350. if (auto* runtime = offline.launcherStateForSnapshot())
  36351. {
  36352. runtime->tracks[0].playing.store (1);
  36353. runtime->tracks[0].progress.store (0.3f);
  36354. runtime->tracks[1].playing.store (1);
  36355. runtime->tracks[1].progress.store (0.3f);
  36356. runtime->tracks[4].playing.store (0);
  36357. runtime->tracks[4].progress.store (0.5f);
  36358. runtime->running.store (true);
  36359. }
  36360. levels();
  36361. gridView->resized();
  36362. write (ui, "01-session-mixer");
  36363. write (*gridView, "01b-grid-alone");
  36364. using Part = lynx::SessionMixerComponent::Part;
  36365. check ("mixer: Sends rows are the two buses (Reverb 6, Delay 7)", mixer->sendTargets() == std::vector<int> { 6, 7 });
  36366. check ("mixer: the arm buttons moved into the Volume section", mixer->armsShown());
  36367. check ("mixer: Drums strip has activator, solo, arm, pan, volume", ! mixer->partBounds (0, Part::activator).isEmpty() && ! mixer->partBounds (0, Part::solo).isEmpty()
  36368. && ! mixer->partBounds (0, Part::arm).isEmpty() && ! mixer->partBounds (0, Part::pan).isEmpty()
  36369. && ! mixer->partBounds (0, Part::volume).isEmpty());
  36370. check ("mixer: Vox strip (audio track) has Audio From, its channel, Monitor and Audio To", ! mixer->partBounds (3, Part::inType).isEmpty()
  36371. && ! mixer->partBounds (3, Part::inChannel).isEmpty()
  36372. && ! mixer->partBounds (3, Part::monAuto).isEmpty()
  36373. && ! mixer->partBounds (3, Part::output).isEmpty());
  36374. check ("mixer: Bass strip (instrument) shows MIDI From, no Monitor", mixer->partBounds (1, Part::monIn).isEmpty() && ! mixer->partBounds (1, Part::output).isEmpty());
  36375. check ("mixer: FX strip (no clips) has no activator but an arm", mixer->partBounds (5, Part::activator).isEmpty() && ! mixer->partBounds (5, Part::arm).isEmpty());
  36376. check ("mixer: Main strip has volume and pan, no activator", ! mixer->partBounds (-2, Part::volume).isEmpty() && mixer->partBounds (-2, Part::activator).isEmpty());
  36377. {
  36378. const auto hit = mixer->hitAt (mixer->partBounds (2, Part::solo).getCentre());
  36379. check ("mixer: a click on the Keys' S is its solo", hit.column == 2 && hit.part == Part::solo);
  36380. const auto send = mixer->hitAt (mixer->partBounds (1, Part::send, 1).getCentre());
  36381. check ("mixer: the Bass' second knob is its send to Delay", send.column == 1 && send.part == Part::send && send.row == 1);
  36382. }
  36383. {
  36384. juce::PopupMenu menu;
  36385. mixer->addViewItems (menu);
  36386. saveMenus (juce::StringArray { "Mixer (footer button)" }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-mixer-view-menu.png");
  36387. }
  36388. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.trackOptions = true; }, false);
  36389. offline.dispatchPendingMessages();
  36390. gridView->resized();
  36391. levels();
  36392. write (*gridView, "03-mixer-track-options");
  36393. offline.editSong ([] (lynx::Song& s) {
  36394. auto& v = lynx::launcher::ensureGrid (s).mixerView;
  36395. v.trackOptions = v.io = v.sends = false;
  36396. }, false);
  36397. offline.dispatchPendingMessages();
  36398. gridView->resized();
  36399. levels();
  36400. write (*gridView, "04-mixer-volume-only");
  36401. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.shown = false; }, false);
  36402. offline.dispatchPendingMessages();
  36403. gridView->resized();
  36404. write (*gridView, "05-mixer-hidden");
  36405. check ("mixer hidden: the arm buttons are back in the status row", ! mixer->armsShown() && mixer->getHeight() == 0);
  36406. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView = {}; }, false);
  36407. offline.dispatchPendingMessages();
  36408. gridView->resized();
  36409. // the Clip page of the Loop clip (track 4, scene 0) while it plays: Warp on, the Set buttons lit, the title
  36410. detail->showSelection (4, 0);
  36411. detail->setPage (lynx::DetailView::Page::clip);
  36412. offline.editSong ([] (lynx::Song&) {}, false); // (a change message: the Clip panel reads the playing state)
  36413. offline.dispatchPendingMessages();
  36414. write (ui, "06-clip-audio-warp-on");
  36415. // round 190ig (round 190ia CL-20a, the BPM row bug): the Audio box at Live's 190 px, 260 px and 350 px detail
  36416. // heights, in Re-Pitch (no settings rows) and in Beats (three rows: the most a mode shows)
  36417. if (audioChannel >= 0)
  36418. {
  36419. const auto heightBefore = lynx::DetailView::preferredHeight;
  36420. for (const auto beats : { false, true })
  36421. {
  36422. offline.editSong ([audioChannel, beats] (lynx::Song& s) {
  36423. auto& sampler = s.channels[(std::size_t) audioChannel].sampler;
  36424. sampler.keepPitch = beats;
  36425. sampler.stretchMethod = beats ? lynx::StretchMethod::beats : sampler.stretchMethod;
  36426. }, false);
  36427. offline.dispatchPendingMessages();
  36428. for (const auto h : { 190, 260, 350 })
  36429. {
  36430. lynx::DetailView::preferredHeight = h;
  36431. ui.resized();
  36432. if (auto* area = detail->getParentComponent()) // (the Playlist area lays its docked detail view out)
  36433. area->resized();
  36434. offline.dispatchPendingMessages();
  36435. write (ui, (juce::String ("06h-audio-box-") + (beats ? "beats-" : "repitch-") + juce::String (h)).toRawUTF8());
  36436. check ("audio box at " + juce::String (h) + " px: the detail view is that high", detail->getHeight() == h);
  36437. }
  36438. }
  36439. offline.editSong ([audioChannel] (lynx::Song& s) { s.channels[(std::size_t) audioChannel].sampler.keepPitch = false; }, false);
  36440. offline.dispatchPendingMessages();
  36441. lynx::DetailView::preferredHeight = heightBefore;
  36442. ui.resized();
  36443. if (auto* area = detail->getParentComponent())
  36444. area->resized();
  36445. offline.dispatchPendingMessages();
  36446. }
  36447. if (audioChannel >= 0)
  36448. {
  36449. const auto beforeLength = lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length;
  36450. offline.editSong ([audioChannel] (lynx::Song& s) { lynx::clipsample::setWarp (s, audioChannel, false, 4.0); });
  36451. offline.dispatchPendingMessages();
  36452. write (ui, "07-clip-audio-warp-off");
  36453. check ("warp off: the channel plays at its own speed", ! lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  36454. offline.undo();
  36455. offline.dispatchPendingMessages();
  36456. check ("warp: undo gives the clip back as it was", lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length == beforeLength
  36457. && lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  36458. // Set (start) at the play position, half way: one undo step
  36459. const auto clipBefore = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  36460. offline.editSong ([] (lynx::Song& s) {
  36461. for (auto& c : s.clipGrid->clips)
  36462. if (c.track == 4 && c.gridSlot >= 0 && s.clipGrid->slots[(std::size_t) c.gridSlot].scene == 0)
  36463. lynx::clipsample::setStartAt (c, lynx::clipsample::playPosition (c, 0.5f));
  36464. });
  36465. const auto& after = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  36466. check ("set start: the clip starts half way and ends where it did", after.offset == clipBefore.offset + clipBefore.length / 2
  36467. && after.offset + after.length == clipBefore.offset + clipBefore.length);
  36468. offline.undo();
  36469. offline.dispatchPendingMessages();
  36470. }
  36471. // a MIDI clip's Clip page too (the Set buttons are there for every clip), playing through a groove of the pool
  36472. offline.editSong ([] (lynx::Song& s) {
  36473. const auto& bank = lynx::groove::factoryBank();
  36474. if (bank.size() > 9)
  36475. lynx::groove::setClipGroove (s, 0, 1, lynx::groove::add (s.grooves, bank[9].groove));
  36476. }, false);
  36477. detail->showSelection (0, 1);
  36478. offline.editSong ([] (lynx::Song&) {}, false);
  36479. offline.dispatchPendingMessages();
  36480. write (ui, "08-clip-midi-set-buttons");
  36481. // the Device View of Bass (insert 2): its compressor dragged onto Keys (insert 3), then Ctrl-dragged onto Vox
  36482. detail->showSelection (1, 0);
  36483. detail->setPage (lynx::DetailView::Page::devices);
  36484. offline.dispatchPendingMessages();
  36485. write (ui, "09-devices-bass-before");
  36486. lynx::setClipGridDeviceDropForSnapshot (*gridView, 2);
  36487. write (ui, "10-device-dragged-over-keys");
  36488. lynx::setClipGridDeviceDropForSnapshot (*gridView, -1);
  36489. int fromId = 0;
  36490. {
  36491. const auto& s = offline.getSong();
  36492. fromId = (int) (s.mixer[2].effects[1].instance.id & 0x7fffffff);
  36493. }
  36494. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  36495. offline.dispatchPendingMessages();
  36496. check ("drag to Keys: the compressor moved (same device)", offline.getSong().mixer[2].effects.size() == 2 && offline.getSong().mixer[3].effects.size() == 1
  36497. && (int) (offline.getSong().mixer[3].effects[0].instance.id & 0x7fffffff) == fromId);
  36498. detail->showSelection (2, 1);
  36499. offline.dispatchPendingMessages();
  36500. write (ui, "11-devices-keys-after-move");
  36501. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 0, 4, true); });
  36502. offline.dispatchPendingMessages();
  36503. check ("Ctrl-drag to Vox: a copy of the EQ after its reverb, Bass keeps its own", offline.getSong().mixer[4].effects.size() == 2
  36504. && offline.getSong().mixer[4].effects[1].kind == lynx::EffectKind::eq
  36505. && offline.getSong().mixer[2].effects[0].kind == lynx::EffectKind::eq);
  36506. offline.undo();
  36507. offline.undo();
  36508. offline.dispatchPendingMessages();
  36509. check ("undo twice: Bass has its three devices again, Keys none", offline.getSong().mixer[2].effects.size() == 3 && offline.getSong().mixer[3].effects.empty()
  36510. && offline.getSong().mixer[4].effects.size() == 1);
  36511. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  36512. wav.deleteFile();
  36513. }
  36514. void runWarpShot (const juce::String& prefix)
  36515. {
  36516. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  36517. lynx::AudioEngine offline (false);
  36518. lynx::MainComponent ui (offline, false);
  36519. ui.setSize (1600, 900);
  36520. const auto write = [&prefix] (juce::Component& c, const char* name) {
  36521. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  36522. file.deleteFile();
  36523. juce::FileOutputStream out (file);
  36524. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  36525. };
  36526. // a two-bar loop of clicks, a little off the grid (what Quantize is for)
  36527. const auto wav = juce::File (prefix + "-loop.wav");
  36528. wav.deleteFile();
  36529. {
  36530. const double rate = 44100.0;
  36531. juce::AudioBuffer<float> buffer (1, (int) (rate * 4.0));
  36532. buffer.clear();
  36533. for (int hit = 0; hit < 8; ++hit)
  36534. {
  36535. const auto at = (int) ((hit * 0.5 + (hit % 3) * 0.035) * rate);
  36536. for (int k = 0; k < 4000 && at + k < buffer.getNumSamples(); ++k)
  36537. buffer.setSample (0, at + k, (float) (std::sin (k * (hit % 2 ? 0.25 : 0.06)) * std::exp (-k / 700.0) * 0.8));
  36538. }
  36539. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  36540. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  36541. {
  36542. out.release();
  36543. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  36544. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  36545. }
  36546. }
  36547. ui.setVisible (true);
  36548. lynx::DetailView::shownSetting = true;
  36549. ui.selectTabForSnapshot (2);
  36550. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  36551. lynx::autolanes::setShown (true);
  36552. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  36553. offline.dispatchPendingMessages();
  36554. int channel = -1;
  36555. offline.editSong ([&channel] (lynx::Song& s) {
  36556. if (s.playlist.empty())
  36557. return;
  36558. auto audio = s.playlist.front();
  36559. channel = audio.channel;
  36560. audio.track = 1;
  36561. s.playlist.front() = audio;
  36562. for (int k = 1; k < 3; ++k)
  36563. {
  36564. auto more = audio;
  36565. more.start = audio.start + k * 8 * lynx::ppq;
  36566. s.playlist.push_back (more);
  36567. }
  36568. while (s.patterns.size() < 1)
  36569. s.patterns.emplace_back();
  36570. for (int t = 2; t < 5; ++t)
  36571. for (int k = 0; k < 4; ++k)
  36572. {
  36573. lynx::Clip c;
  36574. c.pattern = 0;
  36575. c.track = t;
  36576. c.start = k * 4 * lynx::ppq;
  36577. c.length = 4 * lynx::ppq;
  36578. s.playlist.push_back (c);
  36579. }
  36580. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  36581. s.playlistTracks[1].name = "Loop";
  36582. s.playlistTracks[2].name = "Drums";
  36583. s.playlistTracks[3].name = "Kick";
  36584. s.playlistTracks[4].name = "Hats";
  36585. s.playlistTracks[4].folded = true;
  36586. lynx::noteedit::groupWithAbove (s, 3);
  36587. lynx::noteedit::groupWithAbove (s, 4);
  36588. lynx::arrange::makeGroupBus (s, 3);
  36589. lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::tempo, 0, 0, 0 }, "Tempo", lynx::valueFromTempo (s.bpm));
  36590. if (! s.automations.empty())
  36591. s.automations.back().points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { 8 * lynx::ppq, lynx::valueFromTempo (120.0), 0.0f },
  36592. { 12 * lynx::ppq, lynx::valueFromTempo (180.0), 0.0f }, { 16 * lynx::ppq, lynx::valueFromTempo (140.0), 0.0f } };
  36593. s.addMarker ({ 4 * lynx::ppq, "Verse", 0, 0 });
  36594. s.addMarker ({ 8 * lynx::ppq, {}, 3, 4 });
  36595. s.addMarker ({ 14 * lynx::ppq, {}, 4, 4 });
  36596. s.loopStart = 4 * lynx::ppq;
  36597. s.loopEnd = 12 * lynx::ppq;
  36598. s.loopOff = true;
  36599. s.tempoViewLow = 60.0; // the tempo lane's range
  36600. s.tempoViewHigh = 200.0;
  36601. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& a, const lynx::Clip& b) { return a.start < b.start; });
  36602. // the same audio in the clip grid, for the Clip page
  36603. lynx::Clip slot = audio;
  36604. slot.start = 0;
  36605. slot.pitch = -2.25f;
  36606. slot.gain = 0.7f;
  36607. lynx::launcher::setClip (s, 1, 0, slot);
  36608. // a few warp markers, as Quantize leaves them
  36609. if (channel >= 0 && channel < (int) s.channels.size())
  36610. {
  36611. auto& sampler = s.channels[(std::size_t) channel].sampler;
  36612. lynx::warpedit::ensureMarkers (sampler, 4.0, s.bpm);
  36613. std::vector<double> attacks;
  36614. for (int hit = 1; hit < 8; ++hit)
  36615. attacks.push_back (hit * 0.5 + (hit % 3) * 0.035);
  36616. lynx::warptools::quantize (sampler, attacks, 0.0, 4.0, 0.5, 1.0);
  36617. lynx::warpedit::syncLength (sampler, 4.0);
  36618. }
  36619. }, false);
  36620. offline.dispatchPendingMessages();
  36621. ui.resized();
  36622. write (ui, "arrangement-loop-off");
  36623. offline.editSong ([] (lynx::Song& s) { s.loopOff = false; }, false);
  36624. offline.dispatchPendingMessages();
  36625. write (ui, "arrangement-loop-on");
  36626. juce::String facts;
  36627. {
  36628. const auto& s = offline.getSong();
  36629. facts << "channel " << channel << ", warp markers " << (channel >= 0 ? (int) s.channels[(std::size_t) channel].sampler.warp.size() : -1)
  36630. << ", group bus insert " << lynx::arrange::groupBus (s, 3) << ", folded track 4: " << (lynx::arrange::isFolded (s, 4) ? 1 : 0) << "\n";
  36631. }
  36632. if (auto* detail = ui.getDetailViewForSnapshot())
  36633. {
  36634. detail->showSelection (1, 0);
  36635. detail->setPage (lynx::DetailView::Page::clip);
  36636. offline.dispatchPendingMessages();
  36637. write (ui, "clip-audio");
  36638. }
  36639. if (channel >= 0)
  36640. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  36641. {
  36642. editor->setSize (1120, 600);
  36643. write (*editor, "audio-editor-warp");
  36644. // round 190cy (Live 12.4.16 live check 190cw shot 09): a plain drag of marker 3 holds it two sixteenths
  36645. // later (its audio goes there); Shift + drag slides the audio under it. Round 190db: the Clip-launch
  36646. // workflow draws the warped clip in beats, so the held drag shows the audio stretched around the marker
  36647. // (plain) or slid under it, its attack later (Shift, to the right as in Live's shot)
  36648. const auto& w = offline.getSong().channels[(std::size_t) channel].sampler.warp;
  36649. if (w.size() > 4)
  36650. {
  36651. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].beats + 0.5, false);
  36652. write (*editor, "audio-editor-drag-stretch");
  36653. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].seconds - 0.12, true);
  36654. write (*editor, "audio-editor-drag-slide");
  36655. }
  36656. // the same clip in file time (the Pattern workflow's view, or "Show the audio in beats" off)
  36657. if (auto inFileTime = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  36658. {
  36659. inFileTime->setSize (1120, 600);
  36660. lynx::setAudioEditorBeatTimeForSnapshot (*inFileTime, 0);
  36661. write (*inFileTime, "audio-editor-file-time");
  36662. if (w.size() > 4)
  36663. {
  36664. lynx::holdAudioEditorWarpDragForSnapshot (*inFileTime, 3, w[3].beats + 0.5, false);
  36665. write (*inFileTime, "audio-editor-file-time-drag");
  36666. }
  36667. }
  36668. }
  36669. // round 190cy (Live 12.4.16 live check 190cw shot 02): ÷2 from the editor of the first Playlist clip halves that
  36670. // clip's length with the markers' beats; ÷2 on the grid clip's Clip page halves the grid clip
  36671. {
  36672. const auto lengthOf = [&offline] (int index) { return index < (int) offline.getSong().playlist.size() ? offline.getSong().playlist[(std::size_t) index].length : -1; };
  36673. const auto gridLength = [&offline] {
  36674. const auto& s = offline.getSong();
  36675. const auto* c = s.clipGrid ? lynx::launcher::clipAt (*s.clipGrid, 1, 0) : nullptr;
  36676. return c != nullptr ? c->length : (std::int64_t) -1;
  36677. };
  36678. const auto first = [&offline] {
  36679. const auto& s = offline.getSong();
  36680. for (int i = 0; i < (int) s.playlist.size(); ++i)
  36681. if (s.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  36682. return i;
  36683. return -1;
  36684. }();
  36685. facts << "halve: playlist clip " << first << " length " << lengthOf (first);
  36686. if (first >= 0)
  36687. if (auto editor = lynx::makeAudioEditorPanel (offline, offline.getSong().playlist[(std::size_t) first].channel, first, true))
  36688. {
  36689. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  36690. offline.dispatchPendingMessages();
  36691. }
  36692. facts << " -> " << lengthOf (first) << "; grid clip length " << gridLength();
  36693. if (channel >= 0)
  36694. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, -1, true))
  36695. {
  36696. lynx::setAudioEditorGridClip (*editor, 1, 0);
  36697. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  36698. offline.dispatchPendingMessages();
  36699. }
  36700. facts << " -> " << gridLength() << "\n";
  36701. ui.resized();
  36702. write (ui, "arrangement-halved");
  36703. // Duplicate Time over beats 4-8 holding the locator "Verse" (beat 4): a second "Verse" at beat 8
  36704. offline.editSong ([] (lynx::Song& s) { lynx::arrange::duplicateTime (s, 4 * lynx::ppq, 8 * lynx::ppq); });
  36705. offline.dispatchPendingMessages();
  36706. int verses = 0;
  36707. for (const auto& m : offline.getSong().markers())
  36708. verses += m.name == "Verse" ? 1 : 0;
  36709. facts << "duplicate time: locators named Verse " << verses << "\n";
  36710. write (ui, "arrangement-duplicated-time");
  36711. }
  36712. juce::File (prefix + "-facts.txt").replaceWithText (facts);
  36713. lynx::autolanes::setShown (false);
  36714. }
  36715. void runMtShot190fm (const juce::String& prefix)
  36716. {
  36717. lynx::AudioEngine offline (false);
  36718. offline.editSong ([] (lynx::Song& s) {
  36719. if (s.patterns.empty())
  36720. s.patterns.emplace_back();
  36721. s.patterns[0].notes.clear();
  36722. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  36723. s.currentPattern = 0;
  36724. }, false);
  36725. lynx::MidiToolsPanel panel (offline, [] {
  36726. lynx::MidiToolsPanel::Target t;
  36727. t.pattern = 0;
  36728. t.grid = lynx::ppq / 4;
  36729. t.channel = 0;
  36730. t.length = 4 * lynx::ppq; // one bar, no time selection
  36731. return t;
  36732. });
  36733. panel.setSize (lynx::MidiToolsPanel::panelWidth, lynx::MidiToolsPanel::panelHeight);
  36734. panel.setSection (lynx::MidiToolsPanel::generateSection);
  36735. panel.setGenerateShotSettingsForSnapshot();
  36736. const auto write = [&prefix] (const juce::Image& image, const juce::String& name) {
  36737. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  36738. file.deleteFile();
  36739. juce::FileOutputStream out (file);
  36740. juce::PNGImageFormat().writeImageToStream (image, out);
  36741. };
  36742. std::vector<juce::Image> images;
  36743. juce::String checks;
  36744. for (int g = 0; g < lynx::midigen::Settings::toolCount; ++g)
  36745. {
  36746. panel.setGenerator (g);
  36747. const auto name = juce::String (lynx::midigen::toolName (g)).toLowerCase();
  36748. images.push_back (lynx::shot::paint (panel, lynx::theme::colour::bg2));
  36749. write (images.back(), "generate-" + name);
  36750. panel.generateNow();
  36751. offline.dispatchPendingMessages();
  36752. const auto made = (int) offline.getSong().patterns[0].notes.size();
  36753. offline.undo();
  36754. offline.dispatchPendingMessages();
  36755. const auto after = (int) offline.getSong().patterns[0].notes.size();
  36756. checks << name << ": generated " << made << " notes, after undo " << after << (made > 0 && after == 0 ? " OK" : " FAIL") << "\n";
  36757. }
  36758. // the five side by side (6 px apart, on the window's background)
  36759. const auto gap = juce::roundToInt (6.0f * lynx::shot::scale());
  36760. int width = gap, height = 0;
  36761. for (const auto& image : images)
  36762. {
  36763. width += image.getWidth() + gap;
  36764. height = std::max (height, image.getHeight());
  36765. }
  36766. juce::Image strip (juce::Image::RGB, width, height + 2 * gap, true);
  36767. {
  36768. juce::Graphics g (strip);
  36769. g.fillAll (lynx::theme::colour::bg0);
  36770. int x = gap;
  36771. for (const auto& image : images)
  36772. {
  36773. g.drawImageAt (image, x, gap);
  36774. x += image.getWidth() + gap;
  36775. }
  36776. }
  36777. write (strip, "generate-panels");
  36778. checks << "settings saved with the project: " << (offline.getSong().midiGenerate.stacksOptions.sequence.size() == 2 ? "OK" : "FAIL") << "\n";
  36779. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  36780. }
  36781. // Round 190hy: see --mpeshot190hy
  36782. void runMpeShot190hy (const juce::String& prefix)
  36783. {
  36784. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  36785. lynx::AudioEngine offline (false);
  36786. lynx::MainComponent ui (offline, false);
  36787. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  36788. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  36789. const auto write = [&prefix, &ui] (const char* name) {
  36790. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  36791. file.deleteFile();
  36792. juce::FileOutputStream out (file);
  36793. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  36794. };
  36795. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  36796. offline.editSong ([] (lynx::Song& s) {
  36797. if (s.channels.empty())
  36798. s.channels.resize (1);
  36799. s.channels[0].name = "MPE lead";
  36800. s.channels[0].mixerTrack = 1;
  36801. if (s.mixer.size() < 2)
  36802. s.mixer.resize (2);
  36803. while (s.patterns.empty())
  36804. s.patterns.emplace_back();
  36805. auto& p = s.patterns[0];
  36806. p.name = "MPE take";
  36807. p.notes.clear();
  36808. // four notes as an MPE controller plays them: a slide up an octave, a vibrato, a fall, a held chord tone
  36809. const auto note = [&p] (std::int64_t start, std::int64_t length, int key, lynx::NoteCurves c, float modX = 0.5f) {
  36810. lynx::Note n;
  36811. n.channel = 0;
  36812. n.start = start;
  36813. n.length = length;
  36814. n.key = key;
  36815. n.modX = modX;
  36816. n.curves = std::move (c);
  36817. p.notes.push_back (n);
  36818. };
  36819. const auto beat = (float) lynx::ppq;
  36820. lynx::NoteCurves glide;
  36821. glide.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { beat * 0.5f, 0.0f }, { beat * 1.5f, 1200.0f }, { beat * 2.0f, 1200.0f } };
  36822. glide.lane (lynx::NoteCurveLane::timbre) = { { 0.0f, 0.3f }, { beat * 2.0f, 0.85f } };
  36823. glide.lane (lynx::NoteCurveLane::pressure) = { { 0.0f, 0.2f }, { beat * 0.4f, 0.9f }, { beat * 1.6f, 0.7f }, { beat * 2.0f, 0.0f } };
  36824. note (0, 2 * lynx::ppq, 60, glide, 0.3f);
  36825. lynx::NoteCurves vibrato;
  36826. for (int k = 0; k <= 24; ++k)
  36827. vibrato.lane (lynx::NoteCurveLane::pitch).push_back ({ beat * 0.0833f * (float) k, k < 4 ? 0.0f : 40.0f * std::sin ((float) k * 1.5708f) });
  36828. vibrato.lane (lynx::NoteCurveLane::pressure) = { { 0.0f, 0.5f }, { beat * 1.0f, 0.95f }, { beat * 2.0f, 0.4f } };
  36829. note (2 * lynx::ppq, 2 * lynx::ppq, 67, vibrato);
  36830. lynx::NoteCurves fall;
  36831. fall.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { beat * 0.75f, 0.0f }, { beat * 1.0f, -500.0f } };
  36832. fall.lane (lynx::NoteCurveLane::timbre) = { { 0.0f, 0.6f }, { beat * 1.0f, 0.2f } };
  36833. note (4 * lynx::ppq, lynx::ppq, 72, fall, 0.6f);
  36834. note (5 * lynx::ppq, 3 * lynx::ppq, 64, {}); // (a note without curves: its own values, dashed)
  36835. p.lengthTicks = 8 * lynx::ppq;
  36836. }, false);
  36837. offline.dispatchPendingMessages();
  36838. juce::String checks;
  36839. auto& roll = ui.getPianoRollForSnapshot();
  36840. ui.selectTabForSnapshot (1);
  36841. roll.selectMidiToolResult ({ 0 });
  36842. roll.scrollToNotes();
  36843. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneMpePitch, "pitch" },
  36844. { lynx::PianoRollComponent::laneMpeSlide, "slide" },
  36845. { lynx::PianoRollComponent::laneMpePressure, "pressure" } })
  36846. {
  36847. roll.setLaneForSnapshot (lane);
  36848. offline.dispatchPendingMessages();
  36849. write (name);
  36850. checks << "lane " << name << ": areas " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  36851. }
  36852. roll.setLaneForSnapshot (lynx::PianoRollComponent::laneVelocity);
  36853. int curved = 0;
  36854. for (const auto& n : offline.getSong().patterns[0].notes)
  36855. curved += n.curves.has() ? 1 : 0;
  36856. checks << "notes with curves: " << curved << " of " << (int) offline.getSong().patterns[0].notes.size() << "\n";
  36857. // the Clip-launch layout: the clip's Notes tab, then its MPE tab (Live 11+'s note expression lanes)
  36858. ui.selectTabForSnapshot (2);
  36859. lynx::DetailView::shownSetting = true;
  36860. lynx::DetailView::devicesPage = false;
  36861. ui.setClipLaunchWorkflow (true);
  36862. offline.editSong ([] (lynx::Song& s) {
  36863. lynx::Clip clip;
  36864. clip.pattern = 0;
  36865. clip.length = 8 * lynx::ppq;
  36866. lynx::launcher::setClip (s, 0, 0, clip);
  36867. }, false);
  36868. offline.dispatchPendingMessages();
  36869. if (auto* detail = ui.getDetailViewForSnapshot())
  36870. {
  36871. detail->showSelection (0, 0);
  36872. detail->setPage (lynx::DetailView::Page::clip);
  36873. detail->setClipTab (false);
  36874. offline.dispatchPendingMessages();
  36875. roll.scrollToNotes();
  36876. write ("clip-notes");
  36877. checks << "clip notes tab: mpe view " << (roll.isMpeView() ? 1 : 0) << "\n";
  36878. detail->setMpeTab();
  36879. offline.dispatchPendingMessages();
  36880. roll.selectMidiToolResult ({ 0 });
  36881. roll.scrollToNotes();
  36882. write ("clip-mpe");
  36883. checks << "clip MPE tab: mpe view " << (roll.isMpeView() ? 1 : 0) << ", lanes " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  36884. // round 190jd (Live 12.4's MPE tab): the value ghost point on note 1's Pressure line, the "Show Lane:" menu,
  36885. // then all four lanes shown (Slide, Pressure, Velocity, Release Velocity)
  36886. checks << "ghost on the Pressure line: '" << roll.hoverMpeLineForSnapshot (lynx::PianoRollComponent::laneMpePressure, (double) lynx::ppq) << "'\n";
  36887. write ("clip-mpe-ghost190jd");
  36888. roll.hoverMpeLineForSnapshot (0, 0.0);
  36889. saveMenus (juce::StringArray { "MPE tab: Show Lane" }, std::vector<juce::PopupMenu> { roll.getMpeLaneMenuForSnapshot() },
  36890. prefix + "-clip-mpe-showlane190jd.png");
  36891. roll.setMpeLanesForSnapshot (lynx::mpetab::allLanes);
  36892. offline.dispatchPendingMessages();
  36893. write ("clip-mpe-lanes4-190jd");
  36894. checks << "four lanes: " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  36895. roll.setMpeLanesForSnapshot (lynx::mpetab::defaultLanes);
  36896. detail->setClipTab (false);
  36897. offline.dispatchPendingMessages();
  36898. checks << "back to Notes: mpe view " << (roll.isMpeView() ? 1 : 0) << "\n";
  36899. }
  36900. else
  36901. checks << "no detail view\n";
  36902. lynx::shot::file (juce::File (prefix + "-checks.txt")).replaceWithText (checks);
  36903. }
  36904. // round 190kk: Live's Erosion / Vinyl Distortion / Corpus imported, their LYNX engines on the Device View
  36905. void runMeldShot190ko (const juce::String& prefix, const juce::String& meld, const juce::String& time, const juce::String& resonator)
  36906. {
  36907. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  36908. lynx::AudioEngine offline (false);
  36909. lynx::MainComponent ui (offline, false);
  36910. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  36911. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  36912. juce::String checks;
  36913. // a Live device preset (.adv, gzip) → its device element's text
  36914. const auto deviceOf = [] (const juce::String& path, lynx::xml::Document& doc) {
  36915. juce::MemoryBlock raw;
  36916. juce::File (path).loadFileAsData (raw);
  36917. juce::MemoryInputStream in (raw, false);
  36918. juce::GZIPDecompressorInputStream gz (&in, false, juce::GZIPDecompressorInputStream::gzipFormat);
  36919. const auto text = gz.readEntireStreamAsString();
  36920. if (! doc.parse (text.toStdString()))
  36921. return lynx::xml::Element();
  36922. const auto kids = doc.root().children();
  36923. return kids.empty() ? lynx::xml::Element() : kids.front();
  36924. };
  36925. lynx::ChannelDef braid;
  36926. braid.instrument = lynx::InstrumentKind::braid;
  36927. braid.name = "Meld";
  36928. {
  36929. lynx::xml::Document doc;
  36930. lynx::alsdev::Notes notes;
  36931. const auto d = deviceOf (meld, doc);
  36932. const auto ok = (bool) d && lynx::alsdev::meldToBraid (d, braid, notes);
  36933. checks << (ok ? "ok " : "FAIL ") << "Meld -> Braid: " << meld << "\n";
  36934. braid.name = juce::File (meld).getFileNameWithoutExtension().toStdString();
  36935. }
  36936. std::vector<lynx::EffectSlot> slots;
  36937. for (const auto& path : { time, resonator })
  36938. {
  36939. lynx::xml::Document doc;
  36940. const auto d = deviceOf (path, doc);
  36941. if (const auto t = d ? lynx::alsdev::effectFromLiveDevice (d) : std::nullopt)
  36942. {
  36943. slots.push_back (t->slot);
  36944. checks << "ok " << t->from << " -> " << t->to << ": " << path << "\n";
  36945. }
  36946. else
  36947. checks << "FAIL NOT TRANSLATED: " << path << "\n";
  36948. }
  36949. offline.editSong ([&slots, &braid] (lynx::Song& s) {
  36950. if (s.channels.empty())
  36951. s.channels.resize (1);
  36952. braid.mixerTrack = 2;
  36953. s.channels[0] = braid;
  36954. if (s.mixer.size() < 3)
  36955. s.mixer.resize (3);
  36956. s.mixer[2].name = braid.name;
  36957. s.mixer[2].effects = slots;
  36958. while (s.patterns.empty())
  36959. s.patterns.emplace_back();
  36960. s.patterns[0].name = "Chords";
  36961. s.patterns[0].notes.clear();
  36962. for (const int key : { 48, 52, 55 })
  36963. {
  36964. lynx::Note note;
  36965. note.channel = 0;
  36966. note.start = 0;
  36967. note.length = 2 * lynx::ppq;
  36968. note.key = key;
  36969. s.patterns[0].notes.push_back (note);
  36970. }
  36971. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  36972. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  36973. s.playlistTracks[1].name = braid.name;
  36974. }, false);
  36975. offline.dispatchPendingMessages();
  36976. ui.setVisible (true);
  36977. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  36978. ui.selectTabForSnapshot (2);
  36979. ui.setClipLaunchWorkflow (true);
  36980. offline.editSong ([] (lynx::Song& s) {
  36981. lynx::Clip clip;
  36982. clip.pattern = 0;
  36983. clip.length = 4 * lynx::ppq;
  36984. lynx::launcher::setClip (s, 1, 0, clip);
  36985. }, false);
  36986. offline.dispatchPendingMessages();
  36987. if (auto* detail = ui.getDetailViewForSnapshot())
  36988. {
  36989. detail->showSelection (1, 0);
  36990. detail->setPage (lynx::DetailView::Page::devices);
  36991. offline.dispatchPendingMessages();
  36992. const auto file = lynx::shot::file (juce::File (prefix + "-devices.png"));
  36993. file.deleteFile();
  36994. juce::FileOutputStream out (file);
  36995. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  36996. checks << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << "\n";
  36997. }
  36998. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  36999. }
  37000. void runLiveDevShot190kk (const juce::String& prefix)
  37001. {
  37002. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37003. lynx::AudioEngine offline (false);
  37004. lynx::MainComponent ui (offline, false);
  37005. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  37006. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  37007. const auto par = [] (const char* name, double v) { return juce::String ("<") + name + "><Manual Value=\"" + juce::String (v) + "\" /></" + name + ">"; };
  37008. // the Core Library presets' values (Erosion "Fizzle", Vinyl Distortion "Crack" with Tracing on, Corpus "Pipe Resonator" closed)
  37009. const juce::String erosion = "<Erosion2 Id=\"1\"><On><Manual Value=\"true\" /></On>" + par ("Amount", 0.9) + par ("Frequency", 16000) +
  37010. par ("FilterWidth", 1.734) + par ("NoiseBlend", 1) + par ("StereoWidth", 1) + "</Erosion2>";
  37011. const juce::String vinyl = "<Vinyl Id=\"1\"><On><Manual Value=\"true\" /></On><Band1On><Manual Value=\"true\" /></Band1On>" + par ("Gain1", 0.5) +
  37012. par ("BandFreq1", 7500) + par ("BandQ1", 3) + "<Band2On><Manual Value=\"false\" /></Band2On>" + par ("Gain2", 0.35) +
  37013. par ("BandFreq2", 5366) + par ("BandQ2", 0.32) + par ("Drive", 1) + par ("SoftHard", 0) + par ("NormalMono", 0) +
  37014. par ("CracleDensity", 50) + par ("CracleVolume", 1) + "</Vinyl>";
  37015. juce::String corpus = "<Corpus Id=\"1\"><On><Manual Value=\"true\" /></On><FilterOn><Manual Value=\"false\" /></FilterOn>";
  37016. for (const auto& [k, v] : std::initializer_list<std::pair<const char*, double>> { { "ResonanceType", 5 }, { "ResonatorQuality", 3 },
  37017. { "Frequency", 0.4603 }, { "Decay", 0.6032 }, { "FreqDamping", 0 }, { "AmpFreq", 0 }, { "Inharmonics", 0 }, { "Radius", 0.8642 },
  37018. { "TubeOpening", 1 }, { "Ratio", 0.5 }, { "ExcitationX", 0.5 }, { "ListeningXL", 0.1 }, { "ListeningXR", 0.9 }, { "Detune", 0.047 },
  37019. { "Drive", 0.405 }, { "Bleed", 0 }, { "DryWet", 0.696 }, { "StereoWidth", 1 }, { "FilterMidFreq", 1000 }, { "FilterBandWidth", 4 } })
  37020. corpus += par (k, v);
  37021. corpus += "</Corpus>";
  37022. std::vector<lynx::EffectSlot> slots;
  37023. juce::String checks;
  37024. for (const auto& text : { erosion, vinyl, corpus })
  37025. {
  37026. lynx::xml::Document doc;
  37027. doc.parse (text.toStdString());
  37028. if (const auto t = lynx::alsdev::effectFromLiveDevice (doc.root()))
  37029. {
  37030. slots.push_back (t->slot);
  37031. checks << t->from << " -> " << t->to << "\n";
  37032. }
  37033. else
  37034. checks << "NOT TRANSLATED\n";
  37035. }
  37036. offline.editSong ([&slots] (lynx::Song& s) {
  37037. if (s.channels.empty())
  37038. s.channels.resize (1);
  37039. s.channels[0].name = "Drums";
  37040. s.channels[0].mixerTrack = 2;
  37041. if (s.mixer.size() < 3)
  37042. s.mixer.resize (3);
  37043. s.mixer[2].name = "Drums";
  37044. s.mixer[2].effects = slots;
  37045. while (s.patterns.empty())
  37046. s.patterns.emplace_back();
  37047. s.patterns[0].name = "Beat";
  37048. s.patterns[0].notes.clear();
  37049. for (int n = 0; n < 4; ++n)
  37050. {
  37051. lynx::Note note;
  37052. note.channel = 0;
  37053. note.start = n * lynx::ppq;
  37054. note.key = 36;
  37055. s.patterns[0].notes.push_back (note);
  37056. }
  37057. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  37058. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  37059. s.playlistTracks[1].name = "Drums";
  37060. }, false);
  37061. offline.dispatchPendingMessages();
  37062. ui.setVisible (true);
  37063. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  37064. ui.selectTabForSnapshot (2);
  37065. ui.setClipLaunchWorkflow (true);
  37066. offline.editSong ([] (lynx::Song& s) {
  37067. lynx::Clip clip;
  37068. clip.pattern = 0;
  37069. clip.length = 4 * lynx::ppq;
  37070. lynx::launcher::setClip (s, 1, 0, clip);
  37071. }, false);
  37072. offline.dispatchPendingMessages();
  37073. if (auto* detail = ui.getDetailViewForSnapshot())
  37074. {
  37075. detail->showSelection (1, 0);
  37076. detail->setPage (lynx::DetailView::Page::devices);
  37077. const auto file = lynx::shot::file (juce::File (prefix + "-devices.png"));
  37078. file.deleteFile();
  37079. juce::FileOutputStream out (file);
  37080. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  37081. checks << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << "\n";
  37082. }
  37083. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  37084. }
  37085. void runDetailShot (const juce::String& prefix)
  37086. {
  37087. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37088. lynx::AudioEngine offline (false);
  37089. lynx::MainComponent ui (offline, false);
  37090. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  37091. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  37092. const auto write = [&prefix, &ui] (const char* name) {
  37093. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  37094. file.deleteFile();
  37095. juce::FileOutputStream out (file);
  37096. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  37097. };
  37098. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  37099. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  37100. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  37101. offline.editSong ([] (lynx::Song& s) {
  37102. if (s.channels.size() < 2)
  37103. s.channels.resize (2);
  37104. s.channels[0].name = "Bass synth";
  37105. s.channels[0].mixerTrack = 2;
  37106. s.channels[1].mixerTrack = 3;
  37107. if (s.mixer.size() < 4)
  37108. s.mixer.resize (4);
  37109. s.mixer[2].name = "Bass";
  37110. s.mixer[2].effects.clear();
  37111. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::reverb, lynx::EffectKind::delay })
  37112. {
  37113. lynx::EffectSlot fx;
  37114. fx.kind = kind;
  37115. const auto& info = lynx::effectInfo (kind);
  37116. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  37117. fx.params[k] = info.params[k].defaultValue;
  37118. fx.enabled = kind != lynx::EffectKind::compressor; // one switched off
  37119. s.mixer[2].effects.push_back (fx);
  37120. }
  37121. while (s.patterns.size() < 2)
  37122. s.patterns.emplace_back();
  37123. s.patterns[0].name = "Bass line";
  37124. s.patterns[0].notes.clear();
  37125. for (int n = 0; n < 4; ++n)
  37126. {
  37127. lynx::Note note;
  37128. note.channel = 0;
  37129. note.start = n * lynx::ppq;
  37130. note.key = 36 + (n % 2) * 7;
  37131. s.patterns[0].notes.push_back (note);
  37132. }
  37133. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  37134. lynx::PatternEvents lane; // a volume swell for the Envelopes tab (slice 3)
  37135. lane.target = lynx::AutomationTarget { lynx::AutomationTargetKind::channelVolume, 0 };
  37136. for (int e = 0; e < 16; ++e)
  37137. lane.events.push_back ({ e * lynx::ppq / 4, 0.3f + 0.6f * (float) e / 15.0f });
  37138. s.patterns[0].events = { lane };
  37139. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  37140. s.playlistTracks[1].name = "Bass";
  37141. }, false);
  37142. offline.dispatchPendingMessages();
  37143. write ("pattern"); // Pattern workflow: no detail view exists
  37144. ui.setClipLaunchWorkflow (true);
  37145. offline.editSong ([] (lynx::Song& s) {
  37146. lynx::Clip clip;
  37147. clip.pattern = 0;
  37148. clip.length = 4 * lynx::ppq;
  37149. lynx::launcher::setClip (s, 1, 0, clip);
  37150. }, false);
  37151. offline.dispatchPendingMessages();
  37152. juce::String counts;
  37153. if (auto* detail = ui.getDetailViewForSnapshot())
  37154. {
  37155. detail->showSelection (1, 0);
  37156. detail->setPage (lynx::DetailView::Page::devices);
  37157. write ("devices");
  37158. counts << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << ", channel " << detail->chainChannelForCheck() << "\n";
  37159. detail->toggleFoldForCheck (3); // the reverb (card 0 is the instrument)
  37160. write ("folded");
  37161. counts << "folded card 3: " << (detail->isFoldedForCheck (3) ? 1 : 0) << "\n";
  37162. detail->showSelection (2, 0); // an empty track
  37163. write ("empty-track");
  37164. detail->showSelection (1, 0);
  37165. detail->setPage (lynx::DetailView::Page::clip);
  37166. offline.dispatchPendingMessages();
  37167. ui.getPianoRollForSnapshot().scrollToNotes(); // (the app does it on the message loop, which this shot doesn't run)
  37168. write ("clip"); // slice 2: the Piano roll docked here
  37169. {
  37170. // round 190s: the Transform panel with each MIDI tool, then Arpeggiate applied (and undone again)
  37171. auto& tools = detail->midiToolsForSnapshot();
  37172. for (int t = 0; t < lynx::MidiToolsPanel::toolCount; ++t)
  37173. {
  37174. tools.setTool (t);
  37175. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase()).toRawUTF8());
  37176. }
  37177. // round 190aa: the pages again with the settings of the Live shots they are compared with
  37178. tools.setAuto (false);
  37179. tools.setLiveShotSettingsForSnapshot();
  37180. for (int t : { (int) lynx::MidiToolsPanel::chop, (int) lynx::MidiToolsPanel::quantize, (int) lynx::MidiToolsPanel::timeWarp })
  37181. {
  37182. tools.setTool (t);
  37183. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase() + "-set").toRawUTF8());
  37184. }
  37185. tools.setAuto (true);
  37186. tools.setTool (lynx::MidiToolsPanel::arpeggiate);
  37187. tools.transformNow();
  37188. offline.dispatchPendingMessages();
  37189. write ("clip-mt-applied");
  37190. counts << "midi tools: arpeggiate made " << (int) offline.getSong().patterns[0].notes.size() << " notes of 4\n";
  37191. offline.undo();
  37192. offline.dispatchPendingMessages();
  37193. counts << "midi tools: undo gives " << (int) offline.getSong().patterns[0].notes.size() << " notes\n";
  37194. }
  37195. counts << "piano roll docked: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  37196. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() == detail ? 1 : 0) << "\n";
  37197. detail->setClipTab (true); // slice 3: the pattern's events in the Envelopes tab
  37198. offline.dispatchPendingMessages();
  37199. write ("envelopes");
  37200. detail->setClipTab (false);
  37201. detail->setPage (lynx::DetailView::Page::devices);
  37202. // round 183c-card: an Audio Effect Rack in the chain draws as its own card (the rack's view, Rand / Map in its
  37203. // title bar), as Live's Device View shows a rack
  37204. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.insert (s.mixer[2].effects.begin() + 1, shotRack()); }, false);
  37205. offline.dispatchPendingMessages();
  37206. detail->showSelection (2, 0);
  37207. detail->showSelection (1, 0);
  37208. write ("devices-rack");
  37209. counts << "rack card: cards " << detail->cardCountForCheck() << "\n";
  37210. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.erase (s.mixer[2].effects.begin() + 1); }, false);
  37211. offline.dispatchPendingMessages();
  37212. counts << "piano roll back in its panel: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  37213. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() != detail ? 1 : 0) << "\n";
  37214. }
  37215. else
  37216. counts << "no detail view\n";
  37217. ui.setClipLaunchWorkflow (false);
  37218. offline.dispatchPendingMessages();
  37219. write ("pattern-after");
  37220. juce::File (prefix + "-counts.txt").replaceWithText (counts);
  37221. }
  37222. void runPerfShot (const juce::String& prefix, const juce::String& projectPath)
  37223. {
  37224. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37225. lynx::AudioEngine offline (false);
  37226. {
  37227. lynx::MainComponent ui (offline, false);
  37228. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  37229. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  37230. if (projectPath.isNotEmpty())
  37231. ui.openFile (juce::File (projectPath));
  37232. offline.dispatchPendingMessages();
  37233. // LYNX_PERFSHOT_PREPARE=1: Tools › Macros › Prepare for performance mode first (16 one-bar columns)
  37234. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PERFSHOT_PREPARE", {}) == "1")
  37235. offline.editSong ([] (lynx::Song& s) { lynx::perf::prepareForPerformance (s, 16, 4 * lynx::ppq); }, false);
  37236. offline.editSong ([] (lynx::Song& s) { s.performanceMode = true; s.mode = lynx::PlayMode::song; }, false);
  37237. offline.dispatchPendingMessages();
  37238. // what the Player would publish: on each of the first tracks with zone clips, one clip playing (part way)
  37239. // and on every other one the next clip waiting for its sync point
  37240. const auto& song = offline.getSong();
  37241. auto& live = offline.performanceStateForSnapshot();
  37242. const auto zone = lynx::perf::zoneClips (song);
  37243. int lastTrack = -1, launched = 0;
  37244. for (const auto index : zone)
  37245. {
  37246. const auto& c = song.playlist[(std::size_t) index];
  37247. if (c.track == lastTrack || c.track >= lynx::perf::maxTracks)
  37248. continue;
  37249. lastTrack = c.track;
  37250. std::int64_t clips[64];
  37251. const auto n = lynx::perf::trackZoneClips (song, zone, c.track, clips, 64);
  37252. auto& view = live.tracks[(std::size_t) c.track];
  37253. view.playing.store (clips[(std::size_t) ((launched % 3) % n)]);
  37254. view.progress.store (0.2f + 0.15f * (float) (launched % 5));
  37255. if (launched % 2 == 1 && n > 1)
  37256. view.pending.store (clips[(std::size_t) ((launched % 3 + 1) % n)]);
  37257. ++launched;
  37258. }
  37259. live.anyPlaying.store (launched > 0);
  37260. ui.selectTabForSnapshot (2);
  37261. offline.dispatchPendingMessages();
  37262. auto& playlist = ui.getPlaylistForSnapshot();
  37263. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-song.png");
  37264. playlist.runAction ("playlist.zoomPerformance"); // as FL opens these demos: the zone fills the view
  37265. offline.dispatchPendingMessages();
  37266. saveSnapshot (ui, prefix + "-playlist.png");
  37267. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-only.png");
  37268. // patcherize: the first insert with effects (all of them) and the first channel that can be
  37269. auto patched = offline.getSong();
  37270. for (int t = 0; t < (int) patched.mixer.size(); ++t)
  37271. if (lynx::patcherize::slotsForAll (patched, t).size() > 1)
  37272. {
  37273. lynx::patcherize::patcherizeSlots (patched, t, 0, true);
  37274. break;
  37275. }
  37276. for (int c = 0; c < (int) patched.channels.size(); ++c)
  37277. if (lynx::patcherize::patcherizeChannel (patched, c))
  37278. break;
  37279. juce::String error;
  37280. lynx::ProjectFile::save (patched, juce::File (prefix + "-patcherized.lynx"), error);
  37281. }
  37282. }
  37283. void runPatcherShot (const juce::String& prefix, const juce::String& projectPath)
  37284. {
  37285. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37286. lynx::AudioEngine offline (false);
  37287. {
  37288. lynx::MainComponent ui (offline, false);
  37289. ui.setSize (1280, 720);
  37290. if (projectPath.isNotEmpty())
  37291. ui.openFile (juce::File (projectPath));
  37292. else
  37293. {
  37294. auto song = lynx::Song::makeDefault();
  37295. song.mixer.resize (4);
  37296. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  37297. slot.patcher.wires.clear();
  37298. for (auto [kind, x, y] : { std::tuple { lynx::EffectKind::frequencySplitter, 200.0f, 60.0f }, { lynx::EffectKind::reverb, 420.0f, 0.0f },
  37299. { lynx::EffectKind::fruityDelay3, 420.0f, 120.0f }, { lynx::EffectKind::peakController, 200.0f, 260.0f } })
  37300. {
  37301. lynx::PatchNode n;
  37302. n.effect = lynx::makeEffectSlot (kind);
  37303. n.x = x;
  37304. n.y = y;
  37305. slot.patcher.nodes.push_back (n);
  37306. }
  37307. { // round 165c: a Hardware Insert node (its editor opens from the node)
  37308. lynx::PatchNode n;
  37309. n.effect = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  37310. n.x = 420.0f, n.y = 260.0f;
  37311. slot.patcher.nodes.push_back (n);
  37312. }
  37313. auto wire = [&] (int from, int fromPort, int to, int toPort, float gain = 1.0f, lynx::PatchWire::Kind kind = lynx::PatchWire::Kind::audio) {
  37314. lynx::PatchWire w;
  37315. w.kind = kind;
  37316. w.from = from, w.fromPort = fromPort, w.to = to, w.toPort = toPort, w.gain = gain;
  37317. slot.patcher.wires.push_back (w);
  37318. };
  37319. wire (lynx::patchFromHost, 0, 0, 0);
  37320. wire (0, 1, 1, 0);
  37321. wire (0, 3, 2, 0, 0.5f);
  37322. wire (1, 0, lynx::patchToHost, 0);
  37323. wire (2, 0, lynx::patchToHost, 0);
  37324. wire (lynx::patchFromHost, 1, 3, 0);
  37325. wire (3, 1, 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  37326. wire (0, 2, lynx::patchToHost, 1, 0.7f);
  37327. // round 171b (issue #65): a Surface knob on the reverb's parameter input 1, the reverb's parameter 0 out to
  37328. // the delay's parameter input 2 (FL's Inputs / Outputs › Parameters)
  37329. {
  37330. lynx::SurfaceControl knob;
  37331. knob.name = "Knob 1";
  37332. knob.value = 0.6f;
  37333. slot.patcher.surface = { knob };
  37334. slot.patcher.surfaceX = 200.0f, slot.patcher.surfaceY = 380.0f;
  37335. lynx::patcher::setParamInput (slot.patcher, 1, 1, true, "Reverb - 2");
  37336. lynx::patcher::setParamOutput (slot.patcher, 1, 0, true);
  37337. lynx::patcher::setParamInput (slot.patcher, 2, 2, true, "Delay - 3");
  37338. wire (lynx::patchSurface, 0, 1, 1, 1.0f, lynx::PatchWire::Kind::control);
  37339. wire (1, lynx::patchParamOutput (0), 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  37340. }
  37341. slot.patcher.outputTracks = { 3 };
  37342. slot.patcher.inputX = -20.0f;
  37343. slot.patcher.outputX = 660.0f;
  37344. song.mixer[1].effects = { slot };
  37345. lynx::ChannelDef ch;
  37346. ch.name = "Patcher";
  37347. ch.instrument = lynx::InstrumentKind::patcher;
  37348. lynx::PatchNode synth, chorus;
  37349. synth.generator = true;
  37350. synth.channel.instrument = lynx::InstrumentKind::synth;
  37351. synth.channel.name = "Synth";
  37352. synth.x = 220.0f;
  37353. chorus.effect = lynx::makeEffectSlot (lynx::EffectKind::chorus);
  37354. chorus.x = 420.0f;
  37355. // round 162: a MIDI Out node between the "MIDI port 5" pin and "To LYNX" MIDI port 3, an Envelope Controller
  37356. // on the notes moving the chorus
  37357. lynx::PatchNode midiOut, envelope;
  37358. midiOut.generator = envelope.generator = true;
  37359. midiOut.channel.instrument = lynx::InstrumentKind::midiOut;
  37360. midiOut.channel.name = "MIDI Out";
  37361. lynx::midictl::writeMidiOut (midiOut.channel.pluginState, { 3, 0, 0, -1, -1 });
  37362. midiOut.x = 220.0f, midiOut.y = 160.0f;
  37363. envelope.channel.instrument = lynx::InstrumentKind::controller;
  37364. envelope.channel.name = "Envelope Controller";
  37365. envelope.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  37366. envelope.x = 220.0f, envelope.y = 260.0f;
  37367. lynx::PatchNode osc; // round 164f: an FL engine node (its editor opens from the node)
  37368. osc.generator = true;
  37369. osc.channel = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  37370. osc.channel.instrument = lynx::InstrumentKind::threeosc;
  37371. osc.channel.name = "3x Osc";
  37372. osc.x = 420.0f, osc.y = 260.0f;
  37373. // round 165c: Keyboard Controller, SoundFont player, Granulizer and Dashboard nodes (their editors open from the node)
  37374. lynx::PatchNode keys, soundfont, granulizer, dashboard;
  37375. keys.generator = soundfont.generator = granulizer.generator = dashboard.generator = true;
  37376. keys.channel.instrument = lynx::InstrumentKind::controller;
  37377. keys.channel.name = "Keyboard Controller";
  37378. {
  37379. lynx::KeyboardControllerData ramp;
  37380. for (std::size_t k = 0; k < ramp.keys.size(); ++k)
  37381. ramp.keys[k] = (float) k / (float) (ramp.keys.size() - 1);
  37382. lynx::writeKeyboardController (ramp, keys.channel.controllerState);
  37383. }
  37384. soundfont.channel = lynx::sf::makeChannel();
  37385. granulizer.channel = lynx::natives::makeChannel (lynx::InstrumentKind::granulizer, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  37386. granulizer.channel.instrument = lynx::InstrumentKind::granulizer;
  37387. granulizer.channel.name = "Fruity Granulizer";
  37388. dashboard.channel.instrument = lynx::InstrumentKind::dashboard;
  37389. dashboard.channel.name = "Dashboard";
  37390. dashboard.channel.patcher.surface = lynx::surface::starterControls();
  37391. keys.x = 20.0f, keys.y = 440.0f;
  37392. soundfont.x = 220.0f, soundfont.y = 440.0f;
  37393. granulizer.x = 420.0f, granulizer.y = 440.0f;
  37394. dashboard.x = 20.0f, dashboard.y = 540.0f;
  37395. // and a Layer node playing the SoundFont and Granulizer nodes on its Children pin (crossfaded)
  37396. lynx::PatchNode layerNode;
  37397. layerNode.generator = true;
  37398. layerNode.channel.instrument = lynx::InstrumentKind::layer;
  37399. layerNode.channel.name = "Layer";
  37400. layerNode.channel.layer.crossfade = true;
  37401. layerNode.channel.layer.fade = 0.35f;
  37402. layerNode.x = 220.0f, layerNode.y = 540.0f;
  37403. ch.patcher.nodes = { synth, chorus, midiOut, envelope, osc, keys, soundfont, granulizer, dashboard, layerNode };
  37404. lynx::PatchWire notes, a, b, portIn, portOut, envNotes, envControl;
  37405. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  37406. a.from = 0, a.to = 1;
  37407. b.from = 1;
  37408. portIn.kind = lynx::PatchWire::Kind::midi, portIn.fromPort = lynx::patchMidiPortPin (5), portIn.to = 2;
  37409. portOut.kind = lynx::PatchWire::Kind::midi, portOut.from = 2, portOut.to = lynx::patchToHost, portOut.toPort = 3;
  37410. envNotes.kind = lynx::PatchWire::Kind::midi, envNotes.to = 3;
  37411. envControl.kind = lynx::PatchWire::Kind::control, envControl.from = 3, envControl.to = 1, envControl.toPort = 0;
  37412. lynx::PatchWire oscNotes, oscOut;
  37413. oscNotes.kind = lynx::PatchWire::Kind::midi, oscNotes.to = 4;
  37414. oscOut.from = 4;
  37415. lynx::PatchWire layerNotes, layerToFont, layerToGrains, fontOut, grainsOut;
  37416. layerNotes.kind = layerToFont.kind = layerToGrains.kind = lynx::PatchWire::Kind::midi;
  37417. layerNotes.to = 9;
  37418. layerToFont.from = 9, layerToFont.to = 6;
  37419. layerToGrains.from = 9, layerToGrains.to = 7;
  37420. fontOut.from = 6;
  37421. grainsOut.from = 7;
  37422. ch.patcher.wires = { notes, a, b, portIn, portOut, envNotes, envControl, oscNotes, oscOut, layerNotes, layerToFont, layerToGrains, fontOut, grainsOut };
  37423. ch.patcher.fromMidiPorts = { 1, 5 };
  37424. ch.patcher.toMidiPorts = { 3 };
  37425. ch.patcher.outputX = 640.0f;
  37426. song.channels.push_back (ch);
  37427. // LYNX_PATCHERSHOT_SAVE=file.lynx: the demo as a project (a GUI check of the same Patchers, round 164f)
  37428. if (const auto save = juce::SystemStats::getEnvironmentVariable ("LYNX_PATCHERSHOT_SAVE", {}); save.isNotEmpty())
  37429. {
  37430. if (! song.patterns.empty())
  37431. for (int k = 0; k < 4; ++k)
  37432. song.patterns[0].notes.push_back ({ (std::int64_t) k * lynx::ppq, lynx::ppq / 2, (int) song.channels.size() - 1, 60 + 4 * k, 0.8f });
  37433. juce::String error;
  37434. lynx::ProjectFile::save (song, juce::File (save), error);
  37435. // round 171b: the saved Patchers come back the same (parameter ports, event cables, published)
  37436. juce::String report;
  37437. if (const auto loaded = lynx::ProjectFile::load (juce::File (save), error))
  37438. {
  37439. const auto same = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  37440. && loaded->mixer[1].effects[0].patcher == song.mixer[1].effects[0].patcher;
  37441. const auto& d = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty() ? loaded->mixer[1].effects[0].patcher : lynx::PatcherDoc {};
  37442. report << "patcher round trip: " << (same ? "OK" : "DIFFERENT") << "\n";
  37443. if (! same && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty())
  37444. {
  37445. const auto& a = song.mixer[1].effects[0].patcher;
  37446. report << "wires " << (a.wires == d.wires ? "same" : "differ") << ", published " << (a.published == d.published ? "same" : "differ")
  37447. << ", surface " << (a.surface == d.surface ? "same" : "differ") << "\n";
  37448. for (std::size_t n = 0; n < std::min (a.nodes.size(), d.nodes.size()); ++n)
  37449. if (! (a.nodes[n] == d.nodes[n]))
  37450. report << "node " << (int) n << " differs: ports " << (a.nodes[n].paramIns == d.nodes[n].paramIns && a.nodes[n].paramOuts == d.nodes[n].paramOuts ? "same" : "differ")
  37451. << ", effect " << (a.nodes[n].effect == d.nodes[n].effect ? "same" : "differ") << ", xy "
  37452. << (a.nodes[n].x == d.nodes[n].x && a.nodes[n].y == d.nodes[n].y ? "same" : "differ") << "\n";
  37453. }
  37454. for (int n = 0; n < (int) d.nodes.size(); ++n)
  37455. report << "node " << n << " paramIns " << (int) d.nodes[(std::size_t) n].paramIns.size() << " paramOuts "
  37456. << (int) d.nodes[(std::size_t) n].paramOuts.size() << "\n";
  37457. for (const auto& w : d.wires)
  37458. if (w.kind == lynx::PatchWire::Kind::control)
  37459. report << "control " << w.from << ":" << w.fromPort << " -> " << w.to << ":" << w.toPort << "\n";
  37460. for (const auto& p : d.published)
  37461. report << "published " << p.node << ":" << p.param << " " << juce::String::fromUTF8 (p.name.c_str()) << "\n";
  37462. }
  37463. else
  37464. report << "patcher round trip: load failed: " << error << "\n";
  37465. juce::File (prefix + "-roundtrip.txt").replaceWithText (report);
  37466. }
  37467. offline.setSong (std::move (song));
  37468. }
  37469. offline.dispatchPendingMessages();
  37470. const auto& song = offline.getSong();
  37471. auto shootOpen = [&] (const juce::String& name) {
  37472. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  37473. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  37474. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  37475. {
  37476. auto* c = w->getContentComponent();
  37477. savePng (lynx::shot::snapshot (*c), prefix + name);
  37478. delete w;
  37479. return;
  37480. }
  37481. };
  37482. int shots = 0;
  37483. for (int t = 0; t < (int) song.mixer.size() && shots < 12; ++t)
  37484. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  37485. if (song.mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::patcher)
  37486. {
  37487. lynx::PatcherWindows::openSlot (offline, t, s);
  37488. shootOpen ("-insert" + juce::String (t) + "-slot" + juce::String (s) + ".png");
  37489. // each built-in node's editor, as a double-click opens it (round 165c)
  37490. lynx::PatcherWindows::shootNodeEditors (offline, false, t, s, [&] (const juce::Image& image, int n) {
  37491. savePng (image, prefix + "-insert" + juce::String (t) + "-slot" + juce::String (s) + "-node" + juce::String (n) + ".png");
  37492. });
  37493. ++shots;
  37494. if (shots == 1) // its menus (round 162)
  37495. lynx::PatcherWindows::shootMenus (offline, false, t, s, [&] (const juce::Image& image, const juce::String& name) {
  37496. savePng (image, prefix + "-menu-" + name + ".png");
  37497. });
  37498. }
  37499. for (int c = 0; c < (int) song.channels.size(); ++c)
  37500. if (song.channels[(std::size_t) c].instrument == lynx::InstrumentKind::patcher)
  37501. {
  37502. lynx::PatcherWindows::openChannel (offline, c);
  37503. shootOpen ("-channel" + juce::String (c) + ".png");
  37504. // each node's editor, as a double-click opens it (round 164f; every built-in node since round 165c)
  37505. lynx::PatcherWindows::shootNodeEditors (offline, true, c, 0, [&] (const juce::Image& image, int n) {
  37506. savePng (image, prefix + "-channel" + juce::String (c) + "-node" + juce::String (n) + ".png");
  37507. });
  37508. lynx::PatcherWindows::shootMenus (offline, true, c, 0, [&] (const juce::Image& image, const juce::String& name) {
  37509. savePng (image, prefix + "-channel" + juce::String (c) + "-menu-" + name + ".png");
  37510. });
  37511. }
  37512. }
  37513. }
  37514. // Issue #64: FL's letter keys in a plugin menu (quickpick::showMenu), checked on the real menu windows
  37515. struct TypeAheadTest final : private juce::Timer
  37516. {
  37517. juce::File out;
  37518. juce::StringArray log;
  37519. int step = 0, picked = 0;
  37520. bool ok = true, menuShown = false;
  37521. std::unique_ptr<juce::DocumentWindow> owner;
  37522. juce::PopupMenu pending;
  37523. static juce::String highlighted()
  37524. {
  37525. if (auto* window = juce::Component::getCurrentlyModalComponent())
  37526. for (auto* child : window->getChildren())
  37527. if (auto* h = child->getAccessibilityHandler(); h != nullptr && h->hasFocus (false))
  37528. return h->getTitle();
  37529. return "(none)";
  37530. }
  37531. static void press (const juce::KeyPress& key)
  37532. {
  37533. if (auto* window = juce::Component::getCurrentlyModalComponent())
  37534. if (auto* peer = window->getPeer())
  37535. peer->handleKeyPress (key);
  37536. }
  37537. void expect (const juce::String& what, const juce::String& got, const juce::String& wanted)
  37538. {
  37539. const auto good = got == wanted;
  37540. ok = ok && good;
  37541. log.add ((good ? "ok " : "FAIL ") + what + ": " + got + (good ? juce::String() : " (wanted " + wanted + ")"));
  37542. }
  37543. void start()
  37544. {
  37545. juce::PopupMenu menu, sub;
  37546. auto item = [this] (juce::PopupMenu& m, int id, const char* text, bool enabled = true) {
  37547. m.addItem (text, enabled, false, [this, id] { picked = id; });
  37548. };
  37549. menu.addSectionHeader ("LYNX SHARE");
  37550. item (menu, 1, "Echoform");
  37551. item (menu, 2, "EQ");
  37552. item (menu, 3, "Halo");
  37553. menu.addSectionHeader ("Misc");
  37554. item (menu, 4, "Effector");
  37555. item (menu, 5, "Exciter (unavailable)", false);
  37556. item (sub, 10, "Delay");
  37557. item (sub, 11, "Edison");
  37558. item (sub, 12, "Eventide");
  37559. menu.addSubMenu ("Tree", sub);
  37560. // the menu belongs to a window in the foreground, as when the user right-clicks a mixer slot (JUCE closes a
  37561. // menu of a background process at once)
  37562. owner = std::make_unique<juce::DocumentWindow> ("LYNX type-ahead test", juce::Colours::black, 0);
  37563. owner->setBounds (200, 200, 300, 200);
  37564. owner->setVisible (true);
  37565. lynx::forceForegroundForTest (*owner);
  37566. pending = menu; // shown once the window is up and active (X11 maps and activates it asynchronously)
  37567. startTimer (300);
  37568. }
  37569. void timerCallback() override
  37570. {
  37571. const auto e = juce::KeyPress ('e', {}, 'e');
  37572. if (step == 0 && owner != nullptr && ! menuShown)
  37573. {
  37574. menuShown = true;
  37575. lynx::forceForegroundForTest (*owner);
  37576. lynx::quickpick::showMenu (pending, juce::PopupMenu::Options().withTargetComponent (owner.get()), {});
  37577. return;
  37578. }
  37579. switch (step++)
  37580. {
  37581. case 0: expect ("menu open", juce::String ((int) (juce::Component::getCurrentlyModalComponent() != nullptr)), "1"); break;
  37582. case 1: press (e); expect ("e", highlighted(), "Echoform"); break;
  37583. case 2: press (e); expect ("e again", highlighted(), "EQ"); break;
  37584. case 3: press (juce::KeyPress ('E', juce::ModifierKeys::shiftModifier, 'E')); expect ("E (shift)", highlighted(), "Effector"); break;
  37585. case 4: press (e); expect ("e wraps (skips the disabled one)", highlighted(), "Echoform"); break;
  37586. case 5: press (juce::KeyPress ('m', {}, 'm')); expect ("m (only a heading starts with it: no move)", highlighted(), "Echoform"); break;
  37587. case 6: press (juce::KeyPress (juce::KeyPress::downKey)); expect ("down arrow", highlighted(), "EQ"); break;
  37588. case 7: press (e); expect ("e after the arrow", highlighted(), "Effector"); break;
  37589. case 8: press (juce::KeyPress ('t', {}, 't')); expect ("t", highlighted(), "Tree"); break;
  37590. case 9: press (juce::KeyPress (juce::KeyPress::rightKey)); break; // opens the submenu (it takes the keys)
  37591. case 10: press (e); expect ("e in the submenu", highlighted(), "Edison"); break;
  37592. case 11: press (e); expect ("e again in the submenu", highlighted(), "Eventide"); break;
  37593. case 12: expect ("nothing picked by the letters", juce::String (picked), "0"); press (juce::KeyPress (juce::KeyPress::returnKey)); break;
  37594. case 13: break;
  37595. default:
  37596. expect ("Enter closed the menu", juce::String ((int) (juce::Component::getCurrentlyModalComponent() == nullptr)), "1");
  37597. expect ("Enter picked", juce::String (picked), "12");
  37598. stopTimer();
  37599. owner.reset();
  37600. log.add (ok ? "result=OK" : "result=FAIL");
  37601. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  37602. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  37603. juce::JUCEApplication::quit();
  37604. return;
  37605. }
  37606. }
  37607. };
  37608. std::unique_ptr<TypeAheadTest> typeAheadTest;
  37609. struct ChooserTest final : private juce::Timer
  37610. {
  37611. juce::File out, file;
  37612. juce::StringArray log;
  37613. std::unique_ptr<juce::FileChooser> chooser;
  37614. double started = 0;
  37615. bool shot = false, done = false;
  37616. void start()
  37617. {
  37618. log.add ("LYNX_FILE_DIALOG=" + juce::SystemStats::getEnvironmentVariable ("LYNX_FILE_DIALOG", {}));
  37619. log.add ("native=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  37620. chooser = lynx::ui::makeFileChooser ("Open audio file", file.getParentDirectory(), "*.wav;*.flac");
  37621. started = juce::Time::getMillisecondCounterHiRes();
  37622. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  37623. [this] (const juce::FileChooser& fc) { finish (fc.getResult()); });
  37624. startTimer (200);
  37625. }
  37626. static juce::FileChooserDialogBox* builtInDialog()
  37627. {
  37628. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i)
  37629. if (auto* box = dynamic_cast<juce::FileChooserDialogBox*> (juce::Desktop::getInstance().getComponent (i)); box != nullptr && box->isShowing())
  37630. return box;
  37631. return nullptr;
  37632. }
  37633. static juce::FileBrowserComponent* findBrowser (juce::Component& c)
  37634. {
  37635. if (auto* b = dynamic_cast<juce::FileBrowserComponent*> (&c))
  37636. return b;
  37637. for (auto* child : c.getChildren())
  37638. if (auto* b = findBrowser (*child))
  37639. return b;
  37640. return nullptr;
  37641. }
  37642. void timerCallback() override
  37643. {
  37644. if (done)
  37645. return;
  37646. if (auto* box = builtInDialog(); box != nullptr && ! shot)
  37647. {
  37648. shot = true;
  37649. log.add ("built-in dialog shown after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms");
  37650. const auto image = lynx::shot::snapshot (*box);
  37651. juce::FileOutputStream png (out.getSiblingFile (out.getFileName() + ".png"));
  37652. if (png.openedOk())
  37653. {
  37654. png.setPosition (0), png.truncate();
  37655. juce::PNGImageFormat().writeImageToStream (image, png);
  37656. }
  37657. if (auto* browser = findBrowser (*box))
  37658. {
  37659. browser->setRoot (file.getParentDirectory());
  37660. browser->setFileName (file.getFileName());
  37661. log.add ("typed " + file.getFileName());
  37662. box->exitModalState (1);
  37663. }
  37664. else
  37665. log.add ("no file browser in the dialog");
  37666. }
  37667. if (juce::Time::getMillisecondCounterHiRes() - started > 30000.0)
  37668. finish ({}, "timeout");
  37669. }
  37670. void finish (const juce::File& result, const juce::String& why = {})
  37671. {
  37672. if (done)
  37673. return;
  37674. done = true;
  37675. stopTimer();
  37676. log.add ("callback after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms: "
  37677. + (why.isNotEmpty() ? why : result.getFullPathName().isEmpty() ? juce::String ("(no file)") : result.getFullPathName()));
  37678. log.add ("native now=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  37679. const auto ok = result == file && result.existsAsFile();
  37680. log.add (ok ? "result=OK" : "result=FAIL");
  37681. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  37682. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  37683. juce::MessageManager::callAsync ([] { juce::JUCEApplication::quit(); });
  37684. }
  37685. };
  37686. std::unique_ptr<ChooserTest> chooserTest;
  37687. void runChooserTest (const juce::File& out, const juce::File& file)
  37688. {
  37689. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37690. chooserTest = std::make_unique<ChooserTest>();
  37691. chooserTest->out = out;
  37692. chooserTest->file = file;
  37693. chooserTest->start();
  37694. }
  37695. void runTypeAheadTest (const juce::File& out)
  37696. {
  37697. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37698. typeAheadTest = std::make_unique<TypeAheadTest>();
  37699. typeAheadTest->out = out;
  37700. typeAheadTest->start();
  37701. }
  37702. void runStabilityShot (const juce::String& folder)
  37703. {
  37704. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37705. const juce::File dir (folder);
  37706. dir.createDirectory();
  37707. {
  37708. lynx::AudioEngine offline (false);
  37709. const auto save = [&dir] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  37710. juce::Component frame;
  37711. frame.setSize (c->getWidth(), c->getHeight());
  37712. frame.setOpaque (true);
  37713. if (c->isOnDesktop()) // (an AlertWindow: never shown, so it takes no foreground)
  37714. c->removeFromDesktop();
  37715. frame.addAndMakeVisible (*c);
  37716. c->setTopLeftPosition (0, 0);
  37717. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  37718. const auto file = dir.getChildFile (name);
  37719. file.deleteFile();
  37720. juce::PNGImageFormat png;
  37721. if (auto out = file.createOutputStream())
  37722. png.writeImageToStream (image, *out);
  37723. };
  37724. save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "crash-prompt.png");
  37725. save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", true), "crash-prompt-onload.png");
  37726. save (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "crash-notice.png");
  37727. save (lynx::makePluginManagerPanel (offline, false), "plugin-manager.png");
  37728. save (lynx::makePluginMonitorPanel (offline), "plugin-monitor.png");
  37729. }
  37730. setApplicationReturnValue (0);
  37731. quit();
  37732. }
  37733. void runDetails190ihShot (const juce::String& prefix)
  37734. {
  37735. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37736. juce::String report;
  37737. auto line = [&report] (const juce::String& t) { report << t << "\n"; };
  37738. {
  37739. // R2: Gross Beat on Insert 1 — the first time slot and a half-beat volume gate, as in FL's capture ("Empty",
  37740. // "1/2 Bt Gate")
  37741. lynx::AudioEngine offline (false);
  37742. lynx::Song song;
  37743. song.mixer = lynx::Song::defaultMixer (2);
  37744. song.bpm = 150.0;
  37745. auto gb = lynx::makeEffectSlot (lynx::EffectKind::grossBeat);
  37746. const auto names = lynx::grossbeat::slotNames (gb.state, true);
  37747. int gate = 0;
  37748. for (int k = 0; k < (int) names.size(); ++k)
  37749. if (names[(std::size_t) k] == "Gate 1/2 beat") // (LYNX's factory slot for FL's "1/2 Bt Gate")
  37750. gate = k;
  37751. gb.params[0] = lynx::grossbeat::paramFromRaw (0, 0);
  37752. gb.params[1] = lynx::grossbeat::paramFromRaw (1, gate);
  37753. song.mixer[1].effects.push_back (gb);
  37754. offline.setSong (std::move (song));
  37755. offline.dispatchPendingMessages();
  37756. // the real effect played to beat 2.9 of its bar: its published outputs go where the rack writes them
  37757. auto run = lynx::makeEffect (gb);
  37758. run->prepare (48000.0);
  37759. const auto tps = 150.0 / 60.0 * lynx::ppq / 48000.0;
  37760. std::vector<float> l (480, 0.3f), r (480, 0.3f);
  37761. std::size_t done = 0;
  37762. auto block = [&] (lynx::EffectParams& params) {
  37763. run->setSongPosition ((double) done * tps);
  37764. run->process (l.data(), r.data(), 480, params, 150.0);
  37765. done += 480;
  37766. };
  37767. auto publish = [&] (bool playing) {
  37768. const auto key = (std::size_t) (1 * lynx::maxEffectSlots + 0) * lynx::ProcessTimes::meterOutputs;
  37769. if (auto* times = offline.getProcessTimes())
  37770. for (int k = 0; k < lynx::ProcessTimes::meterOutputs; ++k)
  37771. times->effectMeters[key + (std::size_t) k].store (run->controlOutput (k), std::memory_order_relaxed);
  37772. else
  37773. line ("no process times: the editor shows nothing live");
  37774. offline.getTransport().playing.store (playing);
  37775. juce::String values;
  37776. for (int k = 0; k < 7; ++k)
  37777. values << " " << juce::String (run->controlOutput (k), 3);
  37778. line ("gross beat outputs:" + values);
  37779. };
  37780. while ((double) done * tps / lynx::ppq < 2.9)
  37781. block (gb.params);
  37782. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f);
  37783. editor->setSize (editor->getWidth(), editor->getHeight());
  37784. for (const int view : { 1, 0 })
  37785. {
  37786. lynx::showGrossBeatEnvelopeForSnapshot (*editor, view);
  37787. publish (true);
  37788. lynx::tickNativeEffectEditor (*editor);
  37789. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-playing-" + (view == 1 ? "volume" : "time") + ".png");
  37790. }
  37791. lynx::ui::motion::enabled() = false;
  37792. lynx::tickNativeEffectEditor (*editor);
  37793. editor->repaint();
  37794. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-playing-noanim.png");
  37795. lynx::ui::motion::enabled() = true;
  37796. // a click on another time slot: queued until the next 4 beats
  37797. auto queued = gb.params;
  37798. queued[0] = lynx::grossbeat::paramFromRaw (0, 5);
  37799. block (queued);
  37800. publish (true);
  37801. lynx::tickNativeEffectEditor (*editor);
  37802. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-queued.png");
  37803. publish (false); // stopped: no locator, no fill
  37804. lynx::tickNativeEffectEditor (*editor);
  37805. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-stopped.png");
  37806. // round 190jd (live check 190iw Q7): the locator in FL's colours (the editor's Options menu) on the beat (cream,
  37807. // 3 px trail), a third into it (orange) and near its end (dusty red); LYNX's playhead colour stays the default
  37808. lynx::gblocator::setFlStyle (true);
  37809. lynx::showGrossBeatEnvelopeForSnapshot (*editor, 1);
  37810. for (const auto at : { 4.02, 4.35, 4.9 })
  37811. {
  37812. while ((double) done * tps / lynx::ppq < at)
  37813. block (queued);
  37814. publish (true);
  37815. juce::Thread::sleep (60); // (the editor's frame budget: ~21 frames a second in this style)
  37816. lynx::tickNativeEffectEditor (*editor);
  37817. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-fl-colours-" + juce::String (at - 4.0, 2) + ".png");
  37818. }
  37819. lynx::gblocator::setFlStyle (false);
  37820. offline.getTransport().playing.store (false);
  37821. }
  37822. {
  37823. // R7: the Envelope Controller's Keyboard / Velocity mapping pages after a note (key 64, velocity 0.8)
  37824. lynx::AudioEngine offline (false);
  37825. lynx::Song song;
  37826. lynx::ChannelDef env;
  37827. env.name = "Envelope Controller";
  37828. env.instrument = lynx::InstrumentKind::controller;
  37829. auto ec = lynx::defaultEnvelopeController();
  37830. ec[0].maps[lynx::mapKeyboard].count = 2;
  37831. ec[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  37832. ec[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  37833. ec[0].maps[lynx::mapVelocity] = ec[0].maps[lynx::mapKeyboard];
  37834. env.controllerState = lynx::writeEnvelopeController (ec);
  37835. song.channels.push_back (env);
  37836. song.patterns.emplace_back();
  37837. offline.setSong (std::move (song));
  37838. offline.dispatchPendingMessages();
  37839. auto editor = lynx::makeEnvelopeControllerEditor (
  37840. offline, [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; }, 0,
  37841. [] (int k) { return k == 8 ? 64.0f : k == 9 ? 0.8f : 0.5f; });
  37842. for (const int part : { 2, 3 })
  37843. {
  37844. for (auto* child : editor->getChildren())
  37845. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  37846. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  37847. savePng (lynx::shot::snapshot (*editor), prefix + "-r7-ec-" + (part == 2 ? "keyboard" : "velocity") + "-line.png");
  37848. }
  37849. }
  37850. {
  37851. lynx::AudioEngine offline (false);
  37852. lynx::MainComponent ui (offline, false);
  37853. ui.setSize (1920, 1080);
  37854. lynx::Song song;
  37855. song.mixer = lynx::Song::defaultMixer (4);
  37856. for (const auto* name : { "Grv Kick 27", "Snare", "Hat", "Bass (locked)" })
  37857. {
  37858. lynx::ChannelDef c;
  37859. c.name = name;
  37860. c.instrument = lynx::InstrumentKind::sampler;
  37861. song.channels.push_back (c);
  37862. }
  37863. song.channels[3].receiveFrom = "MIDI keyboard";
  37864. song.patterns.emplace_back();
  37865. offline.setSong (std::move (song));
  37866. offline.dispatchPendingMessages();
  37867. ui.showDesktopForSnapshot (false);
  37868. offline.dispatchPendingMessages();
  37869. // R4: the rack's activity light — before, at note-on, held, after the release; a locked channel lit (orange)
  37870. auto& rack = ui.getRackForSnapshot();
  37871. const std::pair<const char*, float> states[] { { "before", 0.0f }, { "noteon", 1.0f }, { "held", lynx::activity::held }, { "after", 0.0f } };
  37872. for (const auto& [name, level] : states)
  37873. {
  37874. rack.setActivityForSnapshot (0, level);
  37875. rack.setActivityForSnapshot (3, level);
  37876. savePng (lynx::shot::snapshot (rack), prefix + "-r4-rack-" + name + ".png");
  37877. }
  37878. rack.setActivityForSnapshot (0, 0.0f);
  37879. rack.setActivityForSnapshot (3, 0.0f);
  37880. // R3: the transport stopped, playing, recording (both blink phases), armed and stopped; the hint bar
  37881. const auto toolbar = ui.getToolbarBoundsForSnapshot();
  37882. auto& transport = offline.getTransport();
  37883. ui.transportForSnapshot (false, true);
  37884. saveArea (ui, toolbar, prefix + "-r3-toolbar-stopped.png");
  37885. transport.playing.store (true);
  37886. ui.transportForSnapshot (true, true);
  37887. saveArea (ui, toolbar, prefix + "-r3-toolbar-playing.png");
  37888. transport.recording.store (true);
  37889. ui.transportForSnapshot (true, true);
  37890. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-lit.png");
  37891. ui.transportForSnapshot (true, false);
  37892. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-dark.png");
  37893. lynx::ui::motion::enabled() = false;
  37894. ui.transportForSnapshot (true, false);
  37895. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-noanim.png");
  37896. lynx::ui::motion::enabled() = true;
  37897. transport.playing.store (false);
  37898. ui.transportForSnapshot (false, false);
  37899. saveArea (ui, toolbar, prefix + "-r3-toolbar-armed-stopped.png");
  37900. transport.recording.store (false);
  37901. ui.transportForSnapshot (false, true);
  37902. for (const bool on : { true, false })
  37903. {
  37904. offline.markLiveNote (60, 100, on);
  37905. const auto hint = ui.liveNoteHintForSnapshot();
  37906. line ("hint: " + hint);
  37907. ui.setHintForSnapshot ({ hint, {}, false, false });
  37908. saveArea (ui, toolbar, prefix + "-r3-hint-note" + (on ? "on" : "off") + ".png");
  37909. }
  37910. offline.editSong ([] (lynx::Song& s) { s.bpm = 128.0; }); // (a change: the project is modified)
  37911. offline.dispatchPendingMessages();
  37912. const auto reminder = ui.saveReminderForSnapshot();
  37913. line ("reminder: " + reminder);
  37914. ui.setHintForSnapshot ({ reminder, {}, false, false });
  37915. saveArea (ui, toolbar, prefix + "-r3-save-reminder.png");
  37916. // R14: the Simple dock's input level
  37917. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  37918. offline.dispatchPendingMessages();
  37919. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  37920. if (auto* dock = simple->dockForSnapshot())
  37921. {
  37922. dock->inputLevelForSnapshot (0.72f);
  37923. offline.dispatchPendingMessages();
  37924. savePng (lynx::shot::snapshot (*dock), prefix + "-r14-dock-input-level.png");
  37925. line ("dock: " + juce::String (dock->getWidth()) + "x" + juce::String (dock->getHeight()));
  37926. }
  37927. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  37928. offline.dispatchPendingMessages();
  37929. }
  37930. juce::File (prefix + "-report.txt").replaceWithText (report);
  37931. }
  37932. void runJsfxShots (const juce::String& folderPath)
  37933. {
  37934. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37935. const juce::File folder (folderPath);
  37936. folder.createDirectory();
  37937. lynx::jsfx::installPack();
  37938. juce::StringArray made;
  37939. {
  37940. lynx::AudioEngine offline (false);
  37941. lynx::JsfxPluginFormat format;
  37942. auto& known = offline.getPluginHost().getKnownPlugins();
  37943. for (const auto& f : format.searchPathsForPlugins (juce::FileSearchPath (lynx::jsfx::packFolder().getFullPathName()), true, false))
  37944. {
  37945. juce::OwnedArray<juce::PluginDescription> found;
  37946. format.findAllTypesForFile (found, f);
  37947. for (auto* d : found)
  37948. known.addType (*d);
  37949. }
  37950. // the slider panels (the plugin window's editor) of four bundled scripts
  37951. for (const auto* rel : { "chokehold/Clipper/soft_clipper.jsfx", "chokehold/Generator/test_signals.jsfx",
  37952. "chokehold/Instrument FX/mic_combiner.jsfx", "chokehold/MIDI/midi_chord_trigger.jsfx" })
  37953. {
  37954. const auto file = lynx::jsfx::packFolder().getChildFile (rel);
  37955. juce::OwnedArray<juce::PluginDescription> found;
  37956. format.findAllTypesForFile (found, file.getFullPathName());
  37957. if (found.isEmpty())
  37958. continue;
  37959. juce::String error;
  37960. auto instance = format.createInstanceFromDescription (*found[0], 48000.0, 512, error);
  37961. if (instance == nullptr)
  37962. {
  37963. made.add (juce::String (rel) + ": " + error);
  37964. continue;
  37965. }
  37966. lynx::preparePlugin (*instance, 48000.0, 512);
  37967. juce::AudioBuffer<float> buffer (2, 512);
  37968. juce::MidiBuffer midi;
  37969. for (int b = 0; b < 8; ++b)
  37970. {
  37971. buffer.clear();
  37972. instance->processBlock (buffer, midi);
  37973. }
  37974. offline.dispatchPendingMessages(); // (the latency it reported)
  37975. std::unique_ptr<juce::AudioProcessorEditor> editor (instance->createEditor());
  37976. const auto name = "jsfx-panel-" + file.getFileNameWithoutExtension() + ".png";
  37977. saveSnapshot (*editor, folder.getChildFile (name).getFullPathName());
  37978. made.add (name);
  37979. editor = nullptr;
  37980. }
  37981. // the Browser's Plugin database with its JSFX categories open, in the default desktop
  37982. lynx::MainComponent ui (offline, false);
  37983. ui.setSize (1280, 720);
  37984. offline.dispatchPendingMessages();
  37985. ui.waitForBrowserForSnapshot();
  37986. ui.getBrowserForSnapshot().showJsfxForSnapshot();
  37987. offline.dispatchPendingMessages();
  37988. saveSnapshot (ui, folder.getChildFile ("jsfx-browser.png").getFullPathName());
  37989. saveArea (ui, ui.getBrowserForSnapshot().getBoundsInParent(), folder.getChildFile ("jsfx-browser-panel.png").getFullPathName());
  37990. made.add ("jsfx-browser.png");
  37991. // Settings › File with the JSFX folders list
  37992. auto settings = lynx::makeSettingsPanel (offline, lynx::SettingsPage::files);
  37993. if (settings->getWidth() < 200 || settings->getHeight() < 200)
  37994. settings->setSize (720, 640);
  37995. offline.dispatchPendingMessages();
  37996. saveSnapshot (*settings, folder.getChildFile ("jsfx-settings-files.png").getFullPathName());
  37997. made.add ("jsfx-settings-files.png");
  37998. }
  37999. folder.getChildFile ("jsfxshots.txt").replaceWithText (made.joinIntoString ("\n") + "\n");
  38000. setApplicationReturnValue (0);
  38001. quit();
  38002. }
  38003. void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
  38004. {
  38005. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  38006. // LYNX_SNAPSHOT_THEME=file.lynxtheme: the pictures in that theme (round 162d)
  38007. if (const auto themeFile = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_THEME", {}); themeFile.isNotEmpty())
  38008. if (const auto spec = lynx::themeui::loadFile (juce::File (themeFile)))
  38009. lynx::themeui::apply (*spec, false);
  38010. {
  38011. lynx::AudioEngine offline (false);
  38012. lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
  38013. // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
  38014. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
  38015. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  38016. if (projectPath.isNotEmpty())
  38017. ui.openFile (juce::File (projectPath));
  38018. offline.dispatchPendingMessages(); // change notifications are asynchronous
  38019. ui.waitForBrowserForSnapshot();
  38020. // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
  38021. // (and a sample hint in the status strip, as when hovering a knob)
  38022. ui.showDesktopForSnapshot (false);
  38023. ui.setMetersForSnapshot (0.23, (std::int64_t) 412 << 20, 6);
  38024. offline.dispatchPendingMessages();
  38025. saveSnapshot (ui, prefix + "-desktop.png");
  38026. // the first start: the setup wizard over the main window (round 140), also on a small screen (it scrolls)
  38027. {
  38028. const auto size = ui.getBounds();
  38029. ui.showSetupWizard();
  38030. offline.dispatchPendingMessages();
  38031. saveSnapshot (ui, prefix + "-desktop-setup.png");
  38032. ui.setSize (1024, 600);
  38033. offline.dispatchPendingMessages();
  38034. saveSnapshot (ui, prefix + "-desktop-setup-small.png");
  38035. ui.closeSetupWizardForSnapshot();
  38036. ui.setBounds (size);
  38037. offline.dispatchPendingMessages();
  38038. }
  38039. // the start-up desktop and the toolbar at the usual window sizes: the untouched default layout
  38040. // follows the window (default rects, not scaled ones); panels drop from the toolbar by priority
  38041. {
  38042. const auto size = ui.getBounds();
  38043. for (const auto& [w, h] : std::vector<std::pair<int, int>> { { 1280, 720 }, { 1366, 768 }, { 1600, 900 }, { 1920, 1080 }, { 2560, 1440 }, { 3840, 2160 } })
  38044. {
  38045. ui.setSize (w, h);
  38046. offline.dispatchPendingMessages();
  38047. saveSnapshot (ui, prefix + "-desktop-" + juce::String (w) + ".png");
  38048. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + juce::String (w) + ".png");
  38049. if (w == 1920) // the rack scrolled to its last steps: the controls column stays in view (round 90)
  38050. {
  38051. ui.scrollRackForSnapshot (100000);
  38052. offline.dispatchPendingMessages();
  38053. saveSnapshot (ui, prefix + "-desktop-rack-scrolled.png");
  38054. ui.scrollRackForSnapshot (0);
  38055. }
  38056. }
  38057. // the toolbar with small and large icons, and a customized one (groups hidden and reordered)
  38058. ui.setSize (1600, 900);
  38059. for (auto [iconSize, name] : { std::pair { lynx::toolbarlayout::IconSize::small, "small" }, { lynx::toolbarlayout::IconSize::large, "large" } })
  38060. {
  38061. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  38062. layout.iconSize = iconSize;
  38063. ui.setToolbarLayoutForSnapshot (layout);
  38064. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + name + "-1600.png");
  38065. }
  38066. {
  38067. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  38068. layout.move (lynx::toolbarlayout::Group::windows, -3);
  38069. layout.setShown (lynx::toolbarlayout::Group::record, false);
  38070. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  38071. ui.setToolbarLayoutForSnapshot (layout);
  38072. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-custom-1600.png");
  38073. }
  38074. {
  38075. // round 170e: the toolbar after a knob was moved: the last tweaked read-out (its caption) and the snap magnet
  38076. ui.setSize (1920, 1080); // the read-out needs room beside the hint bar
  38077. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  38078. lynx::AutomationTarget t;
  38079. t.kind = lynx::AutomationTargetKind::mixerVolume;
  38080. t.index = 0;
  38081. offline.noteTweaked (t);
  38082. ui.refreshTweakReadoutForSnapshot();
  38083. offline.dispatchPendingMessages();
  38084. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-tweak-1920.png");
  38085. ui.setSize (1600, 900);
  38086. }
  38087. {
  38088. // the toolbar's edit mode (round 115): outlined panels and the tray of panels under it
  38089. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  38090. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  38091. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  38092. ui.setToolbarLayoutForSnapshot (layout);
  38093. ui.setToolbarEditingForSnapshot (true);
  38094. offline.dispatchPendingMessages();
  38095. saveArea (ui, ui.getToolbarBoundsForSnapshot().withHeight (ui.getToolbarAndTrayHeightForSnapshot()), prefix + "-toolbar-edit-1600.png");
  38096. ui.setToolbarEditingForSnapshot (false);
  38097. // Ctrl+F11: only the menu and the hint bar
  38098. layout = lynx::toolbarlayout::Layout::makeDefault();
  38099. layout.visible = false;
  38100. ui.setToolbarLayoutForSnapshot (layout);
  38101. saveArea (ui, ui.getLocalBounds().withHeight (120), prefix + "-toolbar-hidden-1600.png");
  38102. }
  38103. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  38104. // quick tips: the toolbar and title bars with a few name bubbles, and every tip on one sheet
  38105. offline.dispatchPendingMessages();
  38106. saveQuickTips (ui, prefix);
  38107. ui.setBounds (size);
  38108. offline.dispatchPendingMessages();
  38109. }
  38110. // the hint bar: a value control while it is dragged (live value), a gesture line with mouse and key
  38111. // glyphs, and a text too long for one line (two lines)
  38112. {
  38113. const auto toolbar = ui.getToolbarBoundsForSnapshot().withWidth (juce::jmin (ui.getWidth(), 900));
  38114. const lynx::ui::Hint hints[] = {
  38115. { lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "-3.2 dB", true, true },
  38116. { lynx::tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"), {}, false, false },
  38117. { lynx::tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  38118. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"), {}, false, true },
  38119. };
  38120. for (int i = 0; i < 3; ++i)
  38121. {
  38122. ui.setHintForSnapshot (hints[i], i == 0);
  38123. saveArea (ui, toolbar, prefix + "-hint-" + juce::String (i + 1) + ".png");
  38124. }
  38125. }
  38126. ui.showDesktopForSnapshot (true);
  38127. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  38128. saveSnapshot (ui, prefix + "-desktop-all.png");
  38129. ui.selectTabForSnapshot (0);
  38130. saveSnapshot (ui, prefix + "-rack.png");
  38131. // round 190io (design190ia FM-10…14): steps on the first channels, audio clip channels included (they show
  38132. // their steps as in FL), a few selected rows, a muted channel; then the project as it was
  38133. {
  38134. const auto& kept = offline.getSong();
  38135. const auto keptSelection = offline.getSelectedChannels();
  38136. const auto keptPrimary = offline.getSelectedChannel();
  38137. const auto channels = (int) kept.channels.size();
  38138. offline.editSong ([channels] (lynx::Song& s) {
  38139. auto& p = s.activePattern();
  38140. for (int c = 0; c < juce::jmin (12, channels); ++c)
  38141. for (const auto step : { 0, 4 + (c % 3) * 2, 8, 12 + (c % 2) * 2 })
  38142. if (! p.hasStep (c, step))
  38143. p.toggleStep (c, step);
  38144. if (channels > 5)
  38145. s.channels[5].muted = true;
  38146. });
  38147. if (channels > 3)
  38148. offline.setChannelSelection ({ 1, 2, 3 }, 2);
  38149. offline.dispatchPendingMessages();
  38150. saveSnapshot (ui, prefix + "-rack190io-steps.png");
  38151. offline.undo(); // (one undo step: the project and its history as they were)
  38152. offline.setChannelSelection (keptSelection, keptPrimary);
  38153. offline.dispatchPendingMessages();
  38154. }
  38155. {
  38156. // a pattern with piano-roll notes: those rows show a miniature instead of steps (round 90)
  38157. int found = -1;
  38158. const auto before = offline.getSong().currentPattern;
  38159. {
  38160. const auto& song = offline.getSong();
  38161. for (int p = 0; p < (int) song.patterns.size() && found < 0; ++p)
  38162. for (int c = 0; c < (int) song.channels.size() && found < 0; ++c)
  38163. if (lynx::showsNotePreview (song.patterns[(std::size_t) p], c))
  38164. found = p;
  38165. }
  38166. if (found >= 0)
  38167. {
  38168. offline.editSong ([found] (lynx::Song& s) { s.currentPattern = found; }, false);
  38169. offline.dispatchPendingMessages();
  38170. saveSnapshot (ui, prefix + "-rack-preview.png");
  38171. offline.editSong ([before] (lynx::Song& s) { s.currentPattern = before; }, false);
  38172. offline.dispatchPendingMessages();
  38173. }
  38174. }
  38175. ui.selectTabForSnapshot (1);
  38176. saveSnapshot (ui, prefix + "-pianoroll.png");
  38177. {
  38178. // View › Keyboard style › Piano keys (round 190j, discussion #136), also with tall keys
  38179. auto& roll = ui.getPianoRollForSnapshot();
  38180. const auto keysBefore = lynx::PianoRollComponent::keyStyle; // (round 190oo: FL's keys are the default)
  38181. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::piano;
  38182. roll.repaint();
  38183. saveSnapshot (ui, prefix + "-pianoroll-pianokeys.png");
  38184. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::flat;
  38185. roll.repaint();
  38186. saveSnapshot (ui, prefix + "-pianoroll-flatkeys.png");
  38187. lynx::PianoRollComponent::keyStyle = keysBefore;
  38188. roll.repaint();
  38189. // round 190j (discussion #10): the toolbar in a narrow window: the chord stamp as an icon button, and
  38190. // the menu button still there
  38191. for (int narrower : { 150, 270, 330 })
  38192. {
  38193. roll.squeezeToolbarForSnapshot (narrower);
  38194. saveSnapshot (ui, prefix + "-pianoroll-narrow" + juce::String (narrower) + ".png");
  38195. roll.squeezeToolbarForSnapshot (-narrower);
  38196. }
  38197. }
  38198. if (const auto strip = ui.getToolStripAreaForSnapshot (false); ! strip.isEmpty())
  38199. saveArea (ui, strip, prefix + "-pianoroll-tools.png");
  38200. // the editors' mouse feel: the hovered note / clip edge (grip, outline) and its hint in the hint bar
  38201. ui.setHintForSnapshot (ui.getPianoRollForSnapshot().hoverForSnapshot());
  38202. saveSnapshot (ui, prefix + "-pianoroll-hover.png");
  38203. {
  38204. // a pattern with note Chance or a Velocity Range (round 187c): the Piano roll with those lanes
  38205. const auto& song = offline.getSong();
  38206. const auto& notes = song.patterns[(std::size_t) std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1)].notes;
  38207. if (std::any_of (notes.begin(), notes.end(), [] (const lynx::Note& n) { return n.hasChance(); }))
  38208. {
  38209. auto& roll = ui.getPianoRollForSnapshot();
  38210. ui.setHintForSnapshot ({});
  38211. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneChance, "chance" },
  38212. { lynx::PianoRollComponent::laneVelocityRange, "velrange" },
  38213. { lynx::PianoRollComponent::laneVelocity, "velocity" } })
  38214. {
  38215. roll.setLaneForSnapshot (lane);
  38216. offline.dispatchPendingMessages();
  38217. saveSnapshot (ui, prefix + "-pianoroll-" + name + ".png");
  38218. }
  38219. }
  38220. }
  38221. ui.selectTabForSnapshot (2);
  38222. saveSnapshot (ui, prefix + "-playlist.png");
  38223. {
  38224. // round 190nr: the same with the song zoomed to fit (the site's and the Store's Playlist picture: at FL's
  38225. // open zoom the demo song fills only the first fifth)
  38226. auto& pl = ui.getPlaylistForSnapshot();
  38227. const auto view = pl.viewForSnapshot();
  38228. pl.zoomAllForSnapshot();
  38229. saveSnapshot (ui, prefix + "-playlist-fit.png");
  38230. pl.restoreViewForSnapshot (view);
  38231. }
  38232. if (const auto strip = ui.getToolStripAreaForSnapshot (true); ! strip.isEmpty())
  38233. saveArea (ui, strip, prefix + "-playlist-tools.png");
  38234. ui.setHintForSnapshot (ui.getPlaylistForSnapshot().hoverForSnapshot());
  38235. saveSnapshot (ui, prefix + "-playlist-hover.png");
  38236. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  38237. // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
  38238. ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
  38239. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
  38240. offline.dispatchPendingMessages();
  38241. saveSnapshot (ui, prefix + "-playlist-timesel.png");
  38242. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
  38243. // round 177b: automation lanes on (two lanes under track 2: a volume ramp and a pan wobble)
  38244. {
  38245. const auto before = offline.getSong();
  38246. offline.editSong ([] (lynx::Song& s) {
  38247. s.loopStart = s.loopEnd = 0; // (no time selection in this one)
  38248. const auto bar = s.barTicks();
  38249. const auto vol = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Insert 1 - Volume", 0.3f);
  38250. s.automations[(std::size_t) vol].points = { { 0, 0.3f, 0.0f }, { bar * 2, 0.8f, 0.4f }, { bar * 4, 0.6f, 0.0f } };
  38251. const auto pan = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, "Insert 1 - Pan", 0.5f);
  38252. s.automations[(std::size_t) pan].points = { { 0, 0.5f, 0.0f }, { bar, 0.2f, 0.0f }, { bar * 2, 0.8f, 0.0f }, { bar * 3, 0.5f, 0.0f } };
  38253. }, false);
  38254. lynx::autolanes::setShown (true);
  38255. ui.getPlaylistForSnapshot().resized();
  38256. offline.dispatchPendingMessages();
  38257. saveSnapshot (ui, prefix + "-playlist-lanes.png");
  38258. lynx::autolanes::setShown (false);
  38259. offline.editSong ([before] (lynx::Song& s) { s = before; }, false);
  38260. offline.dispatchPendingMessages();
  38261. }
  38262. // round 104: a folded track group (FL's thin member rows) and the Picker's audio tab
  38263. {
  38264. int header = -1;
  38265. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && header < 0; ++t)
  38266. if (lynx::noteedit::isGroupHeader (offline.getSong(), t))
  38267. header = t;
  38268. if (header >= 0)
  38269. {
  38270. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, true); }, false);
  38271. offline.dispatchPendingMessages();
  38272. saveSnapshot (ui, prefix + "-playlist-group-folded.png");
  38273. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, false); }, false);
  38274. }
  38275. ui.getPickerForSnapshot().setView (1);
  38276. offline.dispatchPendingMessages();
  38277. saveSnapshot (ui, prefix + "-playlist-picker-audio.png");
  38278. ui.getPickerForSnapshot().setView (0);
  38279. }
  38280. // round 104: the Channel Rack filtered to its first filter group
  38281. if (! offline.getSong().channelGroups.empty())
  38282. {
  38283. ui.selectTabForSnapshot (0);
  38284. ui.getRackForSnapshot().setFilterGroup (0);
  38285. offline.dispatchPendingMessages();
  38286. saveSnapshot (ui, prefix + "-rack-filter.png");
  38287. ui.getRackForSnapshot().setFilterGroup (-1);
  38288. }
  38289. ui.selectTabForSnapshot (3);
  38290. // LYNX_SNAPSHOT_ARRANGE=1 (round 186c): Mixer menu › "Arrange inserts like the Playlist" first
  38291. if (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_ARRANGE", {}) == "1")
  38292. {
  38293. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::arrangeLikePlaylist (s); });
  38294. offline.dispatchPendingMessages();
  38295. }
  38296. // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
  38297. if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
  38298. {
  38299. ui.selectMixerTrackForSnapshot (track.getIntValue(),
  38300. juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
  38301. offline.dispatchPendingMessages();
  38302. }
  38303. saveSnapshot (ui, prefix + "-mixer.png");
  38304. // round 190ir (Discord report, "it isnt picking up my audio input"): an armed insert without an input says so
  38305. // in its input box (record colour)
  38306. // (the first insert no channel plays into: armed without an input, it records silence)
  38307. {
  38308. const auto& song = offline.getSong();
  38309. auto target = -1;
  38310. for (int t = 1; t < (int) song.mixer.size() && target < 0; ++t)
  38311. if (song.mixer[(std::size_t) t].inputChannel < 0
  38312. && std::none_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  38313. target = t;
  38314. if (target > 0)
  38315. {
  38316. offline.setInsertArmed (target, true);
  38317. ui.selectMixerTrackForSnapshot (target, -1);
  38318. offline.dispatchPendingMessages();
  38319. saveSnapshot (ui, prefix + "-mixer190ir-armed-noinput.png");
  38320. offline.setInsertArmed (target, false);
  38321. offline.dispatchPendingMessages();
  38322. }
  38323. }
  38324. // round 190am: LYNX's two mixer extras, before and after (the demo project leaves most inserts unused). The
  38325. // loudness panel shows a real measurement of 12 s of a test tone (a 1 kHz sine at -14 dBFS after a quieter
  38326. // stretch, pushed through the Master's tap as the audio thread does)
  38327. {
  38328. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  38329. saveSnapshot (ui, prefix + "-mixer190am-before.png");
  38330. strips.setShowUsedOnly (true);
  38331. offline.dispatchPendingMessages();
  38332. saveSnapshot (ui, prefix + "-mixer190am-usedonly.png");
  38333. strips.setShowUsedOnly (false);
  38334. strips.setShowLoudness (true);
  38335. {
  38336. const double sr = 48000.0;
  38337. std::vector<float> tone (480);
  38338. auto& tap = offline.getMeters().loudness;
  38339. for (int block = 0; block < 1200; ++block)
  38340. {
  38341. const auto gain = std::pow (10.0, (block < 400 ? -20.0 : -14.0) / 20.0);
  38342. for (int i = 0; i < 480; ++i)
  38343. tone[(std::size_t) i] = (float) (gain * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * (block * 480 + i) / sr));
  38344. tap.push (tone.data(), tone.data(), 480, sr);
  38345. }
  38346. }
  38347. strips.refreshLoudnessForSnapshot();
  38348. offline.dispatchPendingMessages();
  38349. saveSnapshot (ui, prefix + "-mixer190am-loudness.png");
  38350. for (const auto l : { lynx::mixerlayout::Layout::compact, lynx::mixerlayout::Layout::extraLarge })
  38351. {
  38352. const auto was = lynx::MixerStrips::layout;
  38353. strips.setLayout (l);
  38354. offline.dispatchPendingMessages();
  38355. saveSnapshot (ui, prefix + "-mixer190am-loudness-" + juce::String ((int) l) + ".png");
  38356. strips.setLayout (was);
  38357. }
  38358. strips.setShowUsedOnly (true);
  38359. offline.dispatchPendingMessages();
  38360. saveSnapshot (ui, prefix + "-mixer190am-both.png");
  38361. strips.setShowUsedOnly (false);
  38362. strips.setShowLoudness (false);
  38363. offline.dispatchPendingMessages();
  38364. }
  38365. // round 168h (issue #52): FL's 8 Mixer layouts
  38366. {
  38367. const auto before = lynx::MixerStrips::layout;
  38368. for (int l = 0; l < lynx::mixerlayout::layoutCount; ++l)
  38369. {
  38370. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout ((lynx::mixerlayout::Layout) l);
  38371. offline.dispatchPendingMessages();
  38372. saveSnapshot (ui, prefix + "-mixer168h-" + juce::String (l) + ".png");
  38373. }
  38374. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout (before);
  38375. offline.dispatchPendingMessages();
  38376. }
  38377. // round 163: the Mixer at short heights (UI zoom 150%+): the EQ folds, then the effects panel scrolls
  38378. {
  38379. const auto size = ui.getBounds();
  38380. for (auto h : { 450, 560, 680, 820 })
  38381. {
  38382. ui.setSize (size.getWidth(), h);
  38383. offline.dispatchPendingMessages();
  38384. saveSnapshot (ui, prefix + "-mixer163-" + juce::String (h) + ".png");
  38385. }
  38386. ui.setBounds (size);
  38387. offline.dispatchPendingMessages();
  38388. }
  38389. // round 170b (Busy Works Beats' review): inserts 1-3 selected and routed together to insert 4, a single effect
  38390. // moved down into slot 2 (FL's slot places), and the plugin menus grouped by category, LYNX SHARE first
  38391. {
  38392. const auto before = offline.getSong();
  38393. offline.editSong ([] (lynx::Song& s) {
  38394. if (s.mixer.size() < 5)
  38395. return;
  38396. s.mixer[1].effects.clear();
  38397. lynx::EffectSlot fx;
  38398. fx.kind = lynx::EffectKind::compressor;
  38399. s.mixer[1].effects.push_back (fx);
  38400. lynx::mixerops::moveEffectBy (s, 1, 0, 1);
  38401. lynx::mixerops::switchSelectedRoute (s, { 1, 2, 3 }, 4, true);
  38402. });
  38403. ui.selectMixerTrackForSnapshot (1);
  38404. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 1);
  38405. offline.dispatchPendingMessages();
  38406. saveSnapshot (ui, prefix + "-mixer170b.png");
  38407. juce::PopupMenu effects, generators;
  38408. lynx::quickpick::addFolderGroups (effects, offline, std::function<void (lynx::EffectSlot)> ([] (lynx::EffectSlot) {}));
  38409. lynx::quickpick::addFolderViewItems (effects, offline);
  38410. lynx::quickpick::addGeneratorMenu (generators, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  38411. lynx::quickpick::addFolderViewItems (generators, offline);
  38412. saveMenus (juce::StringArray { "Mixer slot: add an effect", "Channel Rack: add" }, { effects, generators }, prefix + "-menus170b.png");
  38413. // round 190bf (fl190be Q3): the Channel Rack's "+" menu in FL's three views, with two root entries (plugins
  38414. // at the top of the database, in no folder) and the Categories / Simple / Tree switch at the end
  38415. {
  38416. auto& host = offline.getPluginHost();
  38417. const auto keep = host.databaseFolders();
  38418. auto folders = keep;
  38419. int added = 0;
  38420. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  38421. if (e.folder == 3 && e.available && added < 2) // (installed plugins: FL's root entries are such)
  38422. {
  38423. folders.top.insert (e.key);
  38424. ++added;
  38425. }
  38426. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  38427. if (e.folder != 3 && added < 2)
  38428. {
  38429. folders.top.insert (e.key);
  38430. ++added;
  38431. }
  38432. static const char* const views[] { "categories", "simple", "tree" };
  38433. for (int v = 0; v < 3; ++v)
  38434. {
  38435. folders.view = v;
  38436. host.setDatabaseFolders (folders);
  38437. juce::PopupMenu plus;
  38438. lynx::quickpick::addGeneratorMenu (plus, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  38439. lynx::quickpick::addFolderViewItems (plus, offline);
  38440. saveMenus (juce::StringArray { juce::String ("Channel Rack +: ") + views[v] }, { plus }, prefix + "-menus190bf-" + views[v] + ".png");
  38441. }
  38442. host.setDatabaseFolders (keep);
  38443. }
  38444. offline.setSong (before);
  38445. offline.dispatchPendingMessages();
  38446. }
  38447. // standalone windows, with the theme background
  38448. auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  38449. juce::Component frame;
  38450. frame.setSize (c->getWidth(), c->getHeight());
  38451. frame.setOpaque (true);
  38452. // an AlertWindow is built on the desktop: shown there first, it would take the foreground from whoever has it
  38453. // (TopLevelWindow::visibilityChanged calls toFront (true)). Off the desktop, its control that showing it would
  38454. // have focused (what grabKeyboardFocus picks) is marked, so the picture keeps that control's focus ring
  38455. if (c->isOnDesktop())
  38456. {
  38457. c->removeFromDesktop();
  38458. auto* focus = c.get();
  38459. for (int depth = 0; focus != nullptr && depth < 32; ++depth)
  38460. {
  38461. if (focus->getWantsKeyboardFocus() && (focus->isEnabled() || focus == c.get()))
  38462. {
  38463. focus->getProperties().set ("lynxSnapshotFocus", true);
  38464. break;
  38465. }
  38466. auto traverser = focus->createKeyboardFocusTraverser();
  38467. focus = traverser != nullptr ? traverser->getDefaultComponent (focus) : nullptr;
  38468. }
  38469. }
  38470. frame.addAndMakeVisible (*c);
  38471. c->setTopLeftPosition (0, 0);
  38472. checkTextFit (*c, name.fromFirstOccurrenceOf ("-", false, false).upToLastOccurrenceOf (".", false, false));
  38473. auto image = lynx::shot::paint (frame, lynx::theme::panel);
  38474. const auto file = lynx::shot::file (juce::File (prefix + name));
  38475. file.deleteFile();
  38476. juce::PNGImageFormat png;
  38477. if (auto out = file.createOutputStream())
  38478. png.writeImageToStream (image, *out);
  38479. };
  38480. saveWindow (lynx::makeExportPanel (offline), "-export.png");
  38481. saveWindow (lynx::makeExportPanel (offline, 1), "-export-mp3.png");
  38482. saveWindow (lynx::makeExportPanel (offline, 3), "-export-flac-stems.png");
  38483. saveWindow (lynx::makeExportPanel (offline, 4), "-export-aiff.png"); // owner decision D5
  38484. if (lynx::aac::available())
  38485. saveWindow (lynx::makeExportPanel (offline, 5), "-export-m4a.png");
  38486. {
  38487. // REA round 165f-mixer: the mixer track's Track latency / routing submenus, Disk recording, PDC, and the
  38488. // Export window for "Render selected tracks to wave file(s)"
  38489. const auto before = offline.getSong();
  38490. offline.editSong ([] (lynx::Song& s) {
  38491. if (s.mixer.size() > 3)
  38492. {
  38493. s.mixer[1].latencyMs = 5.0f;
  38494. s.mixer[1].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  38495. s.mixer[2].latencyMs = -1.5f;
  38496. }
  38497. });
  38498. offline.dispatchPendingMessages();
  38499. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  38500. strips.setSelection ({ 1, 2, 3 }, 1);
  38501. const auto menu = strips.buildMenu (1);
  38502. juce::StringArray names { "Mixer track" };
  38503. std::vector<juce::PopupMenu> menus { menu };
  38504. const auto latencyPrefix = lynx::tr ("Track latency: {0}", { juce::String() });
  38505. const juce::String wanted[] = { lynx::tr ("Selected tracks ⇄ this track"), lynx::tr ("Disk recording"),
  38506. lynx::tr ("Plugin delay compensation") };
  38507. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  38508. {
  38509. const auto& item = it.getItem();
  38510. if (item.subMenu != nullptr && (item.text.startsWith (latencyPrefix) || std::find (std::begin (wanted), std::end (wanted), item.text) != std::end (wanted)))
  38511. {
  38512. names.add (item.text.upToFirstOccurrenceOf (":", false, false));
  38513. menus.push_back (*item.subMenu);
  38514. }
  38515. }
  38516. saveMenus (names, menus, prefix + "-menus165-mixer.png");
  38517. saveWindow (lynx::makeExportPanelForTracks (offline, { 1, 2, 3 }), "-export165-tracks.png");
  38518. offline.setSong (before);
  38519. offline.dispatchPendingMessages();
  38520. }
  38521. saveSplashFrames (prefix);
  38522. saveIconSheet (prefix + "-icons.png", 1.0f);
  38523. saveIconSheet (prefix + "-icons-150.png", 1.5f);
  38524. saveStateSheet (prefix + "-states190je.png", 1.0f); // round 190je: the one state rule, per button kind
  38525. saveStateSheet (prefix + "-states190je-z3.png", 3.0f);
  38526. saveWindow (lynx::MainComponent::makeHelpContent (nullptr, [] {}), "-help.png"); // (round 190ns: with its Manage shortcuts link)
  38527. saveWindow (lynx::ui::makeTrackIconGrid (5, {}), "-trackicons168h.png"); // round 168h: the icon picker
  38528. saveWindow (std::make_unique<lynx::toolbar::CustomizePanel> (lynx::toolbarlayout::Layout::makeDefault()), "-customize-toolbar.png");
  38529. // two moved controls: Tools › Last tweaked and Add › Automation for last tweaked parameter show them (REA round 143)
  38530. offline.noteTweaked ({ lynx::AutomationTargetKind::channelVolume, 0 });
  38531. offline.noteTweaked ({ lynx::AutomationTargetKind::mixerVolume, 0 });
  38532. saveMenus (ui, prefix + "-menus.png");
  38533. {
  38534. // the windows' own menus (title bars) and the toolbar's recording menu
  38535. juce::StringArray names;
  38536. std::vector<juce::PopupMenu> menus;
  38537. for (auto [panel, name] : { std::pair { lynx::workspace::Panel::playlist, "Playlist" }, { lynx::workspace::Panel::channelRack, "Channel Rack" },
  38538. { lynx::workspace::Panel::pianoRoll, "Piano Roll" }, { lynx::workspace::Panel::mixer, "Mixer" },
  38539. { lynx::workspace::Panel::browser, "Browser" } })
  38540. {
  38541. names.add (name);
  38542. menus.push_back (ui.getPanelMenuForSnapshot (panel));
  38543. }
  38544. names.add ("Recording");
  38545. menus.push_back (ui.getRecordMenuForSnapshot());
  38546. names.add ("Toolbar");
  38547. menus.push_back (ui.getToolbarMenuForSnapshot());
  38548. saveMenus (names, menus, prefix + "-panel-menus.png");
  38549. }
  38550. // round 189e: the Playlist menu's Edit and Select submenus (FL's items and order) and the header drop question
  38551. saveMenus (juce::StringArray { "Playlist: Edit", "Playlist: Select" },
  38552. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().editMenu(), ui.getPlaylistForSnapshot().selectMenu() },
  38553. prefix + "-playlist-edit189e.png");
  38554. saveWindow (lynx::PlaylistComponent::makeHeaderDropDialog(), "-header-drop189e.png");
  38555. {
  38556. // round 189i: FL's fade handle menu (right-click on an audio clip's fade handle), on the song's first audio
  38557. // clip, or on one added for the shot
  38558. const auto before = offline.getSong();
  38559. auto clipIndex = -1;
  38560. for (std::size_t i = 0; i < before.playlist.size() && clipIndex < 0; ++i)
  38561. if (before.playlist[i].kind == lynx::ClipKind::audio)
  38562. clipIndex = (int) i;
  38563. if (clipIndex < 0)
  38564. {
  38565. auto song = before;
  38566. lynx::ChannelDef channel;
  38567. channel.instrument = lynx::InstrumentKind::audioClip;
  38568. channel.name = "Audio clip";
  38569. song.channels.push_back (channel);
  38570. lynx::Clip clip;
  38571. clip.kind = lynx::ClipKind::audio;
  38572. clip.channel = (int) song.channels.size() - 1;
  38573. clip.length = lynx::ppq * 4;
  38574. song.playlist.push_back (clip);
  38575. clipIndex = (int) song.playlist.size() - 1;
  38576. offline.setSong (song);
  38577. offline.dispatchPendingMessages();
  38578. }
  38579. saveMenus (juce::StringArray { "Fade handle" },
  38580. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().fadeHandleMenu (clipIndex, 1) },
  38581. prefix + "-fade-handle189i.png");
  38582. if (offline.getSong().playlist.size() != before.playlist.size())
  38583. {
  38584. offline.setSong (before);
  38585. offline.dispatchPendingMessages();
  38586. }
  38587. }
  38588. {
  38589. // round 189n: FL's gain handle menu with two overlapping clips selected (Normalize selection individually / as a
  38590. // group) and the later clip's fade in menu (Create crossfade enabled); FL shots in /mnt/e/lynx-work/flgap189n
  38591. const auto before = offline.getSong();
  38592. auto song = before;
  38593. lynx::ChannelDef channel;
  38594. channel.instrument = lynx::InstrumentKind::audioClip;
  38595. channel.name = "Audio clip";
  38596. song.channels.push_back (channel);
  38597. int lane = 0;
  38598. for (const auto& c : song.playlist)
  38599. lane = std::max (lane, c.track + 1);
  38600. for (int k = 0; k < 2; ++k)
  38601. {
  38602. lynx::Clip clip;
  38603. clip.kind = lynx::ClipKind::audio;
  38604. clip.channel = (int) song.channels.size() - 1;
  38605. clip.track = lane;
  38606. clip.start = k * lynx::ppq * 3;
  38607. clip.length = lynx::ppq * 4;
  38608. song.playlist.push_back (clip);
  38609. }
  38610. const auto second = (int) song.playlist.size() - 1;
  38611. song.autoCrossfades = true; // FL's capture: Thief has Automatic crossfades on
  38612. offline.setSong (song);
  38613. offline.dispatchPendingMessages();
  38614. auto& playlist = ui.getPlaylistForSnapshot();
  38615. playlist.selectForSnapshot ({ second - 1, second });
  38616. auto gain = playlist.gainMenu (second);
  38617. auto fadeIn = playlist.fadeHandleMenu (second, 0); // (both selected, as in FL's capture)
  38618. playlist.selectForSnapshot ({});
  38619. saveMenus (juce::StringArray { "Gain handle, 2 selected", "Fade in, overlapping" },
  38620. std::vector<juce::PopupMenu> { gain, fadeIn }, prefix + "-fade-gain189n.png");
  38621. // round 189o: the audio clip menu with both overlapping clips selected (FL's Fades › Crossfade selected
  38622. // shown) and with none selected (hidden)
  38623. playlist.selectForSnapshot ({ second - 1, second });
  38624. auto clipSelected = playlist.getClipMenuForSnapshot (second);
  38625. playlist.selectForSnapshot ({});
  38626. auto clipAlone = playlist.getClipMenuForSnapshot (second);
  38627. saveMenus (juce::StringArray { "Audio clip, 2 selected", "Audio clip, none selected" },
  38628. std::vector<juce::PopupMenu> { clipSelected, clipAlone }, prefix + "-xfadesel189o.png");
  38629. offline.setSong (before);
  38630. offline.dispatchPendingMessages();
  38631. }
  38632. {
  38633. // REA round 143: the piano roll Tools menu, a Playlist track menu and a mixer insert menu (FL's layouts)
  38634. std::vector<juce::PopupMenu> menus { ui.getPianoRollForSnapshot().getToolsMenuForSnapshot(),
  38635. ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (0),
  38636. ui.getMixerForSnapshot().getStripsForSnapshot().buildMenu (1) };
  38637. saveMenus (juce::StringArray { "Piano roll tools", "Playlist track", "Mixer track" }, menus, prefix + "-menus143.png");
  38638. // round 190as: the Piano roll's scripts (FL's Tools › Scripts column) and a script's form
  38639. saveMenus (juce::StringArray { "Piano roll scripts" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getScriptsMenuForSnapshot() },
  38640. prefix + "-prscripts-menu.png");
  38641. {
  38642. lynx::prscript::Score score;
  38643. const auto out = lynx::prscript::run (lynx::prscript::builtins().front().source, score, {});
  38644. if (out.status == lynx::prscript::Outcome::Status::needsForm)
  38645. {
  38646. lynx::ScriptPanel::Options options;
  38647. options.acceptText = lynx::tr ("Accept");
  38648. saveWindow (std::make_unique<lynx::ScriptPanel> (out.form, [] (const lynx::scriptform::Form&) {}, [] (const lynx::scriptform::Form&) {},
  38649. nullptr, options),
  38650. "-prscript-form.png");
  38651. }
  38652. }
  38653. // round 190j (discussion #10): the Piano roll menu's Chord stamp list
  38654. saveMenus (juce::StringArray { "Chord stamp" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getStampMenuForSnapshot() },
  38655. prefix + "-stamp-menu.png");
  38656. // round 167l: the channel menu ("Lock active/mute state")
  38657. if (! offline.getSong().channels.empty())
  38658. saveMenus (juce::StringArray { "Channel" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (0) }, prefix + "-channel-menu.png");
  38659. // round 163: menu density, compact (default) and comfortable, on a Browser folder menu
  38660. {
  38661. juce::PopupMenu folder;
  38662. folder.addSectionHeader ("Documents");
  38663. folder.addItem (1, "Expand all");
  38664. folder.addItem (2, "Collapse all");
  38665. folder.addSeparator();
  38666. folder.addItem (3, "Refresh");
  38667. folder.addSectionHeader ("System");
  38668. folder.addItem (4, "Open");
  38669. folder.addItem (5, "Copy the file path");
  38670. folder.addSectionHeader ("Tags");
  38671. folder.addItem (6, "Starred", true, true);
  38672. folder.addSeparator();
  38673. folder.addItem (7, "Add folder...");
  38674. const auto wasCompact = lynx::theme::menus::compact();
  38675. lynx::theme::menus::setCompact (true);
  38676. saveMenus (juce::StringArray { "Compact" }, { folder }, prefix + "-menu163-compact.png");
  38677. lynx::theme::menus::setCompact (false);
  38678. saveMenus (juce::StringArray { "Comfortable" }, { folder }, prefix + "-menu163-comfortable.png");
  38679. lynx::theme::menus::setCompact (wasCompact);
  38680. }
  38681. // and the clip menus of the first pattern, audio and automation clips of the project
  38682. juce::StringArray clipNames;
  38683. std::vector<juce::PopupMenu> clipMenus;
  38684. for (auto [kind, name] : { std::pair { lynx::ClipKind::pattern, "Pattern clip" }, { lynx::ClipKind::audio, "Audio clip" },
  38685. { lynx::ClipKind::automation, "Automation clip" } })
  38686. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  38687. if (offline.getSong().playlist[(std::size_t) c].kind == kind)
  38688. {
  38689. clipNames.add (name);
  38690. clipMenus.push_back (ui.getPlaylistForSnapshot().getClipMenuForSnapshot (c));
  38691. break;
  38692. }
  38693. if (! clipMenus.empty())
  38694. saveMenus (clipNames, clipMenus, prefix + "-menus143-clips.png");
  38695. }
  38696. auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
  38697. alert->setOpaque (true);
  38698. saveWindow (std::move (alert), name);
  38699. };
  38700. saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
  38701. saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
  38702. saveAlert (lynx::support::makeSupportWindow(), "-support.png"); // round 190fq: Help › Support LYNX SHARE...
  38703. saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
  38704. saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
  38705. // round 190ah: Online Sessions — a guest's "go back in?" at start-up, the host's question at a guest's file limit
  38706. saveAlert (lynx::liveui::makeRejoinDialog ("Ana", juce::Time (2026, 10, 10, 21, 40).toString (true, true, false, true)), "-live-rejoin.png");
  38707. saveAlert (lynx::liveui::makeMediaLimitDialog ("Pedro", (juce::int64) 1010 << 20, (juce::int64) 1 << 30), "-live-media-limit.png");
  38708. saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
  38709. saveAlert (lynx::makeGradientColourDialog (juce::Colour (0xffe5383b), juce::Colour (0xff3a7bd5), 8), "-gradient.png"); // round 177a
  38710. saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
  38711. // round 186c: FL's mixer "Delete" questions and its Settings › General › Manage messages menu
  38712. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Delete tracks"), lynx::tr ("This will |delete| {0} selected mixer track(s). Are you sure?", { "1" }),
  38713. { lynx::tr ("Yes"), lynx::tr ("No") }, true }),
  38714. "-delete-tracks.png");
  38715. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Playlist tracks"),
  38716. lynx::tr ("One or more mixer tracks that will be deleted are connected to instrument/audio tracks.") + "\n"
  38717. + lynx::tr ("Do you want to unlink the tracks and channels or delete them?"),
  38718. { lynx::tr ("Delete tracks and channels"), lynx::tr ("Unlink tracks and channels"), lynx::tr ("Cancel") }, false }),
  38719. "-delete-tracks-linked.png");
  38720. saveMenus (juce::StringArray { "Manage messages" }, std::vector<juce::PopupMenu> { lynx::messages::manageMenu() }, prefix + "-manage-messages.png");
  38721. saveWindow (lynx::makeSetupWizardContent (offline, {}, {}), "-setup.png");
  38722. saveWindow (lynx::crashreporter::makeDialogForSnapshot (false), "-crash-report.png"); // round 159
  38723. saveWindow (lynx::crashreporter::makeDialogForSnapshot (true), "-report-problem.png");
  38724. // round 166b: the update bar in its states (available, downloading, failed, ready) and the release notes window
  38725. {
  38726. struct Bars final : juce::Component
  38727. {
  38728. Bars()
  38729. {
  38730. constexpr int h = lynx::updater::UpdateBar::height;
  38731. setSize (1100, 6 * (h + 6));
  38732. for (int state = 0; state < 6; ++state) // (round 190gh: 4 going back, 5 went back)
  38733. {
  38734. bars[state].setBounds (0, state * (h + 6), getWidth(), h);
  38735. bars[state].showForSnapshot (state);
  38736. addAndMakeVisible (bars[state]);
  38737. }
  38738. }
  38739. lynx::updater::UpdateBar bars[6];
  38740. };
  38741. saveWindow (std::make_unique<Bars>(), "-update-bar.png");
  38742. saveWindow (lynx::updater::makeReleaseNotesForSnapshot(), "-update-notes.png");
  38743. // round 190gh (B23): Help › Test audio output... in its states
  38744. for (int state = 0; state < 5; ++state)
  38745. saveWindow (lynx::makeAudioCheckForSnapshot (offline, state), "-audio-check-" + juce::String (state) + ".png");
  38746. }
  38747. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 0, 1), "-missing-files.png");
  38748. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 1), "-missing-plugins.png");
  38749. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 2), "-missing-found.png");
  38750. {
  38751. // the Settings pages, with credits like a project imported from FL would carry
  38752. offline.editSong ([] (lynx::Song& s) {
  38753. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  38754. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  38755. }, false);
  38756. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::project), "-settings-project.png");
  38757. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::info), "-settings-info.png");
  38758. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::files), "-settings-files.png");
  38759. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::general), "-settings-general.png");
  38760. {
  38761. // round 189o: the whole General page (the Editing and Plugins sections hold FL's "Monophonic painting in
  38762. // piano roll" and "Limit the number of open plugin editors")
  38763. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  38764. tall->setSize (tall->getWidth(), 3200);
  38765. saveWindow (std::move (tall), "-settings-general-tall189o.png");
  38766. }
  38767. {
  38768. // the whole General page (round 186a: the Startup section is below the first screen)
  38769. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  38770. tall->setSize (tall->getWidth(), 1500);
  38771. saveWindow (std::move (tall), "-settings-general-tall.png");
  38772. }
  38773. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
  38774. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::extras), "-settings-extras.png"); // round 190am
  38775. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
  38776. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
  38777. {
  38778. // round 190bj (QA): the MIDI page in a small window keeps each row's switch and device name
  38779. auto small = lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi);
  38780. small->setSize (390, 390);
  38781. saveWindow (std::move (small), "-settings-midi-small.png");
  38782. }
  38783. {
  38784. // round 190bj (QA): the Apex Limiter's window content at its default size, as sized before (JUCE's ratio
  38785. // on the whole window: the status row cut off) and now
  38786. lynx::AudioEngine apexEngine (false);
  38787. lynx::Song song;
  38788. song.mixer.resize (2);
  38789. song.mixer[0].name = "Master";
  38790. song.mixer[1].name = "Insert 1";
  38791. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::apexLimiter));
  38792. apexEngine.setSong (std::move (song));
  38793. apexEngine.dispatchPendingMessages();
  38794. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, true), prefix + "-apex-window-before190bj.png");
  38795. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, false), prefix + "-apex-window.png");
  38796. }
  38797. saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
  38798. // round 190gg: the crash prompt and a plugin window's crash notice, with "Always run ... in a separate process"
  38799. saveWindow (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "-plugin-crash-prompt.png");
  38800. saveWindow (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "-plugin-crash-notice.png");
  38801. saveWindow (lynx::makeShortcutManagerPanel (false), "-shortcuts.png");
  38802. }
  38803. {
  38804. // round 84: New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
  38805. saveWindow (lynx::makeNewProjectPanel(), "-new-project.png");
  38806. const auto& clips = offline.getSong().playlist;
  38807. for (int i = 0; i < (int) clips.size(); ++i)
  38808. if (clips[(std::size_t) i].kind == lynx::ClipKind::pattern)
  38809. {
  38810. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i, (i + 1) % (int) clips.size() }), "-clip-properties.png");
  38811. break;
  38812. }
  38813. for (int i = 0; i < (int) clips.size(); ++i)
  38814. if (clips[(std::size_t) i].kind == lynx::ClipKind::audio)
  38815. {
  38816. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i }), "-clip-properties-audio.png");
  38817. break;
  38818. }
  38819. if (offline.getSong().arrangements.size() < 2)
  38820. offline.editSong ([] (lynx::Song& s) {
  38821. const auto current = s.currentArrangement;
  38822. s.addArrangement ("Radio edit", true);
  38823. s.addArrangement ("Intro loop");
  38824. s.selectArrangement (current);
  38825. }, false);
  38826. saveWindow (lynx::makeArrangementsPanel (offline), "-arrangements.png");
  38827. saveWindow (lynx::makePluginMonitorPanel (offline), "-plugin-monitor.png");
  38828. saveWindow (lynx::makeTouchKeyboardPanel (offline), "-touch-keyboard.png");
  38829. }
  38830. {
  38831. // round 142: the Newtone / Newtime editors on a synthetic sung line (A3 B3 C4 · E4), one note moved
  38832. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-newtone.wav");
  38833. {
  38834. juce::AudioBuffer<float> line (1, 44100 * 2);
  38835. const double hz[] = { 220.0, 246.94, 261.63, 0.0, 329.63 };
  38836. double ph = 0.0;
  38837. for (int i = 0; i < line.getNumSamples(); ++i)
  38838. {
  38839. const auto f0 = hz[std::min (4, i / 17640)];
  38840. ph += 2.0 * juce::MathConstants<double>::pi * f0 * (1.0 + 0.004 * std::sin (2.0 * juce::MathConstants<double>::pi * 5.5 * i / 44100.0)) / 44100.0;
  38841. float v = 0.0f;
  38842. for (int h = 1; f0 > 0.0 && h < 8; ++h)
  38843. v += (float) (0.3 / h * std::sin (h * ph));
  38844. line.setSample (0, i, v);
  38845. }
  38846. wav.deleteFile();
  38847. juce::WavAudioFormat format;
  38848. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  38849. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0) : nullptr)
  38850. {
  38851. out.release();
  38852. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  38853. writer->writeFromAudioSampleBuffer (line, 0, line.getNumSamples());
  38854. }
  38855. }
  38856. if (const auto sample = offline.getSampleLibrary().load (wav.getFullPathName()))
  38857. {
  38858. auto notes = lynx::newtonefx::analyseNotes (*sample);
  38859. if (notes.pitches.size() > 1)
  38860. notes.pitches[1].shift = 2.0;
  38861. lynx::newtonefx::WarpMap warp;
  38862. warp.frames = (std::int64_t) sample->frames();
  38863. warp.markers = { { 22050, 33075 } };
  38864. int at = 0;
  38865. offline.editSong ([&] (lynx::Song& song) {
  38866. if (song.mixer.size() < 2)
  38867. song.mixer.resize (2);
  38868. auto& fx = song.mixer[1].effects;
  38869. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  38870. tone.samplePath = wav.getFullPathName().toStdString();
  38871. tone.state = lynx::newtonefx::writeNative (notes);
  38872. auto time = lynx::makeEffectSlot (lynx::EffectKind::newtime);
  38873. time.samplePath = tone.samplePath;
  38874. time.state = lynx::newtonefx::writeWarp (warp);
  38875. at = (int) fx.size();
  38876. fx.push_back (tone);
  38877. fx.push_back (time);
  38878. }, false);
  38879. saveWindow (lynx::makeNewtoneEditor (offline, 1, at), "-newtone.png");
  38880. saveWindow (lynx::makeNewtoneEditor (offline, 1, at + 1), "-newtime.png");
  38881. offline.editSong ([at] (lynx::Song& song) {
  38882. auto& fx = song.mixer[1].effects;
  38883. fx.erase (fx.begin() + at, fx.begin() + at + 2);
  38884. }, false);
  38885. }
  38886. }
  38887. if (! offline.getSong().automations.empty())
  38888. {
  38889. auto editor = lynx::makeAutomationEditor (offline, 0);
  38890. editor->setSize (760, 300);
  38891. saveWindow (std::move (editor), "-automation.png");
  38892. // round 177b: the same clip in FL's LFO mode: FL's defaults, then one shaped state (the UI gate pairs)
  38893. const auto before = offline.getSong().automations[0].lfo;
  38894. const auto lfoShot = [&offline, &saveWindow] (std::function<void (lynx::AutomationLfo&)> set, const char* suffix) {
  38895. offline.editSong ([&set] (lynx::Song& song) {
  38896. auto& lfo = song.automations[0].lfo;
  38897. lfo = lynx::AutomationLfo {};
  38898. lfo.on = true;
  38899. set (lfo);
  38900. }, false);
  38901. auto lfoEditor = lynx::makeAutomationEditor (offline, 0);
  38902. lfoEditor->setSize (760, 346);
  38903. saveWindow (std::move (lfoEditor), suffix);
  38904. };
  38905. lfoShot ([] (lynx::AutomationLfo&) {}, "-automation-lfo.png");
  38906. lfoShot ([] (lynx::AutomationLfo& lfo) {
  38907. // the state set through FL's own UI for the UI gate (TNS 50 %, SKEW 25 %, PW 25 %, two points), as FL saved it
  38908. lfo.tension = 64;
  38909. lfo.skew = 32;
  38910. lfo.pulseWidth = 28;
  38911. lfo.amp = { { 0, 0.6716f, 0.0f }, { (std::int64_t) (lynx::ppq * 1.4128), 0.9204f, 0.0f } };
  38912. }, "-automation-lfo-shape.png");
  38913. offline.editSong ([before] (lynx::Song& song) { song.automations[0].lfo = before; }, false);
  38914. }
  38915. // round 177b: LYNX's modulators window, with one routed modulator
  38916. {
  38917. offline.editSong ([] (lynx::Song& song) {
  38918. lynx::Modulator m;
  38919. m.name = "LFO 1";
  38920. m.shape = lynx::ModShape::triangle;
  38921. m.routes = { { { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0.25f }, { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  38922. song.modulators.push_back (m);
  38923. lynx::Modulator r;
  38924. r.name = "LFO 2";
  38925. r.shape = lynx::ModShape::smoothRandom;
  38926. r.sync = false;
  38927. r.hz = 0.5;
  38928. song.modulators.push_back (r);
  38929. }, false);
  38930. auto mods = lynx::makeModulatorsPanel (offline);
  38931. mods->setSize (900, 420); // (round 190ox: the stage 2 rows are wider)
  38932. saveWindow (std::move (mods), "-modulators.png");
  38933. offline.editSong ([] (lynx::Song& song) { song.modulators.clear(); }, false);
  38934. }
  38935. saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
  38936. // the channel window frame (REA round 143b): header strip + tabs; the Misc tab of the first channel and of a synth
  38937. saveWindow (lynx::makeChannelFrame (offline, 0), "-channel-frame.png");
  38938. saveWindow (lynx::makeChannelFrame (offline, 0, -1), "-channel-misc.png");
  38939. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  38940. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
  38941. {
  38942. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
  38943. saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
  38944. break;
  38945. }
  38946. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  38947. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
  38948. {
  38949. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
  38950. break;
  38951. }
  38952. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  38953. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  38954. if (offline.getSong().channels[(std::size_t) c].instrument == kind)
  38955. {
  38956. saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
  38957. break;
  38958. }
  38959. // round 180c: Fruity Slicer's editor
  38960. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  38961. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fruityslicer)
  38962. {
  38963. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fruityslicer.png");
  38964. // rounds 190f / 190m: its Envelope / instrument page, one picture per target
  38965. saveWindow (lynx::makeChannelFrame (offline, c, 1), "-fruityslicer-envelope.png");
  38966. for (const auto& [target, name] : std::vector<std::pair<int, const char*>> { { 0, "panning" }, { 2, "modx" }, { 3, "mody" }, { 4, "pitch" } })
  38967. {
  38968. auto frame = lynx::makeChannelFrame (offline, c, 1);
  38969. lynx::showFlVoiceTarget (*frame, target);
  38970. saveWindow (std::move (frame), juce::String ("-fruityslicer-envelope-") + name + ".png");
  38971. }
  38972. break;
  38973. }
  38974. // round 190r: Slicex's editor
  38975. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  38976. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  38977. {
  38978. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-slicex.png");
  38979. break;
  38980. }
  38981. // round 190q: FPC's editor
  38982. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  38983. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fpc)
  38984. {
  38985. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fpc.png");
  38986. break;
  38987. }
  38988. // round 190hz: DirectWave's editor
  38989. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  38990. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::directwave)
  38991. {
  38992. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-directwave.png");
  38993. break;
  38994. }
  38995. // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
  38996. {
  38997. int bestTrack = -1, bestSlot = -1;
  38998. double bestShape = -1.0;
  38999. const auto& mixer = offline.getSong().mixer;
  39000. for (int t = 0; t < (int) mixer.size(); ++t)
  39001. for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
  39002. if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
  39003. {
  39004. double shape = 0.0;
  39005. for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
  39006. shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
  39007. if (shape > bestShape)
  39008. {
  39009. bestShape = shape;
  39010. bestTrack = t;
  39011. bestSlot = s;
  39012. }
  39013. }
  39014. if (bestTrack >= 0)
  39015. saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
  39016. }
  39017. // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
  39018. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
  39019. saveWindow (std::move (inspector), "-noteinspector.png");
  39020. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
  39021. saveWindow (std::move (inspector), "-noteinspector-one.png");
  39022. // workflow P2: note tool dialogs (they preview on the pattern; each one puts the notes back when destroyed)
  39023. {
  39024. auto& roll = ui.getPianoRollForSnapshot();
  39025. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::strum, "-tool-strum.png" },
  39026. { lynx::NoteTool::arpeggiate, "-tool-arpeggiate.png" },
  39027. { lynx::NoteTool::flip, "-tool-flip.png" },
  39028. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  39029. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  39030. { lynx::NoteTool::limit, "-tool-limit.png" },
  39031. { lynx::NoteTool::quantize, "-tool-quantize.png" },
  39032. { lynx::NoteTool::chop, "-tool-chop.png" },
  39033. { lynx::NoteTool::flam, "-tool-flam.png" },
  39034. { lynx::NoteTool::lfo, "-tool-lfo.png" },
  39035. { lynx::NoteTool::claw, "-tool-claw.png" },
  39036. { lynx::NoteTool::articulate, "-tool-articulate.png" },
  39037. { lynx::NoteTool::riffMachine, "-tool-riff.png" },
  39038. { lynx::NoteTool::chordProgression, "-tool-chords.png" } };
  39039. for (const auto& [tool, name] : tools)
  39040. saveWindow (lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot()), name);
  39041. }
  39042. // round 83: the event editor, with sample events on the selected channel's volume (removed afterwards)
  39043. {
  39044. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::channelVolume, offline.getSelectedChannel() };
  39045. const auto before = offline.getSong().patterns[(std::size_t) offline.getSong().currentPattern].events;
  39046. offline.editSong ([&] (lynx::Song& s) {
  39047. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], volume);
  39048. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.2f, 0.9f, lynx::ticksPerStep);
  39049. lynx::prtools::LfoOptions lfo;
  39050. lfo.startSpeed = 7 * 4096; // one beat
  39051. lynx::eventedit::applyLfo (lane, lynx::ppq * 2, lynx::ppq * 4, lfo, lynx::ticksPerStep);
  39052. }, false);
  39053. saveWindow (lynx::makeEventEditor (offline, volume), "-eventeditor.png");
  39054. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  39055. // issue #86: the same editor on the Tempo target, with the project's own Tempo events (a sample ramp if none)
  39056. const lynx::AutomationTarget tempo { lynx::AutomationTargetKind::tempo, 0 };
  39057. offline.editSong ([&] (lynx::Song& s) {
  39058. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], tempo);
  39059. if (lane.events.empty())
  39060. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.05f, 0.11f, lynx::ticksPerStep);
  39061. }, false);
  39062. saveWindow (lynx::makeEventEditor (offline, tempo), "-eventeditor-tempo.png");
  39063. {
  39064. auto compact = lynx::makeEventEditor (offline, tempo); // the toolbar in a small window
  39065. compact->setSize (640, 300);
  39066. saveWindow (std::move (compact), "-eventeditor-tempo-small.png");
  39067. auto narrowest = lynx::makeEventEditor (offline, tempo); // the tool window's lower limit
  39068. narrowest->setSize (400, 300);
  39069. saveWindow (std::move (narrowest), "-eventeditor-tempo-narrowest.png");
  39070. }
  39071. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  39072. }
  39073. // round 86: the audio editor with a synthetic drum loop (markers, a region, a loop), waveform and spectrogram,
  39074. // and its menu items (-audioeditor-menu.txt)
  39075. {
  39076. namespace ae = lynx::audioedit;
  39077. ae::Document d;
  39078. d.title = "Drum loop";
  39079. d.audio.sampleRate = 44100.0;
  39080. const auto frames = (std::size_t) (44100 * 2);
  39081. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  39082. std::uint32_t seed = 7;
  39083. for (int hit = 0; hit < 8; ++hit)
  39084. {
  39085. const auto at = (std::size_t) hit * frames / 8;
  39086. const auto kick = hit % 2 == 0;
  39087. double phase = 0.0;
  39088. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  39089. {
  39090. seed = seed * 1664525u + 1013904223u;
  39091. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  39092. const auto t = (double) i / 44100.0;
  39093. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  39094. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  39095. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  39096. d.audio.channels[0][at + i] += v;
  39097. d.audio.channels[1][at + i] += kick ? v : v * 0.8f + 0.1f * noise * (float) std::exp (-t * 30.0);
  39098. }
  39099. }
  39100. ae::addMarker (d, (std::int64_t) frames / 8, "Snare");
  39101. ae::addRegion (d, { (std::int64_t) frames / 2, (std::int64_t) frames * 3 / 4 }, "Fill");
  39102. ae::setLoop (d, { 0, (std::int64_t) frames });
  39103. auto wave = lynx::makeAudioEditorForSnapshot (offline, d, false);
  39104. juce::File (prefix + "-audioeditor-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*wave).joinIntoString ("\n") + "\n");
  39105. saveWindow (std::move (wave), "-audioeditor.png");
  39106. saveWindow (lynx::makeAudioEditorForSnapshot (offline, d, true), "-audioeditor-spectrum.png");
  39107. }
  39108. // warp markers (round 175a, M3): the audio editor of the first audio clip whose channel has warp markers,
  39109. // opened as the Playlist opens it, with its warp lane
  39110. {
  39111. const auto& song = offline.getSong();
  39112. for (int i = 0; i < (int) song.playlist.size(); ++i)
  39113. {
  39114. const auto& c = song.playlist[(std::size_t) i];
  39115. if (c.kind == lynx::ClipKind::audio && juce::isPositiveAndBelow (c.channel, (int) song.channels.size())
  39116. && song.channels[(std::size_t) c.channel].sampler.warp.size() >= 3)
  39117. {
  39118. if (auto panel = lynx::makeAudioEditorPanel (offline, c.channel, i, true))
  39119. saveWindow (std::move (panel), "-audioeditor-warp.png");
  39120. break;
  39121. }
  39122. }
  39123. }
  39124. // the tempo tapper after five steady taps (round 132)
  39125. saveWindow (lynx::makeTempoTapperForSnapshot (offline, 5, 128.0), "-tempotapper.png");
  39126. // the Channel Rack's piano-roll view (round 132)
  39127. ui.selectTabForSnapshot (0);
  39128. ui.getRackForSnapshot().setPianoRollView (true);
  39129. offline.dispatchPendingMessages();
  39130. saveSnapshot (ui, prefix + "-rack-pianoroll-view.png");
  39131. ui.getRackForSnapshot().setPianoRollView (false);
  39132. // the Channel Rack with the step graph lane (velocity), and the Euclidean fill window
  39133. ui.selectTabForSnapshot (0);
  39134. ui.getRackForSnapshot().setGraphLevelForSnapshot (0);
  39135. offline.dispatchPendingMessages();
  39136. saveSnapshot (ui, prefix + "-rack-graph.png");
  39137. ui.getRackForSnapshot().setGraphLevelForSnapshot (1);
  39138. saveSnapshot (ui, prefix + "-rack-graph-pan.png");
  39139. // FL's Note pitch, Shift and Repeat lanes (issue #208)
  39140. ui.getRackForSnapshot().setGraphLevelForSnapshot ((int) lynx::notetools::Level::notePitch);
  39141. saveSnapshot (ui, prefix + "-rack-graph-pitch.png");
  39142. ui.getRackForSnapshot().setGraphLevelForSnapshot ((int) lynx::notetools::Level::shift);
  39143. saveSnapshot (ui, prefix + "-rack-graph-shift.png");
  39144. ui.getRackForSnapshot().setGraphLevelForSnapshot ((int) lynx::notetools::Level::repeat);
  39145. saveSnapshot (ui, prefix + "-rack-graph-repeat.png");
  39146. ui.getRackForSnapshot().toggleGraphLanes();
  39147. saveWindow (ui.getRackForSnapshot().makeEuclideanPanel (0), "-euclidean.png");
  39148. // the Mixer with three inserts selected and one armed for recording
  39149. ui.selectTabForSnapshot (3);
  39150. if (offline.getSong().mixer.size() > 4)
  39151. {
  39152. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 2);
  39153. offline.setInsertArmed (3, true);
  39154. offline.dispatchPendingMessages();
  39155. saveSnapshot (ui, prefix + "-mixer-multi.png");
  39156. // the armed insert with an audio input (its input row in the side panel, the level bar on the strip)
  39157. offline.editSong ([] (lynx::Song& s) { s.mixer[3].inputChannel = 0; });
  39158. ui.getMixerForSnapshot().selectTrack (3);
  39159. offline.dispatchPendingMessages();
  39160. saveSnapshot (ui, prefix + "-mixer-input.png");
  39161. offline.undo();
  39162. offline.setInsertArmed (3, false);
  39163. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({}, 0);
  39164. }
  39165. // the Mixer's routing lane: an insert with sends selected (send knobs and wires)
  39166. if (offline.getSong().mixer.size() > 6)
  39167. {
  39168. int source = -1;
  39169. for (int t = 1; t < (int) offline.getSong().mixer.size() && source < 0; ++t)
  39170. if (! offline.getSong().mixer[(std::size_t) t].sends.empty())
  39171. source = t;
  39172. const auto temporary = source < 0;
  39173. if (temporary) // the demo has no sends: add two for the picture
  39174. {
  39175. source = 1;
  39176. offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, true, 0.6f); s.setRoute (1, 6, true, 0.3f); s.setRoute (4, 1, true, 0.8f); });
  39177. }
  39178. ui.getMixerForSnapshot().selectTrack (source);
  39179. offline.dispatchPendingMessages();
  39180. saveSnapshot (ui, prefix + "-mixer-sends.png");
  39181. if (temporary)
  39182. offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, false); s.setRoute (1, 6, false); s.setRoute (4, 1, false); });
  39183. ui.getMixerForSnapshot().selectTrack (0);
  39184. }
  39185. // round 190io (issue #154 part 2): the Mixer view that lists each strip's insert effects (a LYNX view, off by
  39186. // default), with an insert selected whose sends light the route arrows
  39187. {
  39188. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  39189. strips.setShowStripInserts (true);
  39190. offline.dispatchPendingMessages();
  39191. saveSnapshot (ui, prefix + "-mixer190io-inserts.png");
  39192. strips.setShowStripInserts (false);
  39193. offline.dispatchPendingMessages();
  39194. }
  39195. // the Playlist with ripple editing on
  39196. ui.selectTabForSnapshot (2);
  39197. ui.getPlaylistForSnapshot().setRipple (true);
  39198. saveSnapshot (ui, prefix + "-playlist-ripple.png");
  39199. ui.getPlaylistForSnapshot().setRipple (false);
  39200. // FL's legacy Pattern Blocks (round 170f, issue #60): the section under the clip tracks, a row per pattern
  39201. {
  39202. const auto saved = offline.getSong();
  39203. offline.editSong ([] (lynx::Song& s) {
  39204. s.patternBlocksOn = true;
  39205. while (s.patterns.size() < 5) // a few rows to show (Drums, Bass...: copies of the demo's pattern)
  39206. lynx::clonePattern (s, (int) s.patterns.size() - 1);
  39207. const auto rows = juce::jmin (6, (int) s.patterns.size());
  39208. for (int r = 0; r < rows; ++r)
  39209. lynx::patternblocks::paintRange (s, r, (std::int64_t) (r % 3) * 4 * lynx::ppq * 2,
  39210. (std::int64_t) (8 + r * 2) * 4 * lynx::ppq);
  39211. }, false);
  39212. offline.dispatchPendingMessages();
  39213. saveSnapshot (ui, prefix + "-playlist-blocks.png");
  39214. // issue #127 (PR #132 and our follow-up): the Playlist's pencil, brush and eraser on the blocks, driven
  39215. // with real mouse events on the view. One picture per tool, and the gestures' results in
  39216. // <prefix>-playlist-blocks-tools.txt ("OK", or the checks that failed).
  39217. if (auto* blocks = ui.getPlaylistForSnapshot().getBlocksViewForSnapshot())
  39218. {
  39219. juce::StringArray failed;
  39220. const auto expect = [&failed] (bool ok, const char* what) { if (! ok) failed.add (what); };
  39221. const auto bar = offline.getSong().barTicks();
  39222. offline.editSong ([bar] (lynx::Song& s) {
  39223. s.blocks.clear();
  39224. for (std::size_t r = 0; r < 4 && r < s.patterns.size(); ++r)
  39225. s.patterns[r].lengthTicks = r == 1 ? 2 * bar : bar; // row 2 holds a 2-bar pattern
  39226. }, false);
  39227. offline.dispatchPendingMessages();
  39228. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  39229. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
  39230. juce::Point<float> pressedAt;
  39231. const auto event = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  39232. const auto at = blocks->pointForSnapshot (row, tick).toFloat();
  39233. const auto now = juce::Time::getCurrentTime();
  39234. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, 1, false);
  39235. };
  39236. const auto press = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  39237. pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
  39238. blocks->mouseDown (event (row, tick, mods));
  39239. };
  39240. const auto dragTo = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (event (row, tick, mods)); };
  39241. const auto release = [&] (int row, std::int64_t tick) { blocks->mouseUp (event (row, tick, {})); };
  39242. // the starts of row `row`'s blocks, as "0,2,5" (bars from 0)
  39243. const auto rowBars = [&] (int row) {
  39244. juce::StringArray bars;
  39245. for (const auto& b : offline.getSong().blocks)
  39246. if (b.pattern == row)
  39247. bars.add (juce::String (b.start / bar) + (b.start % bar != 0 ? "+" : ""));
  39248. return bars.joinIntoString (",");
  39249. };
  39250. auto& tools = ui.getPlaylistForSnapshot();
  39251. // Pencil: a press on empty space places one block that follows the mouse along its row
  39252. tools.setToolForSnapshot (lynx::EditTool::pencil);
  39253. press (0, 2 * bar + 40, left);
  39254. expect (rowBars (0) == "2", "pencil: a press places one block");
  39255. dragTo (2, 5 * bar + 40, left); // (over another row: the block stays in its own)
  39256. release (2, 5 * bar + 40);
  39257. expect (rowBars (0) == "5" && rowBars (2).isEmpty(), "pencil: the placed block follows the drag in its row");
  39258. // a 2-bar block grabbed by its second bar keeps that bar under the mouse (it used to jump a bar)
  39259. press (1, 1 * bar + 40, left);
  39260. release (1, 1 * bar + 40);
  39261. expect (rowBars (1) == "1", "pencil: a click places the 2-bar block");
  39262. press (1, 2 * bar + 40, left);
  39263. dragTo (1, 2 * bar + bar / 2, left);
  39264. expect (rowBars (1) == "1", "move: a small move on the grabbed bar leaves the block in place");
  39265. dragTo (1, 4 * bar + 40, left);
  39266. release (1, 4 * bar + 40);
  39267. expect (rowBars (1) == "3", "move: the grabbed bar stays under the mouse");
  39268. offline.dispatchPendingMessages();
  39269. saveSnapshot (ui, prefix + "-playlist-blocks-pencil.png");
  39270. // Brush: a drag over empty space paints a run; a press on a block moves it
  39271. tools.setToolForSnapshot (lynx::EditTool::brush);
  39272. press (2, 0, left);
  39273. dragTo (2, 3 * bar + 40, left);
  39274. release (2, 3 * bar + 40);
  39275. expect (rowBars (2) == "0,1,2,3", "brush: a drag paints a run");
  39276. press (2, 3 * bar + 40, left);
  39277. dragTo (2, 6 * bar + 40, left);
  39278. release (2, 6 * bar + 40);
  39279. expect (rowBars (2) == "0,1,2,6", "brush: a press on a block moves it");
  39280. offline.dispatchPendingMessages();
  39281. saveSnapshot (ui, prefix + "-playlist-blocks-brush.png");
  39282. // Eraser, and the right button with any tool: only the blocks under the mouse, row by row
  39283. offline.editSong ([bar] (lynx::Song& s) {
  39284. for (int r = 0; r < 4 && r < (int) s.patterns.size(); ++r)
  39285. lynx::patternblocks::place (s, r, 8 * bar);
  39286. }, false);
  39287. offline.dispatchPendingMessages();
  39288. expect (rowBars (0) == "5,8" && rowBars (3) == "8", "eraser: the column is set up");
  39289. saveSnapshot (ui, prefix + "-playlist-blocks-eraser-before.png");
  39290. tools.setToolForSnapshot (lynx::EditTool::eraser);
  39291. press (0, 8 * bar + 40, left);
  39292. expect (rowBars (0) == "5" && rowBars (1) == "3,8" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8",
  39293. "eraser: a click takes only the block under the mouse");
  39294. dragTo (1, 8 * bar + 60, left); // down one row: that row's block goes too, the rows below stay
  39295. release (1, 8 * bar + 60);
  39296. expect (rowBars (1) == "3" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8", "eraser: the drag erases the rows it crosses, no others");
  39297. tools.setToolForSnapshot (lynx::EditTool::pencil);
  39298. press (3, 8 * bar + 40, right);
  39299. release (3, 8 * bar + 40);
  39300. expect (rowBars (3).isEmpty() && rowBars (2) == "0,1,2,6,8", "right click: erases only the block under the mouse");
  39301. offline.dispatchPendingMessages();
  39302. saveSnapshot (ui, prefix + "-playlist-blocks-eraser.png");
  39303. juce::File (prefix + "-playlist-blocks-tools.txt").replaceWithText (failed.isEmpty() ? juce::String ("OK\n") : "ERROR\n" + failed.joinIntoString ("\n") + "\n");
  39304. }
  39305. offline.editSong ([saved] (lynx::Song& s) { s = saved; }, false);
  39306. offline.dispatchPendingMessages();
  39307. }
  39308. // quick-add palette, and the Browser searching
  39309. saveWindow (ui.makeQuickAddForSnapshot(), "-quickadd.png");
  39310. ui.showDesktopForSnapshot (false);
  39311. ui.getBrowserForSnapshot().setSearchForSnapshot ("kick");
  39312. offline.dispatchPendingMessages();
  39313. saveSnapshot (ui, prefix + "-browser-search.png");
  39314. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  39315. ui.getBrowserForSnapshot().selectFirstSampleForSnapshot(); // the tree with a sample selected and its waveform
  39316. offline.dispatchPendingMessages();
  39317. saveSnapshot (ui, prefix + "-browser-tree.png");
  39318. // the Browser's PROJECT tab: the patterns, generators and audio files of the project in their colours
  39319. ui.getBrowserForSnapshot().showProjectForSnapshot();
  39320. offline.dispatchPendingMessages();
  39321. saveSnapshot (ui, prefix + "-browser-project.png");
  39322. ui.getBrowserForSnapshot().showPluginDatabaseForSnapshot(); // round 142: the Plugin database's FL engines
  39323. offline.dispatchPendingMessages();
  39324. saveSnapshot (ui, prefix + "-browser-plugins.png");
  39325. // round 190bf (fl190be Q1): the Plugin database's right-click menus, a folder's and an entry's (FL's System group)
  39326. saveMenus (juce::StringArray { "Plugin database: folder", "Plugin database: entry" }, ui.getBrowserForSnapshot().pluginDatabaseMenusForSnapshot(),
  39327. prefix + "-browser190bf-menus.png");
  39328. ui.getBrowserForSnapshot().setTab (lynx::BrowserComponent::allTab);
  39329. saveWindow (ui.getBrowserForSnapshot().makeFoldersPanelForSnapshot(), "-browser-folders.png"); // round 164
  39330. {
  39331. // round 164: the content filter leaves out the folders with nothing to list (a small library)
  39332. const auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-library");
  39333. lib.deleteRecursively();
  39334. for (const auto* path : { "Drums/Kicks/kick 1.wav", "Drums/Kicks/kick 2.wav", "Drums/snare.wav", "Keys/pad.sf2", "Presets/Synth/lead.fst",
  39335. "Projects/beat.flp", "Projects/MIDI/chords.mid", "Notes/readme.txt", "Empty/Nothing/.keep" })
  39336. lib.getChildFile (path).create();
  39337. ui.showDesktopForSnapshot (false);
  39338. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  39339. offline.dispatchPendingMessages();
  39340. saveSnapshot (ui, prefix + "-browser164-all.png");
  39341. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::samples);
  39342. offline.dispatchPendingMessages();
  39343. saveSnapshot (ui, prefix + "-browser164-samples.png");
  39344. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::projects);
  39345. offline.dispatchPendingMessages();
  39346. saveSnapshot (ui, prefix + "-browser164-projects.png");
  39347. lib.deleteRecursively();
  39348. ui.getBrowserForSnapshot().resetViewForSnapshot();
  39349. }
  39350. {
  39351. // round 190as: "Find similar samples" on a small library of kicks, hats and pads (LYNX_SNAPSHOT_SIMILAR =
  39352. // "<folder>|<file>" lists a real folder instead)
  39353. auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-similar");
  39354. auto query = lib.getChildFile ("Drums/Kicks/Kick 2.wav");
  39355. const auto real = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIMILAR", {});
  39356. const auto made = real.isEmpty();
  39357. if (made)
  39358. {
  39359. lib.deleteRecursively();
  39360. juce::Random random (190);
  39361. const auto write = [&] (const juce::String& path, char kind, int v) {
  39362. const auto rate = 44100.0;
  39363. const auto frames = (int) (rate * (kind == 'k' ? 0.35 : kind == 'h' ? 0.09 : 2.5));
  39364. juce::AudioBuffer<float> audio (1, frames);
  39365. double phase = 0.0;
  39366. float last = 0.0f;
  39367. for (int i = 0; i < frames; ++i)
  39368. {
  39369. const auto t = i / rate;
  39370. float x = 0.0f;
  39371. if (kind == 'k')
  39372. {
  39373. phase += juce::MathConstants<double>::twoPi * ((46.0 + 3.0 * v) + 150.0 * std::exp (-t * 35.0)) / rate;
  39374. x = (float) (std::sin (phase) * std::exp (-t * (8.0 + v)));
  39375. }
  39376. else if (kind == 'h')
  39377. {
  39378. const auto n = random.nextFloat() * 2.0f - 1.0f;
  39379. x = (n - last) * 0.5f * (float) std::exp (-t * (50.0 + 12.0 * v));
  39380. last = n;
  39381. }
  39382. else
  39383. {
  39384. const auto base = 220.0 * std::pow (2.0, v / 12.0);
  39385. x = (float) (0.25 * std::min (1.0, t / 0.4) * std::min (1.0, (2.5 - t) / 0.5)
  39386. * (std::sin (juce::MathConstants<double>::twoPi * base * t) + std::sin (juce::MathConstants<double>::twoPi * base * 1.5 * t)));
  39387. }
  39388. audio.setSample (0, i, 0.8f * x);
  39389. }
  39390. const auto file = lib.getChildFile (path);
  39391. file.getParentDirectory().createDirectory();
  39392. juce::WavAudioFormat wav;
  39393. if (auto out = file.createOutputStream())
  39394. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (out.release(), rate, 1, 16, {}, 0)))
  39395. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  39396. };
  39397. for (int v = 1; v <= 5; ++v)
  39398. {
  39399. write ("Drums/Kicks/Kick " + juce::String (v) + ".wav", 'k', v);
  39400. write ("Drums/Hats/Hat " + juce::String (v) + ".wav", 'h', v);
  39401. write ("Keys/Pad " + juce::String (v) + ".wav", 'p', v);
  39402. }
  39403. }
  39404. else
  39405. {
  39406. lib = juce::File (real.upToFirstOccurrenceOf ("|", false, false));
  39407. query = juce::File (real.fromFirstOccurrenceOf ("|", false, false));
  39408. }
  39409. ui.showDesktopForSnapshot (false);
  39410. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  39411. ui.getBrowserForSnapshot().findSimilarForSnapshot (query, lib);
  39412. offline.dispatchPendingMessages();
  39413. saveSnapshot (ui, prefix + "-browser-similar.png");
  39414. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  39415. if (made)
  39416. lib.deleteRecursively();
  39417. ui.getBrowserForSnapshot().resetViewForSnapshot();
  39418. }
  39419. // the undo history after a few edits
  39420. offline.editSong ([] (lynx::Song& s) { s.bpm += 1.0; });
  39421. offline.editSong ([] (lynx::Song& s) { if (! s.channels.empty()) s.channels[0].muted = ! s.channels[0].muted; });
  39422. offline.editSong ([] (lynx::Song& s) { if (! s.patterns.empty()) s.patterns[(std::size_t) s.currentPattern].notes.push_back ({}); });
  39423. offline.undo();
  39424. saveWindow (lynx::makeHistoryPanel (offline), "-history.png");
  39425. // spectral waveforms: a synthetic beat (kick, hats, a chord, a noise riser) as audio clips in spectral
  39426. // colours, zoomed in, classic and stereo; the same file in the Sampler editor and the Browser preview
  39427. {
  39428. const juce::File wav (prefix + "-wavedemo.wav");
  39429. writeWaveDemo (wav, offline.getSong().bpm);
  39430. const auto path = wav.getFullPathName();
  39431. const auto pathUtf8 = path.toStdString();
  39432. int samplerChannel = -1, firstTrack = 0;
  39433. offline.editSong ([&] (lynx::Song& s) {
  39434. for (const auto& clip : s.playlist)
  39435. firstTrack = std::max (firstTrack, clip.track + 1);
  39436. lynx::ChannelDef audio;
  39437. audio.name = "Beat (audio)";
  39438. audio.instrument = lynx::InstrumentKind::audioClip;
  39439. audio.samplePath = pathUtf8;
  39440. s.channels.push_back (audio);
  39441. const auto audioChannel = (int) s.channels.size() - 1;
  39442. lynx::ChannelDef sampler = audio;
  39443. sampler.name = "Beat (sampler)";
  39444. sampler.instrument = lynx::InstrumentKind::sampler;
  39445. sampler.sampler.regionStart = 0.06f;
  39446. sampler.sampler.regionEnd = 0.94f;
  39447. s.channels.push_back (sampler);
  39448. samplerChannel = (int) s.channels.size() - 1;
  39449. const auto bar = s.barTicks();
  39450. const auto whole = (std::int64_t) std::llround (8.0 * s.bpm / 60.0 * lynx::ppq);
  39451. lynx::Clip clip;
  39452. clip.kind = lynx::ClipKind::audio;
  39453. clip.channel = audioChannel;
  39454. clip.track = firstTrack;
  39455. clip.length = whole;
  39456. s.playlist.push_back (clip);
  39457. clip.track = firstTrack + 1; // a slice of it, later in the song
  39458. clip.start = bar;
  39459. clip.offset = bar;
  39460. clip.length = 2 * bar;
  39461. s.playlist.push_back (clip);
  39462. // taller rows for the audio (tracks can be resized: P18)
  39463. if ((int) s.playlistTracks.size() < firstTrack + 2)
  39464. s.playlistTracks.resize ((std::size_t) firstTrack + 2);
  39465. s.playlistTracks[(std::size_t) firstTrack].height = 80;
  39466. s.playlistTracks[(std::size_t) firstTrack + 1].height = 60;
  39467. });
  39468. offline.dispatchPendingMessages();
  39469. auto& cache = *lynx::ui::WaveformCache::getInstance();
  39470. cache.find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  39471. cache.waitUntilIdle (30000);
  39472. ui.selectTabForSnapshot (2);
  39473. auto& playlist = ui.getPlaylistForSnapshot();
  39474. playlist.setTimeSelectionForSnapshot (0, 0);
  39475. {
  39476. // the Playlist alone (the floating Channel Rack would cover the clips)
  39477. auto saveSnapshot = [&playlist] (juce::Component&, const juce::String& file) { saveArea (playlist, playlist.getLocalBounds(), file); };
  39478. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  39479. saveSnapshot (ui, prefix + "-playlist-audio.png");
  39480. playlist.setViewForSnapshot (1400.0, 0, std::max (0, firstTrack - 3));
  39481. saveSnapshot (ui, prefix + "-playlist-audio-zoom.png");
  39482. lynx::ui::WaveformCache::stereo = true;
  39483. saveSnapshot (ui, prefix + "-playlist-audio-stereo.png");
  39484. lynx::ui::WaveformCache::stereo = false;
  39485. lynx::ui::WaveformCache::spectral = true;
  39486. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  39487. saveSnapshot (ui, prefix + "-playlist-audio-spectral.png");
  39488. lynx::ui::WaveformCache::spectral = false;
  39489. playlist.setViewForSnapshot (40.0, 0, 0);
  39490. saveSnapshot (ui, prefix + "-playlist-audio-far.png");
  39491. // LYNX_SNAPSHOT_AUDIO=a.wav;b.wav...: real audio as clips (default-height tracks, one tall,
  39492. // a fade, a reversed copy), at three zoom levels
  39493. if (const auto files = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_AUDIO", {}), ";", "");
  39494. ! files.isEmpty())
  39495. {
  39496. const auto realTrack = firstTrack + 2;
  39497. std::vector<juce::String> paths;
  39498. for (const auto& f : files)
  39499. if (juce::File (f.trim()).existsAsFile())
  39500. paths.push_back (f.trim());
  39501. offline.editSong ([&] (lynx::Song& s) {
  39502. const auto bar = s.barTicks();
  39503. const std::uint32_t colours[] = { 0, 0xffd9a441, 0xff6fb36a, 0xffb06fd0, 0xff5fb7c9, 0xffd06f6f };
  39504. for (std::size_t i = 0; i < paths.size(); ++i)
  39505. {
  39506. lynx::ChannelDef audio;
  39507. audio.name = juce::File (paths[i]).getFileNameWithoutExtension().toStdString();
  39508. audio.instrument = lynx::InstrumentKind::audioClip;
  39509. audio.samplePath = paths[i].toStdString();
  39510. audio.colour = colours[i % 6];
  39511. audio.sampler.stretchBeats = i % 2 == 0 ? 16.0f : 0.0f; // fitted to 4 bars, or as recorded
  39512. audio.sampler.keepPitch = true;
  39513. s.channels.push_back (audio);
  39514. lynx::Clip clip;
  39515. clip.kind = lynx::ClipKind::audio;
  39516. clip.channel = (int) s.channels.size() - 1;
  39517. clip.track = realTrack + (int) i;
  39518. clip.length = 4 * bar;
  39519. clip.fadeIn = i == 1 ? bar / 2 : 0;
  39520. s.playlist.push_back (clip);
  39521. clip.start = 4 * bar;
  39522. clip.fadeIn = 0;
  39523. clip.fadeOut = i == 0 ? bar : 0;
  39524. s.playlist.push_back (clip);
  39525. }
  39526. if ((int) s.playlistTracks.size() < realTrack + (int) paths.size())
  39527. s.playlistTracks.resize ((std::size_t) realTrack + paths.size());
  39528. if (! paths.empty())
  39529. s.playlistTracks[(std::size_t) realTrack].height = 90;
  39530. });
  39531. offline.dispatchPendingMessages();
  39532. for (const auto& path2 : paths)
  39533. cache.find (path2, [&offline, path2] { return offline.getSampleLibrary().load (path2); });
  39534. cache.waitUntilIdle (60000);
  39535. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  39536. saveSnapshot (ui, prefix + "-playlist-real.png");
  39537. playlist.setViewForSnapshot (700.0, 0, std::max (0, realTrack - 1));
  39538. saveSnapshot (ui, prefix + "-playlist-real-zoom.png");
  39539. playlist.setViewForSnapshot (2400.0, 0, std::max (0, realTrack - 1));
  39540. saveSnapshot (ui, prefix + "-playlist-real-close.png");
  39541. playlist.setViewForSnapshot (50.0, 0, std::max (0, realTrack - 4));
  39542. saveSnapshot (ui, prefix + "-playlist-real-far.png");
  39543. // the clip menu of the first real clip
  39544. if (const auto menu = playlist.getClipMenuForSnapshot ((int) offline.getSong().playlist.size() - (int) paths.size() * 2); menu.getNumItems() > 0)
  39545. saveMenus (juce::StringArray { "Audio clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-audio.png");
  39546. if (const auto menu = playlist.getClipMenuForSnapshot (0); menu.getNumItems() > 0)
  39547. saveMenus (juce::StringArray { "Pattern clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-pattern.png");
  39548. // the clip menu's actions, run through the menu itself; results in -clip-actions.txt
  39549. {
  39550. juce::StringArray log;
  39551. auto clipOf = [&offline] (const std::string& channelName, int nth) {
  39552. const auto& sg = offline.getSong();
  39553. for (int i = 0; i < (int) sg.playlist.size(); ++i)
  39554. {
  39555. const auto& c = sg.playlist[(std::size_t) i];
  39556. if (c.kind == lynx::ClipKind::audio && c.channel >= 0 && sg.channels[(std::size_t) c.channel].name == channelName && nth-- == 0)
  39557. return i;
  39558. }
  39559. return -1;
  39560. };
  39561. std::function<bool (const juce::PopupMenu&, const juce::String&)> run = [&run] (const juce::PopupMenu& m, const juce::String& text) {
  39562. for (juce::PopupMenu::MenuItemIterator it (m); it.next();)
  39563. {
  39564. auto& item = it.getItem();
  39565. if (item.subMenu != nullptr && run (*item.subMenu, text))
  39566. return true;
  39567. // (without the menu mnemonic's mark: FL's underlined letters, round 190dz)
  39568. if (item.text.removeCharacters (juce::String::charToString (1)).startsWith (text) && item.isEnabled && item.action)
  39569. {
  39570. item.action();
  39571. return true;
  39572. }
  39573. }
  39574. return false;
  39575. };
  39576. auto act = [&] (const std::string& name, int nth, const juce::String& text) {
  39577. const auto clip = clipOf (name, nth);
  39578. const auto ok = clip >= 0 && run (playlist.getClipMenuForSnapshot (clip), text);
  39579. offline.dispatchPendingMessages();
  39580. return ok;
  39581. };
  39582. auto channelOf = [&] (const std::string& name) -> const lynx::ChannelDef* {
  39583. for (const auto& c : offline.getSong().channels)
  39584. if (c.name == name)
  39585. return &c;
  39586. return nullptr;
  39587. };
  39588. auto check = [&log] (const juce::String& what, bool ok) { log.add ((ok ? "OK " : "FAIL ") + what); };
  39589. const auto names = [&] { std::vector<std::string> n; for (auto& p2 : paths) n.push_back (juce::File (p2).getFileNameWithoutExtension().toStdString()); return n; }();
  39590. if (names.size() >= 4)
  39591. {
  39592. const auto channelsBefore = offline.getSong().channels.size();
  39593. check ("Reverse", act (names[2], 0, lynx::tr ("Reverse")) && channelOf (names[2])->sampler.reverse);
  39594. offline.undo();
  39595. offline.dispatchPendingMessages();
  39596. check ("Reverse undone", ! channelOf (names[2])->sampler.reverse);
  39597. act (names[2], 0, lynx::tr ("Reverse"));
  39598. check ("Make unique", act (names[3], 1, lynx::tr ("Make unique")) && offline.getSong().channels.size() == channelsBefore + 1
  39599. && channelOf (names[3] + " #2") != nullptr);
  39600. check ("Fit to tempo, resample", act (names[1], 0, lynx::tr ("Fit to tempo, resample ({0})", { juce::String() }).upToFirstOccurrenceOf ("(", false, false))
  39601. && channelOf (names[1])->sampler.stretchBeats > 0.0f && ! channelOf (names[1])->sampler.keepPitch);
  39602. const auto gainBefore = offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain;
  39603. check ("Normalize", act (names[0], 1, lynx::tr ("Normalize"))
  39604. && offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain != gainBefore);
  39605. const auto clipsBefore = offline.getSong().playlist.size();
  39606. check ("Split here", act (names[3], 0, lynx::tr ("Split here")) && offline.getSong().playlist.size() == clipsBefore + 1);
  39607. check ("Mute", act (names[0], 0, lynx::tr ("Mute")) && offline.getSong().playlist[(std::size_t) clipOf (names[0], 0)].muted);
  39608. check ("Copy + Paste here", act (names[0], 0, lynx::tr ("Copy")) && act (names[0], 1, lynx::tr ("Paste here"))
  39609. && offline.getSong().playlist.size() == clipsBefore + 2);
  39610. check ("Delete", act (names[0], 2, lynx::tr ("Delete")) && offline.getSong().playlist.size() == clipsBefore + 1);
  39611. check ("Chop to grid", act (names[3], 0, lynx::tr ("Chop to grid")) && offline.getSong().playlist.size() > clipsBefore + 1);
  39612. }
  39613. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  39614. saveSnapshot (ui, prefix + "-playlist-real-actions.png");
  39615. juce::File (prefix + "-clip-actions.txt").replaceWithText (log.joinIntoString ("\n") + "\n");
  39616. }
  39617. }
  39618. }
  39619. saveWindow (lynx::makeChannelSettingsPanel (offline, samplerChannel), "-sampler-wave.png");
  39620. ui.showDesktopForSnapshot (false);
  39621. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  39622. saveSnapshot (ui, prefix + "-browser-preview.png");
  39623. }
  39624. }
  39625. // round 165o: every Label / button / tick box whose text the drawing squeezes below its minimum scale or cuts
  39626. // (an ellipsis), per language: `LYNX --lang de --snapshot shots/de` -> shots/de-textfit.txt
  39627. juce::File (prefix + "-textfit.txt").replaceWithText (textFitLog().joinIntoString ("\n") + "\n");
  39628. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  39629. quit();
  39630. }
  39631. // --snapshot: 8 s of a synthetic stereo beat whose parts sit in different bands (kick = low, chord = mid,
  39632. // hats and the noise riser = high), to show the spectral waveform colours
  39633. #include "BrowserShot190iz.inc" // round 190iz
  39634. #include "LynxModelShot190ni.inc" // round 190ni
  39635. #include "UndoGesture190jv.inc" // round 190jv
  39636. #include "TrimShot190jv.inc" // round 190jv
  39637. #include "PrChordShot190kd.inc" // round 190kd
  39638. #include "ModalShot190mc.inc" // round 190mc
  39639. #include "KeysShot190nu.inc" // round chord2_190nu
  39640. #include "SectionsShot190ol.inc" // round 190ol (research190oe P1 / P6)
  39641. #include "ChordLaneShot190pf.inc" // round 190pf (research190oe P13 / P12)
  39642. #include "PrShot190jv.inc" // round 190jv
  39643. #include "HostPlay190ll.inc" // round 190ll (issue #199)
  39644. #include "IssuesShot190ll.inc" // round 190ll (issues #200, #201, #203)
  39645. #include "IssuesShot190qr.inc" // round 190qr (issues #274-#281: the FL | LYNX pictures)
  39646. #include "SimpleGbShot190ke.inc" // round 190ke
  39647. #include "LoopShot190kf.inc" // round gaps190kf
  39648. #include "QaRest190lcShot.inc" // rollup 0.1.30 step 7 (round 190lc)
  39649. #include "LoopInfoShot190kx.inc" // round 190kx
  39650. static void writeWaveDemo (const juce::File& file, double bpm)
  39651. {
  39652. constexpr double rate = 44100.0;
  39653. const auto frames = (int) (8.0 * rate);
  39654. juce::AudioBuffer<float> buffer (2, frames);
  39655. buffer.clear();
  39656. auto* l = buffer.getWritePointer (0);
  39657. auto* r = buffer.getWritePointer (1);
  39658. const auto beat = 60.0 / juce::jlimit (40.0, 300.0, bpm);
  39659. std::uint32_t noise = 0x9e3779b9u;
  39660. auto white = [&noise] {
  39661. noise ^= noise << 13;
  39662. noise ^= noise >> 17;
  39663. noise ^= noise << 5;
  39664. return (float) (noise & 0xffffff) / (float) 0x800000 - 1.0f;
  39665. };
  39666. float previous = 0.0f;
  39667. for (int i = 0; i < frames; ++i)
  39668. {
  39669. const auto t = i / rate;
  39670. const auto inBeat = std::fmod (t, beat);
  39671. const auto bar = (int) (t / (beat * 4.0));
  39672. float left = 0.0f, right = 0.0f;
  39673. // kick on every beat: a falling sine
  39674. {
  39675. const auto phase = 2.0 * juce::MathConstants<double>::pi * (48.0 * inBeat + 4.0 * (1.0 - std::exp (-inBeat * 30.0)));
  39676. const auto k = (float) (std::sin (phase) * std::exp (-inBeat * 7.0)) * 0.85f;
  39677. left += k;
  39678. right += k;
  39679. }
  39680. // hats on the off-beats: high-passed noise bursts, a little to the right
  39681. {
  39682. const auto h = std::fmod (t + beat * 0.5, beat);
  39683. const auto n = white();
  39684. const auto hp = (n - previous) * 0.5f;
  39685. previous = n;
  39686. const auto hat = hp * (float) std::exp (-h * 45.0) * 0.55f;
  39687. left += hat * 0.6f;
  39688. right += hat;
  39689. }
  39690. // a chord in the second and third bars (mid band)
  39691. if (bar == 1 || bar == 2)
  39692. {
  39693. const auto env = (float) std::min (1.0, std::min (t - beat * 4.0, beat * 12.0 - t) * 8.0);
  39694. float chord = 0.0f;
  39695. for (const auto hz : { 523.25, 659.25, 783.99 })
  39696. chord += (float) (std::sin (2.0 * juce::MathConstants<double>::pi * hz * t) + 0.3 * std::sin (4.0 * juce::MathConstants<double>::pi * hz * t));
  39697. left += chord * 0.09f * std::max (0.0f, env);
  39698. right += chord * 0.09f * std::max (0.0f, env);
  39699. }
  39700. // a white-noise riser over the last two seconds (high band)
  39701. if (t > 6.0)
  39702. {
  39703. const auto rise = (float) ((t - 6.0) / 2.0);
  39704. left += white() * 0.4f * rise * rise;
  39705. right += white() * 0.4f * rise * rise;
  39706. }
  39707. l[i] = left;
  39708. r[i] = right;
  39709. }
  39710. buffer.applyGain (0.9f / juce::jmax (1.0e-6f, buffer.getMagnitude (0, frames)));
  39711. file.deleteFile();
  39712. juce::WavAudioFormat wav;
  39713. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0) })
  39714. writer->writeFromAudioSampleBuffer (buffer, 0, frames);
  39715. }
  39716. // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
  39717. static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
  39718. {
  39719. const auto names = ui.getMenuNamesForSnapshot();
  39720. std::vector<juce::PopupMenu> source;
  39721. for (int m = 0; m < names.size(); ++m)
  39722. source.push_back (ui.getMenuForSnapshot (m));
  39723. saveMenus (names, source, path);
  39724. }
  39725. // menus side by side, each under its name, in the columns JUCE shows them in: its own column breaks, or (round 190je,
  39726. // cmake/LynxPatchJuce.cmake fix 40) the split of a menu taller than 70 % of a 1080 px screen
  39727. static void saveMenus (const juce::StringArray& names, const std::vector<juce::PopupMenu>& source, const juce::String& path)
  39728. {
  39729. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  39730. struct Row
  39731. {
  39732. const juce::PopupMenu::Item* item;
  39733. int height;
  39734. };
  39735. struct Laid
  39736. {
  39737. juce::PopupMenu menu;
  39738. std::vector<std::vector<Row>> columns;
  39739. std::vector<int> widths;
  39740. int width = 0, height = 0;
  39741. };
  39742. std::vector<Laid> menus;
  39743. menus.reserve ((std::size_t) names.size());
  39744. const auto border = lf.getPopupMenuBorderSize();
  39745. const auto separatorWidth = lf.getPopupMenuColumnSeparatorWidthWithOptions (juce::PopupMenu::Options());
  39746. for (int m = 0; m < names.size(); ++m)
  39747. {
  39748. menus.push_back (Laid { source[(std::size_t) m] });
  39749. auto& laid = menus.back();
  39750. std::vector<Row> rows;
  39751. std::vector<lynx::themes::MenuRow> shape;
  39752. std::vector<int> breaks;
  39753. for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
  39754. {
  39755. const auto& item = it.getItem();
  39756. int w = 0, h = 0;
  39757. if (item.customComponent != nullptr)
  39758. item.customComponent->getIdealSize (w, h); // (a title band: its own height, as JUCE asks it)
  39759. else
  39760. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  39761. if (item.isSectionHeader) h += h / 2; // as JUCE does
  39762. rows.push_back ({ &item, h });
  39763. shape.push_back ({ h, item.isSeparator, item.isSectionHeader });
  39764. if (item.shouldBreakAfter)
  39765. breaks.push_back ((int) rows.size() - 1);
  39766. }
  39767. if (breaks.empty())
  39768. if (const auto at = lynx::themes::tallMenuBreak (shape, 1080 * 7 / 10); at >= 0)
  39769. breaks.push_back (at);
  39770. laid.columns.emplace_back();
  39771. laid.widths.push_back (160);
  39772. for (int i = 0; i < (int) rows.size(); ++i)
  39773. {
  39774. const auto& item = *rows[(std::size_t) i].item;
  39775. int w = 0, h = 0;
  39776. if (item.customComponent != nullptr)
  39777. item.customComponent->getIdealSize (w, h);
  39778. else
  39779. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  39780. if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
  39781. w += 90;
  39782. laid.columns.back().push_back (rows[(std::size_t) i]);
  39783. laid.widths.back() = juce::jmax (laid.widths.back(), w + 10);
  39784. if (std::find (breaks.begin(), breaks.end(), i) != breaks.end() && i + 1 < (int) rows.size())
  39785. {
  39786. laid.columns.emplace_back();
  39787. laid.widths.push_back (160);
  39788. }
  39789. }
  39790. laid.width = (int) (laid.columns.size() - 1) * separatorWidth;
  39791. for (std::size_t c = 0; c < laid.columns.size(); ++c)
  39792. {
  39793. laid.width += laid.widths[c];
  39794. int h = 2 * border;
  39795. for (const auto& row : laid.columns[c])
  39796. h += row.height;
  39797. laid.height = juce::jmax (laid.height, h);
  39798. }
  39799. }
  39800. int totalWidth = 16, totalHeight = 0;
  39801. for (const auto& l : menus)
  39802. {
  39803. totalWidth += l.width + 16;
  39804. totalHeight = juce::jmax (totalHeight, l.height + 32);
  39805. }
  39806. auto image = lynx::shot::canvas (totalWidth, totalHeight);
  39807. {
  39808. juce::Graphics g (image);
  39809. lynx::shot::logical (g);
  39810. g.fillAll (lynx::theme::colour::bg1);
  39811. int x = 16;
  39812. bool first = true;
  39813. for (int m = 0; m < (int) menus.size(); ++m)
  39814. {
  39815. const auto& l = menus[(std::size_t) m];
  39816. g.setColour (lynx::theme::colour::textSecondary);
  39817. g.setFont (lynx::theme::font (lynx::theme::type::small, true));
  39818. g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
  39819. {
  39820. juce::Graphics::ScopedSaveState state (g);
  39821. g.reduceClipRegion (x, 24, l.width, l.height);
  39822. g.setOrigin (x, 24);
  39823. lf.drawPopupMenuBackground (g, l.width, l.height);
  39824. int columnX = 0;
  39825. for (std::size_t c = 0; c < l.columns.size(); ++c)
  39826. {
  39827. int y = border;
  39828. for (const auto& row : l.columns[c])
  39829. {
  39830. const auto& item = *row.item;
  39831. const juce::Rectangle<int> r (columnX + (c == 0 ? border : 0), y, l.widths[c] - (c == 0 ? border : 0) - (c + 1 == l.columns.size() ? border : 0),
  39832. row.height);
  39833. auto text = item.text, shortcut = item.shortcutKeyDescription;
  39834. if (text.containsChar ('\t'))
  39835. {
  39836. shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
  39837. text = text.upToFirstOccurrenceOf ("\t", false, false);
  39838. }
  39839. if (item.isSectionHeader)
  39840. lf.drawPopupMenuSectionHeader (g, r, text);
  39841. else if (item.customComponent != nullptr)
  39842. {
  39843. juce::Graphics::ScopedSaveState itemState (g);
  39844. g.setOrigin (r.getPosition());
  39845. item.customComponent->setSize (r.getWidth(), r.getHeight());
  39846. item.customComponent->paintEntireComponent (g, false);
  39847. }
  39848. else
  39849. lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
  39850. item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
  39851. first = false;
  39852. y += row.height;
  39853. }
  39854. columnX += l.widths[c];
  39855. if (c + 1 < l.columns.size())
  39856. {
  39857. lf.drawPopupMenuColumnSeparatorWithOptions (g, juce::Rectangle<int> (columnX, border, separatorWidth, l.height - 2 * border),
  39858. juce::PopupMenu::Options());
  39859. columnX += separatorWidth;
  39860. }
  39861. }
  39862. }
  39863. x += l.width + 16;
  39864. }
  39865. }
  39866. const auto file = lynx::shot::file (juce::File (path));
  39867. file.deleteFile();
  39868. juce::PNGImageFormat png;
  39869. if (auto out = file.createOutputStream())
  39870. png.writeImageToStream (image, *out);
  39871. }
  39872. static void writePng (const juce::Image& image, const juce::String& path)
  39873. {
  39874. const auto file = lynx::shot::file (juce::File (path));
  39875. file.deleteFile();
  39876. juce::PNGImageFormat png;
  39877. if (auto out = file.createOutputStream())
  39878. png.writeImageToStream (image, *out);
  39879. }
  39880. // the splash screen: one settled frame, and a strip of frames through its animation
  39881. static void saveSplashFrames (const juce::String& prefix)
  39882. {
  39883. lynx::SplashScreen splash;
  39884. splash.setStatus (lynx::tr ("Loading the workspace..."));
  39885. splash.setTimeForSnapshot (1.6);
  39886. writePng (lynx::shot::snapshot (splash), prefix + "-splash.png");
  39887. const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
  39888. const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
  39889. auto strip = lynx::shot::canvas (4 * (w + 8) + 8, 2 * (h + 8) + 8);
  39890. {
  39891. juce::Graphics g (strip);
  39892. lynx::shot::logical (g);
  39893. g.fillAll (lynx::theme::colour::bg1);
  39894. for (int i = 0; i < 8; ++i)
  39895. {
  39896. splash.setTimeForSnapshot (times[i]);
  39897. const auto frame = lynx::shot::snapshot (splash);
  39898. g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
  39899. }
  39900. }
  39901. writePng (strip, prefix + "-splash-frames.png");
  39902. }
  39903. // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
  39904. // colours: at rest, hovered and switched on
  39905. // round 190je (design190ia G1): one state sheet per button kind: idle, hover, pressed, on, disabled, as the one state rule
  39906. // draws them (core/ThemePalette.h buttonLook); the menu rows in both menu styles
  39907. static void saveStateSheet (const juce::String& path, float scale)
  39908. {
  39909. using namespace lynx;
  39910. scale *= shot::scale();
  39911. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  39912. const int labelWidth = 220, cellW = 120, cellH = 40, columns = 5;
  39913. const juce::String heads[] = { "idle", "hover", "pressed", "on", "disabled" };
  39914. enum Kind { text, iconFilled, iconOnce, iconSwitch, iconSwitchOwn, tick, radio, combo, tab, menuDark, menuFl, kinds };
  39915. const char* names[] = { "Text button", "Icon button (filled)", "Toolbar icon (acts once)", "Toolbar switch", "Toolbar switch (own colours)",
  39916. "Tick box", "Radio choice", "Combo box", "Tab", "Menu item (LYNX dark)", "Menu item (FL classic)" };
  39917. const auto w = labelWidth + columns * cellW + 16, h = 30 + kinds * cellH + 16;
  39918. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  39919. {
  39920. juce::Graphics g (image);
  39921. g.addTransform (juce::AffineTransform::scale (scale));
  39922. g.fillAll (theme::colour::bg3);
  39923. g.setFont (theme::font (theme::type::small, true));
  39924. g.setColour (theme::colour::textSecondary);
  39925. for (int c = 0; c < columns; ++c)
  39926. g.drawText (heads[c], labelWidth + c * cellW, 6, cellW, 20, juce::Justification::centred);
  39927. const auto styleBefore = theme::menus::style();
  39928. for (int k = 0; k < kinds; ++k)
  39929. {
  39930. const auto y = 30 + k * cellH;
  39931. g.setFont (theme::font (theme::type::small));
  39932. g.setColour (theme::colour::textPrimary);
  39933. g.drawText (names[k], 8, y, labelWidth - 12, cellH, juce::Justification::centredLeft);
  39934. for (int c = 0; c < columns; ++c)
  39935. {
  39936. const auto hover = c == 1, down = c == 2, on = c == 3, disabled = c == 4;
  39937. const juce::Rectangle<int> cell (labelWidth + c * cellW, y, cellW, cellH);
  39938. juce::Graphics::ScopedSaveState state (g);
  39939. g.reduceClipRegion (cell);
  39940. switch (k)
  39941. {
  39942. case text:
  39943. {
  39944. juce::TextButton b ("Export");
  39945. b.setSize (96, 26);
  39946. b.setToggleState (on, juce::dontSendNotification);
  39947. b.setEnabled (! disabled);
  39948. g.setOrigin (cell.getX() + 12, cell.getY() + 7);
  39949. lf.drawButtonBackground (g, b, b.findColour (on ? juce::TextButton::buttonOnColourId : juce::TextButton::buttonColourId), hover, down);
  39950. lf.drawButtonText (g, b, hover, down);
  39951. break;
  39952. }
  39953. case iconFilled:
  39954. case iconOnce:
  39955. case iconSwitch:
  39956. case iconSwitchOwn:
  39957. {
  39958. IconButton b ("state", k == iconFilled ? Icon::plus : k == iconOnce ? Icon::save : Icon::metronome);
  39959. b.setFlat (k != iconFilled);
  39960. if (k == iconSwitch)
  39961. b.setToggleLook (true);
  39962. if (k == iconSwitchOwn)
  39963. {
  39964. b.setOnColour (theme::colour::bg6);
  39965. b.setIconColourWhenOn (theme::colour::accent);
  39966. }
  39967. b.setSize (k == iconFilled ? 34 : 30, 30);
  39968. b.setToggleState (on, juce::dontSendNotification);
  39969. b.setEnabled (! disabled);
  39970. g.setOrigin (cell.getX() + 12, cell.getY() + 5);
  39971. b.paintButton (g, hover, down);
  39972. break;
  39973. }
  39974. case tick:
  39975. case radio:
  39976. {
  39977. juce::ToggleButton b (k == tick ? "Snap to grid" : "Pattern");
  39978. if (k == radio)
  39979. b.getProperties().set ("lynxRadio", true);
  39980. b.setSize (110, 24);
  39981. b.setToggleState (on, juce::dontSendNotification);
  39982. b.setEnabled (! disabled);
  39983. g.setOrigin (cell.getX() + 6, cell.getY() + 8);
  39984. lf.drawToggleButton (g, b, hover, down);
  39985. break;
  39986. }
  39987. case combo:
  39988. {
  39989. if (hover || down || on) // (a combo box's hover comes from the mouse itself: --uitest covers it)
  39990. break;
  39991. juce::ComboBox b;
  39992. b.setSize (100, 24);
  39993. b.setEnabled (! disabled);
  39994. g.setOrigin (cell.getX() + 10, cell.getY() + 8);
  39995. lf.drawComboBox (g, 100, 24, false, 0, 0, 0, 0, b);
  39996. g.setColour (disabled ? theme::colour::textDisabled : theme::colour::textPrimary);
  39997. g.setFont (lf.getComboBoxFont (b));
  39998. g.drawText ("1/16 step", 6, 0, 70, 24, juce::Justification::centredLeft);
  39999. break;
  40000. }
  40001. case tab:
  40002. {
  40003. if (disabled)
  40004. break;
  40005. juce::TabbedButtonBar bar (juce::TabbedButtonBar::TabsAtTop);
  40006. bar.setSize (220, 32);
  40007. bar.addTab ("Audio", theme::colour::bg2, -1);
  40008. bar.addTab ("MIDI", theme::colour::bg2, -1);
  40009. bar.setCurrentTabIndex (on ? 1 : 0, false);
  40010. auto* tabButton = bar.getTabButton (1);
  40011. tabButton->setBounds (0, 0, 100, 32);
  40012. g.setOrigin (cell.getX() + 10, cell.getY() + 4);
  40013. g.setColour (theme::colour::bg1);
  40014. g.fillRect (0, 0, 100, 32);
  40015. lf.drawTabButton (*tabButton, g, hover, down);
  40016. break;
  40017. }
  40018. case menuDark:
  40019. case menuFl:
  40020. {
  40021. if (down)
  40022. break;
  40023. theme::menus::setStyle (k == menuFl ? themes::MenuStyle::flClassic : themes::MenuStyle::lynxDark);
  40024. g.setOrigin (cell.getX() + 4, cell.getY() + 8);
  40025. lf.drawPopupMenuBackground (g, 112, 25);
  40026. lf.drawPopupMenuItem (g, { 2, 2, 108, 21 }, false, ! disabled, hover, on, false, theme::mnemonic ("Open", 'O'), "Ctrl+O", nullptr, nullptr);
  40027. theme::menus::setStyle (styleBefore);
  40028. break;
  40029. }
  40030. default:
  40031. break;
  40032. }
  40033. }
  40034. }
  40035. }
  40036. writePng (image, path);
  40037. }
  40038. static void saveIconSheet (const juce::String& path, float scale)
  40039. {
  40040. scale *= lynx::shot::scale();
  40041. const int sizes[] = { 16, 20, 24 };
  40042. const int cell = 34, columns = 3 * 3, labelWidth = 110;
  40043. const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
  40044. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  40045. {
  40046. juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
  40047. g.addTransform (juce::AffineTransform::scale (scale));
  40048. g.fillAll (lynx::theme::colour::bg3);
  40049. g.setFont (lynx::theme::font (lynx::theme::type::small));
  40050. for (int i = 1; i < lynx::iconCount; ++i)
  40051. {
  40052. const auto y = 8 + (i - 1) * cell;
  40053. g.setColour (lynx::theme::colour::textDisabled);
  40054. g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
  40055. for (int v = 0; v < 3; ++v)
  40056. for (int s = 0; s < 3; ++s)
  40057. {
  40058. const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
  40059. const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
  40060. g.setColour (bg);
  40061. g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
  40062. const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
  40063. : lynx::theme::colour::textSecondary.brighter (0.25f);
  40064. lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
  40065. }
  40066. }
  40067. }
  40068. writePng (image, path);
  40069. }
  40070. // a part of a component (e.g. the main toolbar)
  40071. static void saveArea (juce::Component& c, juce::Rectangle<int> area, const juce::String& path)
  40072. {
  40073. const auto file = lynx::shot::file (juce::File (path));
  40074. file.deleteFile();
  40075. juce::PNGImageFormat png;
  40076. if (auto out = file.createOutputStream())
  40077. png.writeImageToStream (lynx::shot::snapshot (c, area), *out);
  40078. }
  40079. static void savePng (const juce::Image& image, const juce::String& path)
  40080. {
  40081. const auto file = lynx::shot::file (juce::File (path));
  40082. file.deleteFile();
  40083. juce::PNGImageFormat png;
  40084. if (auto out = file.createOutputStream())
  40085. png.writeImageToStream (image, *out);
  40086. }
  40087. // -toolbar-tips.png: the top of the window with the bubbles of a few controls as they appear under the
  40088. // mouse; -tips-sheet.png: every quick tip of the window, to check names, shortcuts and translations
  40089. static void saveQuickTips (lynx::MainComponent& ui, const juce::String& prefix)
  40090. {
  40091. const auto tips = ui.getQuickTipsForSnapshot();
  40092. const auto top = juce::Rectangle<int> (0, 0, ui.getWidth(), juce::jmin (ui.getHeight(), ui.getToolbarBoundsForSnapshot().getHeight() + 72));
  40093. auto image = lynx::shot::snapshot (ui, top);
  40094. {
  40095. juce::Graphics g (image);
  40096. lynx::shot::logical (g);
  40097. const juce::String shown[] = { lynx::tr ("Pattern mode"), lynx::tr ("Play"), lynx::tr ("Metronome"), lynx::tr ("Mixer"), lynx::tr ("Save project"),
  40098. lynx::tr ("Window options"), lynx::tr ("Close") };
  40099. std::vector<juce::Rectangle<int>> used;
  40100. for (const auto& [area, tip] : tips)
  40101. {
  40102. const auto name = tip.upToFirstOccurrenceOf ("\t", false, false);
  40103. if (std::find (std::begin (shown), std::end (shown), name) == std::end (shown))
  40104. continue;
  40105. const auto bubble = lynx::ui::quickTipBounds (tip, area, top);
  40106. if (std::any_of (used.begin(), used.end(), [&] (const auto& r) { return r.intersects (bubble); }))
  40107. continue;
  40108. used.push_back (bubble);
  40109. g.setColour (juce::Colours::white.withAlpha (0.075f)); // the hovered control
  40110. g.fillRoundedRectangle (area.toFloat().reduced (0.5f), lynx::theme::radius::md);
  40111. lynx::ui::paintQuickTip (g, bubble.toFloat(), tip);
  40112. }
  40113. }
  40114. savePng (image, prefix + "-toolbar-tips.png");
  40115. // the sheet: bubbles in rows
  40116. const int width = 900;
  40117. int x = 12, y = 12;
  40118. std::vector<std::pair<juce::Rectangle<int>, juce::String>> placed;
  40119. for (const auto& [area, tip] : tips)
  40120. {
  40121. auto r = lynx::ui::quickTipSize (tip);
  40122. if (x + r.getWidth() > width - 12)
  40123. {
  40124. x = 12;
  40125. y += r.getHeight() + 10;
  40126. }
  40127. placed.emplace_back (r.withPosition (x, y), tip);
  40128. x += r.getWidth() + 10;
  40129. }
  40130. auto sheet = lynx::shot::canvas (width, y + 20 + 12);
  40131. {
  40132. juce::Graphics g (sheet);
  40133. lynx::shot::logical (g);
  40134. g.fillAll (lynx::theme::colour::bg3);
  40135. for (const auto& [r, tip] : placed)
  40136. lynx::ui::paintQuickTip (g, r.toFloat(), tip);
  40137. }
  40138. savePng (sheet, prefix + "-tips-sheet.png");
  40139. }
  40140. static juce::StringArray& textFitLog()
  40141. {
  40142. static juce::StringArray log;
  40143. return log;
  40144. }
  40145. // drawFittedText would shrink `text` below `minScale` or cut it: fewer visible glyphs than the text has
  40146. static bool textIsCut (const juce::Font& font, const juce::String& text, juce::Rectangle<int> area, int maxLines, float minScale)
  40147. {
  40148. if (text.trim().isEmpty() || area.getWidth() <= 4 || area.getHeight() <= 4)
  40149. return false;
  40150. auto visible = [] (juce::GlyphArrangement& ga) {
  40151. int n = 0;
  40152. for (int i = 0; i < ga.getNumGlyphs(); ++i)
  40153. n += ga.getGlyph (i).isWhitespace() ? 0 : 1;
  40154. return n;
  40155. };
  40156. juce::GlyphArrangement fitted, full;
  40157. fitted.addFittedText (font, text, 0.0f, 0.0f, (float) area.getWidth(), (float) area.getHeight(), juce::Justification::centredLeft,
  40158. juce::jmax (1, maxLines), minScale);
  40159. full.addLineOfText (font, text, 0.0f, 0.0f);
  40160. return visible (fitted) < visible (full);
  40161. }
  40162. // walks the visible components under `root` and logs the texts that don't fit (labels, text buttons, tick boxes)
  40163. static void checkTextFit (juce::Component& root, const juce::String& where)
  40164. {
  40165. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  40166. if (! c.isVisible() || c.getWidth() <= 0 || c.getHeight() <= 0)
  40167. return;
  40168. juce::String text;
  40169. bool cut = false;
  40170. if (auto* label = dynamic_cast<juce::Label*> (&c); label != nullptr && ! label->isBeingEdited())
  40171. {
  40172. const auto font = label->getLookAndFeel().getLabelFont (*label);
  40173. const auto area = label->getBorderSize().subtractedFrom (label->getLocalBounds());
  40174. text = label->getText();
  40175. cut = textIsCut (font, text, area, juce::jmax (1, (int) ((float) area.getHeight() / font.getHeight())),
  40176. label->getMinimumHorizontalScale());
  40177. }
  40178. else if (auto* toggle = dynamic_cast<juce::ToggleButton*> (&c))
  40179. {
  40180. const auto tick = juce::jmin (16.0f, (float) c.getHeight() - 4.0f);
  40181. text = toggle->getButtonText();
  40182. cut = textIsCut (juce::Font (lynx::theme::font (juce::jmin ((float) lynx::theme::type::body, (float) c.getHeight() * 0.75f))), text,
  40183. c.getLocalBounds().withTrimmedLeft (juce::roundToInt (tick) + 8).withTrimmedRight (2), 2, 0.85f);
  40184. }
  40185. else if (auto* button = dynamic_cast<juce::TextButton*> (&c);
  40186. button != nullptr && (int) button->getProperties().getWithDefault (lynx::theme::LookAndFeel::iconProperty, 0) == 0)
  40187. {
  40188. text = button->getButtonText();
  40189. cut = textIsCut (button->getLookAndFeel().getTextButtonFont (*button, button->getHeight()), text,
  40190. button->getLocalBounds().reduced (juce::jmin (8, button->getWidth() / 6), 0), 2, 0.85f);
  40191. }
  40192. if (cut)
  40193. {
  40194. juce::String path;
  40195. for (auto* p = &c; p != nullptr && p != &root; p = p->getParentComponent())
  40196. if (p->getName().isNotEmpty())
  40197. path = p->getName() + (path.isEmpty() ? "" : "/") + path;
  40198. const auto line = where + " | " + juce::String (c.getWidth()) + "x" + juce::String (c.getHeight()) + " | " + text.replace ("\n", "\\n")
  40199. + (path.isEmpty() ? juce::String() : " | " + path);
  40200. textFitLog().addIfNotAlreadyThere (line);
  40201. }
  40202. for (auto* child : c.getChildren())
  40203. visit (*child);
  40204. };
  40205. visit (root);
  40206. }
  40207. static void saveSnapshot (juce::Component& c, const juce::String& path)
  40208. {
  40209. checkTextFit (c, juce::File (path).getFileNameWithoutExtension());
  40210. const auto file = lynx::shot::file (juce::File (path));
  40211. file.deleteFile();
  40212. juce::PNGImageFormat png;
  40213. if (auto out = file.createOutputStream())
  40214. png.writeImageToStream (lynx::shot::snapshot (c), *out);
  40215. }
  40216. class MainWindow final : public juce::DocumentWindow
  40217. {
  40218. public:
  40219. MainWindow (const juce::String& name, lynx::AudioEngine& engine)
  40220. : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons, false)
  40221. {
  40222. probeEngine = &engine;
  40223. // (round 190hd) one desktop window, made with the native title bar: before, JUCE made one with its own title
  40224. // bar and setUsingNativeTitleBar made it again (~20-35 ms each, the Direct2D context included)
  40225. setUsingNativeTitleBar (true);
  40226. addToDesktop();
  40227. setIcon (lynx::logoImage());
  40228. startupTrace.mark (" window: its desktop window (native title bar), icon");
  40229. content = new lynx::MainComponent (engine);
  40230. setContentOwned (content, true);
  40231. startupTrace.mark (" window: content set");
  40232. setResizable (true, true);
  40233. setResizeLimits (800, 400, 10000, 10000);
  40234. // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
  40235. // display: the AppImage catalog test runs on an 800x600 screen)
  40236. if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
  40237. {
  40238. const auto area = display->userArea;
  40239. const auto fit = [] (int design, int available) {
  40240. return juce::jmin (available, juce::jmax (design, (int) (available * 0.88)));
  40241. };
  40242. setSize (fit (getWidth(), area.getWidth()), fit (getHeight(), area.getHeight()));
  40243. }
  40244. centreWithSize (getWidth(), getHeight());
  40245. // where it was last time (round 167v); the first start opens maximized, the Playlist filling the screen
  40246. // with the Browser at the left and the Channel Rack above it, like FL Studio's first start
  40247. const auto saved = stateFile().loadFileAsString().trim();
  40248. // (LYNX_TEST_MODE keeps the fixed-size window scripted checks expect, unless LYNX_TEST_MAXIMIZE=1)
  40249. const auto firstStart = saved.isEmpty()
  40250. && (! lynx::platform::testMode() || juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MAXIMIZE", {}) == "1");
  40251. maximiseOnReveal = firstStart || saved.startsWithIgnoreCase ("fs");
  40252. if (saved.isNotEmpty())
  40253. restoreWindowStateFromString (saved.startsWithIgnoreCase ("fs") ? saved.substring (2).trim() : saved);
  40254. }
  40255. // Shows the window (built hidden while the splash screen is up).
  40256. void reveal()
  40257. {
  40258. if (lynx::uitrace::enabled()) // LYNX_TRACE_UI: the frames per second and the longest gap in ui.log (round 173f)
  40259. watchFrames ({});
  40260. setVisible (true);
  40261. // LYNX_LOCATOR_PROBE=1 (round 190ip, measurements): a floating window with a locator moving 30 times a second
  40262. if (juce::SystemStats::getEnvironmentVariable ("LYNX_LOCATOR_PROBE", {}) == "1")
  40263. juce::Timer::callAfterDelay (1500, [e = probeEngine] {
  40264. lynx::ui::openLocatorProbe ([e] {
  40265. const auto& transport = e->getTransport();
  40266. const auto bar = (double) juce::jmax<std::int64_t> (1, e->getSong().barTicks());
  40267. return transport.playing.load() ? std::fmod (transport.positionTicks.load(), bar) / bar : -1.0;
  40268. });
  40269. });
  40270. lynx::applyWindowChrome (*this);
  40271. lynx::fitWindowOnScreen (*this); // a size saved at another UI zoom still fits (round 163)
  40272. if (maximiseOnReveal)
  40273. setFullScreen (true); // (a title-bar window: maximized, the taskbar stays)
  40274. toFront (true);
  40275. content->grabKeyboardFocus();
  40276. // issue #62: the detached panels restored with the layout (built before this window was shown): their saved
  40277. // place and above it, once the window manager has placed this one
  40278. juce::Timer::callAfterDelay (250, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  40279. if (safe != nullptr)
  40280. safe->content->restoreDetachedWindows();
  40281. });
  40282. }
  40283. // Runs `then` once, right after the window's next frame (round 190go: the audio device opens behind the
  40284. // window's first frame, not before it); at the latest after 300 ms (a window that paints nothing: minimised).
  40285. void whenPainted (std::function<void()> then)
  40286. {
  40287. afterPaint = std::move (then);
  40288. afterPaintPosted = false;
  40289. repaint();
  40290. juce::Timer::callAfterDelay (300, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  40291. if (safe != nullptr)
  40292. safe->runAfterPaint();
  40293. });
  40294. }
  40295. void runAfterPaint()
  40296. {
  40297. if (auto then = std::exchange (afterPaint, nullptr))
  40298. then();
  40299. }
  40300. // The window's place and maximized state for the next start (main-window.txt in the settings folder).
  40301. void saveState() { stateFile().replaceWithText (getWindowStateAsString()); }
  40302. static juce::File stateFile() { return lynx::PluginHost::settingsFolder().getChildFile ("main-window.txt"); }
  40303. void openFile (const juce::File& file) { content->openFile (file); }
  40304. lynx::MainComponent& getContent() { return *content; }
  40305. void showSetupWizard() { content->showSetupWizard(); }
  40306. void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
  40307. void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
  40308. // Every frame the window paints, with its dirty area (ui/FrameProbe.h; --uiperf, LYNX_TRACE_UI). The trace keeps
  40309. // counting when --uiperf watches too.
  40310. void watchFrames (std::function<void (double, juce::Rectangle<int>)> callback)
  40311. {
  40312. if (probe == nullptr)
  40313. {
  40314. probe = std::make_unique<lynx::ui::FrameProbe>();
  40315. Component::addAndMakeVisible (*probe); // (ResizableWindow hides the plain overload)
  40316. probe->setBounds (getLocalBounds());
  40317. }
  40318. probe->onFrame = [callback = std::move (callback)] (double now, juce::Rectangle<int> area) {
  40319. if (lynx::uitrace::enabled())
  40320. lynx::uitrace::frame (now);
  40321. if (callback)
  40322. callback (now, area);
  40323. };
  40324. }
  40325. void resized() override
  40326. {
  40327. DocumentWindow::resized();
  40328. if (probe != nullptr)
  40329. probe->setBounds (getLocalBounds());
  40330. }
  40331. // --uiperf: the time of each frame the window paints (its own paint, then every child's, up to the last)
  40332. std::function<void (double)> onFrame;
  40333. void paint (juce::Graphics& g) override
  40334. {
  40335. if (onFrame)
  40336. frameStart = juce::Time::getMillisecondCounterHiRes();
  40337. DocumentWindow::paint (g);
  40338. }
  40339. void paintOverChildren (juce::Graphics& g) override
  40340. {
  40341. DocumentWindow::paintOverChildren (g);
  40342. if (afterPaint != nullptr && ! std::exchange (afterPaintPosted, true)) // (the frame is presented first)
  40343. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainWindow> (this)] {
  40344. if (safe != nullptr)
  40345. safe->runAfterPaint();
  40346. });
  40347. if (onFrame && frameStart > 0.0)
  40348. onFrame (juce::Time::getMillisecondCounterHiRes() - frameStart);
  40349. frameStart = 0.0;
  40350. }
  40351. private:
  40352. lynx::MainComponent* content = nullptr; // owned by the window
  40353. std::unique_ptr<lynx::ui::FrameProbe> probe; // (on top of the content; see watchFrames)
  40354. double frameStart = 0.0;
  40355. bool maximiseOnReveal = false;
  40356. std::function<void()> afterPaint; // (whenPainted)
  40357. lynx::AudioEngine* probeEngine = nullptr; // (LYNX_LOCATOR_PROBE)
  40358. bool afterPaintPosted = false;
  40359. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  40360. };
  40361. lynx::theme::LookAndFeel lookAndFeel;
  40362. std::unique_ptr<lynx::AudioEngine> engine;
  40363. std::unique_ptr<lynx::RemoteControl> remoteControl;
  40364. std::unique_ptr<juce::XmlElement> savedDeviceState; // --rtstress: the user's device before this run's --type/--buffer
  40365. // Hidden test mode --asiodll "<driver.dll>[|{CLSID}]" (REA round 97): an ASIO driver loaded straight from its file,
  40366. // without registering it, listed as the driver type "ASIO driver file". True when one was added.
  40367. bool addDriverFileDeviceType()
  40368. {
  40369. const auto args = juce::JUCEApplication::getCommandLineParameterArray();
  40370. const auto i = args.indexOf ("--asiodll");
  40371. if (i < 0 || i + 1 >= args.size() || engine == nullptr)
  40372. return false;
  40373. auto& devices = engine->getDeviceManager();
  40374. devices.getAvailableDeviceTypes(); // creates the standard types first
  40375. for (auto* t : devices.getAvailableDeviceTypes())
  40376. if (t->getTypeName() == lynx::dllAsioTypeName)
  40377. return true;
  40378. auto type = lynx::makeDllAsioDeviceType (args[i + 1].unquoted());
  40379. if (type == nullptr)
  40380. return false;
  40381. devices.addAudioDeviceType (std::move (type));
  40382. return true;
  40383. }
  40384. void restoreSavedDeviceState()
  40385. {
  40386. if (engine != nullptr)
  40387. engine->restoreAudioDeviceState (savedDeviceState.get());
  40388. }
  40389. std::unique_ptr<MainWindow> mainWindow;
  40390. std::unique_ptr<juce::Timer> perf; // --uiperf
  40391. std::unique_ptr<lynx::StartupSplash> splash;
  40392. static constexpr double landingSeconds = 1.05; // the logo's drop (SplashScreen::remainingDuration's `landing`)
  40393. std::shared_future<std::pair<juce::Image, double>> graphicsDeviceJob; // (round 190hd) holds the graphics device
  40394. bool graphicsDeviceMarked = false, windowRevealed = false;
  40395. std::future<std::shared_ptr<const lynx::SampleData>> startupSampleJob; // (round 190go: the built-in start-up sound)
  40396. bool startedAfterWindow = false, startupSoundPlayed = false;
  40397. double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
  40398. lynx::StartupOptions startupOptions;
  40399. juce::File fileToOpen;
  40400. bool startupFileHandled = false;
  40401. bool startWithoutPlugins = false; // --no-plugins project.lynx (round 190ap)
  40402. juce::File openTimeReport; // --opentime
  40403. int openTimeIdleSeconds = 10;
  40404. };
  40405. START_JUCE_APPLICATION (LynxApplication)