Main.cpp 2.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668
  1. #include <cfenv>
  2. #include <random> // round 190sp (src/Undo190spCheck.inc)
  3. #if defined(__linux__)
  4. #include <malloc.h> // round 190sp: mallinfo2 (src/Undo190spCheck.inc)
  5. #endif
  6. #if defined(__has_include)
  7. #if __has_include(<valgrind/callgrind.h>) // round 190sp: --stoppedbench190sp marks its measured blocks for callgrind (no-ops outside valgrind)
  8. #include <valgrind/callgrind.h>
  9. #define LYNX_STOPPEDBENCH_CALLGRIND 1
  10. #endif
  11. #endif
  12. #include <juce_gui_basics/juce_gui_basics.h>
  13. #if JUCE_MAC
  14. #include <CoreFoundation/CoreFoundation.h> // (rollup 0.1.32 step 6: the message pump of Stab190rpCheck.inc on macOS)
  15. #endif
  16. #include "engine/UniqueSamples.h"
  17. #include "engine/AraHost.h"
  18. #include "engine/FileSort.h"
  19. #include "platform/Paths.h"
  20. #include "core/CacheCheck.h" // round 190tg (src/CacheCheck190tgCheck.inc)
  21. #include "core/SongBytes.h" // round 190rn (src/Perf190rnCheck.inc)
  22. #include "core/SectionOps.h" // round 190ol (P1: the Sections lane)
  23. #include "core/SignatureEdit.h" // round 190ol (P6)
  24. #include "ui/SectionsLane190ol.h" // round 190ol (P1: the shot route drives the lane)
  25. #include "ui/ChordLane190pf.h" // round 190pf (P13: the shot route drives the lane)
  26. #include "ui/SmartTempo190pf.h" // round 190pf (P12)
  27. #include "core/SmartTempo.h"
  28. #include "core/Offline.h"
  29. #include "core/GrooveAudio.h"
  30. #include "core/SmartDisableTip.h" // (round 190ok: --smarttipshot190ok)
  31. #include "core/SimpleTracks.h" // (round 190ot: --simpleduck190otshot)
  32. #include "core/TrackImport.h" // (round 190pe: --tracks190peshot, --selftest tracks190pe)
  33. #include "core/TrackVersions.h"
  34. #include "ui/TrackImportDialog.h"
  35. #include "core/EditorScale.h"
  36. #include "core/SimplePads.h"
  37. #include "core/SimSynth.h" // (round 190om: the selftest's SimSynth channel)
  38. #include "core/ClipEnvelope.h"
  39. #include "core/ClipWarp.h"
  40. #include "core/KeyGuess.h"
  41. #include "core/EditorPolish.h"
  42. #include "core/FlpExport.h"
  43. #include "core/FruityBasicFx.h" // (round 190my: Fruity Balance in --details190myshot)
  44. #include "core/TrackClips.h"
  45. #include "core/TrackStates.h"
  46. #include "core/RangeEdit.h" // round 190pa (P14)
  47. #include "core/AutomationModes.h" // round 190pa (P21)
  48. #include "core/Groove.h"
  49. #include "core/DrawMode.h"
  50. #include "core/SessionOps.h"
  51. #include "ui/ClipGridComponent.h"
  52. #include "ui/ArticulatorTools.h"
  53. #include "ui/ExternalDrag.h"
  54. #include "ui/LabelFont.h"
  55. #include "ui/SessionMixer.h"
  56. #include "core/FlSamplers.h"
  57. #include "core/ArrangeOps.h"
  58. #include "core/ClipSample.h"
  59. #include "core/WarpModes.h"
  60. #include "ui/ClipAudioPanel.h"
  61. #include "core/DetailChain.h"
  62. #include "core/SessionMixer.h"
  63. #include "core/PlaylistOps.h"
  64. #include "core/LastTweaked.h"
  65. #include "core/ClipOps.h"
  66. #include "core/TransportEdit.h" // (round 190jz: --issueshot190jz)
  67. #include "core/SamplerPage.h"
  68. #include "core/FlTrackMenus.h"
  69. #include "core/FlClipMenu.h"
  70. #include "core/OneClickRec.h"
  71. #include "core/WarpTools.h"
  72. #include "core/Comping.h"
  73. #include "core/ExportSilence.h"
  74. #include "core/Drumaxx.h"
  75. #include "core/PatternBlocks.h"
  76. #include "core/LoadTrace.h"
  77. #include "core/ProjectSafety.h"
  78. #include "core/Patcher.h"
  79. #include "core/Rack.h"
  80. #include "core/LynxDrums.h"
  81. #include "ui/RackEditor.h"
  82. #include "ui/HelixEditor.h"
  83. #include "ui/LynxModelEditor.h"
  84. #include "core/physmod/LynxModel.h"
  85. #include "core/PluginCatalog.h"
  86. #include "engine/GeneratorCatalog.h"
  87. #include "core/AlsDevices.h"
  88. #include "core/XmlLite.h"
  89. #include "ui/DrumRackShot.h"
  90. #include "ui/GroovePoolComponent.h"
  91. #include "core/Patcherize.h"
  92. #include "core/Performance.h"
  93. #include "core/VideoPlayer.h"
  94. #include "core/Effects.h"
  95. #include "core/MixSuite.h"
  96. #include "core/LowLifterFl.h" // (rollup step 12: the 0.1.28 copy item)
  97. #include "core/HardwareInsert.h"
  98. #include "core/EchoSuite.h"
  99. #include "core/LuxeVerb.h"
  100. #include "core/LynxVerbs.h"
  101. #include "core/LynxTune.h"
  102. #include "core/FlEffects.h"
  103. #include "core/FlpImport.h"
  104. #include "core/NoteEdit.h"
  105. #include "core/PlaylistTrackOps.h" // round 190jf (FoldersShot190jf.inc)
  106. #include "ui/DawProjectExport.h" // round 190jf (--dawprojcheck190jf)
  107. #include "ui/FlmExportDialog.h" // round 190og (--export-flm, --flmexportshot)
  108. #include "core/NoteNames.h"
  109. #include "core/MaximusFx.h"
  110. #include "core/ChainPresets.h"
  111. #include "core/GoalKnobs.h"
  112. #include "core/MasterLooks.h"
  113. #include "core/Harmor.h"
  114. #include "core/KiloheartsDsp.h" // (rollup step 14: the copy for 0.1.28 self-test)
  115. #include "core/ThreeOsc.h" // (rollup 0.1.32 step 1: the copy for 0.1.31 self-test)
  116. #include "core/WavetableSynth.h" // (round 190oc: the copy for 0.1.30 self-test)
  117. #include "core/AutoLook.h" // (rollup 0.1.31 step 4: the copy for 0.1.30 self-test)
  118. #include "flp/Flp.h"
  119. #include "flp/FlpWrite.h" // round 190qs (issue #282 self-test)
  120. #include "core/DemoSongs.h"
  121. #include "core/FirstSongTour.h"
  122. #include "core/PerfProjects.h"
  123. #include "core/ShowcaseSong.h"
  124. #include "core/RenderAhead.h"
  125. #include "core/SynthPresets.h"
  126. #include "core/FlWrapper.h"
  127. #include "engine/AudioEngine.h"
  128. #include "engine/RecoveryTest.h" // round 190rp
  129. #include "engine/DeviceGuard.h" // round 190rp
  130. #include "engine/ProjectDowngrade.h"
  131. #include "engine/RemoteNotes.h" // (round 190pm: --selftest repeats190pm)
  132. #include "core/NoteConditions.h" // (round 190pm)
  133. #include "ui/TouchInput.h" // (round 190pm)
  134. #include "ui/TrackerComponent.h"
  135. #include "core/ClipLauncher.h"
  136. #include "core/SimpleSteps.h"
  137. #include "core/DirectWaveState.h"
  138. #include "core/SamplerImport.h" // (round 190tf: src/Downgrade0132_190tfCheck.inc)
  139. #include "ui/SamplerImportUi.h"
  140. #include "core/MixSnapshots.h"
  141. #include "core/VoiceShift.h"
  142. #include "core/PeakShapes.h" // rollup step 7: the copy for 0.1.28 self-test
  143. #include "core/DynamicsSuite.h"
  144. #include "core/TempoMarkers.h"
  145. #include "engine/RemoteControl.h"
  146. #include "engine/RemoteError.h"
  147. #include "ui/RemoteControlSettings.h"
  148. #include "engine/PreviewPlayer.h"
  149. #include "engine/Metronome.h"
  150. #include "engine/AudioLogger.h"
  151. #include "engine/DllAsioDevice.h"
  152. #include "engine/PipeWireDevice.h"
  153. #include "platform/LinuxRealtime.h"
  154. #include "engine/PowerHints.h"
  155. #include "engine/Exporter.h"
  156. #include "engine/AacEncoder.h"
  157. #include "engine/FlStudioExport.h"
  158. #include "engine/MidiFileIo.h"
  159. #include "core/MidiPreview.h" // round 190qi
  160. #include "core/PluginPicks.h" // round 190qi
  161. #include "engine/PluginHost.h"
  162. #include "engine/Vst3NoteTuning.h"
  163. #include "engine/PluginSandbox.h"
  164. #include "engine/Bridge32Test.h"
  165. #include "engine/ClapFormat.h"
  166. #include "engine/JsfxFormat.h"
  167. #include "engine/ClapTeardownTest.h"
  168. #include "engine/RenderAgainTest.h"
  169. #include "engine/Determinism190poTest.h"
  170. #include "ui/TiltViewport.h"
  171. #if JUCE_LINUX
  172. #include <dlfcn.h> // (round 190ou: --hwheel254test presses X11 buttons through XTest)
  173. #if __has_include(<execinfo.h>)
  174. #include <execinfo.h> // (round 190sz: --undomem190sp --trace, where the history's shared containers are copied)
  175. #endif
  176. namespace juce { void* lynxX11Display(); } // (JUCE fix 41's accessor of its X11 display; round 190rv's #319 check)
  177. #if JUCE_LINUX || JUCE_BSD
  178. namespace juce { extern unsigned long lynxX11WindowBackground; } // (JUCE fix 58, issue #337: round 190sk)
  179. namespace juce { extern int (*lynxFdWithQueuedEvents)(); } // (JUCE fix 59, issue #347: the event loop's queued X events)
  180. // (JUCE fix 60: #334's XDND relay into a plugin's editor, #290's touchpad pinch; for src/Batch334svCheck.inc)
  181. namespace juce { extern bool lynxXdndRelayOn; unsigned long lynxXdndRelayTargetForTest(); int lynxPinchOpcodeForTest (int*);
  182. void lynxPinchForTest (unsigned long, int, double, double, double, int); }
  183. #endif
  184. #include <sys/prctl.h> // (round 190ou: --multieditor255test LYNX_ME_PTRACE=1)
  185. #include <sys/socket.h> // (round 190rf: --qa190rfchild display)
  186. #include <fcntl.h> // (round 190th: src/Children190thCheck.inc)
  187. #include <signal.h>
  188. #include <sys/wait.h>
  189. #include <unistd.h>
  190. #endif
  191. #include "engine/HostingTests.h"
  192. #include "engine/Modulators190oxTest.h"
  193. #include "ui/ModRing.h"
  194. #include "core/EdisonFx.h"
  195. #include "engine/ProjectFile.h"
  196. #include "ui/RemoteControl.h"
  197. #include "core/FlControlMenus.h"
  198. #include "core/PlaylistOps.h"
  199. #include "core/Sha256.h"
  200. #include "engine/SessionPack.h"
  201. #include "engine/LiveSessions.h"
  202. #include "engine/LiveTest.h"
  203. #include "engine/ShortExportTest.h"
  204. #include "core/SessionIds.h"
  205. #include "core/SessionParts.h"
  206. #include "engine/SampleLibrary.h"
  207. #include "engine/Text.h"
  208. #include "platform/FileTypes.h"
  209. #include "platform/Package.h"
  210. #include "core/AlsExport.h"
  211. #include "core/AlsImport.h"
  212. #include "core/LiveScaleControl.h" // round 190oo (--design190ooshot)
  213. #include "core/PlaylistViewOptions.h"
  214. #include "core/PianoRollScript.h"
  215. #include "ui/ScriptPanel.h"
  216. #include "ui/AlsExportDialog.h"
  217. #include "ui/LiveRemoteUi.h"
  218. #include "ui/GamepadInput.h"
  219. #include "ui/SettingsPages.h"
  220. #include "ui/ValueControl.h" // (round 190sr: #302 check)
  221. #include "core/KnobWheel.h"
  222. #include "core/SlotAltClick.h"
  223. #include "core/TrackInserts.h"
  224. #include "core/ExtrasDefaults.h"
  225. #include "core/ExtrasDefaults.h" // round 190qk (--selftest extras190qk)
  226. #include "ui/Notices.h" // round 190qx (--selftest optionsux190qx)
  227. #include "ui/HowTo.h"
  228. #include "ui/ExtendedHintPanel.h"
  229. #include "core/FlSettings.h"
  230. #include "ui/OtherAppsExport.h"
  231. #include "ui/TimerWhileShowing.h"
  232. #include "ui/MixerBasicsCheck.h"
  233. #include "ui/VideoPlayerView.h"
  234. #include "ui/VideoMedia.h"
  235. #include "ui/VideoTracks.h"
  236. #include "ui/AdrWindow.h"
  237. #include "ui/PluginPicker.h"
  238. #include "ui/PlaylistComponent.h"
  239. #include "ui/PictureCheck.h"
  240. #include "ui/PatternBlocksView.h"
  241. #include "ui/PaintAB.h"
  242. #include <typeinfo>
  243. #include "ui/PatcherEditor.h"
  244. #include "ui/VisualEditors.h"
  245. #include "ui/FlExtraEditors.h"
  246. #include "ui/VisualGl.h"
  247. #include "ui/DanceView.h"
  248. #include "ui/PluginPresetMenu.h"
  249. #include "ui/GeneratorPresetMenu.h"
  250. #include "core/GeneratorPresets.h"
  251. #include "ui/PluginWindow.h"
  252. #include "platform/NativeEmbed.h"
  253. #include "ui/Motion.h"
  254. #include "ui/ShotShowing.h"
  255. #include "ui/SimpleLook.h"
  256. #include "ui/NativeChild.h"
  257. #include "ui/FrameTicker.h"
  258. #include "ui/DockPaintCheck.h"
  259. #include "ui/Workspace.h"
  260. #include "ui/PluginThumbs.h"
  261. #include "ui/ClipProperties.h"
  262. #include "ui/NewProjectDialog.h"
  263. #include "ui/PluginMonitorWindow.h"
  264. #include "ui/TouchKeyboard.h"
  265. #include "ui/AutomationUi.h"
  266. #include "core/GrossBeatLocator.h"
  267. #include "ui/PluginSkin.h"
  268. #include "ui/ChannelSettings.h"
  269. #include "ui/TempoDetectionDialog.h"
  270. #include "ui/AudioClipboard.h"
  271. #include "ui/FlVoicePanel.h"
  272. #include "ui/SlicexEditor.h"
  273. #include "ui/DirectWaveEditor.h"
  274. #include "ui/FruitySlicerEditor.h"
  275. #include "core/GrossBeat.h"
  276. #include "core/LynxBanks.h"
  277. #include "core/NativeData.h"
  278. #include "core/NativeEngines.h"
  279. #include "ui/ControllerEditors.h"
  280. #include "ui/NewtoneEditor.h"
  281. #include "core/NewtoneFx.h"
  282. #include "core/FormulaController.h"
  283. #include "core/MidiControls.h"
  284. #include "core/FlSynths.h"
  285. #include "core/SoundFont.h"
  286. #include "core/Sfz.h"
  287. #include "core/Slicex.h"
  288. #include "ui/Dialogs.h"
  289. #include "ui/DialogFrame.h"
  290. #include "ui/FileChoosers.h"
  291. #include "ui/TrackIcons.h"
  292. #include "core/MeterScale.h"
  293. #include "core/RackOps.h"
  294. #include "core/RackAutomation.h" // round 190oo (PAT-7, --selftest rackauto190oo)
  295. #include "core/Layer.h"
  296. #include "core/XyController.h"
  297. #include "core/FlCurve.h"
  298. #include "core/ControlSurface.h"
  299. #include "core/VoltageController.h"
  300. #include "ui/Controllers164.h"
  301. #include "core/StandIns.h"
  302. #include "ui/ExportDialog.h"
  303. #include "ui/QuickAddPalette.h"
  304. #include "ui/I18n.h"
  305. #include "ui/KeyFocus.h"
  306. #include "core/TrackIconScale.h"
  307. #include "core/EscClose.h"
  308. #include "ui/MainComponent.h"
  309. #include "ui/MixerRowsView.h" // round 190so
  310. #include "core/ViewExtras.h" // round 190so
  311. #include "core/PinnedTracks.h" // round 190so
  312. #include "core/MixerRows.h" // round 190so
  313. #include "core/MarkerJump.h" // round 190so
  314. #include "ui/LynxWindows.h" // --tabs2test190nz (issue #232 stage 2)
  315. #include "ui/WindowClipboard.h"
  316. #include "ui/SimpleDock.h"
  317. #include "core/ScaleKeys.h"
  318. #include "core/KeyFollow.h"
  319. #include "core/SoundLibrary.h"
  320. #include "ui/MidiToolsPanel.h"
  321. #include "ui/FrameProbe.h"
  322. #include "ui/MotionOverlay.h"
  323. #include "ui/UiTrace.h"
  324. #include "core/MixerOps.h"
  325. #include "ui/QuickPick.h"
  326. #include "ui/InlineTypeIn.h"
  327. #include "core/NoLength.h"
  328. #include "core/ClipLinks.h"
  329. #include "core/FolderWatcher.h"
  330. #include "core/FruityDynamics.h"
  331. #include "core/PluginDbFolder.h"
  332. #include "core/NoteTools.h"
  333. #include "engine/ProjectPackage.h"
  334. #include "engine/SafeWrite.h" // round 190rm (src/Iox190rmCheck.inc)
  335. #include "core/FlVoiceBlock.h" // round 190rt (src/Issues190rtShot.inc)
  336. #include "ui/SetupWizard.h"
  337. #include "ui/DemoMode.h" // (round 190np)
  338. #if JUCE_LINUX || JUCE_WINDOWS // (rollup 0.1.31 step 2: Windows too, so --onboard190npshot runs its async callbacks there)
  339. namespace juce::detail { bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages); } // juce_Messaging_linux / _windows.cpp (--onboard190npshot)
  340. #endif
  341. #include "ui/Onboarding.h"
  342. #include "engine/FlStudio.h"
  343. #include "ui/HistoryPanel.h"
  344. #include "ui/UndoNameText.h" // round 190td
  345. #include "ui/VersionsPanel.h"
  346. #include "ui/CleanVoiceMenu.h"
  347. #include "ui/LyricsPanel.h"
  348. #include "ui/NotesPanel.h" // round 190tj (src/Notes190tjCheck.inc)
  349. #include "ui/ReferenceMatchPanel.h"
  350. #include "ui/StartFromPanel.h"
  351. #include "ui/FirstSongTour.h"
  352. #include "ui/PluginsOffPanel.h"
  353. #include "ui/MissingFilesDialog.h"
  354. #include "ui/SettingsDialog.h"
  355. #include "ui/PluginManager.h"
  356. #include "ui/ShortcutManager.h"
  357. #include "ui/ActionSearch.h" // (round 190sr: #351 check)
  358. #include "ui/NoteToolDialogs.h"
  359. #include "ui/ChordStripView.h" // round 190kd (--prchord190kd)
  360. #include "ui/ChordHelper.h" // round 190mc (--modal190mc)
  361. #include "core/KeyRegions.h" // round chord2_190nu (--selftest, --keys190nu)
  362. #include "core/TransistorBass.h" // round 190mc (--modal190mc)
  363. #include "core/ModelParams.h" // round 190mc (--modal190mc)
  364. #include "ui/EventEditor.h"
  365. #include "ui/AudioEditor.h"
  366. #include "ui/SampleProperties.h"
  367. #include "ui/TempoTapper.h"
  368. #include "core/Timecode.h" // round 190ta (src/Rea190taCheck.inc)
  369. #include "core/SlicexInstrument.h" // round 190ti (src/Round190tiCheck.inc)
  370. #include "ui/ProjectPickerView.h" // (round 190my)
  371. #include "ui/WindowPlaces.h" // (round 190oa)
  372. #include "ui/HintBar.h" // (round 190oa)
  373. #include "ui/CouldNotOpen.h" // (round 190sq, issue #346)
  374. #include "core/SaveExtras.h" // (round 190sq, issue #251)
  375. #if JUCE_LINUX || JUCE_BSD
  376. #include "ui/XdndTestSourceX11.h" // (round 190sk, issues #332 / #333)
  377. #include <thread>
  378. #endif
  379. #include "core/EventEdit.h"
  380. #include "core/FacetEq.h"
  381. #include "core/LimiterLaw.h" // (rollup step 9: the copy for 0.1.28 self-test)
  382. #include "core/ApexLimiter.h" // (rollup step 10: likewise)
  383. #include "core/Reeverb2.h"
  384. #include "core/VoiceTools.h"
  385. #include "platform/ThreadInstructions.h" // (rollup step 9: --paintbench counts instructions)
  386. #include "ui/FacetEqEditor.h"
  387. #include "core/RackRenderer.h"
  388. #include "ui/ProEditors.h"
  389. #include "ui/ParametricEqEditor.h"
  390. #include "ui/PluginEditors.h"
  391. #include "core/PluginLayout.h"
  392. #include "core/EffectPresets.h"
  393. #include "ui/PluginHeader.h"
  394. #include "core/Vfx.h"
  395. #include "core/TransistorBass.h"
  396. #include "ui/Splash.h"
  397. #include "core/ExportDone.h" // round 190qr (#280)
  398. #include "core/StartupSound.h" // round 190qr (#280)
  399. #include "core/ClipHandle.h" // round 190qr (#274)
  400. #include "core/ZoomAnchor.h" // round 190qr (#276)
  401. #include "ui/Theme.h"
  402. #include "ui/ThemeSettings.h"
  403. #include "ui/ChannelRackComponent.h" // (round 190qw: --polish190qwshot)
  404. #include "core/LynxExtras.h" // (round 190qw: --polish190qwshot)
  405. #include "ui/AutoLookEditor.h" // (round 190od, issue #239)
  406. #include "core/StartPage.h" // (round 190oq, issue #252)
  407. #include "core/MuteKeys.h"
  408. #include "core/AraRegions.h"
  409. #include "ui/StartPage.h"
  410. #include "ui/DeleteFade.h"
  411. #include "ui/AraMenu.h"
  412. #include "ui/WaveformView.h"
  413. #include "ui/WindowOwner.h"
  414. #include "ui/PluginKeysTest.h"
  415. #include "ui/ZOrder191Test.h"
  416. #include "ui/Toolbar.h"
  417. #include "ui/ToolWindow.h"
  418. #include "core/Details190mv.h" // (round 190mv)
  419. #include "platform/CrashGuard.h"
  420. #include "platform/ChildHygiene.h"
  421. #include "ui/CrashReporter.h"
  422. #include "ui/Updater.h"
  423. #include "ui/AudioCheck.h"
  424. #include "ui/StemExtract.h"
  425. #include "core/RegionLoop.h" // round 190jr: --bandlab190jrshot
  426. #include "core/FactoryContent.h" // round 190ke: --simplegb190keshot
  427. #include "core/KeyFollow.h" // round 190kx: --loopinfo190kxshot
  428. #include "core/LoopAnalysis.h"
  429. #include "../tests/LoopCorpus190kx.h" // (LYNX's own synthetic loops, written for the shot)
  430. #include "core/SongFade.h"
  431. #include "core/SoundLibrary.h"
  432. #include "core/SynthParams.h"
  433. #include "core/GoalKnobs.h"
  434. #include "core/DetailChain.h"
  435. #include "ui/FinishDock.h"
  436. #include "ui/SimpleDock.h"
  437. #include "ui/SimpleTuner.h"
  438. #include "ui/AudioToMidi.h"
  439. #include "ui/PolyEditor.h"
  440. #include "core/PolyEdit.h"
  441. #include "ui/ShotScale.h"
  442. #include "core/LaneView.h" // round 190iu
  443. #include "core/PlaylistTrackOps.h"
  444. #include "core/MidiDrop.h"
  445. #include "core/TakeCleanup.h"
  446. #include "core/TrackOnly.h"
  447. #include "core/WheelZones.h"
  448. #include "ui/WorkflowExtras.h"
  449. #include "core/LatencyTransport.h" // (round 190te, issue #356)
  450. #include "core/Links.h"
  451. #include "core/SliceExtras.h" // round 190st (#339, #340: src/AudioEdit190stShot.inc)
  452. #include "core/StretchGrip.h" // round 190st (#291: src/AudioEdit190stShot.inc)
  453. #include "core/ArrowKeys.h" // round 190tb (src/Details190tbCheck.inc)
  454. #include <algorithm>
  455. #include <set> // (round 190jf: --dawprojcheck190jf)
  456. #include <atomic>
  457. #include <exception>
  458. #include <chrono>
  459. #include <cstdio>
  460. #include <ctime>
  461. #include <cstdlib>
  462. #include <future>
  463. #include <mutex>
  464. #include <deque>
  465. #include <thread>
  466. namespace
  467. {
  468. lynx::AudioEngine* crashEngine = nullptr;
  469. // --export-dawproject --stress (round 190ri, kainproctor's DAWproject export): a song as heavy as his imported FL project —
  470. // the arrangement repeated to past 1,200 bars, some clips muted, every kind of time marker (also two skips in a row), an
  471. // audio clip whose sample is not on this computer and a channel whose plugin is not installed
  472. void community190riStressSong (lynx::Song& s)
  473. {
  474. const auto barTicks = (std::int64_t) 4 * lynx::ppq;
  475. lynx::laneview::clipsToLanes (s); // (his: "many lanes made with clips to lanes")
  476. auto end = std::max<std::int64_t> (s.songLength(), barTicks * 4);
  477. const auto once = s.playlist;
  478. for (std::int64_t at = end; at < barTicks * 1200 && ! once.empty(); at += end)
  479. for (auto c : once)
  480. {
  481. c.start += at;
  482. c.uid = 0;
  483. s.playlist.push_back (c);
  484. }
  485. for (std::size_t i = 0; i < s.playlist.size(); i += 7)
  486. s.playlist[i].muted = true;
  487. int bar = 1;
  488. for (const auto action : { lynx::Marker::none, lynx::Marker::start, lynx::Marker::markerSkip, lynx::Marker::markerSkip, lynx::Marker::markerLoop,
  489. lynx::Marker::markerPause, lynx::Marker::timeSignature, lynx::Marker::punchIn, lynx::Marker::punchOut, lynx::Marker::songLoop })
  490. {
  491. lynx::Marker m;
  492. m.tick = barTicks * (bar += 8);
  493. m.name = "m" + std::to_string (bar);
  494. m.action = action;
  495. if (action == lynx::Marker::timeSignature)
  496. m.numerator = 3;
  497. s.addMarker (m);
  498. }
  499. lynx::ChannelDef missing;
  500. missing.name = "Missing sample";
  501. missing.instrument = lynx::InstrumentKind::audioClip;
  502. missing.samplePath = "/nonexistent/round190ri/kick.wav";
  503. s.channels.push_back (missing);
  504. lynx::Clip audio;
  505. audio.kind = lynx::ClipKind::audio;
  506. audio.channel = (int) s.channels.size() - 1;
  507. audio.start = barTicks * 3;
  508. audio.length = barTicks;
  509. audio.track = 0;
  510. s.playlist.push_back (audio);
  511. lynx::ChannelDef plugin;
  512. plugin.name = "Missing plugin";
  513. plugin.instrument = lynx::InstrumentKind::plugin;
  514. plugin.plugin.name = "Not Installed Synth";
  515. plugin.plugin.id = "VST3-NotInstalledSynth-1a2b3c4d-5e6f7a8b";
  516. s.channels.push_back (plugin);
  517. }
  518. // Startup trace (REA round 116): with LYNX_TRACE_STARTUP set, the time of each startup step since the C++ runtime
  519. // started is written to %APPDATA%\LYNX\startup.log (the loader's own time before that is not included).
  520. struct StartupTrace
  521. {
  522. using clock = std::chrono::steady_clock;
  523. const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
  524. const std::chrono::system_clock::time_point t0System = std::chrono::system_clock::now(); // (round 190hd: vs the process's creation)
  525. // (round 190go: always kept, as a field-readable start-up timeline; written to startup.log 5 s and 15 s after the
  526. // window — with LYNX_TRACE_STARTUP set, at every step as before, so a start that hangs still leaves its last step)
  527. const bool on = true;
  528. const bool eachStep = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
  529. juce::String text;
  530. clock::time_point last = t0;
  531. std::int64_t lastPrivate = 0;
  532. double seconds() const { return std::chrono::duration<double> (clock::now() - t0).count(); } // since the process started
  533. void mark (const char* step)
  534. {
  535. if (! on)
  536. return;
  537. const auto now = clock::now();
  538. const auto ms = [] (clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); };
  539. // (round 190gd: the process's memory after each step too, so the log says where the megabytes of a start go)
  540. const auto mb = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1).paddedLeft (' ', 7); };
  541. const auto priv = lynx::toolbar::PerformanceMeter::processPrivateBytes();
  542. const auto ws = lynx::toolbar::PerformanceMeter::processMemoryBytes();
  543. text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7)
  544. << " private " << mb (priv) << " MB (+" << mb (priv - lastPrivate).trim() << ") ws " << mb (ws) << " MB " << step << "\n";
  545. lastPrivate = priv;
  546. last = now;
  547. if (eachStep)
  548. write();
  549. }
  550. void write() const { lynx::platform::settingsFile ("startup.log").replaceWithText (text); }
  551. };
  552. StartupTrace startupTrace;
  553. void startupMarkHook (const char* step) { startupTrace.mark (step); }
  554. // Round 190rb: a sanitizer build (-DLYNX_SANITIZE) leaves SIGSEGV / SIGBUS / SIGFPE / SIGABRT to ASan and UBSan (their
  555. // report names the bad access and where the memory came from); LYNX_CRASHGUARD=1 installs LYNX's handlers anyway
  556. bool sanitizerOwnsSignals()
  557. {
  558. #if defined(LYNX_SANITIZER_BUILD)
  559. return juce::SystemStats::getEnvironmentVariable ("LYNX_CRASHGUARD", {}) != "1";
  560. #else
  561. return false;
  562. #endif
  563. }
  564. juce::File crashFolderForTest; // --faulttest: where the crash file goes instead of the settings' autosave folder
  565. // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
  566. void onCrash (void* exceptionPointers)
  567. {
  568. // round 190oh (Windows): a fault on a hosted plugin's own thread that nothing handled — that thread waits for good
  569. // inside this call and the main window's timer switches the plugin off (crashguard::parkFaultingPluginThread)
  570. if (lynx::crashguard::parkFaultingPluginThread (exceptionPointers))
  571. return;
  572. // (round 190ci: once. The hook for stacks Windows cannot walk, crashguard::setUnwalkableFaultHandler, may have run
  573. // this before the top-level filter does)
  574. static std::atomic<bool> reported { false };
  575. if (reported.exchange (true))
  576. return;
  577. // rollup 0.1.30 step 12 (owner decision after round 190mo): whatever follows, the process ends within the watchdog's
  578. // time (60 s): after a heap corruption everything below that allocates can wait for ever on the allocator's lock
  579. lynx::crashguard::armCrashWatchdog (exceptionPointers);
  580. // ... and after the C library's (or Windows') heap-corruption abort, nothing that allocates runs at all: a crash file
  581. // written without the heap, no session note, no emergency save (the project in memory may be what was broken)
  582. if (lynx::crashguard::heapCorruptionCrash (exceptionPointers))
  583. {
  584. lynx::crashguard::writeHeapCrashFile (exceptionPointers);
  585. return;
  586. }
  587. const auto folder = crashFolderForTest != juce::File() ? crashFolderForTest : lynx::platform::settingsFile ("autosave");
  588. folder.createDirectory();
  589. const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
  590. // JUCE's backtrace (named frames only), then every frame of the faulting thread as module+offset (round 157a: a
  591. // release LYNX.exe has no symbols, so its own frames were missing from the file)
  592. // (round 190rp: an abort that is not a heap corruption names what the C library said and gets the emergency save)
  593. const auto libraryMessage = juce::String::fromUTF8 (lynx::crashguard::abortMessage()).trim();
  594. const auto crashFile = folder.getChildFile ("crash " + stamp + ".txt");
  595. crashFile.replaceWithText (juce::SystemStats::getStackBacktrace() + "\n--- frames (module+offset)\n"
  596. + juce::String::fromUTF8 (lynx::crashguard::exceptionBacktrace (exceptionPointers).c_str())
  597. + (libraryMessage.isNotEmpty() ? "\n--- C library: " + libraryMessage + " (not a heap corruption: the emergency save is attempted)\n"
  598. : juce::String()));
  599. lynx::crashguard::note (("crashed: backtrace in autosave\\crash " + stamp + ".txt").toStdString());
  600. if (lynx::crashguard::hangInCrashHandlerForTest()) // (--faulttest hang: a handler that never returns; the watchdog ends it)
  601. for (;;)
  602. std::this_thread::sleep_for (std::chrono::seconds (1));
  603. if (crashEngine != nullptr)
  604. {
  605. juce::String error;
  606. const auto saved = lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
  607. crashFile.appendText ("--- emergency save: " + (saved ? "recovered " + stamp + lynx::ProjectFile::extension : "failed (" + error + ")") + "\n");
  608. }
  609. }
  610. // Round 190rf (Linux): the X server went away (crashguard::watchDisplayConnection): the project in memory is saved as a
  611. // recovered project, as after a crash, before the process ends (it cannot go on without a display)
  612. void onDisplayLost()
  613. {
  614. if (crashEngine == nullptr)
  615. return;
  616. const auto folder = lynx::platform::settingsFile ("autosave");
  617. folder.createDirectory();
  618. juce::String error;
  619. lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S")
  620. + lynx::ProjectFile::extension), error);
  621. }
  622. juce::File sessionsFolder()
  623. {
  624. return lynx::PluginHost::settingsFolder().getChildFile ("sessions");
  625. }
  626. // Sessions of earlier runs whose process is gone without closing (a fail-fast, a crash, a forced end): each is appended
  627. // to %APPDATA%\LYNX\crash-history.log and its file removed. Returns the last step of the newest one ("" when none).
  628. juce::StringArray uncleanSteps; // the newest unclean session's steps (without their times)
  629. juce::String uncleanSessionText; // the newest unclean session's whole file (round 159: the crash report reads it)
  630. // What the newest unclean session tells (round 157a): the plugin whose editor was opening / shown when it ended, and
  631. // whether its crash file blames a graphics driver
  632. struct UncleanCause
  633. {
  634. juce::String editorPlugin; // the last steps were that plugin's editor
  635. bool gpuDriver = false; // the crash file's top frames are in a GPU driver / Direct3D / Direct2D module
  636. juce::String driverModule;
  637. };
  638. UncleanCause uncleanCause()
  639. {
  640. UncleanCause cause;
  641. juce::File crashFile;
  642. for (int i = uncleanSteps.size(); --i >= 0 && i >= uncleanSteps.size() - 4;)
  643. {
  644. const auto& step = uncleanSteps[i];
  645. if (step.startsWith ("crashed: backtrace in "))
  646. crashFile = lynx::platform::settingsFolder().getChildFile (step.fromFirstOccurrenceOf ("backtrace in ", false, false).replaceCharacter ('\\', '/'));
  647. for (const auto* prefix : { "opening the editor of ", "editor open: ", "editor shown: " })
  648. if (cause.editorPlugin.isEmpty() && step.startsWith (prefix))
  649. cause.editorPlugin = step.fromFirstOccurrenceOf (prefix, false, false).trim();
  650. if (step.startsWith ("closing the editor of ") || step.startsWith ("loaded plugin") || step.startsWith ("opening project"))
  651. break; // older steps than these did not end the session
  652. }
  653. // issue #32 (round 174a): a plugin whose editor already faulted in this session (caught, LYNX went on) is the
  654. // likely cause when the session then ended without a word: offer it a separate process too
  655. for (int i = uncleanSteps.size(); --i >= 0 && cause.editorPlugin.isEmpty();)
  656. if (const auto editor = lynx::crashreport::parseEditorCrashStep (uncleanSteps[i].toStdString()); ! editor.plugin.empty())
  657. cause.editorPlugin = juce::String::fromUTF8 (editor.plugin.c_str());
  658. if (crashFile.existsAsFile())
  659. {
  660. // the first frames after the crash handler's own (the "--- frames" part lists the faulting thread)
  661. auto text = crashFile.loadFileAsString();
  662. if (text.contains ("--- frames"))
  663. text = text.fromFirstOccurrenceOf ("--- frames", false, false);
  664. auto lines = juce::StringArray::fromLines (text);
  665. int looked = 0;
  666. for (const auto& line : lines)
  667. {
  668. const auto module = line.fromFirstOccurrenceOf (": ", false, false).upToFirstOccurrenceOf ("+", false, false).trim().toLowerCase();
  669. if (module.isEmpty() || ! module.endsWith (".dll"))
  670. continue;
  671. if (++looked > 12)
  672. break;
  673. for (const auto* driver : { "igd", "ig9icd", "ig7icd", "igxelp", "nvwgf2um", "nvoglv", "nvd3dum", "atidxx", "atio6axx", "amdxx", "aticfx",
  674. "d3d11.dll", "d3d10warp", "dxgi.dll", "d2d1.dll", "opengl32.dll", "dcomp.dll" })
  675. if (module.startsWith (driver))
  676. {
  677. cause.gpuDriver = true;
  678. cause.driverModule = module;
  679. break;
  680. }
  681. if (cause.gpuDriver)
  682. break;
  683. }
  684. }
  685. return cause;
  686. }
  687. // Round 190rp (crash reports since 0.1.31.2, G1): the device the newest unclean session was opening when it ended (its
  688. // last steps, after the hang watch's own lines, are AudioEngine::openingDeviceStep without "audio device opened"): the
  689. // driver hung or crashed in its open. "" when the session got past it.
  690. juce::String uncleanDeviceOpen()
  691. {
  692. for (int i = uncleanSteps.size(); --i >= 0;)
  693. {
  694. const auto& step = uncleanSteps[i];
  695. if (step.startsWith ("UI not responding") || step.startsWith ("UI responding again") || step.startsWith ("crashed: "))
  696. continue;
  697. return step.startsWith (lynx::AudioEngine::openingDeviceStep) ? step.fromFirstOccurrenceOf (lynx::AudioEngine::openingDeviceStep, false, false).trim()
  698. : juce::String();
  699. }
  700. return {};
  701. }
  702. juce::String collectUncleanSessions()
  703. {
  704. juce::String lastStep;
  705. juce::Time newest;
  706. for (const auto& file : sessionsFolder().findChildFiles (juce::File::findFiles, false, "session-*.txt"))
  707. {
  708. const auto text = file.loadFileAsString();
  709. juce::StringPairArray values;
  710. juce::StringArray steps;
  711. for (const auto& line : juce::StringArray::fromLines (text))
  712. {
  713. if (line.startsWith ("step="))
  714. steps.add (line.fromFirstOccurrenceOf ("=", false, false));
  715. else if (line.contains ("="))
  716. values.set (line.upToFirstOccurrenceOf ("=", false, false), line.fromFirstOccurrenceOf ("=", false, false));
  717. }
  718. const auto pid = (std::uint32_t) values["pid"].getLargeIntValue();
  719. const auto start = (std::uint64_t) values["start"].getLargeIntValue();
  720. if (pid == lynx::crashguard::processId() || lynx::crashguard::processRunning (pid, start))
  721. continue; // this run, or another LYNX window still open
  722. lynx::PluginHost::settingsFolder().getChildFile ("crash-history.log")
  723. .appendText (juce::Time::getCurrentTime().toISO8601 (true) + " previous session ended without closing\n" + text + "\n");
  724. file.deleteFile();
  725. if (const auto modified = file.getLastModificationTime(); lastStep.isEmpty() || modified > newest)
  726. {
  727. newest = modified;
  728. lastStep = steps.isEmpty() ? juce::String ("start-up") : steps[steps.size() - 1].fromFirstOccurrenceOf (" ", false, false);
  729. uncleanSessionText = text;
  730. uncleanSteps.clear();
  731. for (const auto& step : steps)
  732. uncleanSteps.add (step.fromFirstOccurrenceOf (" ", false, false));
  733. }
  734. }
  735. return lastStep;
  736. }
  737. } // namespace
  738. // --uiperf (round 173f, discussion #10): a mixer fader dragged up and down with the mouse while the pattern plays. A
  739. // high-resolution timer delivers 125 moves a second to the message thread through the window's own mouse path
  740. // (ComponentPeer::handleMouseEvent), at most one waiting at a time as Windows does with WM_MOUSEMOVE; every frame the
  741. // window paints tells whether it covered the fader. Measured: how long a move waited for the message thread, the time
  742. // from a move to the first frame that shows the fader after it (input → paint), and whether the value stays put when
  743. // the mouse is released.
  744. #if JUCE_WINDOWS
  745. namespace juce
  746. {
  747. extern int lynxD2DPresents; // (cmake/LynxPatchJuce.cmake, round 190gv: every Direct2D window present)
  748. }
  749. #endif
  750. // round 190jy: --uiperf's presents per second (190kb's cycles line reads it too)
  751. static int uiPerfPresents()
  752. {
  753. #if JUCE_WINDOWS
  754. return juce::lynxD2DPresents;
  755. #else
  756. return 0;
  757. #endif
  758. }
  759. struct UiPerfDrag final : public std::enable_shared_from_this<UiPerfDrag>,
  760. private juce::HighResolutionTimer
  761. {
  762. ~UiPerfDrag() override { stopTimer(); }
  763. void start (juce::Component& windowIn, juce::Component& strips, juce::Rectangle<int> rail, lynx::AudioEngine* engineIn, int trackIn)
  764. {
  765. window = &windowIn;
  766. engine = engineIn;
  767. track = trackIn;
  768. railInWindow = window->getLocalArea (&strips, rail);
  769. watch = railInWindow.expanded (6, 40); // the cap, its tip above and the dB read-out below
  770. visible = strips.isShowing() && window->getLocalArea (&strips, strips.getLocalBounds()).contains (railInWindow.getCentre());
  771. const auto volume = engine->getSong().mixer[(std::size_t) track].volume;
  772. x = (float) railInWindow.getCentreX();
  773. startY = (float) railInWindow.getBottom() - volume * (float) railInWindow.getHeight(); // on the cap: no jump
  774. amplitude = 0.4f * (float) railInWindow.getHeight();
  775. centreY = juce::jlimit ((float) railInWindow.getY() + amplitude, (float) railInWindow.getBottom() - amplitude, startY);
  776. t0 = juce::Time::getMillisecondCounterHiRes();
  777. inject (x, startY, false);
  778. juce::ModifierKeys::currentModifiers = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  779. inject (x, startY, true);
  780. active = true;
  781. startTimer (8);
  782. }
  783. // message thread
  784. void framePainted (double now, juce::Rectangle<int> area)
  785. {
  786. if (pending.empty() || ! area.intersects (watch))
  787. return;
  788. for (const auto t : pending)
  789. latencies.push_back (now - t);
  790. pending.clear();
  791. ++framesOverFader;
  792. }
  793. // the moves end; as in the reporter's clip, the song is stopped while the button is still down
  794. juce::String stop()
  795. {
  796. stopTimer();
  797. active = false;
  798. valueAtRelease = engine->getSong().mixer[(std::size_t) track].volume;
  799. engine->stop();
  800. juce::String text;
  801. text << " drag of insert " << track << "'s fader" << (visible ? "" : " (NOT VISIBLE)") << ": " << moves << " moves handled, " << dropped
  802. << " folded into the next (the message thread still busy with the previous one)\n"
  803. << " move waited for the message thread: " << describe (queueDelays) << "\n"
  804. << " input -> paint (move to the first frame over the fader): " << describe (latencies) << ", " << framesOverFader
  805. << " frames over the fader\n";
  806. return text;
  807. }
  808. juce::String release()
  809. {
  810. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  811. juce::ModifierKeys::currentModifiers = {};
  812. inject (x, lastY, false);
  813. return " song stopped, button still down: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " at the last move) "
  814. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  815. }
  816. juce::String released() const
  817. {
  818. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  819. return " after the release: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " when released) "
  820. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  821. }
  822. private:
  823. juce::Component* window = nullptr;
  824. lynx::AudioEngine* engine = nullptr;
  825. int track = 1;
  826. juce::Rectangle<int> railInWindow, watch;
  827. bool visible = false;
  828. float x = 0.0f, startY = 0.0f, centreY = 0.0f, amplitude = 0.0f, lastY = 0.0f;
  829. double t0 = 0.0;
  830. std::atomic<bool> active { false }, posted { false };
  831. std::atomic<int> dropped { 0 };
  832. int moves = 0, framesOverFader = 0;
  833. float valueAtRelease = 0.0f;
  834. std::vector<double> pending, latencies, queueDelays;
  835. static juce::String describe (std::vector<double> v)
  836. {
  837. if (v.empty())
  838. return "none";
  839. std::sort (v.begin(), v.end());
  840. const auto at = [&v] (double q) { return v[std::min (v.size() - 1, (std::size_t) (q * (double) v.size()))]; };
  841. return "p50 " + juce::String (at (0.5), 1) + " / p95 " + juce::String (at (0.95), 1) + " / p99 " + juce::String (at (0.99), 1) + " / max "
  842. + juce::String (v.back(), 1) + " ms";
  843. }
  844. void inject (float px, float py, bool down)
  845. {
  846. lastY = py;
  847. if (auto* peer = window != nullptr ? window->getPeer() : nullptr)
  848. {
  849. const auto local = peer->globalToLocal (window->localPointToGlobal (juce::Point<float> (px, py)));
  850. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local,
  851. down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys(),
  852. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation,
  853. juce::Time::currentTimeMillis());
  854. }
  855. }
  856. void hiResTimerCallback() override
  857. {
  858. if (! active.load())
  859. return;
  860. if (posted.exchange (true))
  861. {
  862. ++dropped;
  863. return;
  864. }
  865. const auto postedAt = juce::Time::getMillisecondCounterHiRes();
  866. juce::MessageManager::callAsync ([self = shared_from_this(), postedAt] {
  867. self->posted = false;
  868. if (! self->active.load())
  869. return;
  870. const auto now = juce::Time::getMillisecondCounterHiRes();
  871. self->queueDelays.push_back (now - postedAt);
  872. // up and down ~1.3 times a second, like the reporter's hand
  873. const auto y = self->centreY + self->amplitude * (float) std::sin (2.0 * juce::MathConstants<double>::pi * 1.3 * (now - self->t0) / 1000.0);
  874. self->inject (self->x, y, true);
  875. self->pending.push_back (postedAt);
  876. ++self->moves;
  877. });
  878. }
  879. };
  880. // --uiperf (round 190ry, Q3 fluidity): input -> paint of single events — a click on a note, a knob turned, a clip dragged,
  881. // a key typed in a search box. `arm` before the event is sent (the place it changes, in the window's coordinates); the
  882. // first frame the window paints over that place ends the wait. An event that painted nothing there before the next one
  883. // counts as missed.
  884. struct UiPerfLatency
  885. {
  886. double armedAt = -1.0;
  887. juce::Rectangle<int> watch;
  888. std::vector<double> ms;
  889. int missed = 0;
  890. void arm (juce::Rectangle<int> areaInWindow)
  891. {
  892. if (armedAt >= 0.0)
  893. ++missed;
  894. watch = areaInWindow;
  895. armedAt = juce::Time::getMillisecondCounterHiRes();
  896. }
  897. void framePainted (double now, juce::Rectangle<int> area)
  898. {
  899. if (armedAt >= 0.0 && area.intersects (watch))
  900. {
  901. ms.push_back (now - armedAt);
  902. armedAt = -1.0;
  903. }
  904. }
  905. juce::String take (const juce::String& what)
  906. {
  907. if (armedAt >= 0.0)
  908. ++missed;
  909. auto v = ms;
  910. std::sort (v.begin(), v.end());
  911. const auto at = [&v] (double q) { return v[std::min (v.size() - 1, (std::size_t) (q * (double) v.size()))]; };
  912. const auto text = " input -> paint (" + what + "): " + (v.empty() ? juce::String ("none")
  913. : "p50 " + juce::String (at (0.5), 1) + " / p95 " + juce::String (at (0.95), 1)
  914. + " / max " + juce::String (v.back(), 1) + " ms")
  915. + ", " + juce::String ((int) v.size()) + " events shown, " + juce::String (missed) + " missed\n";
  916. ms.clear();
  917. missed = 0;
  918. armedAt = -1.0;
  919. return text;
  920. }
  921. };
  922. class LynxApplication final : public juce::JUCEApplication
  923. {
  924. public:
  925. const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
  926. const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
  927. // the plugin scan runs copies of LYNX as child processes
  928. bool moreThanOneInstanceAllowed() override { return true; }
  929. // A file handed to the running application. macOS does this for every Finder double-click, "Open With" and Dock drop,
  930. // also the one that starts LYNX (its argv has no file). On Windows and Linux a second start is a second process
  931. // (moreThanOneInstanceAllowed) with the file as an argument, so this is not called there. Only the first file of a
  932. // multiple selection opens: a project replaces the one before it. (D#92, round 180a)
  933. void anotherInstanceStarted (const juce::String& commandLine) override
  934. {
  935. const auto files = lynx::safety::filesInCommandLine (commandLine.toStdString());
  936. if (files.empty())
  937. return;
  938. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile (juce::String::fromUTF8 (files.front().c_str()));
  939. if (! startupFileHandled) // still starting: openStartupFile takes it, nothing to ask about yet
  940. {
  941. fileToOpen = file;
  942. return;
  943. }
  944. if (mainWindow != nullptr)
  945. {
  946. mainWindow->toFront (true);
  947. mainWindow->getContent().openFileRequest (file);
  948. }
  949. }
  950. void initialise (const juce::String& commandLine) override
  951. {
  952. #if JUCE_LINUX || JUCE_BSD
  953. // issue #337 (round 190sk, JUCE fix 58): new X windows get LYNX's background colour, filled by the X server when
  954. // they are mapped, instead of showing the screen under them until the first paint
  955. juce::lynxX11WindowBackground = (unsigned long) lynx::theme::colour::bg1.getARGB() | 0xFF000000ul;
  956. #endif
  957. // round 190nx: --offline (or LYNX_OFFLINE=1) = no network connection of LYNX's own, before anything can start one
  958. if (juce::StringArray::fromTokens (commandLine, true).contains ("--offline"))
  959. lynx::offline::set (true);
  960. // round 166b: the copy of LYNX.exe that installs an update (ui/Updater.h) waits, installs, starts LYNX again
  961. if (commandLine.contains ("--apply-update") && lynx::updater::runApplyHelper (juce::StringArray::fromTokens (commandLine, true)))
  962. {
  963. updateHelper = true;
  964. quit();
  965. return;
  966. }
  967. // Windows, LYNX.exe in a folder with accents: run again from its ASCII short path (Waves editors crash otherwise)
  968. if (int code = 0; lynx::platform::relaunchFromAsciiPath (code))
  969. {
  970. relaunched = true;
  971. setApplicationReturnValue (code);
  972. quit();
  973. return;
  974. }
  975. // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave. A sanitizer build
  976. // (-DLYNX_SANITIZE, round 190rb) leaves the fault signals to ASan / UBSan, whose reports name the bad access,
  977. // unless LYNX_CRASHGUARD=1 asks for LYNX's own handlers (their tests)
  978. if (! sanitizerOwnsSignals())
  979. juce::SystemStats::setApplicationCrashHandler (onCrash);
  980. // rollup step 12: the crash handler's watchdog and its allocation-free crash file (platform/CrashGuard.h)
  981. lynx::crashguard::prepareCrashWatchdog (lynx::platform::settingsFile ("autosave").getFullPathName().toStdString());
  982. // rollup 0.1.28 (REA 190hb action 4, FL's "Init DWM"): the compositor on MMCSS, steadier frames under CPU load
  983. // (Windows; LYNX_DWM_MMCSS=0 leaves it off)
  984. lynx::powerhints::enableCompositorMmcss();
  985. // round als190ka (issue #193): a video's sound track for the sample library (a Live set's video clips)
  986. lynx::SampleLibrary::setVideoSoundDecoder ([] (const juce::File& video) { return lynx::videotracks::soundTrackWav (video); });
  987. // round 190ci: also for a fault on a stack Windows cannot walk, which never reaches that handler (Windows)
  988. lynx::crashguard::setUnwalkableFaultHandler (onCrash);
  989. if (const auto args = juce::StringArray::fromTokens (commandLine, true); args.contains ("--faulttest"))
  990. {
  991. // LYNX.exe --faulttest plain|unwalkable <folder> (round 190ci): ends by an access violation on purpose,
  992. // before any window, so that --selftest can check that the crash file gets written (into <folder>)
  993. const auto i = args.indexOf ("--faulttest");
  994. crashFolderForTest = juce::File (args[i + 2].unquoted());
  995. lynx::crashguard::setCrashFolder (crashFolderForTest.getFullPathName().toStdString());
  996. lynx::crashguard::quietCrashReports();
  997. // rollup step 12: heap = the C library's heap-corruption abort (no recovered project may be written: an
  998. // engine is set for the emergency save on purpose); hang = a crash handler that never returns (the watchdog
  999. // must end the process: LYNX_CRASH_WATCHDOG_S makes the test short)
  1000. // round 190rp: recovery = the project <folder>/before.lynx in an engine, then a crash: the crash handler's
  1001. // emergency save is what the recovery round trip (engine/RecoveryTest.cpp) opens and compares
  1002. // round 190rp: abort / terminate / unwind = aborts that are not a heap corruption (the emergency save runs:
  1003. // an engine with <folder>/before.lynx, if any, is set for it)
  1004. if (args[i + 1] == "abort" || args[i + 1] == "terminate" || args[i + 1] == "unwind")
  1005. {
  1006. static lynx::AudioEngine* engine = new lynx::AudioEngine (false);
  1007. juce::String error;
  1008. if (auto song = lynx::ProjectFile::load (crashFolderForTest.getChildFile ("before.lynx"), error))
  1009. engine->setSong (std::move (*song));
  1010. crashEngine = engine;
  1011. if (! sanitizerOwnsSignals())
  1012. lynx::crashguard::hardenSignals(); // (Windows: abort() reaches the crash handler through it)
  1013. lynx::crashguard::abortForTest (args[i + 1] == "terminate" ? 1 : args[i + 1] == "unwind" ? 2 : 0);
  1014. }
  1015. if (args[i + 1] == "recovery")
  1016. {
  1017. static lynx::AudioEngine* engine = new lynx::AudioEngine (false);
  1018. juce::String error;
  1019. if (auto song = lynx::ProjectFile::load (crashFolderForTest.getChildFile ("before.lynx"), error))
  1020. engine->setSong (std::move (*song));
  1021. crashEngine = engine;
  1022. lynx::crashguard::faultForTest (false);
  1023. }
  1024. if (args[i + 1] == "heap" || args[i + 1] == "hang")
  1025. {
  1026. static lynx::AudioEngine* engine = new lynx::AudioEngine (false);
  1027. crashEngine = engine;
  1028. if (args[i + 1] == "heap")
  1029. lynx::crashguard::heapCorruptionForTest();
  1030. lynx::crashguard::setHangInCrashHandlerForTest();
  1031. lynx::crashguard::faultForTest (false);
  1032. }
  1033. // round 190dt: guarded / guarded-libc = LYNX's own fault inside a guarded plugin call (Linux / macOS): it must
  1034. // reach the crash handler like any other; a return means the guard swallowed it
  1035. // round 190gg: thread / thread-libc = a fault on a thread of LYNX's own, with LYNX's executable watched as
  1036. // a plugin's module: it must not be parked as a plugin's thread
  1037. if (args[i + 1].startsWith ("thread"))
  1038. {
  1039. lynx::crashguard::faultOnOwnThreadForTest (args[i + 1] == "thread-libc");
  1040. crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText ("parked");
  1041. lynx::crashguard::exitNow (4);
  1042. }
  1043. if (args[i + 1].startsWith ("guarded"))
  1044. {
  1045. const auto code = lynx::crashguard::faultInGuardedCallForTest (args[i + 1] == "guarded-libc");
  1046. crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText (lynx::crashguard::describe (code));
  1047. lynx::crashguard::exitNow (4);
  1048. }
  1049. lynx::crashguard::faultForTest (args[i + 1] == "unwalkable");
  1050. }
  1051. // round 190rp: LYNX --recoverychild autosave|save|take <folder> (engine/RecoveryTest.cpp): writes until killed
  1052. if (const auto args = juce::StringArray::fromTokens (commandLine, true); args.contains ("--recoverychild"))
  1053. {
  1054. lynx::crashguard::quietCrashReports();
  1055. lynx::runRecoveryChild (args);
  1056. }
  1057. if (! sanitizerOwnsSignals())
  1058. lynx::crashguard::hardenSignals(); // issue #115: stack overflows and SIGTERM / SIGHUP leave a trace (Linux / macOS)
  1059. // issue #359 (round 190th): what LYNX opened so far (JUCE's message socket pair, the end-signal pipe, ...) is not
  1060. // handed on to the programs plugins start (Linux)
  1061. lynx::childhygiene::closeOnExecForOwnDescriptors();
  1062. // SFZ instruments (round 167o): their FLAC / OGG / AIFF / MP3 samples through JUCE's readers
  1063. lynx::sfz::setDecoder ([] (const std::string& path, lynx::sfz::Audio& out) {
  1064. juce::AudioFormatManager formats;
  1065. formats.registerBasicFormats();
  1066. std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (juce::File (juce::String::fromUTF8 (path.c_str()))));
  1067. if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (1 << 28) || reader->numChannels == 0)
  1068. return false;
  1069. const auto frames = (int) reader->lengthInSamples;
  1070. juce::AudioBuffer<float> buffer ((int) std::min (2u, reader->numChannels), frames);
  1071. if (! reader->read (&buffer, 0, frames, 0, true, buffer.getNumChannels() > 1))
  1072. return false;
  1073. out.channels.clear();
  1074. for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
  1075. out.channels.emplace_back (buffer.getReadPointer (ch), buffer.getReadPointer (ch) + frames);
  1076. out.sampleRate = reader->sampleRate;
  1077. out.loopStart = out.loopEnd = -1;
  1078. return true;
  1079. });
  1080. // child process of a sandboxed plugin: no window or audio of its own
  1081. if (lynx::runPluginSandboxWorker (commandLine))
  1082. {
  1083. lynx::crashguard::quietCrashReports();
  1084. sandboxChild = true;
  1085. return;
  1086. }
  1087. // --shot-scale <v> / --shot-suffix <text> (round 190bi, ui/ShotScale.h): the pixel scale and file-name suffix of every
  1088. // picture route, taken out here so the routes' own arguments keep their places
  1089. const auto args = lynx::shot::takeArguments (juce::StringArray::fromTokens (commandLine, true));
  1090. // round 190qw: --soft-look (picture routes, tests): this run draws in Options › Theme › Appearance › Soft (not saved)
  1091. if (args.contains ("--soft-look"))
  1092. {
  1093. auto soft = lynx::themeui::current();
  1094. soft.soft = true;
  1095. lynx::themeui::apply (soft, false);
  1096. }
  1097. // round 190np: whether this profile already had LYNX's UI settings before this start (an upgrade keeps what it had:
  1098. // no welcome card), and --demo (ui/DemoMode.h: the tutorial-video pipeline's automation mode)
  1099. lynx::onboardui::profileExistedAtStart() = lynx::PluginHost::settingsFolder().getChildFile ("ui-options.txt").existsAsFile();
  1100. if (args.contains ("--demo"))
  1101. lynx::demo::setActive (true);
  1102. // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
  1103. lynx::i18n::initialise (args);
  1104. // interface font: saved in Settings › General; --uifont "Name" overrides it for this run
  1105. const auto uiFontArg = args.indexOf ("--uifont");
  1106. lookAndFeel.applyInterfaceFont (lynx::i18n::current(), uiFontArg >= 0 ? args[uiFontArg + 1].unquoted() : juce::String());
  1107. // text size (issue #189): saved in Settings › General; --textsize 125 overrides it for this run
  1108. const auto textSizeArg = args.indexOf ("--textsize");
  1109. lynx::theme::setTextSize (textSizeArg >= 0 ? args[textSizeArg + 1].getIntValue() : lynx::theme::savedTextSize());
  1110. // bold text (round 190jp): saved in Settings › General; --boldtext 1 (labels) or 2 (all) overrides it for this run
  1111. const auto boldTextArg = args.indexOf ("--boldtext");
  1112. lynx::theme::setBoldText (boldTextArg >= 0 ? args[boldTextArg + 1].getIntValue() : lynx::theme::savedBoldText());
  1113. // round 190je: FL-style condensed labels (Settings › General); --condensedlabels for one run. --menustyle flClassic: FL's
  1114. // light menus for one run (Settings › Theme keeps the saved choice)
  1115. lynx::theme::setCondensedLabels (args.contains ("--condensedlabels") || lynx::theme::savedCondensedLabels());
  1116. if (const auto menuStyleArg = args.indexOf ("--menustyle"); menuStyleArg >= 0)
  1117. {
  1118. lynx::theme::menus::setStyle (lynx::themes::menuStyleFromId (args[menuStyleArg + 1].unquoted().toStdString()));
  1119. lookAndFeel.refreshColours();
  1120. }
  1121. if (args.contains ("--showcase"))
  1122. {
  1123. // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
  1124. const auto i = args.indexOf ("--showcase");
  1125. runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
  1126. return;
  1127. }
  1128. if (args.contains ("--demosongs"))
  1129. {
  1130. // round 190dv: LYNX's two short genre demos (core/DemoSongs.h) as .lynx files: --demosongs <folder>
  1131. // (resources/demos/ in the repository)
  1132. const auto i = args.indexOf ("--demosongs");
  1133. runDemoSongs (args[i + 1].unquoted());
  1134. return;
  1135. }
  1136. if (args.contains ("--perfgen"))
  1137. {
  1138. // round perfgate190id: the big-project performance gate's synthetic projects (core/PerfProjects.h) as .lynx
  1139. // files with their WAVs: --perfgen <folder> [report.txt] [name,name...]; the save and load times in the report
  1140. const auto i = args.indexOf ("--perfgen");
  1141. const auto report = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1142. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1143. runPerfGen (args[i + 1].unquoted(), report, only);
  1144. return;
  1145. }
  1146. if (args.contains ("--sandboxtest"))
  1147. {
  1148. const auto i = args.indexOf ("--sandboxtest");
  1149. runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1150. return;
  1151. }
  1152. // round 190jg (BUILD-LIST 11 + 18, engine/HostingTests.h): grouped plugin processes, CLAP extensions, timing
  1153. if (args.contains ("--sandboxgrouptest") || args.contains ("--sandboxbench") || args.contains ("--clapext")
  1154. || args.contains ("--automationtimingtest") || args.contains ("--pluginbench") || args.contains ("--temposynctest")
  1155. || args.contains ("--latency356test"))
  1156. {
  1157. const auto value = [&args] (const char* name, int fallback) {
  1158. return args.contains (name) ? args[args.indexOf (name) + 1].getIntValue() : fallback;
  1159. };
  1160. auto code = 1;
  1161. if (const auto i = args.indexOf ("--sandboxgrouptest"); i >= 0)
  1162. code = lynx::runSandboxGroupTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1163. args.contains ("--crash") ? args[args.indexOf ("--crash") + 1].unquoted() : juce::String());
  1164. else if (const auto b = args.indexOf ("--sandboxbench"); b >= 0)
  1165. code = lynx::runSandboxBench (args[b + 1].unquoted(), args[b + 2].unquoted(), value ("--plugins", 8), value ("--block", 256),
  1166. args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 5.0);
  1167. else if (const auto pb = args.indexOf ("--pluginbench"); pb >= 0) // round 190of: per-plugin cost (engine/HostingTests.h)
  1168. code = lynx::runPluginBench (args[pb + 1].unquoted(), args[pb + 2].unquoted(), value ("--block", 256),
  1169. args.contains ("--rate") ? args[args.indexOf ("--rate") + 1].getDoubleValue() : 48000.0,
  1170. args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 4.0, value ("--types", 8),
  1171. args.contains ("--names") ? args[args.indexOf ("--names") + 1].unquoted() : juce::String(),
  1172. args.contains ("--editors"));
  1173. else if (const auto c = args.indexOf ("--clapext"); c >= 0)
  1174. code = lynx::runClapExtTest (args[c + 1].unquoted(), args[c + 2].unquoted());
  1175. else if (const auto t = args.indexOf ("--automationtimingtest"); t >= 0)
  1176. code = lynx::runAutomationTimingTest (args[t + 1].unquoted(), args[t + 2].unquoted());
  1177. else if (const auto ts = args.indexOf ("--temposynctest"); ts >= 0) // round 190sj (Discord 10.net): engine/HostingTests.h
  1178. {
  1179. juce::StringArray plugins;
  1180. for (int k = ts + 2; k < args.size() && ! args[k].startsWith ("--"); ++k)
  1181. plugins.add (args[k].unquoted());
  1182. code = lynx::runTempoSyncTest (plugins, args[ts + 1].unquoted());
  1183. }
  1184. else if (const auto lt = args.indexOf ("--latency356test"); lt >= 0) // round 190te (issue #356): engine/HostingTests.h
  1185. {
  1186. juce::StringArray plugins;
  1187. for (int k = lt + 2; k < args.size() && ! args[k].startsWith ("--"); ++k)
  1188. plugins.add (args[k].unquoted());
  1189. code = lynx::runLatencyTransportTest (plugins, args[lt + 1].unquoted());
  1190. }
  1191. setApplicationReturnValue (code);
  1192. quit();
  1193. return;
  1194. }
  1195. if (args.contains ("--bridge32test"))
  1196. {
  1197. // LYNX.exe --bridge32test "LYNX Test Synth 32.dll" report.txt [--compare "LYNX Test Synth.dll"] (round 176a):
  1198. // the 32-bit plugin bridge (engine/Bridge32Test.cpp)
  1199. const auto i = args.indexOf ("--bridge32test");
  1200. const auto compare = args.contains ("--compare") ? args[args.indexOf ("--compare") + 1].unquoted() : juce::String();
  1201. setApplicationReturnValue (lynx::runBridge32Test (args[i + 1].unquoted(), args[i + 2].unquoted(), compare));
  1202. quit();
  1203. return;
  1204. }
  1205. if (args.contains ("--rtstress"))
  1206. {
  1207. // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--type "driver type"] [--device "output"]
  1208. // [--no-window] [--record take.wav]: the real app (window, audio device) plays the project and reports the callbacks
  1209. // that missed their deadline (REA round 87); --type/--device pick another driver for this run only (round 97);
  1210. // --record also records the input during the run, like Rec + Play, and moves the take to take.wav (round 106)
  1211. const auto i = args.indexOf ("--rtstress");
  1212. const auto seconds = args[i + 3].getDoubleValue();
  1213. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  1214. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1215. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  1216. runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer,
  1217. option ("--type"), option ("--device"), option ("--record"));
  1218. return;
  1219. }
  1220. if (args.contains ("--stoppedbench190sp"))
  1221. {
  1222. // LYNX --stoppedbench190sp project report [--blocks N] [--warmup W] [--settle S] [--buffer B] [--rate R] (round 190sp,
  1223. // src/StoppedBench190sp.inc): the engine's device callback while stopped, for instruction-count compares
  1224. const auto i = args.indexOf ("--stoppedbench190sp");
  1225. const auto value = [&args] (const char* name, double fallback) {
  1226. return args.contains (name) ? args[args.indexOf (name) + 1].getDoubleValue() : fallback;
  1227. };
  1228. runStoppedBench190sp (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), (int) value ("--blocks", 400),
  1229. (int) value ("--warmup", 400), value ("--settle", 3.0), juce::jlimit (16, 4096, (int) value ("--buffer", 256)),
  1230. juce::jlimit (8000.0, 384000.0, value ("--rate", 44100.0)));
  1231. return;
  1232. }
  1233. if (args.contains ("--renderaheadtest"))
  1234. {
  1235. // LYNX --renderaheadtest report.txt [project.flp|.lynx ...] [--buffer N] [--seconds S] (round 190gq): the engine's
  1236. // own device callback (a stand-in device driven block by block, as --cliplooptest) plays the showcase song (from
  1237. // the start, round a loop region that wraps mid-block, in Pattern mode) and each project with Options › Audio
  1238. // settings › "Render ahead" off, then on. The two outputs must be the same to the bit, nothing rendered ahead
  1239. // may be dropped, and most blocks must come from the ring. No window, no audio device.
  1240. const auto i = args.indexOf ("--renderaheadtest");
  1241. juce::StringArray projects;
  1242. for (int k = i + 2; k < args.size() && ! args[k].startsWith ("--"); ++k)
  1243. projects.add (args[k].unquoted());
  1244. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 128;
  1245. const auto seconds = args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 12.0;
  1246. runRenderAheadTest (juce::File (args[i + 1].unquoted()), projects, juce::jlimit (16, 2048, buffer), seconds > 0.0 ? seconds : 12.0);
  1247. return;
  1248. }
  1249. if (args.contains ("--cliplooptest"))
  1250. {
  1251. // LYNX --cliplooptest report.txt [export.wav] (round 167q, issue #25: 0.1.21 drew the repeats of a stretched
  1252. // pattern clip but played the pattern once). The real engine's device callback (a stand-in device, driven
  1253. // block by block) plays a synth's 1-bar pattern in a 4-bar clip: every repeat must sound as bar 1, also
  1254. // starting inside a repeat, after a jump mid-clip and in a loop region; the WAV export (written to
  1255. // export.wav and read back) the same. With the LYNX extra off, bars 2-4 must be silent (FL's behaviour).
  1256. const auto i = args.indexOf ("--cliplooptest");
  1257. runClipLoopTest (juce::File (args[i + 1].unquoted()), args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File());
  1258. return;
  1259. }
  1260. if (args.contains ("--devicechangetest"))
  1261. {
  1262. // LYNX --devicechangetest report.txt [switches] [--plugin file]... (round 190c, issue #134: changing the
  1263. // output device with a project open crashed LYNX). The engine plays a project of every instrument and effect
  1264. // it can make here on stand-in devices with real callback threads, while the output device, its sample
  1265. // rate and its buffer size change the way Settings > Audio changes them (8 kHz mono to 192 kHz, buffers of
  1266. // 32 to 16384 samples, a device plugged in, the open one unplugged, one that refuses to open). After every
  1267. // change the song must sound, finite, at the new rate. No window, no real audio or MIDI device.
  1268. const auto i = args.indexOf ("--devicechangetest");
  1269. const juce::File report (args[i + 1].unquoted());
  1270. const auto switches = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  1271. juce::StringArray plugins;
  1272. for (int k = 0; k + 1 < args.size(); ++k)
  1273. if (args[k] == "--plugin")
  1274. plugins.add (args[k + 1].unquoted());
  1275. auto text = std::make_shared<juce::String>();
  1276. // --quick: the selftest's handful of instruments and effects instead of every one
  1277. const auto result = lynx::AudioEngine::deviceChangeSelfTest (switches > 0 ? switches : 40, ! args.contains ("--quick"), plugins, [report, text] (const juce::String& line) {
  1278. *text << line << "\n";
  1279. report.replaceWithText (*text + "(running)\n"); // what was reached, if it crashes
  1280. });
  1281. *text << "device_change=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1282. report.replaceWithText (*text);
  1283. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1284. quit();
  1285. return;
  1286. }
  1287. if (args.contains ("--exportlivetest"))
  1288. {
  1289. // LYNX --exportlivetest report.txt [--plugin file]... (round 190jb): exports with the live plugin instances (as
  1290. // FL renders) against playback on a stand-in device, the plugins given back afterwards. No window.
  1291. const auto i = args.indexOf ("--exportlivetest");
  1292. const juce::File report (args[i + 1].unquoted());
  1293. juce::StringArray files;
  1294. for (int k = 0; k + 1 < args.size(); ++k)
  1295. if (args[k] == "--plugin")
  1296. files.add (args[k + 1].unquoted());
  1297. juce::String text;
  1298. const auto result = lynx::AudioEngine::exportLiveSelfTest ([&text] (const juce::String& line) { text << line << "\n"; }, files);
  1299. text << "export_live=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1300. report.replaceWithText (text);
  1301. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1302. quit();
  1303. return;
  1304. }
  1305. if (args.contains ("--sharetest"))
  1306. {
  1307. // LYNX --sharetest <folder> <case> report.txt (round 190ks): the memory 8 identical SoundFont / Sampler channels
  1308. // cost (LYNX_CONTENT_SHARE=0: byte copies held separately, as before). No window.
  1309. const auto i = args.indexOf ("--sharetest");
  1310. const auto result = lynx::AudioEngine::shareMemorySelfTest (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted());
  1311. juce::File (args[i + 3].unquoted()).replaceWithText ("share=" + result + "\nresult=" + (result.startsWith ("OK") ? "OK" : "FAILED") + "\n");
  1312. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1313. quit();
  1314. return;
  1315. }
  1316. if (args.contains ("--padrectest"))
  1317. {
  1318. // LYNX --padrectest "<LYNX Test Pads.vst3>" report.txt (round 190ks, GitHub #198): a take records the notes a
  1319. // hosted plugin plays from its own window (the live engine on a stand-in device). No window.
  1320. const auto i = args.indexOf ("--padrectest");
  1321. const auto result = lynx::AudioEngine::padRecordSelfTest (args[i + 1].unquoted());
  1322. juce::File (args[i + 2].unquoted()).replaceWithText ("pad_record=" + result + "\nresult=" + (result.startsWith ("OK") ? "OK" : "FAILED") + "\n");
  1323. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1324. quit();
  1325. return;
  1326. }
  1327. if (args.contains ("--midiouttest"))
  1328. {
  1329. // LYNX --midiouttest report.txt (round 190jl): MIDI Out channels to the hardware MIDI outputs on their port
  1330. // (the sender's dry run and the live engine on a stand-in device). No window.
  1331. const auto i = args.indexOf ("--midiouttest");
  1332. const auto result = lynx::AudioEngine::midiOutPortSelfTest();
  1333. juce::File (args[i + 1].unquoted()).replaceWithText ("midi_out_ports=" + result + "\nresult=" + (result.startsWith ("OK") ? "OK" : "FAILED") + "\n");
  1334. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1335. quit();
  1336. return;
  1337. }
  1338. if (args.contains ("--aratest"))
  1339. {
  1340. // LYNX --aratest <plugin.vst3> <audio.wav> <out folder> [project.lynx] (round 190kx, engine/AraTest.cpp): ARA 2
  1341. // hosting end to end (a plain clip vs the clip in the ARA plugin, the document archived and restored). No window.
  1342. const auto i = args.indexOf ("--aratest");
  1343. const juce::File out (args[i + 3].unquoted());
  1344. juce::String text;
  1345. const auto result = lynx::araSelfTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), out,
  1346. args.size() > i + 4 ? juce::File (args[i + 4].unquoted()) : juce::File(),
  1347. [&text, out] (const juce::String& line) {
  1348. text << line << "\n";
  1349. out.getChildFile ("aratest.txt").replaceWithText (text + "(running)\n");
  1350. });
  1351. text << "ara=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1352. out.getChildFile ("aratest.txt").replaceWithText (text);
  1353. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1354. quit();
  1355. return;
  1356. }
  1357. if (args.contains ("--exportparitytest") || args.contains ("--midihotplugtest"))
  1358. {
  1359. // LYNX --exportparitytest report.txt (round 190gh, B7): the export against playback through a stand-in audio
  1360. // device, stems adding up to the mix with one length, the PDC trim. LYNX --midihotplugtest report.txt (B8):
  1361. // MIDI devices plugged in and out (stand-in device lists) while messages arrive. No window.
  1362. const auto parity = args.contains ("--exportparitytest");
  1363. const auto i = args.indexOf (parity ? "--exportparitytest" : "--midihotplugtest");
  1364. const juce::File report (args[i + 1].unquoted());
  1365. juce::String text;
  1366. const auto result = parity ? lynx::AudioEngine::exportParitySelfTest ([&text] (const juce::String& line) { text << line << "\n"; })
  1367. : lynx::AudioEngine::midiHotplugSelfTest();
  1368. text << (parity ? "export_parity=" : "midi_hotplug=") << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1369. report.replaceWithText (text);
  1370. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1371. quit();
  1372. return;
  1373. }
  1374. if (args.contains ("--shortexportstress"))
  1375. {
  1376. // LYNX --shortexportstress report.txt [count] [--seed N] [--no-realtime] [--plugin file] (round 190hn, issue #138): `count`
  1377. // random export settings over short sounds at the very start of the song, each exported again a bar later; a
  1378. // file that comes out silent or quieter fails (engine/ShortExportTest.h). No window.
  1379. const auto i = args.indexOf ("--shortexportstress");
  1380. const juce::File report (args[i + 1].unquoted());
  1381. const auto count = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 200;
  1382. const auto s = args.indexOf ("--seed");
  1383. const auto seed = s >= 0 && s + 1 < args.size() ? args[s + 1].getLargeIntValue() : juce::Time::currentTimeMillis();
  1384. auto text = std::make_shared<juce::String>();
  1385. const auto pl = args.indexOf ("--plugin");
  1386. lynx::shortexport::stress (count, seed, ! args.contains ("--no-realtime"), pl >= 0 && pl + 1 < args.size() ? args[pl + 1].unquoted() : juce::String(),
  1387. [report, text] (const juce::String& line) {
  1388. *text << line << "\n";
  1389. report.replaceWithText (*text + "(running)\n");
  1390. },
  1391. [this, report, text] (juce::String result) {
  1392. *text << "short_export_stress=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1393. report.replaceWithText (*text);
  1394. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1395. quit();
  1396. });
  1397. return;
  1398. }
  1399. if (args.contains ("--shortexporttest"))
  1400. {
  1401. // LYNX --shortexporttest report.txt [repeats] [--plugin file]... (round 190c, issue #138: a short note at
  1402. // the very start of the Playlist exported quiet). Every instrument LYNX can make here, and a synth with
  1403. // effects, tail modes, normalising and other rates, exported through the Export window's path (the job
  1404. // made on the message thread, run on its own thread, the message loop running) with a 2-second note at
  1405. // tick 0 and again with it at bar 2: the note must come out the same. No window.
  1406. const auto i = args.indexOf ("--shortexporttest");
  1407. const juce::File report (args[i + 1].unquoted());
  1408. const auto repeats = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  1409. juce::StringArray plugins;
  1410. for (int k = 0; k + 1 < args.size(); ++k)
  1411. if (args[k] == "--plugin")
  1412. plugins.add (args[k + 1].unquoted());
  1413. auto text = std::make_shared<juce::String>();
  1414. lynx::shortexport::run (! args.contains ("--quick"), repeats > 0 ? repeats : 3, plugins, // (--quick: a handful of instruments, round 190hn)
  1415. [report, text] (const juce::String& line) {
  1416. *text << line << "\n";
  1417. report.replaceWithText (*text + "(running)\n");
  1418. },
  1419. [this, report, text] (juce::String result) {
  1420. *text << "short_export=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1421. report.replaceWithText (*text);
  1422. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1423. quit();
  1424. });
  1425. return;
  1426. }
  1427. if (args.contains ("--slicexedittest"))
  1428. {
  1429. // LYNX --slicexedittest project script.txt report.txt [png-prefix] (round 190aj): the Slicex editor of the
  1430. // project's first Slicex channel, off screen, driven by the script's commands (ui/SlicexEditor.h; mouse
  1431. // gestures at fractions of the deck's width, the menu entries, shortcuts). The report holds each command
  1432. // and what the state held after it; "shot <name>" writes <png-prefix><name>.png.
  1433. const auto i = args.indexOf ("--slicexedittest");
  1434. runSlicexEditTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
  1435. args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
  1436. return;
  1437. }
  1438. if (args.contains ("--dwedittest"))
  1439. {
  1440. // LYNX --dwedittest project script.txt report.txt [png-prefix] (round 190hz): the DirectWave editor of the
  1441. // project's first DirectWave channel, off screen, driven by the script's commands (ui/DirectWaveEditor.h);
  1442. // "shot <name>" writes <png-prefix><name>.png. A project path "new" makes a new DirectWave channel.
  1443. const auto i = args.indexOf ("--dwedittest");
  1444. runDirectWaveEditTest (args[i + 1].unquoted(), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
  1445. args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
  1446. return;
  1447. }
  1448. if (args.contains ("--slicexkeytest"))
  1449. {
  1450. // LYNX --slicexkeytest report.txt (round 190ac): what a click on the Slicex editor's keyboard sends
  1451. // (AudioEngine::sendLiveNote on the channel, velocity 100/128) through the real engine's device callback
  1452. // (a stand-in device, driven block by block): the key's region must sound, on the channel's mixer meter
  1453. // too, another key must play another region, and the note-off must end it.
  1454. runSlicexKeyTest (juce::File (args[args.indexOf ("--slicexkeytest") + 1].unquoted()));
  1455. return;
  1456. }
  1457. if (args.contains ("--countinrectest"))
  1458. {
  1459. // LYNX --countinrectest report.txt (round 170d, the Busy Works video: the chord on the downbeat after the
  1460. // pre-count was lost). The real engine's device callback (a stand-in device: 48 kHz, blocks of 512, 256
  1461. // samples of output latency) records a Song-mode take from bar 3 with a 1-bar count-in. Pass 1 finds where
  1462. // the metronome's bar-3 click is heard; pass 2 plays MIDI notes stamped at the times they are heard around
  1463. // 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
  1464. // LYNX's MIDI input. Every note must land on the tick it was heard at (the chord on bar 3).
  1465. const auto i = args.indexOf ("--countinrectest");
  1466. runCountInRecordTest (juce::File (args[i + 1].unquoted()));
  1467. return;
  1468. }
  1469. if (args.contains ("--bendrectest"))
  1470. {
  1471. // LYNX --bendrectest report.txt [song|pattern] (round 167a, issue #12): pitch bend recording end to end. A
  1472. // controller's pitch wheel is injected into LYNX's MIDI input (as a device would send it) while recording
  1473. // plays: a held note and a wheel sweep 0 → full up → full down → centre. The recorded lane (pattern mode) or
  1474. // automation clip (song mode) of the channel's pitch bend must follow the sweep.
  1475. const auto i = args.indexOf ("--bendrectest");
  1476. const auto songMode = args.size() > i + 2 && args[i + 2] == "song";
  1477. runBendRecordTest (juce::File (args[i + 1].unquoted()), songMode);
  1478. return;
  1479. }
  1480. if (args.contains ("--rectest"))
  1481. {
  1482. // LYNX --rectest report.txt [seconds] [--type T] [--device D] [--input I] [--loop] [--buffer N]
  1483. // (round 163): records a click track through a loopback (cable, interface loopback or PipeWire's
  1484. // pw-loopback): pings the round trip, plays a click on every beat from an audio clip, records it on Insert 1,
  1485. // stops, and checks every recorded click's song position on the Playlist against its beat (samples).
  1486. // --loop: loop recording over bars 2-4 (take lanes). --punch: punch in/out on bars 3-4 with 1 bar of pre-roll
  1487. // and 1 of post-roll (playback stops by itself after the post-roll).
  1488. const auto i = args.indexOf ("--rectest");
  1489. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  1490. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  1491. runRecordTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 20.0, option ("--type"), option ("--device"), option ("--input"),
  1492. args.contains ("--loop") ? 1 : args.contains ("--punch") ? 2 : 0, option ("--pdc").getIntValue(), option ("--buffer").getIntValue());
  1493. return;
  1494. }
  1495. if (args.contains ("--hwinserttest"))
  1496. {
  1497. // LYNX --hwinserttest report.txt [seconds] [--type T] [--device D] [--input I] [--buffer N] (round 164d): a
  1498. // hardware insert through a loopback cable (output pair 1-2 -> input pair 1-2; the Master plays nowhere, so
  1499. // the cable carries the send only). The same click track plays on two inserts: Insert 1 through the
  1500. // hardware insert (panned left), Insert 2 dry (panned right). The insert's own ping measures the round
  1501. // trip, PDC delays the dry path by it, and every click of the Master's left side must sit on the same
  1502. // sample as the right side's.
  1503. const auto i = args.indexOf ("--hwinserttest");
  1504. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  1505. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 10.0;
  1506. // round 165c: --patcher puts the insert inside a Patcher on Insert 1; --bounce file.wav then exports the song in real
  1507. // time through the device (Export › "Render through the hardware in real time") and offline, and compares them
  1508. runHwInsertTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 10.0, option ("--type"), option ("--device"), option ("--input"),
  1509. option ("--buffer").getIntValue(), args.contains ("--patcher"),
  1510. args.contains ("--bounce") ? juce::File (option ("--bounce")) : juce::File());
  1511. return;
  1512. }
  1513. if (args.contains ("--uiperf"))
  1514. {
  1515. // LYNX --uiperf project.(flp|lynx) report.txt: the heavy UI cases in the real window, every frame timed (round 161)
  1516. const auto i = args.indexOf ("--uiperf");
  1517. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1518. runUiPerf (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1519. return;
  1520. }
  1521. if (args.contains ("--cachetest"))
  1522. {
  1523. // LYNX --cachetest project.(flp|lynx) report.txt (round 174f): the Playlist's cached picture against exact
  1524. // paints after zooms, scrolls and repaints, off screen (no window)
  1525. const auto i = args.indexOf ("--cachetest");
  1526. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1527. runCacheTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1528. return;
  1529. }
  1530. if (args.contains ("--picturetest"))
  1531. {
  1532. // LYNX --picturetest report.txt [project.(flp|lynx)] (round 190bm): the Playlist and the Mixer drawn through
  1533. // their cached pictures at 100-300 %, into native and software targets, against straight paints; off
  1534. // screen (no window)
  1535. const auto i = args.indexOf ("--picturetest");
  1536. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1537. runPictureTest (juce::File (args[i + 1].unquoted()), i + 2 < args.size() ? juce::File (args[i + 2].unquoted()) : juce::File());
  1538. return;
  1539. }
  1540. if (args.contains ("--paintcachetest"))
  1541. {
  1542. // LYNX --paintcachetest report.txt (round 190ki): --selftest's paint_caches item alone (the shape tiles, the
  1543. // cached FL toolbar tiles; LYNX_TILE_DEBUG=<folder> keeps the tiles' pictures as PNGs), off screen
  1544. const auto i = args.indexOf ("--paintcachetest");
  1545. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1546. auto result = lynx::theme::paintCacheSelfTest();
  1547. const auto tiles = lynx::flTileCacheSelfTest();
  1548. juce::File (args[i + 1].unquoted()).replaceWithText ("paint_caches=" + result + "\nfl_tiles=" + tiles + "\n");
  1549. setApplicationReturnValue (result.startsWith ("OK") && tiles == "OK" ? 0 : 1);
  1550. quit();
  1551. return;
  1552. }
  1553. if (args.contains ("--timertest"))
  1554. {
  1555. // LYNX --timertest report.txt (round 174f): ui::TimerWhileShowing through hide / show / minimise (opens a small window)
  1556. runTimerTest (juce::File (args[args.indexOf ("--timertest") + 1].unquoted()));
  1557. return;
  1558. }
  1559. if (args.contains ("--livepeer"))
  1560. {
  1561. // LYNX --livepeer host|guest|rejoin <folder> [--relay URL] [--code CODE|@file]: one computer's side of a live
  1562. // session between two real computers, no window (round 190ah)
  1563. setApplicationReturnValue (lynx::livetest::runPeer (args));
  1564. quit();
  1565. return;
  1566. }
  1567. if (args.contains ("--offlinetest"))
  1568. {
  1569. // LYNX --offlinetest report.txt [--offline] (round 190nx): with LYNX_OFFLINE=1 or --offline every place that
  1570. // would use the network refuses and says so. The test script runs it under `unshare -rn` with strace and counts
  1571. // the connect() calls of internet sockets: zero (tests/offline-network-test.sh)
  1572. const auto report = juce::File::getCurrentWorkingDirectory().getChildFile (args[args.indexOf ("--offlinetest") + 1].unquoted());
  1573. juce::String log;
  1574. bool ok = true;
  1575. auto check = [&] (bool good, const juce::String& what) {
  1576. ok = ok && good;
  1577. log << (good ? "ok " : "FAIL ") << what << "\n";
  1578. };
  1579. check (lynx::offline::enabled(), "offline mode is on");
  1580. {
  1581. std::string why;
  1582. check (! lynx::livelink::Connection::available (&why) && why.find ("offline") != std::string::npos, "live link unavailable: " + juce::String (why));
  1583. 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");
  1584. }
  1585. {
  1586. lynx::AudioEngine offlineEngine (false);
  1587. lynx::LiveSessionManager live (offlineEngine);
  1588. lynx::LiveSessionManager::Options o;
  1589. o.relay = "https://relay.lynx-share.com";
  1590. o.name = "Offline test";
  1591. o.inlineWork = true;
  1592. live.start (o);
  1593. check (live.getState() == lynx::LiveSessionManager::State::ended && ! live.isActive(), "Start live session refused: " + live.getStatus());
  1594. lynx::LiveSessionManager joiner (offlineEngine);
  1595. joiner.join ("LYNX-AAAA-AAAA-AAAA-AAAA-AAAA", o);
  1596. check (joiner.getState() == lynx::LiveSessionManager::State::ended && ! joiner.isActive(), "Join live session refused: " + joiner.getStatus());
  1597. }
  1598. {
  1599. const auto err = lynx::crashreporter::sendNow ("{\"offline\":\"test\"}");
  1600. check (err.containsIgnoreCase ("offline"), "crash report upload refused: " + err);
  1601. }
  1602. lynx::updater::startAutomaticCheck();
  1603. lynx::updater::checkNow();
  1604. lynx::updater::goBack();
  1605. check (true, "update check, update dialog and go-back opened no connection (see strace)");
  1606. log << (ok ? "RESULT OK\n" : "RESULT FAIL\n");
  1607. report.replaceWithText (log);
  1608. setApplicationReturnValue (ok ? 0 : 1);
  1609. quit();
  1610. return;
  1611. }
  1612. if (args.contains ("--livetest"))
  1613. {
  1614. // LYNX --livetest report.txt [--relay URL]: a live session of four peers over the relay (round 169b)
  1615. setApplicationReturnValue (lynx::livetest::run (args));
  1616. quit();
  1617. return;
  1618. }
  1619. if (args.contains ("--selftest"))
  1620. {
  1621. const auto i = args.indexOf ("--selftest");
  1622. // round 190mo: a temp folder of this run alone (two runs at once shared the fixed temp names of its items),
  1623. // and on Linux room for its main-thread stack (it reached 7.4 of the usual 8 MB: AudioEngines on the stack)
  1624. selfTestTemp = lynx::platform::useOwnTempFolder ("lynx-selftest");
  1625. lynx::platform::allowMainThreadStack ((std::size_t) 64 << 20);
  1626. runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1627. return;
  1628. }
  1629. if (args.contains ("--scan-one"))
  1630. {
  1631. // child process of the plugin scan (see PluginHost::scan)
  1632. const auto i = args.indexOf ("--scan-one");
  1633. // no crash dialogs from the plugin being examined; and once the result is written, the process ends without
  1634. // unloading it: a Waves shell crashed in its own teardown at exit (Intel GPU driver fail-fast, 0xC0000409),
  1635. // which showed Windows' crash dialog and made the scan reject the whole shell (round 111)
  1636. lynx::crashguard::quietCrashReports();
  1637. lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
  1638. lynx::crashguard::exitNow (0);
  1639. }
  1640. if (args.contains ("--splashshot"))
  1641. {
  1642. // LYNX --splashshot <folder> (round 190hd): the splash card drawn as the JUCE card is and as the card on its own
  1643. // thread is (ui/Splash.h), side by side; no window
  1644. const auto shots = lynx::writeSplashShots (juce::File (args[args.indexOf ("--splashshot") + 1].unquoted()));
  1645. setApplicationReturnValue (shots.size() == 20 ? 0 : 1);
  1646. quit();
  1647. return;
  1648. }
  1649. if (args.contains ("--browser-indexer"))
  1650. {
  1651. // round 190hd: the Browser's indexer, a low-priority child of the LYNX window (BrowserComponent.h): no window,
  1652. // no session, no audio; it ends with its parent
  1653. lynx::crashguard::quietCrashReports();
  1654. lynx::crashguard::exitNow (lynx::BrowserComponent::runIndexerProcess (args));
  1655. }
  1656. if (args.contains ("--packageinfo"))
  1657. {
  1658. // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
  1659. // workflow runs it inside the installed test package
  1660. juce::File (args[args.indexOf ("--packageinfo") + 1].unquoted()).replaceWithText (lynx::platform::packageReport());
  1661. quit();
  1662. return;
  1663. }
  1664. if (args.contains ("--paths"))
  1665. {
  1666. // diagnostics: folders LYNX searches
  1667. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  1668. juce::String report;
  1669. report << "programs=" << programs.getFullPathName() << "\n";
  1670. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  1671. report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
  1672. juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
  1673. quit();
  1674. return;
  1675. }
  1676. if (args.contains ("--fldb"))
  1677. {
  1678. // diagnostics: LYNX.exe --fldb report.txt [project.flp]: the FL Studio installation, its plugin database,
  1679. // the suggested plugin folders and, for a project, how each of its plugins resolves (read-only)
  1680. const auto i = args.indexOf ("--fldb");
  1681. const auto fl = lynx::findFlStudio();
  1682. lynx::PluginHost host (false);
  1683. juce::String report;
  1684. report << "install=" << fl.installDir.getFullPathName() << "\nuserdata=" << fl.userData.getFullPathName() << "\n";
  1685. for (const auto& f : fl.vstFolders)
  1686. report << "flvstfolder=" << f << "\n";
  1687. report << "dbfiles=" << host.flPluginDatabaseFiles() << " entries=" << (int) host.flPluginDatabase().entries().size() << "\n";
  1688. for (const auto& e : host.flPluginDatabase().entries())
  1689. report << " entry: " << juce::String::fromUTF8 (e.name.c_str()) << " | " << juce::String::fromUTF8 (e.path.c_str()) << " | role=" << e.role << "\n";
  1690. const auto suggested = host.suggestedFolders();
  1691. for (int k = 0; k < suggested.getNumPaths(); ++k)
  1692. report << "folder=" << suggested[k].getFullPathName() << "\n";
  1693. if (const juce::File project (args[i + 2].unquoted()); project.existsAsFile())
  1694. {
  1695. juce::MemoryBlock data;
  1696. project.loadFileAsData (data);
  1697. try
  1698. {
  1699. for (const auto& use : lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })))
  1700. {
  1701. juce::String how;
  1702. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  1703. const auto* entry = host.flPluginDatabase().match (use.plugin, use.instrument);
  1704. report << "plugin: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  1705. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known"))
  1706. << (entry != nullptr ? " | fl db: " + juce::String::fromUTF8 (entry->path.c_str()) : juce::String()) << "\n";
  1707. }
  1708. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  1709. const auto candidates = host.filesToScanFor (uses);
  1710. report << "scan_candidates=" << candidates.joinIntoString (";") << "\n";
  1711. if (args.contains ("--scan"))
  1712. {
  1713. // the targeted scan an open would run (child processes; the user's plugin list is not touched)
  1714. report << "scanned_new=" << host.scanFiles (candidates, {}) << "\n";
  1715. for (const auto& use : uses)
  1716. {
  1717. juce::String how;
  1718. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  1719. report << "after_scan: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  1720. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known")) << "\n";
  1721. }
  1722. }
  1723. }
  1724. catch (const flp::Error& e)
  1725. {
  1726. report << "error=" << e.what() << "\n";
  1727. }
  1728. }
  1729. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1730. quit();
  1731. return;
  1732. }
  1733. if (args.contains ("--midisync-test"))
  1734. {
  1735. // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
  1736. const auto i = args.indexOf ("--midisync-test");
  1737. const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1738. const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1739. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
  1740. quit();
  1741. return;
  1742. }
  1743. if (args.contains ("--linktest"))
  1744. {
  1745. // LYNX --linktest report.txt [seconds] [peer] (round 190gl): Ableton Link with simulated audio callbacks; with
  1746. // "peer" a second Link peer in this process, else a peer on the network (Ableton's LinkHut) is expected
  1747. const auto i = args.indexOf ("--linktest");
  1748. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  1749. const auto ownPeer = args.contains ("peer");
  1750. juce::File (args[i + 1].unquoted()).replaceWithText (juce::String (lynx::AbletonLink::selfTest (seconds > 0.0 ? seconds : 20.0, ownPeer)));
  1751. quit();
  1752. return;
  1753. }
  1754. if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
  1755. {
  1756. // diagnostics: driver types and output devices JUCE offers (without opening any)
  1757. juce::AudioDeviceManager manager;
  1758. juce::String report;
  1759. manager.getAvailableDeviceTypes();
  1760. if (auto pipeWire = lynx::makePipeWireDeviceType()) // Linux: LYNX's own PipeWire client (round 161)
  1761. manager.addAudioDeviceType (std::move (pipeWire));
  1762. #if JUCE_LINUX
  1763. report << lynx::describePipeWire() << "\n";
  1764. #endif
  1765. for (auto* type : manager.getAvailableDeviceTypes())
  1766. {
  1767. type->scanForDevices();
  1768. report << "type=" << type->getTypeName() << "\n";
  1769. for (const auto& name : type->getDeviceNames (false))
  1770. report << " output=" << name << "\n";
  1771. for (const auto& name : type->getDeviceNames (true))
  1772. report << " input=" << name << "\n";
  1773. }
  1774. for (const auto& d : juce::MidiInput::getAvailableDevices())
  1775. report << "midi-in=" << d.name << "\n";
  1776. for (const auto& d : juce::MidiOutput::getAvailableDevices())
  1777. report << "midi-out=" << d.name << "\n";
  1778. const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
  1779. juce::File (args[flag + 1].unquoted()).replaceWithText (report);
  1780. quit();
  1781. return;
  1782. }
  1783. if (args.contains ("--devicetest"))
  1784. {
  1785. // LYNX.exe --devicetest "type" "device" report.txt ["input device"] [--buffer N] [--roundtrip]: opens that output device (and, with the
  1786. // 4th argument, an input: "*" = the same device / the driver's default input), receives 1 s of callbacks
  1787. // writing silence, closes it and reports rate, block size, latency, callbacks and the input channels with
  1788. // their peak level (driver check, no sound). --roundtrip: clicks out, found again on input 1 through a loopback
  1789. // cable / PipeWire link: the round-trip latency (3 s)
  1790. const auto i = args.indexOf ("--devicetest");
  1791. const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
  1792. auto inputName = args.size() > i + 4 && ! args[i + 4].startsWith ("--") ? args[i + 4].unquoted() : juce::String();
  1793. const auto wantInput = inputName.isNotEmpty();
  1794. juce::String report;
  1795. const juce::File reportFile (args[i + 3].unquoted());
  1796. auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
  1797. step ("step=start");
  1798. juce::AudioDeviceManager manager;
  1799. manager.getAvailableDeviceTypes();
  1800. if (auto pipeWire = lynx::makePipeWireDeviceType())
  1801. manager.addAudioDeviceType (std::move (pipeWire));
  1802. std::unique_ptr<juce::AudioIODevice> device;
  1803. for (auto* type : manager.getAvailableDeviceTypes())
  1804. if (type->getTypeName() == typeName)
  1805. {
  1806. type->scanForDevices();
  1807. if (wantInput && type->hasSeparateInputsAndOutputs())
  1808. {
  1809. const auto inputs = type->getDeviceNames (true);
  1810. if (inputName == "*" || ! inputs.contains (inputName))
  1811. {
  1812. const auto index = type->getDefaultDeviceIndex (true);
  1813. inputName = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  1814. }
  1815. for (const auto& n : inputs)
  1816. step ("input_device=" + n);
  1817. step ("input_chosen=" + inputName);
  1818. }
  1819. else if (wantInput)
  1820. inputName = deviceName;
  1821. step ("step=create");
  1822. device.reset (type->createDevice (deviceName, type->hasSeparateInputsAndOutputs() ? inputName : juce::String()));
  1823. step ("step=created");
  1824. }
  1825. struct Silence final : juce::AudioIODeviceCallback
  1826. {
  1827. std::atomic<int> calls { 0 }, inputs { 0 };
  1828. std::array<std::atomic<float>, 64> peaks {};
  1829. // --roundtrip (round 161): a click every quarter second on the outputs, found again on input 1 through a
  1830. // loopback; the delays in samples
  1831. bool roundtrip = false;
  1832. int period = 12000;
  1833. std::int64_t position = 0, lastClick = -1;
  1834. std::vector<int> delays;
  1835. void audioDeviceIOCallbackWithContext (const float* const* in, int numIn, float* const* out, int channels, int n,
  1836. const juce::AudioIODeviceCallbackContext&) override
  1837. {
  1838. for (int c = 0; c < channels; ++c)
  1839. if (out[c] != nullptr)
  1840. juce::FloatVectorOperations::clear (out[c], n);
  1841. if (roundtrip)
  1842. {
  1843. for (int i = 0; i < n; ++i)
  1844. {
  1845. if (numIn > 0 && in[0] != nullptr && lastClick >= 0 && std::abs (in[0][i]) > 0.5f)
  1846. {
  1847. if (delays.size() < delays.capacity())
  1848. delays.push_back ((int) (position + i - lastClick));
  1849. lastClick = -1;
  1850. }
  1851. if ((position + i) % period == 0 && position + i > 0)
  1852. {
  1853. for (int c = 0; c < channels; ++c)
  1854. if (out[c] != nullptr)
  1855. out[c][i] = 0.9f;
  1856. lastClick = position + i;
  1857. }
  1858. }
  1859. position += n;
  1860. }
  1861. inputs.store (numIn);
  1862. for (int c = 0; c < juce::jmin (numIn, 64); ++c)
  1863. if (in[c] != nullptr)
  1864. {
  1865. const auto range = juce::FloatVectorOperations::findMinAndMax (in[c], n);
  1866. const auto peak = juce::jmax (std::abs (range.getStart()), std::abs (range.getEnd()));
  1867. if (peak > peaks[(std::size_t) c].load())
  1868. peaks[(std::size_t) c].store (peak);
  1869. }
  1870. ++calls;
  1871. }
  1872. void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
  1873. void audioDeviceStopped() override {}
  1874. } silence;
  1875. bool ok = false;
  1876. if (device == nullptr)
  1877. step ("error=device not found");
  1878. else
  1879. {
  1880. step ("step=open");
  1881. juce::BigInteger outputs;
  1882. outputs.setRange (0, 2, true);
  1883. const auto rates = device->getAvailableSampleRates();
  1884. const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
  1885. : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
  1886. step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
  1887. juce::BigInteger inputs;
  1888. if (wantInput)
  1889. {
  1890. const auto names = device->getInputChannelNames();
  1891. step ("input_channels=" + juce::String (names.size()));
  1892. for (int c = 0; c < names.size(); ++c)
  1893. step (" in" + juce::String (c + 1) + "=" + names[c]);
  1894. inputs.setRange (0, juce::jmin (64, names.size()), true);
  1895. }
  1896. // --buffer N: ask for that block size (REA round 97 latency survey); default: the driver's default
  1897. const auto wantedBlock = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  1898. const auto error = device->open (inputs, outputs, rate, wantedBlock > 0 ? wantedBlock : device->getDefaultBufferSize());
  1899. if (error.isNotEmpty())
  1900. step ("error=" + error);
  1901. else
  1902. {
  1903. step ("step=start_callbacks");
  1904. silence.roundtrip = args.contains ("--roundtrip");
  1905. silence.period = juce::jmax (1, (int) (rate / 4));
  1906. silence.delays.reserve (64);
  1907. device->start (&silence);
  1908. juce::Thread::sleep (silence.roundtrip ? 3000 : 1000);
  1909. device->stop();
  1910. if (silence.roundtrip)
  1911. {
  1912. auto d = silence.delays;
  1913. std::sort (d.begin(), d.end());
  1914. report << "roundtrip_clicks=" << (int) d.size() << "\n";
  1915. if (! d.empty())
  1916. report << "roundtrip_samples=min " << d.front() << " median " << d[d.size() / 2] << " max " << d.back() << "\n"
  1917. << "roundtrip_ms=" << juce::String (1000.0 * d[d.size() / 2] / device->getCurrentSampleRate(), 2) << "\n";
  1918. }
  1919. report << "rate=" << device->getCurrentSampleRate() << "\n"
  1920. << "block=" << device->getCurrentBufferSizeSamples() << "\n"
  1921. << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
  1922. << "callbacks=" << silence.calls.load() << "\n";
  1923. if (wantInput)
  1924. {
  1925. report << "input_latency=" << device->getInputLatencyInSamples() << "\n"
  1926. << "active_inputs=" << device->getActiveInputChannels().countNumberOfSetBits() << "\n"
  1927. << "callback_inputs=" << silence.inputs.load() << "\n";
  1928. for (int c = 0; c < juce::jmin (64, silence.inputs.load()); ++c)
  1929. report << " peak_in" << (c + 1) << "=" << juce::Decibels::gainToDecibels (silence.peaks[(std::size_t) c].load(), -150.0f) << " dB\n";
  1930. }
  1931. ok = silence.calls.load() > 0 && (! wantInput || silence.inputs.load() > 0);
  1932. device->close();
  1933. }
  1934. }
  1935. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  1936. setApplicationReturnValue (ok ? 0 : 1);
  1937. quit();
  1938. return;
  1939. }
  1940. if (args.contains ("--pickertime"))
  1941. {
  1942. // LYNX.exe --pickertime report.txt (issue #209): the plugin lists' opening times with the profile's plugin
  1943. // list (LYNX_PROFILE_MAIN samples the message thread meanwhile)
  1944. const auto i = args.indexOf ("--pickertime");
  1945. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1946. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  1947. lynx::crashguard::startMainProfiler (profile.toStdString());
  1948. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1949. lynx::AudioEngine offline (false);
  1950. const auto engineMs = juce::Time::getMillisecondCounterHiRes() - t0;
  1951. const auto report = "engine_ms=" + juce::String (engineMs) + "\n" + lynx::pluginPickerTimings (offline);
  1952. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1953. lynx::crashguard::stopMainProfiler();
  1954. setApplicationReturnValue (0);
  1955. quit();
  1956. return;
  1957. }
  1958. if (args.contains ("--plusmenutime"))
  1959. {
  1960. // LYNX --plusmenutime report.txt [watched] (round 190mf): the Channel rack "+" menu's build time (as
  1961. // showAddChannelMenu builds it, without showing it) with the profile's plugin list and Plugin database
  1962. // folder: the first one, then each one after the old two-second throttle ran out; then one after the
  1963. // folder was marked changed. "watched": as the app (a folder watcher), else as before round 190mf.
  1964. const auto i = args.indexOf ("--plusmenutime");
  1965. const auto watched = i + 2 < args.size() && args[i + 2] == "watched";
  1966. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1967. lynx::AudioEngine offline (false);
  1968. lynx::quickpick::installPluginDatabase (offline);
  1969. std::unique_ptr<lynx::folderwatch::Watcher> watcher;
  1970. if (watched)
  1971. {
  1972. const auto root = lynx::quickpick::pluginDatabaseFolder();
  1973. watcher = std::make_unique<lynx::folderwatch::Watcher> (
  1974. std::vector<std::string> { root.getChildFile ("Effects").getFullPathName().toStdString(), root.getChildFile ("Generators").getFullPathName().toStdString() },
  1975. [] { juce::MessageManager::callAsync ([] { lynx::quickpick::markPluginDatabaseChanged(); }); });
  1976. lynx::quickpick::setPluginDatabaseWatched (true);
  1977. }
  1978. juce::String report;
  1979. report << "types=" << offline.getPluginHost().getKnownPlugins().getNumTypes() << " watched=" << (watched ? 1 : 0) << "\n";
  1980. auto build = [&offline] (int& items) {
  1981. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1982. juce::PopupMenu menu;
  1983. auto picks = lynx::quickpick::renamedGenerators (offline, [] (lynx::ChannelDef) {});
  1984. lynx::quickpick::addPicks (menu, picks);
  1985. lynx::quickpick::addGeneratorMenu (menu, offline, [] (lynx::ChannelDef) {}, [] {}, nullptr, nullptr);
  1986. lynx::quickpick::addFolderViewItems (menu, offline);
  1987. items = menu.getNumItems();
  1988. return juce::Time::getMillisecondCounterHiRes() - t0;
  1989. };
  1990. auto line = [&report, &build] (const juce::String& what) {
  1991. const auto readsBefore = lynx::quickpick::lastRefreshTimes().reads;
  1992. int items = 0;
  1993. const auto ms = build (items);
  1994. const auto t = lynx::quickpick::lastRefreshTimes();
  1995. const auto read = t.reads != readsBefore;
  1996. report << what << " menu_ms=" << juce::String (ms, 2) << " items=" << items << " folder_read=" << (read ? 1 : 0);
  1997. if (read)
  1998. report << " list_ms=" << juce::String (t.listMs, 2) << " read_ms=" << juce::String (t.readMs, 2);
  1999. report << "\n";
  2000. };
  2001. line ("first");
  2002. for (int k = 1; k <= 5; ++k)
  2003. {
  2004. juce::Thread::sleep (2100);
  2005. line ("again" + juce::String (k));
  2006. }
  2007. for (int k = 1; k <= 3; ++k)
  2008. line ("quick" + juce::String (k));
  2009. lynx::quickpick::markPluginDatabaseChanged();
  2010. line ("marked");
  2011. line ("after");
  2012. lynx::quickpick::setPluginDatabaseWatched (false);
  2013. watcher.reset();
  2014. lynx::plugindb::finishInstalledWrites();
  2015. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  2016. setApplicationReturnValue (0);
  2017. quit();
  2018. return;
  2019. }
  2020. if (args.contains ("--scantest"))
  2021. {
  2022. // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
  2023. const auto i = args.indexOf ("--scantest");
  2024. lynx::PluginHost host (false);
  2025. const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
  2026. juce::String report;
  2027. report << "found=" << found << "\n";
  2028. for (const auto& t : host.getKnownPlugins().getTypes())
  2029. report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
  2030. for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
  2031. report << " blacklisted: " << f << "\n";
  2032. juce::File (args[i + 2].unquoted()).replaceWithText (report);
  2033. setApplicationReturnValue (found > 0 ? 0 : 1);
  2034. quit();
  2035. return;
  2036. }
  2037. if (args.contains ("--wrappermiditest"))
  2038. {
  2039. // LYNX.exe --wrappermiditest plugin.dll report.txt (round 181c), with LYNX_TEST_VST2_MIDILOG set: what a
  2040. // hosted plugin receives after a wrapper MIDI option changes while it runs
  2041. const auto i = args.indexOf ("--wrappermiditest");
  2042. runWrapperMidiTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  2043. return;
  2044. }
  2045. if (args.contains ("--wrappershot190oh"))
  2046. {
  2047. // LYNX --wrappershot190oh plugin <folder> [--open] (round 190oh, P3: FL's wrapper Settings › GUI): the
  2048. // plugin (any format; an effect on insert 1) and its wrapper Settings tab drawn offscreen at 100 % and 150 %,
  2049. // with FL's defaults and with "DPI aware" off + "Scale editor dimensions" on; --open also opens its editor
  2050. // with each setting (a real window: Windows reports the editor windows' DPI awareness) -> report.txt
  2051. const auto i = args.indexOf ("--wrappershot190oh");
  2052. runWrapperShot190oh (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--open"));
  2053. return;
  2054. }
  2055. if (args.contains ("--hotfix190ra"))
  2056. {
  2057. // LYNX --hotfix190ra <prefix> [--part name]... [--plugin file]... (hotfix 0.1.31.2, round 190ra): src/Hotfix190ra.inc;
  2058. // <prefix>-checks.txt, result=OK
  2059. const auto i = args.indexOf ("--hotfix190ra");
  2060. juce::StringArray parts, plugins;
  2061. for (int k = 0; k + 1 < args.size(); ++k)
  2062. {
  2063. if (args[k] == "--part")
  2064. parts.add (args[k + 1].unquoted());
  2065. if (args[k] == "--plugin")
  2066. plugins.add (args[k + 1].unquoted());
  2067. }
  2068. runHotfix190ra (args[i + 1].unquoted(), parts, plugins);
  2069. return;
  2070. }
  2071. if (args.contains ("--sweep190retracks"))
  2072. {
  2073. // LYNX --sweep190retracks <report.txt> (round 190re, Discord 11-25): a clip dragged onto another instrument's track in
  2074. // Track-only, Simple and the Pattern layout (src/Sweep190re.inc sweep190reTrackMove); result=OK / FAIL
  2075. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2076. juce::StringArray errors, log;
  2077. sweep190reTrackMove (errors, log);
  2078. log.add (errors.isEmpty() ? "result=OK" : "result=FAIL");
  2079. juce::File (args[args.indexOf ("--sweep190retracks") + 1].unquoted()).replaceWithText (log.joinIntoString ("\n") + "\n");
  2080. setApplicationReturnValue (errors.isEmpty() ? 0 : 1);
  2081. quit();
  2082. return;
  2083. }
  2084. if (args.contains ("--sweep190re"))
  2085. {
  2086. // LYNX --sweep190re <folder> [project]... [--fast] (round 190re, the 0.1.32 regression sweep): each project opened
  2087. // through File › Open, the layouts and panels switched, saved and reopened, ten edit kinds undone and redone
  2088. // (src/Sweep190re.inc); <folder>/checks.txt, result=OK
  2089. const auto i = args.indexOf ("--sweep190re");
  2090. juce::StringArray projects;
  2091. for (int k = i + 2; k < args.size(); ++k)
  2092. if (! args[k].startsWith ("--"))
  2093. projects.add (args[k].unquoted());
  2094. setApplicationReturnValue (runSweep190re (args[i + 1].unquoted(), projects, args.contains ("--fast")) ? 0 : 1);
  2095. quit();
  2096. return;
  2097. }
  2098. if (args.contains ("--hotfixui190qp"))
  2099. {
  2100. // LYNX --hotfixui190qp <prefix> [--plugin file]... (hotfix 0.1.31.1, round 190qp): the Clip-launch Arrangement's
  2101. // track selection reaching the Device View, and channel / plugin windows opened and closed again and again
  2102. // (src/HotfixUi190qp.inc); <prefix>-checks.txt, result=OK
  2103. const auto i = args.indexOf ("--hotfixui190qp");
  2104. juce::StringArray plugins;
  2105. for (int k = 0; k + 1 < args.size(); ++k)
  2106. if (args[k] == "--plugin")
  2107. plugins.add (args[k + 1].unquoted());
  2108. runHotfixUi190qp (args[i + 1].unquoted(), plugins);
  2109. return;
  2110. }
  2111. if (args.contains ("--pertabshot259"))
  2112. {
  2113. // LYNX --pertabshot259 <prefix> [--plugin file]... [--shot-scale 1.5 --shot-suffix @150] (round 190pw, PR #259:
  2114. // channel and plugin windows the size of the tab they show): src/PerTabShot259.inc
  2115. const auto i = args.indexOf ("--pertabshot259");
  2116. juce::StringArray plugins;
  2117. for (int k = 0; k + 1 < args.size(); ++k)
  2118. if (args[k] == "--plugin")
  2119. plugins.add (args[k + 1].unquoted());
  2120. runPerTabShot259 (args[i + 1].unquoted(), plugins);
  2121. return;
  2122. }
  2123. if (args.contains ("--wrappershot"))
  2124. {
  2125. const auto i = args.indexOf ("--wrappershot");
  2126. runWrapperShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2127. return;
  2128. }
  2129. if (args.contains ("--multiouttest"))
  2130. {
  2131. const auto i = args.indexOf ("--multiouttest");
  2132. runMultiOutTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  2133. return;
  2134. }
  2135. if (args.contains ("--vstitest"))
  2136. {
  2137. // LYNX --vstitest plugin folder [project.lynx] (round 190fw, issue #162): an instrument plugin (Image-Line's
  2138. // "FL Studio VSTi") on a channel: notes in, audio out, its state through a saved project, its outputs and
  2139. // the host tempo it follows. See runVstiTest.
  2140. const auto i = args.indexOf ("--vstitest");
  2141. const auto project = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2142. runVstiTest (args[i + 1].unquoted(), args[i + 2].unquoted(), project);
  2143. return;
  2144. }
  2145. if (args.contains ("--vst2test"))
  2146. {
  2147. const auto i = args.indexOf ("--vst2test");
  2148. runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
  2149. return;
  2150. }
  2151. if (args.contains ("--issuesshot190qr"))
  2152. {
  2153. // --issuesshot190qr <prefix> (round 190qr, issues #274-#281): src/IssuesShot190qr.inc
  2154. setApplicationReturnValue (runIssuesShot190qr (args[args.indexOf ("--issuesshot190qr") + 1].unquoted()) ? 0 : 1);
  2155. quit();
  2156. return;
  2157. }
  2158. if (args.contains ("--issuesshot190ll"))
  2159. {
  2160. // --issuesshot190ll <prefix> (round 190ll, issues #200 / #203): src/IssuesShot190ll.inc
  2161. setApplicationReturnValue (runIssuesShot190ll (args[args.indexOf ("--issuesshot190ll") + 1].unquoted()) ? 0 : 1);
  2162. quit();
  2163. return;
  2164. }
  2165. if (args.contains ("--hostplaytest190ll"))
  2166. {
  2167. // LYNX --hostplaytest190ll report.txt "<LYNX Test Synth.vst3>" [--buffer N] (round 190ll, issue #199): src/HostPlay190ll.inc
  2168. const auto i = args.indexOf ("--hostplaytest190ll");
  2169. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 1024;
  2170. runHostPlayTest190ll (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), juce::jlimit (16, 4096, buffer));
  2171. return;
  2172. }
  2173. if (args.contains ("--vst3noteidtest"))
  2174. {
  2175. const auto i = args.indexOf ("--vst3noteidtest");
  2176. runVst3NoteIdTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  2177. return;
  2178. }
  2179. if (args.contains ("--lv2scantest"))
  2180. {
  2181. runLv2ScanTest (args[args.indexOf ("--lv2scantest") + 1].unquoted());
  2182. return;
  2183. }
  2184. if (args.contains ("--wrappertest"))
  2185. {
  2186. const auto i = args.indexOf ("--wrappertest");
  2187. runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  2188. return;
  2189. }
  2190. if (args.contains ("--plugintest"))
  2191. {
  2192. const auto i = args.indexOf ("--plugintest");
  2193. // optional 3rd argument: the plugin's name inside a shell (e.g. "CLA-2A Stereo" in a WaveShell)
  2194. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2195. runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  2196. return;
  2197. }
  2198. if (args.contains ("--crashguardtest"))
  2199. {
  2200. // LYNX --crashguardtest "LYNX Test Crash.vst3|.clap" report.txt [process|memcpy] (round 190dt,
  2201. // tools/testplugin/lynx_test_crash*.{c,cpp}): the plugin crashes in its 40th block on insert 1; LYNX must
  2202. // catch it, mark the slot, keep playing the other inserts, save the project, reload the plugin; then the
  2203. // saved project opens with the plugin crashing on its state; and LYNX's own faults are still crashes
  2204. const auto i = args.indexOf ("--crashguardtest");
  2205. runCrashGuardTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  2206. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("process"));
  2207. return;
  2208. }
  2209. if (args.contains ("--claprestarttest"))
  2210. {
  2211. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c)
  2212. const auto i = args.indexOf ("--claprestarttest");
  2213. runClapRestartTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  2214. return;
  2215. }
  2216. if (args.contains ("--multieditor255test"))
  2217. {
  2218. // LYNX --multieditor255test report.txt <plugin>[::Name] ... (round 190ou, issue #255): several plugin editors open
  2219. // and in use while a keyboard plays; the audio must keep running (src/MultiEditor255Test.inc)
  2220. const auto i = args.indexOf ("--multieditor255test");
  2221. juce::StringArray plugins;
  2222. for (int k = i + 2; k < args.size() && ! args[k].startsWith ("--"); ++k)
  2223. plugins.add (args[k].unquoted());
  2224. runMultiEditor255Test (args[i + 1].unquoted(), plugins);
  2225. return;
  2226. }
  2227. if (args.contains ("--issue258test"))
  2228. {
  2229. // LYNX --issue258test report.txt (round 190pv, issue #258): a cloned channel's own automation clip drives its
  2230. // sound, through the app's engine with render-ahead off and on (src/Issue258Test.inc; Transistor Bass needs
  2231. // FL Studio, LYNX_FL_INSTALL on Linux)
  2232. runIssue258Test (args[args.indexOf ("--issue258test") + 1].unquoted());
  2233. return;
  2234. }
  2235. if (args.contains ("--autolive190qp"))
  2236. {
  2237. // LYNX --autolive190qp <project.flp|.lynx> report.txt [--per-kind N] [--all-modes] (round 190qp, issue #253): the
  2238. // project's automated mixer volumes, send levels and effect parameters heard and shown through the app's engine
  2239. // (src/Hotfix190qpTest.inc)
  2240. const auto i = args.indexOf ("--autolive190qp");
  2241. const auto perKind = args.contains ("--per-kind") ? args[args.indexOf ("--per-kind") + 1].getIntValue() : 2;
  2242. runAutoLive190qpTest (args[i + 1].unquoted(), args[i + 2].unquoted(), perKind, args.contains ("--all-modes"));
  2243. return;
  2244. }
  2245. if (args.contains ("--feel190qetest"))
  2246. {
  2247. // LYNX --feel190qetest report.txt [shot prefix [project]] (round 190qe, TOP-NEXT R1): edge scroll, view stack, zoom
  2248. // glide and anchor, Restore selection, Keep labels on screen, off screen (src/Feel190qeTest.inc)
  2249. const auto i = args.indexOf ("--feel190qetest");
  2250. const auto arg = [&args] (int k) { return k < args.size() && ! args[k].startsWith ("--") ? args[k].unquoted() : juce::String(); };
  2251. setApplicationReturnValue (runFeel190qeTest (arg (i + 1), arg (i + 2), arg (i + 3)) ? 0 : 1);
  2252. quit();
  2253. return;
  2254. }
  2255. if (args.contains ("--issues190rtshot"))
  2256. {
  2257. // LYNX --issues190rtshot <prefix> <sample.wav> [--shot-scale 1.5 --shot-suffix @150] (round 190rt, issues #309 /
  2258. // #311: the channel windows of the Sampler, 3x Osc, DX10, Granulizer, BeepMap, every tab): src/Issues190rtShot.inc
  2259. const auto i = args.indexOf ("--issues190rtshot");
  2260. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2261. runIssues190rtShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2262. return;
  2263. }
  2264. if (args.contains ("--issues190rttest"))
  2265. {
  2266. // LYNX --issues190rttest report.txt (round 190rt; also in --selftest): src/Issues190rtShot.inc
  2267. juce::String log;
  2268. const auto result = issues190rtCheck (log);
  2269. juce::File (args[args.indexOf ("--issues190rttest") + 1].unquoted()).replaceWithText (log + "issues190rt=" + result + "\n");
  2270. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2271. quit();
  2272. return;
  2273. }
  2274. if (args.contains ("--iox190rmtest"))
  2275. {
  2276. // LYNX --iox190rmtest report.txt (round 190rm, the import / export sweep; also in --selftest): src/Iox190rmCheck.inc
  2277. juce::String log;
  2278. const auto result = iox190rmCheck (log);
  2279. juce::File (args[args.indexOf ("--iox190rmtest") + 1].unquoted()).replaceWithText (log + "iox190rm=" + result + "\n");
  2280. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2281. quit();
  2282. return;
  2283. }
  2284. if (args.contains ("--menuwindows190sktest"))
  2285. {
  2286. // LYNX --menuwindows190sktest report.txt (round 190sk, every File-menu "..." item opens its window, DAWproject /
  2287. // FLM written through the menu; also in --selftest): src/MenuWindows190skCheck.inc
  2288. juce::String log;
  2289. const auto result = menuWindows190skCheck (log);
  2290. juce::File (args[args.indexOf ("--menuwindows190sktest") + 1].unquoted()).replaceWithText (log + "menuwindows190sk=" + result + "\n");
  2291. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2292. quit();
  2293. return;
  2294. }
  2295. if (args.contains ("--details190tdshot"))
  2296. {
  2297. // LYNX --details190tdshot <prefix> (round 190td): the pictures of the visible changes (src/Details190tdCheck.inc)
  2298. setApplicationReturnValue (runDetails190tdShot (args[args.indexOf ("--details190tdshot") + 1].unquoted()) ? 0 : 1);
  2299. quit();
  2300. return;
  2301. }
  2302. if (args.contains ("--details190tdtest"))
  2303. {
  2304. // LYNX --details190tdtest report.txt (round 190td: undo names per layout, the Esc switch, undo reselects, Live's
  2305. // Esc in a clip drag; also in --selftest): src/Details190tdCheck.inc
  2306. juce::String log;
  2307. const auto result = details190tdCheck (log);
  2308. juce::File (args[args.indexOf ("--details190tdtest") + 1].unquoted()).replaceWithText (log + "details190td=" + result + "\n");
  2309. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2310. quit();
  2311. return;
  2312. }
  2313. if (args.contains ("--batch334svtest"))
  2314. {
  2315. // LYNX --batch334svtest report.txt (round 190sv: #334 the XDND relay into plugin editors, #290 touchpad pinch, #304
  2316. // command markers; also in --selftest): src/Batch334svCheck.inc
  2317. juce::String log;
  2318. const auto result = batch334svCheck (log);
  2319. juce::File (args[args.indexOf ("--batch334svtest") + 1].unquoted()).replaceWithText (log + "batch334sv=" + result + "\n");
  2320. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2321. quit();
  2322. return;
  2323. }
  2324. if (args.contains ("--round190tktest"))
  2325. {
  2326. // LYNX --round190tktest report.txt (round 190tk: FL's automation timing for imported FL projects against FL's
  2327. // renders, the PPQ through the project file; also in --selftest): src/Round190tkCheck.inc
  2328. juce::String log;
  2329. const auto i = args.indexOf ("--round190tktest");
  2330. const auto result = round190tkCheck (log);
  2331. juce::File (args[i + 1].unquoted()).replaceWithText (log + "round190tk=" + result + "\n");
  2332. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2333. quit();
  2334. return;
  2335. }
  2336. if (args.contains ("--round190totest"))
  2337. {
  2338. // LYNX --round190totest report.txt [shot prefix] (round 190to, QUEUE 0.1.33 item 96: FL's per-insert effects switch,
  2339. // the Master's and the Current column's icons, FL's Extra large icon places; also in --selftest): src/Round190toCheck.inc
  2340. juce::String log;
  2341. const auto i = args.indexOf ("--round190totest");
  2342. const auto shots = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2343. const auto result = round190toCheck (log, shots);
  2344. juce::File (args[i + 1].unquoted()).replaceWithText (log + "round190to=" + result + "\n");
  2345. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2346. quit();
  2347. return;
  2348. }
  2349. if (args.contains ("--round190tmtest"))
  2350. {
  2351. // LYNX --round190tmtest report.txt [shot prefix] (round 190tm, QUEUE 0.1.33 items 91 and 93: Channel settings › Reload
  2352. // reads a changed file again, the Playlist ▾ menu's Time markers, a Playlist key marker in Song mode, muted clips;
  2353. // also in --selftest): src/Round190tmCheck.inc
  2354. juce::String log;
  2355. const auto i = args.indexOf ("--round190tmtest");
  2356. const auto shots = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2357. const auto result = round190tmCheck (log, shots);
  2358. juce::File (args[i + 1].unquoted()).replaceWithText (log + "round190tm=" + result + "\n");
  2359. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2360. quit();
  2361. return;
  2362. }
  2363. if (args.contains ("--round190titest"))
  2364. {
  2365. // LYNX --round190titest report.txt [shot prefix] (round 190ti: Slicex's pitch automation paths, the Playlist's Add key
  2366. // marker; also in --selftest): src/Round190tiCheck.inc
  2367. juce::String log;
  2368. const auto i = args.indexOf ("--round190titest");
  2369. const auto shots = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2370. const auto result = round190tiCheck (log, shots);
  2371. juce::File (args[i + 1].unquoted()).replaceWithText (log + "round190ti=" + result + "\n");
  2372. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2373. quit();
  2374. return;
  2375. }
  2376. if (args.contains ("--rea190tatest"))
  2377. {
  2378. // LYNX --rea190tatest report.txt (round 190ta, the 0.1.33 REA gap-hunt's small FL-exact fixes; also in --selftest):
  2379. // src/Rea190taCheck.inc
  2380. juce::String log;
  2381. const auto i = args.indexOf ("--rea190tatest");
  2382. const auto shots = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2383. const auto result = rea190taCheck (log, shots);
  2384. juce::File (args[i + 1].unquoted()).replaceWithText (log + "rea190ta=" + result + "\n");
  2385. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2386. quit();
  2387. return;
  2388. }
  2389. if (args.contains ("--yannik190sqtest"))
  2390. {
  2391. // LYNX --yannik190sqtest report.txt (round 190sq, yannik's #346 / #251 / #347; also in --selftest): src/Yannik190sqCheck.inc
  2392. juce::String log;
  2393. const auto result = yannik190sqCheck (log);
  2394. juce::File (args[args.indexOf ("--yannik190sqtest") + 1].unquoted()).replaceWithText (log + "yannik190sq=" + result + "\n");
  2395. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2396. quit();
  2397. return;
  2398. }
  2399. if (args.contains ("--drumsynth190sypaint"))
  2400. {
  2401. // LYNX --drumsynth190sypaint report.txt <mode> [n] (round 190sy: the drum pages' paint cost; src/DrumSynth190syCheck.inc)
  2402. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2403. const auto i = args.indexOf ("--drumsynth190sypaint");
  2404. const auto result = drumSynth190syPaint (args[i + 2].unquoted(), args.size() > i + 3 ? args[i + 3].getIntValue() : 50);
  2405. juce::File (args[i + 1].unquoted()).replaceWithText (result + "\n");
  2406. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  2407. quit();
  2408. return;
  2409. }
  2410. if (args.contains ("--drumsynth190sytest"))
  2411. {
  2412. // LYNX --drumsynth190sytest report.txt [shotPrefix] (round 190sy: the drums' editors and docked racks; also in
  2413. // --selftest): src/DrumSynth190syCheck.inc
  2414. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2415. juce::String log;
  2416. const auto i = args.indexOf ("--drumsynth190sytest");
  2417. const auto result = drumSynth190syCheck (log, args.size() > i + 2 ? args[i + 2].unquoted() : juce::String());
  2418. juce::File (args[i + 1].unquoted()).replaceWithText (log + "drumsynth190sy=" + result + "\n");
  2419. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2420. quit();
  2421. return;
  2422. }
  2423. if (args.contains ("--audioedit190sttest"))
  2424. {
  2425. // LYNX --audioedit190sttest report.txt [shotPrefix] (round 190st, issues #339 / #340; also in --selftest): src/AudioEdit190stShot.inc
  2426. juce::String log;
  2427. const auto i = args.indexOf ("--audioedit190sttest");
  2428. const auto result = audioedit190stCheck (log, args.size() > i + 2 ? args[i + 2].unquoted() : juce::String());
  2429. juce::File (args[i + 1].unquoted()).replaceWithText (log + "audioedit190st=" + result + "\n");
  2430. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2431. quit();
  2432. return;
  2433. }
  2434. if (args.contains ("--smallbugs190srtest"))
  2435. {
  2436. // LYNX --smallbugs190srtest report.txt (round 190sr: #350, #349, QUEUE 0.1.33 items 42 / 43; also in --selftest):
  2437. // src/SmallBugs190srCheck.inc
  2438. juce::String log;
  2439. const auto result = smallBugs190srCheck (log);
  2440. juce::File (args[args.indexOf ("--smallbugs190srtest") + 1].unquoted()).replaceWithText (log + "smallbugs190sr=" + result + "\n");
  2441. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2442. quit();
  2443. return;
  2444. }
  2445. if (args.contains ("--quickwins190srtest"))
  2446. {
  2447. // LYNX --quickwins190srtest report.txt (round 190sr's quick wins: #318 ...; also in --selftest): src/QuickWins190srCheck.inc
  2448. juce::String log;
  2449. const auto result = quickWins190srCheck (log);
  2450. juce::File (args[args.indexOf ("--quickwins190srtest") + 1].unquoted()).replaceWithText (log + "quickwins190sr=" + result + "\n");
  2451. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2452. quit();
  2453. return;
  2454. }
  2455. if (args.contains ("--round190tetest"))
  2456. {
  2457. // LYNX --round190tetest report.txt (round 190te: #356 effects told their own audio's position, item 58 XDND drops
  2458. // finished as accepted, item 82 Time markers › Delete; also in --selftest): src/Round190teCheck.inc
  2459. juce::String log;
  2460. const auto result = round190teCheck (log);
  2461. juce::File (args[args.indexOf ("--round190tetest") + 1].unquoted()).replaceWithText (log + "round190te=" + result + "\n");
  2462. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2463. quit();
  2464. return;
  2465. }
  2466. if (args.contains ("--batch292test190sw"))
  2467. {
  2468. // LYNX --batch292test190sw report.txt [picture prefix] (round 190sw: #292 routing cables, #322 macOS's menu bar, #289
  2469. // the hardware outputs export; also in --selftest): src/Batch292Check190sw.inc
  2470. const auto at = args.indexOf ("--batch292test190sw");
  2471. juce::String log;
  2472. const auto result = batch292Check190sw (log, at + 2 < args.size() && ! args[at + 2].startsWith ("--") ? args[at + 2].unquoted() : juce::String());
  2473. juce::File (args[at + 1].unquoted()).replaceWithText (log + "batch292_190sw=" + result + "\n");
  2474. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2475. quit();
  2476. return;
  2477. }
  2478. if (args.contains ("--quickwins190srshot"))
  2479. {
  2480. setApplicationReturnValue (runQuickWins190srShot (args[args.indexOf ("--quickwins190srshot") + 1].unquoted()) ? 0 : 1);
  2481. quit();
  2482. return;
  2483. }
  2484. if (args.contains ("--smallbugs190srshot"))
  2485. {
  2486. setApplicationReturnValue (runSmallBugs190srShot (args[args.indexOf ("--smallbugs190srshot") + 1].unquoted()) ? 0 : 1);
  2487. quit();
  2488. return;
  2489. }
  2490. if (args.contains ("--smallbugs190srflpinfo"))
  2491. {
  2492. const auto i = args.indexOf ("--smallbugs190srflpinfo");
  2493. setApplicationReturnValue (runSmallBugs190srFlpInfo (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted())) ? 0 : 1);
  2494. quit();
  2495. return;
  2496. }
  2497. if (args.contains ("--smallbugs190srmake"))
  2498. {
  2499. setApplicationReturnValue (runSmallBugs190srMake (juce::File (args[args.indexOf ("--smallbugs190srmake") + 1].unquoted())) ? 0 : 1);
  2500. quit();
  2501. return;
  2502. }
  2503. if (args.contains ("--issues330sktest"))
  2504. {
  2505. // LYNX --issues330sktest report.txt (round 190sk, audio2000's Linux issues #330-#342; also in --selftest): src/Issues330skCheck.inc
  2506. juce::String log;
  2507. const auto result = issues330skCheck (log);
  2508. juce::File (args[args.indexOf ("--issues330sktest") + 1].unquoted()).replaceWithText (log + "issues330sk=" + result + "\n");
  2509. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2510. quit();
  2511. return;
  2512. }
  2513. if (args.contains ("--undo190sptest"))
  2514. {
  2515. // LYNX --undo190sptest report.txt (round 190sp, the undo history's shared copies; also in --selftest): src/Undo190spCheck.inc
  2516. juce::String log;
  2517. const auto result = undo190spCheck (log);
  2518. juce::File (args[args.indexOf ("--undo190sptest") + 1].unquoted()).replaceWithText (log + "undo190sp=" + result + "\n");
  2519. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2520. quit();
  2521. return;
  2522. }
  2523. if (args.contains ("--undomem190sp"))
  2524. {
  2525. // LYNX --undomem190sp project report.txt [--steps N] (round 190sp, QUEUE item 13): the undo history's memory after
  2526. // N edits of the usual kinds (src/Undo190spCheck.inc)
  2527. const auto i = args.indexOf ("--undomem190sp");
  2528. const auto steps = args.contains ("--steps") ? args[args.indexOf ("--steps") + 1].getIntValue() : 100;
  2529. // round 190sz: --kinds 12 adds the mixer slot, plugin state, slot list and channel name edits (the default 7 =
  2530. // 190sp's sequence, for its numbers); --trace prints where every shared container was copied (the audit)
  2531. const auto kinds = args.contains ("--kinds") ? args[args.indexOf ("--kinds") + 1].getIntValue() : 7;
  2532. runUndoMemory190sp (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), juce::jlimit (1, 1000, steps),
  2533. juce::jlimit (1, undoKinds190sz, kinds), args.contains ("--trace"));
  2534. return;
  2535. }
  2536. if (args.contains ("--cachecheck190tgtest"))
  2537. {
  2538. // LYNX --cachecheck190tgtest report.txt (round 190tg, the disk caches' integrity check; also in --selftest):
  2539. // src/CacheCheck190tgCheck.inc
  2540. juce::String log;
  2541. const auto result = cachecheck190tgCheck (log);
  2542. juce::File (args[args.indexOf ("--cachecheck190tgtest") + 1].unquoted()).replaceWithText (log + "cachecheck190tg=" + result + "\n");
  2543. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2544. quit();
  2545. return;
  2546. }
  2547. if (args.contains ("--perf190sbtest"))
  2548. {
  2549. // LYNX --perf190sbtest report.txt (round 190sb, FL's plugin database kept between starts; also in --selftest): src/Perf190sbCheck.inc
  2550. juce::String log;
  2551. const auto result = perf190sbCheck (log);
  2552. juce::File (args[args.indexOf ("--perf190sbtest") + 1].unquoted()).replaceWithText (log + "perf190sb=" + result + "\n");
  2553. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2554. quit();
  2555. return;
  2556. }
  2557. if (args.contains ("--perf190rntest"))
  2558. {
  2559. // LYNX --perf190rntest report.txt (round 190rn, the undo history's memory cap; also in --selftest): src/Perf190rnCheck.inc
  2560. juce::String log;
  2561. const auto result = perf190rnCheck (log);
  2562. juce::File (args[args.indexOf ("--perf190rntest") + 1].unquoted()).replaceWithText (log + "perf190rn=" + result + "\n");
  2563. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2564. quit();
  2565. return;
  2566. }
  2567. if (args.contains ("--backlog190rctest"))
  2568. {
  2569. // LYNX --backlog190rctest report.txt (round 190rc, the 0.1.32 backlog; also in --selftest): src/Backlog190rcCheck.inc
  2570. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2571. juce::String log;
  2572. const auto result = backlog190rcCheck (log);
  2573. juce::File (args[args.indexOf ("--backlog190rctest") + 1].unquoted()).replaceWithText (log + "backlog190rc=" + result + "\n");
  2574. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2575. quit();
  2576. return;
  2577. }
  2578. if (args.contains ("--qa190rfchild"))
  2579. {
  2580. // LYNX --qa190rfchild exit|display <folder> (round 190rf; --qa190rbtest starts it): a process with the hang
  2581. // watch's thread running that ends through exit() ("exit": exit code 3 expected; the static hang watch's
  2582. // destructor called std::terminate before) or whose display connection breaks ("display", Linux: exit code 1
  2583. // through crashguard::watchDisplayConnection, its session file names the lost display)
  2584. const auto i = args.indexOf ("--qa190rfchild");
  2585. const auto mode = args[i + 1];
  2586. const juce::File folder (args[i + 2].unquoted());
  2587. folder.createDirectory();
  2588. lynx::crashguard::beginSession (folder.getChildFile ("session.txt").getFullPathName().toStdString(), "LYNX session\n");
  2589. lynx::crashguard::startHangWatch (folder.getFullPathName().toStdString());
  2590. if (mode == "exit")
  2591. std::exit (3);
  2592. #if JUCE_LINUX
  2593. if (mode == "display")
  2594. if (auto* xlib = dlopen ("libX11.so.6", RTLD_LAZY | RTLD_LOCAL))
  2595. {
  2596. using OpenDisplay = void* (*) (const char*);
  2597. using ConnectionNumber = int (*) (void*);
  2598. using Sync = int (*) (void*, int);
  2599. const auto open = (OpenDisplay) dlsym (xlib, "XOpenDisplay");
  2600. const auto number = (ConnectionNumber) dlsym (xlib, "XConnectionNumber");
  2601. const auto sync = (Sync) dlsym (xlib, "XSync");
  2602. if (auto* display = open != nullptr && number != nullptr && sync != nullptr ? open (nullptr) : nullptr)
  2603. {
  2604. lynx::crashguard::watchDisplayConnection (nullptr);
  2605. ::shutdown (number (display), SHUT_RDWR); // (the server "went away")
  2606. sync (display, 0);
  2607. }
  2608. }
  2609. #endif
  2610. std::_Exit (2); // (not reached when the display part ran)
  2611. }
  2612. if (args.contains ("--uhe190sjtest"))
  2613. {
  2614. // LYNX --uhe190sjtest report.txt plugin [plugin ...] (round 190sj, issues #329 / #255): src/KeySheetCheck190sj.inc
  2615. const auto i = args.indexOf ("--uhe190sjtest");
  2616. juce::StringArray plugins;
  2617. for (int k = i + 2; k < args.size() && ! args[k].startsWith ("--"); ++k)
  2618. plugins.add (args[k].unquoted());
  2619. runUhe190sjTest (args[i + 1].unquoted(), plugins);
  2620. return;
  2621. }
  2622. if (args.contains ("--keyroute190sjtest"))
  2623. {
  2624. // LYNX --keyroute190sjtest report.txt (round 190sj, issue #327): src/KeySheetCheck190sj.inc (a window; Windows: GUI lock)
  2625. runKeyRoute190sj (args[args.indexOf ("--keyroute190sjtest") + 1].unquoted());
  2626. return;
  2627. }
  2628. if (args.contains ("--children190thtest"))
  2629. {
  2630. // LYNX --children190thtest report.txt (round 190th, issue #359; also in --selftest): src/Children190thCheck.inc
  2631. juce::String log;
  2632. const auto i = args.indexOf ("--children190thtest");
  2633. const auto result = children190thCheck (log);
  2634. juce::File (args[i + 1].unquoted()).replaceWithText (log + "children190th=" + result + "\n");
  2635. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2636. quit();
  2637. return;
  2638. }
  2639. if (args.contains ("--notes190tjtest"))
  2640. {
  2641. // LYNX --notes190tjtest report.txt (round 190tj, issue #358, the Notes window; also in --selftest): src/Notes190tjCheck.inc
  2642. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2643. juce::String log;
  2644. const auto i = args.indexOf ("--notes190tjtest");
  2645. const auto result = notes190tjCheck (log);
  2646. juce::File (args[i + 1].unquoted()).replaceWithText (log + "notes190tj=" + result + "\n");
  2647. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2648. quit();
  2649. return;
  2650. }
  2651. if (args.contains ("--details190tbtest"))
  2652. {
  2653. // LYNX --details190tbtest report.txt (round 190tb, 0.1.33 details pass; also in --selftest): src/Details190tbCheck.inc
  2654. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2655. juce::String log;
  2656. const auto i = args.indexOf ("--details190tbtest");
  2657. const auto result = details190tbCheck (log);
  2658. juce::File (args[i + 1].unquoted()).replaceWithText (log + "details190tb=" + result + "\n");
  2659. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2660. quit();
  2661. return;
  2662. }
  2663. if (args.contains ("--keysheet190sjtest"))
  2664. {
  2665. // LYNX --keysheet190sjtest report.txt (round 190sj, issue #327; also in --selftest): src/KeySheetCheck190sj.inc
  2666. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2667. juce::String log;
  2668. const auto i = args.indexOf ("--keysheet190sjtest");
  2669. const auto result = keySheet190sjCheck (log);
  2670. juce::File (args[i + 1].unquoted()).replaceWithText (log + "keysheet190sj=" + result + "\n");
  2671. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2672. quit();
  2673. return;
  2674. }
  2675. if (args.contains ("--issue325test"))
  2676. {
  2677. // LYNX --issue325test report.txt [shot prefix] (round 190sg, issue #325; also in --selftest): src/Issue325Check190sg.inc
  2678. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2679. juce::String log;
  2680. const auto i = args.indexOf ("--issue325test");
  2681. const auto result = issue325Check (log, i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2682. juce::File (args[i + 1].unquoted()).replaceWithText (log + "issue325=" + result + "\n");
  2683. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2684. quit();
  2685. return;
  2686. }
  2687. if (args.contains ("--q6190satest"))
  2688. {
  2689. // LYNX --q6190satest report.txt [shot prefix] (round 190sa, 0.1.32 Q6 + the Simple layout's sound drop; also in
  2690. // --selftest): src/Q6Check190sa.inc
  2691. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2692. juce::String log;
  2693. const auto i = args.indexOf ("--q6190satest");
  2694. const auto result = q6190saCheck (log, i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2695. juce::File (args[i + 1].unquoted()).replaceWithText (log + "q6190sa=" + result + "\n");
  2696. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2697. quit();
  2698. return;
  2699. }
  2700. if (args.contains ("--bugs190rvtest"))
  2701. {
  2702. // LYNX --bugs190rvtest report.txt [shot prefix] (round 190rv, the 0.1.32 open bug issues; also in --selftest): src/Bugs190rvCheck.inc
  2703. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2704. juce::String log;
  2705. const auto i = args.indexOf ("--bugs190rvtest");
  2706. const auto result = bugs190rvCheck (log, i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2707. juce::File (args[i + 1].unquoted()).replaceWithText (log + "bugs190rv=" + result + "\n");
  2708. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2709. quit();
  2710. return;
  2711. }
  2712. if (args.contains ("--flparity190tctest"))
  2713. {
  2714. // LYNX --flparity190tctest report.txt [shot prefix] (round 190tc, FL parity block D part 1; also in --selftest):
  2715. // src/FlParity190tcCheck.inc
  2716. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2717. juce::String log;
  2718. const auto i = args.indexOf ("--flparity190tctest");
  2719. const auto result = flParity190tcCheck (log, args[i + 2].unquoted());
  2720. juce::File (args[i + 1].unquoted()).replaceWithText (log + "flparity190tc=" + result + "\n");
  2721. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2722. quit();
  2723. return;
  2724. }
  2725. if (args.contains ("--community190ritest"))
  2726. {
  2727. // LYNX --community190ritest report.txt [shot prefix] (round 190ri, the community batch of 0.1.32; also in --selftest):
  2728. // src/Community190riCheck.inc
  2729. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2730. juce::String log;
  2731. const auto i = args.indexOf ("--community190ritest");
  2732. const auto result = community190riCheck (log, args[i + 2].unquoted());
  2733. juce::File (args[i + 1].unquoted()).replaceWithText (log + "community190ri=" + result + "\n");
  2734. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2735. quit();
  2736. return;
  2737. }
  2738. if (args.contains ("--recoverytest"))
  2739. {
  2740. // LYNX --recoverytest report.txt (round 190rp, 0.1.32 Q4 stability; also in --selftest): src/Stab190rpCheck.inc
  2741. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2742. juce::String log;
  2743. const auto result = stab190rpCheck (log);
  2744. juce::File (args[args.indexOf ("--recoverytest") + 1].unquoted()).replaceWithText (log + "stab190rp=" + result + "\n");
  2745. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2746. quit();
  2747. return;
  2748. }
  2749. if (args.contains ("--qa190rbtest"))
  2750. {
  2751. // LYNX --qa190rbtest report.txt (round 190rb, the 0.1.32 quality round's crash / memory fixes; also in
  2752. // --selftest): src/Qa190rbCheck.inc
  2753. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2754. juce::String log;
  2755. const auto result = qa190rbCheck (log);
  2756. juce::File (args[args.indexOf ("--qa190rbtest") + 1].unquoted()).replaceWithText (log + "qa190rb=" + result + "\n");
  2757. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2758. quit();
  2759. return;
  2760. }
  2761. if (args.contains ("--issues190qrtest"))
  2762. {
  2763. // LYNX --issues190qrtest report.txt (round 190qr, issues #274-#281; also in --selftest): src/Issues190qrCheck.inc
  2764. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2765. juce::String log;
  2766. const auto result = issues190qrCheck (log);
  2767. juce::File (args[args.indexOf ("--issues190qrtest") + 1].unquoted()).replaceWithText (log + "issues190qr=" + result + "\n");
  2768. setApplicationReturnValue (result == "OK" ? 0 : 1);
  2769. quit();
  2770. return;
  2771. }
  2772. if (args.contains ("--hwheel254test"))
  2773. {
  2774. // LYNX --hwheel254test report.txt (round 190ou, issue #254): the horizontal wheel in the Playlist (three layouts),
  2775. // Piano roll, Mixer and Browser, off screen (src/HWheel254Test.inc)
  2776. const auto i = args.indexOf ("--hwheel254test");
  2777. setApplicationReturnValue (runHWheel254Test (args[i + 1].unquoted()) ? 0 : 1);
  2778. quit();
  2779. return;
  2780. }
  2781. if (args.contains ("--determinismtest190po"))
  2782. {
  2783. // LYNX --determinismtest190po report.txt (round 190po, engine/Determinism190poTest.cpp): a render is the same
  2784. // bit for bit on one thread and on several, and two exports have one hash (Windows: the x87 precision)
  2785. const auto i = args.indexOf ("--determinismtest190po");
  2786. juce::String lines;
  2787. const auto result = lynx::determinism190po::check ([&lines] (const juce::String& line) { lines << line << "\n"; });
  2788. juce::File (args[i + 1].unquoted()).replaceWithText (lines + "determinism190po=" + result + "\n");
  2789. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  2790. quit();
  2791. return;
  2792. }
  2793. if (args.contains ("--renderagaintest"))
  2794. {
  2795. // LYNX --renderagaintest report.txt (round 190ou, engine/RenderAgainTest.cpp): offline renders made again
  2796. const auto i = args.indexOf ("--renderagaintest");
  2797. juce::String lines;
  2798. const auto result = lynx::renderagain::check ([&lines] (const juce::String& line) { lines << line << "\n"; });
  2799. juce::File (args[i + 1].unquoted()).replaceWithText (lines + "renderagain190ou=" + result + "\n");
  2800. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  2801. quit();
  2802. return;
  2803. }
  2804. if (args.contains ("--jsfxtest") || args.contains ("--jsfxbench"))
  2805. {
  2806. // LYNX --jsfxtest <folder>: the JSFX format end to end (round 190pj, issue #241; also in --selftest), report in
  2807. // <folder>/jsfx-selftest.txt. LYNX --jsfxbench <out.txt>: CPU per instance of every bundled script.
  2808. const auto test = args.contains ("--jsfxtest");
  2809. const auto i = args.indexOf (test ? "--jsfxtest" : "--jsfxbench");
  2810. const juce::File out (args[i + 1].unquoted());
  2811. juce::String result;
  2812. if (test)
  2813. {
  2814. out.createDirectory();
  2815. result = lynx::jsfx::selfTest (out);
  2816. out.getChildFile ("report.txt").replaceWithText ("jsfx190pj=" + result + "\n");
  2817. }
  2818. else
  2819. result = lynx::jsfx::bench (out);
  2820. std::cout << result << std::endl;
  2821. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  2822. quit();
  2823. return;
  2824. }
  2825. if (args.contains ("--clapteardowntest"))
  2826. {
  2827. // LYNX.exe --clapteardowntest "LYNX Test Restart.clap" report.txt (round 190az, engine/ClapTeardownTest.cpp)
  2828. const auto i = args.indexOf ("--clapteardowntest");
  2829. lynx::runClapTeardownTest (args[i + 1].unquoted(), args[i + 2].unquoted(), [this] (int code) {
  2830. setApplicationReturnValue (code);
  2831. quit();
  2832. });
  2833. return;
  2834. }
  2835. if (args.contains ("--mpetest"))
  2836. {
  2837. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108)
  2838. const auto i = args.indexOf ("--mpetest");
  2839. runMpeTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  2840. return;
  2841. }
  2842. if (args.contains ("--mpeplaytest190hy"))
  2843. {
  2844. // LYNX --mpeplaytest190hy plugin.(clap|vst3) report.txt (round 190hy, issue #108): a song note with a pitch
  2845. // curve played by a hosted plugin with MPE on, through the whole song path (scheduler, renderer, the wrapper's
  2846. // MPE / CLAP note expressions), rendered offline; the pitch heard is measured (report.txt, report.wav)
  2847. const auto i = args.indexOf ("--mpeplaytest190hy");
  2848. runMpePlayTest190hy (args[i + 1].unquoted(), args[i + 2].unquoted());
  2849. return;
  2850. }
  2851. if (args.contains ("--editortest"))
  2852. {
  2853. // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
  2854. // seconds, then closes it (a plugin whose UI crashes the host ends the process before the report says OK)
  2855. const auto i = args.indexOf ("--editortest");
  2856. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2857. runEditorTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  2858. return;
  2859. }
  2860. if (args.contains ("--editorcrashtest"))
  2861. {
  2862. // LYNX.exe --editorcrashtest "LYNX Test Crash.clap" report.txt (issue #32, round 174a; Windows): the test
  2863. // plugin's editor faults in its own window procedure (LYNX_TEST_CRASH=editor). LYNX must catch it, close
  2864. // that editor, record the trace and keep running its message loop.
  2865. const auto i = args.indexOf ("--editorcrashtest");
  2866. runEditorCrashTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  2867. return;
  2868. }
  2869. if (args.contains ("--reloadtest"))
  2870. {
  2871. // LYNX --reloadtest plugin report.txt [shots folder] [--wait-kill]: round 190ao (reload a crashed plugin).
  2872. // Hosts the plugin in a separate process (a channel for an instrument, insert 1 for an effect) in an offline
  2873. // engine, crashes its process (--wait-kill: writes <report>.pid and waits for the process to be killed
  2874. // from outside), checks that nothing reloads by itself, reloads it on request and checks the new process,
  2875. // the state captured last, the untouched song and undo history; twice. With a shots folder: PNGs of the
  2876. // plugin window's crash notice and of the prompt.
  2877. const auto i = args.indexOf ("--reloadtest");
  2878. runReloadTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  2879. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String(), args.contains ("--wait-kill"));
  2880. return;
  2881. }
  2882. if (args.contains ("--pluginoptionstest"))
  2883. {
  2884. // LYNX --pluginoptionstest plugin report.txt [shots folder]: round 190ao. Hosts the plugin inside LYNX (a
  2885. // channel for an instrument, insert 1 for an effect) in an offline engine, opens its window and checks
  2886. // LYNX's own plugin-window options: Pin on top (set, kept above another window, saved with the plugin,
  2887. // back when the window opens again). With a shots folder: PNGs of each state. The window is on screen.
  2888. const auto i = args.indexOf ("--pluginoptionstest");
  2889. runPluginOptionsTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  2890. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String());
  2891. return;
  2892. }
  2893. if (args.contains ("--plugwintest"))
  2894. {
  2895. // LYNX --plugwintest plugin report.txt ["name"] [seconds]: round 162d. Puts the plugin in a channel (an
  2896. // instrument) or on insert 1 (an effect) of an offline engine, opens its plugin window (wrapper header,
  2897. // presets), checks a preset round trip, keeps the window `seconds` on screen (default 15: time for xdotool /
  2898. // screenshots), then removes the plugin from the song and reports whether its window closed by itself.
  2899. const auto i = args.indexOf ("--plugwintest");
  2900. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") && ! args[i + 3].containsOnly ("0123456789") ? args[i + 3].unquoted() : juce::String();
  2901. auto seconds = 15;
  2902. for (int k = i + 3; k < juce::jmin (args.size(), i + 5); ++k)
  2903. if (args[k].containsOnly ("0123456789"))
  2904. seconds = args[k].getIntValue();
  2905. runPlugWinTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only, seconds);
  2906. return;
  2907. }
  2908. if (args.contains ("--zorder191test"))
  2909. {
  2910. // LYNX --zorder191test report.txt [plugin.vst3]: issue #191 (round 190mx), ui/ZOrder191Test.h
  2911. const auto i = args.indexOf ("--zorder191test");
  2912. const auto plugin = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2913. lynx::runZOrder191Test (args[i + 1].unquoted(), plugin, &lookAndFeel, [this] (bool ok) {
  2914. setApplicationReturnValue (ok ? 0 : 1);
  2915. quit();
  2916. });
  2917. return;
  2918. }
  2919. if (args.contains ("--fittest"))
  2920. {
  2921. // LYNX.exe --fittest report.txt [percent]: round 163 — at that UI zoom (default 150) a window taller than
  2922. // the screen and a big resizable window that grows with a zoom change keep their title bar and close
  2923. // button on the screen. The windows show for about two seconds.
  2924. const auto i = args.indexOf ("--fittest");
  2925. runFitTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].getIntValue() : 150);
  2926. return;
  2927. }
  2928. if (args.contains ("--windowtest"))
  2929. {
  2930. // LYNX.exe --windowtest report.txt: opens the Quick-add palette, the Audio editor, a plugin-like window and a name dialog
  2931. // over the main window and checks that each one stays in front, owned by the main window, with the
  2932. // keyboard focus (issue #4). The windows appear on screen for a few seconds.
  2933. runWindowTest (args[args.indexOf ("--windowtest") + 1].unquoted());
  2934. return;
  2935. }
  2936. if (args.contains ("--minimizeclicktest"))
  2937. {
  2938. // LYNX --minimizeclicktest report.txt (issue #188, round 190ir): a tool window over the main window is
  2939. // minimised (through the window manager), the main window comes to the front, and a click where the tool
  2940. // window was must reach the main window's component. Run it under a window manager (openbox on a private
  2941. // Xvfb); exit code 0 = OK.
  2942. runMinimizeClickTest (args[args.indexOf ("--minimizeclicktest") + 1].unquoted());
  2943. return;
  2944. }
  2945. if (args.contains ("--focustest"))
  2946. {
  2947. // LYNX --focustest report.txt (issue #161): the main window with the Playlist and the Piano roll (native
  2948. // child windows with docking on). For each: LYNX goes to the background (the main window loses the focus),
  2949. // the user comes back with a click in the panel, then presses Space: playback must start. Also: a text
  2950. // field's focus comes back with the window, and inside the active window the click's answer is unchanged.
  2951. // Shows a window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  2952. runFocusTest (args[args.indexOf ("--focustest") + 1].unquoted());
  2953. return;
  2954. }
  2955. if (args.contains ("--simplekeytest"))
  2956. {
  2957. // LYNX --simplekeytest report.txt (round 190fc, 0.1.27 RC H2): the main window in the Simple layout; after a
  2958. // demo opened from Welcome › Start from and after clicks in the dock, its tabs, the Lyrics button, a track
  2959. // header and the grid, Space must start playback (a text field clicked into keeps its typing keys). Shows a
  2960. // window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  2961. runSimpleKeyTest (args[args.indexOf ("--simplekeytest") + 1].unquoted());
  2962. return;
  2963. }
  2964. if (args.contains ("--pluginstyle")) // round 126: force one style for this run (glow, neon, hardware, vivid; auto = per plugin)
  2965. {
  2966. const auto i = args.indexOf ("--pluginstyle");
  2967. if (i + 1 < args.size())
  2968. {
  2969. const auto name = args[i + 1].unquoted();
  2970. lynx::skin::setForcedStyle (name.equalsIgnoreCase ("auto") ? -1 : (int) lynx::skin::styleFromName (name));
  2971. }
  2972. }
  2973. if (args.contains ("--gfxprobe"))
  2974. {
  2975. // LYNX.exe --gfxprobe report.txt (round 170c, issue #11): renderer checks on this platform's native images —
  2976. // text drawn with a gradient fill (a word with a space in it) and an empty path filled with a gradient must
  2977. // stay inside their shapes. JUCE 8.0.4's CoreGraphics renderer (macOS) clipped to an empty glyph or path as
  2978. // "no clip" and flooded the whole component (Facet EQ's blank pink window).
  2979. const auto i = args.indexOf ("--gfxprobe");
  2980. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::skin::rendererProbeReport());
  2981. quit();
  2982. return;
  2983. }
  2984. if (args.contains ("--steppertest"))
  2985. {
  2986. // LYNX.exe --steppertest <report.txt>: round 170c (#14) — every value stepper of every generated effect editor
  2987. // driven by synthetic input (arrows, click on the value, drag, wheel, trackpad); ends with result=OK / FAIL
  2988. const auto i = args.indexOf ("--steppertest");
  2989. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2990. juce::String report;
  2991. int fails = 0, count = 0, skips = 0;
  2992. {
  2993. lynx::AudioEngine offline (false);
  2994. auto kinds = lynx::plugui::flLayoutKinds();
  2995. for (const auto own : lynx::plugui::ownLayoutKinds())
  2996. kinds.push_back (own);
  2997. // FL's Default preset when the installation has one (the state-backed controls need FL's state)
  2998. const auto roots = lynx::findFlStudioRoots();
  2999. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  3000. for (const auto kind : kinds)
  3001. {
  3002. auto fx = lynx::makeEffectSlot (kind);
  3003. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  3004. {
  3005. juce::MemoryBlock data;
  3006. const auto file = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str())).getChildFile ("Default.fst");
  3007. if (file.existsAsFile() && file.loadFileAsData (data))
  3008. {
  3009. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  3010. 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)
  3011. fx = *loaded;
  3012. }
  3013. break;
  3014. }
  3015. lynx::Song song;
  3016. song.mixer.resize (2);
  3017. song.mixer[0].name = "Master";
  3018. song.mixer[1].name = "Insert 1";
  3019. song.mixer[1].effects.push_back (fx);
  3020. offline.setSong (std::move (song));
  3021. offline.dispatchPendingMessages();
  3022. const auto lines = lynx::stepperSelfTest (offline, 1, 0, (int) lynx::plugui::layoutFor (kind).pages.size());
  3023. for (const auto& line : juce::StringArray::fromLines (lines))
  3024. if (line.isNotEmpty())
  3025. {
  3026. ++count;
  3027. fails += line.contains (": FAIL") ? 1 : 0;
  3028. skips += line.contains (": SKIP") ? 1 : 0;
  3029. }
  3030. report << lines;
  3031. juce::PopupMenu::dismissAllActiveMenus();
  3032. offline.dispatchPendingMessages();
  3033. }
  3034. }
  3035. report << "steppers=" << count << " failures=" << fails << " skipped=" << skips << "\nresult=" << (fails == 0 && count > 0 ? "OK" : "FAIL") << "\n";
  3036. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  3037. quit();
  3038. return;
  3039. }
  3040. if (args.contains ("--design190inshot"))
  3041. {
  3042. // LYNX --design190inshot prefix [project.flp]: round 190in off screen (no desktop window, no audio device) —
  3043. // the channel window as it shows docked (FL's ▸, two-tone title, presets in the title bar, the 46 px strip
  3044. // with icon tabs, LED, knobs, RANGE / TRACK badges) on each tab, the floating strip, and FL's ▸ menu
  3045. const auto i = args.indexOf ("--design190inshot");
  3046. runDesign190inShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String());
  3047. quit();
  3048. return;
  3049. }
  3050. if (args.contains ("--plugui"))
  3051. {
  3052. // LYNX.exe --plugui <folder>: the native effect editors at FL's size (one PNG per editor and page), each
  3053. // loaded with the FL plugin's Default preset when the FL installation has one
  3054. const auto i = args.indexOf ("--plugui");
  3055. runPluginEditorSnapshots (args[i + 1].unquoted());
  3056. return;
  3057. }
  3058. if (args.contains ("--parityshot"))
  3059. {
  3060. // LYNX.exe --parityshot <out.png> <effect name> [<params file>]: one built-in effect's editor with the given
  3061. // parameters ("index value" lines, tools/fxrender --dump), its displays fed by the demo song — the LYNX side
  3062. // of the third-party parity pictures (round tp172b)
  3063. const auto i = args.indexOf ("--parityshot");
  3064. runParityShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  3065. if (parityShotFailed)
  3066. setApplicationReturnValue (2);
  3067. if (parityShow == nullptr)
  3068. quit();
  3069. return;
  3070. }
  3071. if (args.contains ("--design168rshot"))
  3072. {
  3073. // LYNX.exe --design168rshot <folder>: round 168r's editors (FL effects that had a generated page and LYNX's own
  3074. // simple built-ins) at 100 % and 200 %, with their default settings and, when they have one, the first
  3075. // preset of LYNX's own bank. "--design168rshot <folder> generated": the generated pages they had before
  3076. const auto i = args.indexOf ("--design168rshot");
  3077. if (i + 2 < args.size() && args[i + 2] == "generated")
  3078. lynx::plugui::showGeneratedLayoutsOnly (true);
  3079. runDesign168rShots (args[i + 1].unquoted());
  3080. quit();
  3081. return;
  3082. }
  3083. if (args.contains ("--eq166fshot"))
  3084. {
  3085. // LYNX.exe --eq166fshot <folder>: round 166f's pictures (issue #16) — Parametric EQ 2's spectrum and heatmap
  3086. // (flat, a +12 dB band, a -12 dB band, Top position) and Facet EQ's comparative EQ (listening to the target,
  3087. // its spectrum over the source's), each fed by the demo song rendered offline
  3088. const auto i = args.indexOf ("--eq166fshot");
  3089. runEq166fShots (args[i + 1].unquoted());
  3090. quit();
  3091. return;
  3092. }
  3093. if (args.contains ("--editorcpu"))
  3094. {
  3095. // LYNX.exe --editorcpu report.txt: opens built-in plugin editors one at a time in a small window (no audio
  3096. // device: a silent, idle editor) and writes the process CPU each costs while idle and while its display
  3097. // animates (demo signal) — round 122's check that an idle editor burns no CPU
  3098. const auto i = args.indexOf ("--editorcpu");
  3099. runEditorCpu (args[i + 1].unquoted());
  3100. return;
  3101. }
  3102. if (args.contains ("--precomputeshot"))
  3103. {
  3104. // LYNX.exe --precomputeshot project.(flp|lynx) <prefix>: round 167h — <prefix>-precompute.png (channel 1's
  3105. // Precomputed effects panel) and <prefix>-project.png (Options › Project with "Fast declick for cut groups")
  3106. const auto i = args.indexOf ("--precomputeshot");
  3107. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3108. lynx::AudioEngine shotEngine (false);
  3109. const juce::File input (args[i + 1].unquoted());
  3110. const auto prefix = args[i + 2].unquoted();
  3111. juce::String error;
  3112. bool ok = false;
  3113. if (input.hasFileExtension ("flp"))
  3114. ok = shotEngine.importFlpFile (input, error);
  3115. else if (auto song = lynx::ProjectFile::load (input, error))
  3116. shotEngine.setSong (std::move (*song)), ok = true;
  3117. shotEngine.dispatchPendingMessages();
  3118. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  3119. if (c == nullptr)
  3120. return false;
  3121. if (c->getWidth() <= 0)
  3122. c->setSize (520, 600);
  3123. savePng (lynx::shot::snapshot (*c), prefix + name);
  3124. return true;
  3125. };
  3126. ok = ok && shoot (lynx::makeChannelPrecomputePanel (shotEngine, 0), "-precompute.png");
  3127. ok = ok && shoot (lynx::makeSettingsPanel (shotEngine, lynx::SettingsPage::project), "-project.png");
  3128. setApplicationReturnValue (ok ? 0 : 1);
  3129. quit();
  3130. return;
  3131. }
  3132. if (args.contains ("--pluginthumbs"))
  3133. {
  3134. // LYNX.exe --pluginthumbs <folder> [key,key...]: the Plugin picker's pictures of LYNX's own plugins (round 171c,
  3135. // ui/PluginThumbs.h), each editor drawn off-screen and kept as <folder>/<name>.png; the picker starts this in
  3136. // the background when pictures are missing. One line per plugin on stdout.
  3137. const auto i = args.indexOf ("--pluginthumbs");
  3138. lynx::crashguard::quietCrashReports();
  3139. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3140. juce::StringArray only;
  3141. if (i + 2 < args.size() && ! args[i + 2].startsWith ("--"))
  3142. only.addTokens (args[i + 2].unquoted(), ",", "");
  3143. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  3144. // round 190bi: with --shot-scale / LYNX_SHOT_SCALE each plugin's whole editor at that scale, not the picker's
  3145. // small thumbnail (never for the picker's own cache folder, whatever the environment says)
  3146. const juce::File folder (args[i + 1].unquoted());
  3147. const auto full = lynx::shot::given() && folder != lynx::pluginthumbs::nativeFolder() ? lynx::shot::scale() : 0.0f;
  3148. const auto drawn = lynx::pluginthumbs::renderNative (folder, only, [] (const juce::String& line) {
  3149. std::printf ("%s\n", line.toRawUTF8());
  3150. std::fflush (stdout);
  3151. }, full);
  3152. std::printf ("drawn %d in %.0f ms\n", drawn, juce::Time::getMillisecondCounterHiRes() - t0);
  3153. setApplicationReturnValue (0);
  3154. quit();
  3155. return;
  3156. }
  3157. if (args.contains ("--jsonroundtrip"))
  3158. {
  3159. // LYNX.exe --jsonroundtrip <folder>: round 183c's finding — a project saved, loaded and saved again: both texts
  3160. // (a.json, b.json) and the first lines that differ (diff.txt) for the default song, with and without a Patcher
  3161. const auto i = args.indexOf ("--jsonroundtrip");
  3162. const juce::File out (args[i + 1].unquoted());
  3163. out.createDirectory();
  3164. juce::String report;
  3165. auto check = [&] (const lynx::Song& song, const juce::String& name) {
  3166. const auto a = lynx::ProjectFile::toJson (song);
  3167. juce::String error;
  3168. const auto back = lynx::ProjectFile::fromJson (a, error);
  3169. const auto b = back ? lynx::ProjectFile::toJson (*back) : juce::String ("(not loaded: " + error + ")");
  3170. out.getChildFile (name + "-a.json").replaceWithText (a);
  3171. out.getChildFile (name + "-b.json").replaceWithText (b);
  3172. juce::StringArray la, lb;
  3173. la.addLines (a);
  3174. lb.addLines (b);
  3175. report << name << ": " << (a == b ? "stable" : "DIFFERS") << " (" << la.size() << " / " << lb.size() << " lines)\n";
  3176. int shown = 0;
  3177. for (int k = 0; k < juce::jmax (la.size(), lb.size()) && shown < 12; ++k)
  3178. if (la[k] != lb[k])
  3179. {
  3180. report << " line " << (k + 1) << "\n a: " << la[k].trim().substring (0, 200) << "\n b: " << lb[k].trim().substring (0, 200) << "\n";
  3181. ++shown;
  3182. }
  3183. };
  3184. auto song = lynx::Song::makeDefault();
  3185. check (song, "default");
  3186. song.mixer.resize (3);
  3187. song.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::patcher) };
  3188. check (song, "patcher");
  3189. song.mixer[1].effects = { lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect) };
  3190. check (song, "rack");
  3191. out.getChildFile ("diff.txt").replaceWithText (report);
  3192. setApplicationReturnValue (0);
  3193. quit();
  3194. return;
  3195. }
  3196. // --prshot190jv <folder> (round 190jv: Piano roll › Scale highlighting › Automatic): src/PrShot190jv.inc
  3197. if (args.contains ("--prshot190jv"))
  3198. {
  3199. setApplicationReturnValue (runPrShot190jv (juce::File (args[args.indexOf ("--prshot190jv") + 1].unquoted())) ? 0 : 1);
  3200. quit();
  3201. return;
  3202. }
  3203. // --prchord190kd <folder> (round 190kd: FL's chord tool strip, scale shading, rack name alignment): src/PrChordShot190kd.inc
  3204. if (args.contains ("--prchord190kd"))
  3205. {
  3206. setApplicationReturnValue (runPrChordShot190kd (juce::File (args[args.indexOf ("--prchord190kd") + 1].unquoted())) ? 0 : 1);
  3207. quit();
  3208. return;
  3209. }
  3210. // --keys190nu <folder> (round chord2_190nu: key regions, the Scale degree chord, pinned Chord helper relationships)
  3211. if (args.contains ("--keys190nu"))
  3212. {
  3213. setApplicationReturnValue (runKeysShot190nu (juce::File (args[args.indexOf ("--keys190nu") + 1].unquoted())) ? 0 : 1);
  3214. quit();
  3215. return;
  3216. }
  3217. // --modal190mc <folder> (round 190mc: the Chord helper, Transistor Bass's program row): src/ModalShot190mc.inc
  3218. if (args.contains ("--modal190mc"))
  3219. {
  3220. setApplicationReturnValue (runModalShot190mc (juce::File (args[args.indexOf ("--modal190mc") + 1].unquoted())) ? 0 : 1);
  3221. quit();
  3222. return;
  3223. }
  3224. // --trimshot190jv <folder> (round 190jv: Mixer menu › Trim unused tracks): src/TrimShot190jv.inc
  3225. if (args.contains ("--trimshot190jv"))
  3226. {
  3227. setApplicationReturnValue (runTrimShot190jv (juce::File (args[args.indexOf ("--trimshot190jv") + 1].unquoted())) ? 0 : 1);
  3228. quit();
  3229. return;
  3230. }
  3231. // --q1a190rwtest <report.txt> (round 190rw: the song replaced under a held drag; also in --selftest): src/Q1a190rwCheck.inc
  3232. if (args.contains ("--q1a190rwtest"))
  3233. {
  3234. setApplicationReturnValue (runQ1a190rwTest (juce::File (args[args.indexOf ("--q1a190rwtest") + 1].unquoted())) ? 0 : 1);
  3235. quit();
  3236. return;
  3237. }
  3238. // --undogesture190jv <report.txt> (round 190jv, queue item 73: one undo step per drag): src/UndoGesture190jv.inc
  3239. if (args.contains ("--undogesture190jv"))
  3240. {
  3241. setApplicationReturnValue (runUndoGesture190jv (juce::File (args[args.indexOf ("--undogesture190jv") + 1].unquoted())) ? 0 : 1);
  3242. quit();
  3243. return;
  3244. }
  3245. // --simplegb190keshot <folder> (round 190ke: tuner, fade-out, Controls tab, LYNX content): src/SimpleGbShot190ke.inc
  3246. if (args.contains ("--simplegb190keshot"))
  3247. {
  3248. setApplicationReturnValue (runSimpleGbShot190ke (juce::File (args[args.indexOf ("--simplegb190keshot") + 1].unquoted())) ? 0 : 1);
  3249. quit();
  3250. return;
  3251. }
  3252. // --browsershot190iz <folder> (round 190iz: FL's tabs, tags, Live's browser): src/BrowserShot190iz.inc
  3253. // --qarest190lcshot <folder> [Live set] (rollup step 7: QA-8's View menu submenu, QA-2's take lanes in Simple):
  3254. // src/QaRest190lcShot.inc
  3255. if (args.contains ("--qarest190lcshot"))
  3256. {
  3257. const auto i = args.indexOf ("--qarest190lcshot");
  3258. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3259. setApplicationReturnValue (runQaRest190lcShot (juce::File (args[i + 1].unquoted()), set) ? 0 : 1);
  3260. quit();
  3261. return;
  3262. }
  3263. // --loopinfo190kxshot <folder> (round 190kx: loop key / tempo in the Simple rows, the Loop Browser, the clip menu)
  3264. if (args.contains ("--loopinfo190kxshot"))
  3265. {
  3266. setApplicationReturnValue (runLoopInfoShot190kx (juce::File (args[args.indexOf ("--loopinfo190kxshot") + 1].unquoted())) ? 0 : 1);
  3267. quit();
  3268. return;
  3269. }
  3270. // --loopshot190kf <folder> (round gaps190kf: the Loop Browser): src/LoopShot190kf.inc
  3271. if (args.contains ("--loopshot190kf"))
  3272. {
  3273. setApplicationReturnValue (runLoopShot190kf (juce::File (args[args.indexOf ("--loopshot190kf") + 1].unquoted())) ? 0 : 1);
  3274. quit();
  3275. return;
  3276. }
  3277. if (args.contains ("--lynxmodelshot190ni"))
  3278. {
  3279. // LYNX --lynxmodelshot190ni prefix: round 190ni, LYNX Model's window per preset, its Browser entry, checks
  3280. setApplicationReturnValue (runLynxModelShot190ni (args[args.indexOf ("--lynxmodelshot190ni") + 1].unquoted()) ? 0 : 1);
  3281. quit();
  3282. return;
  3283. }
  3284. if (args.contains ("--browsershot190iz"))
  3285. {
  3286. setApplicationReturnValue (runBrowserShot190iz (juce::File (args[args.indexOf ("--browsershot190iz") + 1].unquoted())) ? 0 : 1);
  3287. quit();
  3288. return;
  3289. }
  3290. if (args.contains ("--rackshot"))
  3291. {
  3292. // LYNX.exe --rackshot <folder>: round 183c's Rack view drawn off-screen (no window), for the LYNX | Live pairs:
  3293. // rack-deviceview.png (an Audio Effect Rack laid out as in Live's reference shot), rack-mapmode.png (Map mode
  3294. // with the mapping list), rack-instrument.png (an Instrument Rack with its key zones)
  3295. const auto i = args.indexOf ("--rackshot");
  3296. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3297. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3298. setApplicationReturnValue (runRackShots (juce::File (args[i + 1].unquoted()), set) ? 0 : 1);
  3299. quit();
  3300. return;
  3301. }
  3302. if (args.contains ("--artshot"))
  3303. {
  3304. // LYNX.exe --artshot <folder> [before|after] [name,name...]: every editor with art of its own (round 170j/170k: the
  3305. // Themed style; or only the named ones, e.g. "sakura,facet-eq") drawn off-screen at 100 % and 200 % as
  3306. // <folder>/<plugin>-<before|after>-<scale>.png. "before" draws each in the style it had before the Themed style
  3307. const auto i = args.indexOf ("--artshot");
  3308. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3309. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  3310. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  3311. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  3312. setApplicationReturnValue (runArtShots (juce::File (args[i + 1].unquoted()), mode == "before") ? 0 : 1);
  3313. quit();
  3314. return;
  3315. }
  3316. if (args.contains ("--artgui"))
  3317. {
  3318. // LYNX.exe --artgui <folder> [before|after|still] [name,name...]: the same editors in REAL windows on the desktop, one at a
  3319. // time (always on top, no focus taken), each held while an outside script screenshots it (it writes
  3320. // <folder>/<plugin>.ready with the window's bounds and waits up to 10 s for <folder>/<plugin>.done), then the
  3321. // process CPU it costs over 6 s is written to <folder>/cpu-<mode>.txt. "still": Themed with the motion off
  3322. const auto i = args.indexOf ("--artgui");
  3323. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3324. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  3325. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  3326. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  3327. runArtGui (juce::File (args[i + 1].unquoted()), mode);
  3328. return;
  3329. }
  3330. if (args.contains ("--instrumentshot"))
  3331. {
  3332. // LYNX.exe --instrumentshot <folder> <engine,engine...|banks> [lynx|fl]: round 168n — the channel window of
  3333. // each engine (its Plugin tab) at 100 %, 150 % and 200 %, as <folder>/<engine>-<source>-<scale>.png. Source
  3334. // "lynx" starts from the engine's LYNX bank (what a PC without FL gets), "fl" from FL's Default preset.
  3335. const auto i = args.indexOf ("--instrumentshot");
  3336. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3337. const auto source = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("lynx");
  3338. setApplicationReturnValue (runInstrumentShots (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted(), source) ? 0 : 1);
  3339. quit();
  3340. return;
  3341. }
  3342. if (args.contains ("--flextrashot"))
  3343. {
  3344. // LYNX.exe --flextrashot <folder>: pictures of the editors of round 165g (Big Clock, Tuner, HTML NoteBook, Mute 2, Scratcher, Transmitter) + round 167n Transporter
  3345. const auto i = args.indexOf ("--flextrashot");
  3346. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3347. lynx::AudioEngine shotEngine (false);
  3348. const auto ok = lynx::runFlExtraShots (shotEngine, juce::File (args[i + 1].unquoted()));
  3349. setApplicationReturnValue (ok ? 0 : 1);
  3350. quit();
  3351. return;
  3352. }
  3353. if (args.contains ("--visualtest"))
  3354. {
  3355. // LYNX.exe --visualtest <folder> [project.flp]: the visual plugins (round 164c) — the audio path's CPU, every
  3356. // Wave Candy mode and Visualizer scene drawn from a test signal (PNG + the editor's CPU each), and the video
  3357. // export of a project (default: FL's first ZGameEditor demo) with ffmpeg and as images. Writes report.txt.
  3358. const auto i = args.indexOf ("--visualtest");
  3359. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3360. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File();
  3361. lynx::runVisualTest (juce::File (args[i + 1].unquoted()), project, [this] (bool ok) {
  3362. setApplicationReturnValue (ok ? 0 : 1);
  3363. quit();
  3364. });
  3365. return;
  3366. }
  3367. if (args.contains ("--menu-entry"))
  3368. {
  3369. // LYNX.AppImage --menu-entry on|off: puts the AppImage in the applications menu (and .lynx files on it) or
  3370. // takes it out again, without opening a window; the same as the switch in Options › General (round 161)
  3371. const auto i = args.indexOf ("--menu-entry");
  3372. const auto on = args[i + 1].unquoted() != "off";
  3373. const auto ok = lynx::runningAsAppImage() && lynx::setAppImageMenuEntry (on);
  3374. std::fprintf (ok ? stdout : stderr, "%s\n", ok ? (on ? "LYNX SHARE added to the applications menu" : "LYNX SHARE removed from the applications menu")
  3375. : "only the LYNX SHARE AppImage on Linux can do this");
  3376. setApplicationReturnValue (ok ? 0 : 1);
  3377. quit();
  3378. return;
  3379. }
  3380. if (args.contains ("--leftovers190nrtest"))
  3381. {
  3382. // round 190nr: going back to an older version removes what newer versions added to the install folder
  3383. // (the --apply-update helper's step after the installer). Prints "result=OK" or the failing check.
  3384. const auto root = juce::File::createTempFile ("lynx-leftovers190nr");
  3385. juce::StringArray fails;
  3386. auto run = [&] (const juce::String& version, bool licensesGone, bool listGone) {
  3387. root.deleteRecursively();
  3388. root.getChildFile ("install/licenses").createDirectory();
  3389. root.getChildFile ("install/licenses/onnxruntime-LICENSE.txt").replaceWithText ("x");
  3390. root.getChildFile ("install/LYNX.exe").replaceWithText ("x");
  3391. root.getChildFile ("install/installed-files.txt").replaceWithText ("LYNX.exe\r\nlicenses\r\n");
  3392. root.getChildFile ("install/My notes.txt").replaceWithText ("x");
  3393. root.getChildFile ("update/installing.txt").create();
  3394. if (version.isNotEmpty())
  3395. root.getChildFile ("update/installing.txt").replaceWithText ("from=0.1.31\nrollback=1\nversion=" + version + "\n");
  3396. const auto removed = lynx::updater::removeNewerLeftovers (root.getChildFile ("install"), root.getChildFile ("update/installing.txt"));
  3397. const auto in = root.getChildFile ("install");
  3398. if (in.getChildFile ("licenses").exists() == licensesGone) fails.add (version + ": licenses");
  3399. if (in.getChildFile ("installed-files.txt").exists() == listGone) fails.add (version + ": installed-files.txt");
  3400. if (! in.getChildFile ("LYNX.exe").existsAsFile() || ! in.getChildFile ("My notes.txt").existsAsFile()) fails.add (version + ": removed too much");
  3401. std::printf ("%s -> removed [%s]\n", version.toRawUTF8(), removed.joinIntoString (", ").toRawUTF8());
  3402. };
  3403. run ("0.1.29-alpha", true, true); // going back to 0.1.29: both newer entries go
  3404. run ("0.1.28.1-alpha", true, true);
  3405. run ("0.1.30-alpha", false, true); // 0.1.30 installs licenses itself
  3406. run ("0.1.31-alpha", false, false); // same or newer: nothing goes
  3407. run ("0.1.32", false, false);
  3408. run ("", false, false); // unreadable note: nothing goes
  3409. root.deleteRecursively();
  3410. std::printf ("result=%s%s\n", fails.isEmpty() ? "OK" : "FAILED ", fails.joinIntoString ("; ").toRawUTF8());
  3411. setApplicationReturnValue (fails.isEmpty() ? 0 : 1);
  3412. quit();
  3413. return;
  3414. }
  3415. if (args.contains ("--send-test-report"))
  3416. {
  3417. // LYNX.exe --send-test-report out.txt [--dry]: builds a crash report marked "test" from the newest crash /
  3418. // hang file and this computer's facts, writes its JSON to out.txt.json and (without --dry) sends it to
  3419. // lynx-share.com (LYNX_CRASH_ENDPOINT overrides); out.txt gets "id=…" and "result=OK" or the error (round 159)
  3420. const auto i = args.indexOf ("--send-test-report");
  3421. const juce::File out (args[i + 1].unquoted());
  3422. lynx::crashreporter::Session session;
  3423. session.version = getApplicationVersion();
  3424. for (const auto* pattern : { "crash *.txt", "hang *.txt" })
  3425. {
  3426. auto files = lynx::platform::settingsFile ("autosave").findChildFiles (juce::File::findFiles, false, pattern);
  3427. lynx::filesort::byTime (files, lynx::filesort::By::modificationTime, true);
  3428. if (! files.isEmpty())
  3429. (juce::String (pattern).startsWith ("crash") ? session.crashFile : session.hangFile) = files[0];
  3430. }
  3431. session.steps = { "00:00:01 test report (LYNX.exe --send-test-report)", "00:00:02 opening project " + out.getFileName() };
  3432. auto input = lynx::crashreporter::makeInput (session, session.crashFile.existsAsFile() ? "crash" : "manual", nullptr);
  3433. input.test = true;
  3434. const auto json = lynx::crashreporter::buildJson (input, false);
  3435. out.withFileExtension (out.getFileExtension() + ".json").replaceWithText (json);
  3436. const auto error = args.contains ("--dry") ? juce::String() : lynx::crashreporter::sendNow (json);
  3437. out.replaceWithText ("id=" + juce::String::fromUTF8 (input.id.c_str()) + "\nendpoint=" + lynx::crashreporter::endpoint() + "\nbytes="
  3438. + juce::String (json.getNumBytesAsUTF8()) + "\nresult=" + (error.isEmpty() ? juce::String ("OK") : error) + "\n");
  3439. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  3440. quit();
  3441. return;
  3442. }
  3443. if (args.contains ("--symbolize"))
  3444. {
  3445. // LYNX.exe --symbolize "crash … .txt" out.txt: names the LYNX.exe+offset frames of a user's crash / hang file
  3446. // (needs this build's LYNX.pdb next to LYNX.exe — the release's "LYNX-symbols" CI artifact; round 157a)
  3447. const auto i = args.indexOf ("--symbolize");
  3448. const auto text = juce::File (args[i + 1].unquoted()).loadFileAsString();
  3449. juce::File (args[i + 2].unquoted()).replaceWithText (juce::String::fromUTF8 (lynx::crashguard::symbolizeOwnFrames (text.toStdString()).c_str()));
  3450. quit();
  3451. return;
  3452. }
  3453. if (args.contains ("--windowopentime"))
  3454. {
  3455. // LYNX --windowopentime report.txt [plugin file ...] (round 190rd, perf 9): every built-in effect and instrument
  3456. // window opened as the Mixer / Channel rack open them, and each plugin file's editor in LYNX's plugin window,
  3457. // each twice (the first and the second open), timed from the call to its first frame painted (wall ms,
  3458. // message thread CPU ms, instructions on Linux)
  3459. const auto i = args.indexOf ("--windowopentime");
  3460. juce::StringArray plugins;
  3461. for (int k = i + 2; k < args.size() && ! args[k].startsWith ("--"); ++k)
  3462. plugins.add (args[k].unquoted());
  3463. runWindowOpenTime (args[i + 1].unquoted(), plugins);
  3464. setApplicationReturnValue (0);
  3465. quit();
  3466. return;
  3467. }
  3468. if (args.contains ("--opentest"))
  3469. {
  3470. // LYNX.exe --opentest report.txt [--visible]: every built-in effect and instrument window opened as the mixer /
  3471. // Channel rack open them, with default, extreme, random and old-project states; a watchdog fails the test on
  3472. // a hang (round 157a: opening the Parametric EQ froze LYNX). Windows stay off-screen without --visible.
  3473. const auto i = args.indexOf ("--opentest");
  3474. runOpenTest (args[i + 1].unquoted(), args.contains ("--visible"), [this] (bool ok) {
  3475. setApplicationReturnValue (ok ? 0 : 1);
  3476. quit();
  3477. });
  3478. return;
  3479. }
  3480. if (args.contains ("--fxfuzz"))
  3481. {
  3482. // LYNX.exe --fxfuzz report.txt [rounds] [--drags]: every built-in effect in its editor, parameters swept (and
  3483. // dragged with the mouse), audio rendered at several rates; a crash ends the process (round 111)
  3484. const auto i = args.indexOf ("--fxfuzz");
  3485. const auto rounds = args.size() > i + 2 ? juce::jmax (1, args[i + 2].getIntValue()) : 6;
  3486. // --drags: also mouse drags over the editors (their menus may flash on screen: not for the selftest)
  3487. const auto ok = runEffectFuzz (rounds, args[i + 1].unquoted(), args.contains ("--drags"));
  3488. setApplicationReturnValue (ok ? 0 : 1);
  3489. quit();
  3490. return;
  3491. }
  3492. if (args.contains ("--controllershot"))
  3493. {
  3494. // LYNX.exe --controllershot prefix: the built-in controllers' editors (round 133) as PNGs
  3495. const auto i = args.indexOf ("--controllershot");
  3496. runControllerShot (args[i + 1].unquoted());
  3497. quit();
  3498. return;
  3499. }
  3500. if (args.contains ("--edisonshot"))
  3501. {
  3502. // LYNX.exe --edisonshot prefix [audio.wav]: the audio editor's Edison tool windows (round 165l) and the
  3503. // editor before / after some of them, as PNGs (a synthetic drum loop without a file)
  3504. const auto i = args.indexOf ("--edisonshot");
  3505. runEdisonShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  3506. quit();
  3507. return;
  3508. }
  3509. if (args.contains ("--arashot190kx"))
  3510. {
  3511. // LYNX --arashot190kx prefix (round 190kx): the Playlist's audio clip menu with its "Edit in ARA plugin" submenu
  3512. // (a stand-in Melodyne entry in this engine's plugin list, as a scan lists the installed one), before and after the
  3513. // clip's channel is edited in it
  3514. const auto i = args.indexOf ("--arashot190kx");
  3515. runAraShot190kx (args[i + 1].unquoted());
  3516. quit();
  3517. return;
  3518. }
  3519. if (args.contains ("--polyshot190lj") && args.indexOf ("--polyshot190lj") + 2 < args.size())
  3520. {
  3521. // LYNX --polyshot190lj prefix audio.wav [bends.wav] (round 190lj): "Convert to MIDI (polyphonic)" — the audio
  3522. // clip menu (Pattern and Simple layouts), the options dialog, Edison's Tools menu, and the result of a
  3523. // conversion (Playlist, Piano roll; with bends on the second file), plus <prefix>-checks.txt (OK / FAIL)
  3524. const auto i = args.indexOf ("--polyshot190lj");
  3525. 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());
  3526. setApplicationReturnValue (ok ? 0 : 1);
  3527. quit();
  3528. return;
  3529. }
  3530. if (args.contains ("--newtoneshot190li"))
  3531. {
  3532. // LYNX --newtoneshot190li prefix audio.wav (round 190li): Newtone with the natural engine (a new slot), as
  3533. // analysed and after Correct pitch 100 / 100 (centre and drift; the vibrato kept), and its Edit menu with the
  3534. // round's items, for the Melodyne | LYNX pairs (with --shot-scale 1.5 for @150)
  3535. const auto i = args.indexOf ("--newtoneshot190li");
  3536. runNewtoneShot190li (args[i + 1].unquoted(), args[i + 2].unquoted());
  3537. quit();
  3538. return;
  3539. }
  3540. if (args.contains ("--polyeditshot190lk") && args.indexOf ("--polyeditshot190lk") + 2 < args.size())
  3541. {
  3542. // LYNX --polyeditshot190lk prefix audio.wav [key] (round 190lk): "Edit notes (polyphonic)" — the audio clip menu,
  3543. // the editor as analysed and after one note (the one nearest `key`, default 64 = E4) moved down a semitone,
  3544. // at 100 % and 150 %, plus <prefix>-checks.txt (OK / FAIL, timings) and <prefix>-notes.txt
  3545. const auto i = args.indexOf ("--polyeditshot190lk");
  3546. const auto ok = runPolyEditShot190lk (args[i + 1].unquoted(), args[i + 2].unquoted(),
  3547. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].getDoubleValue() : 64.0);
  3548. setApplicationReturnValue (ok ? 0 : 1);
  3549. quit();
  3550. return;
  3551. }
  3552. if (args.contains ("--polyeditshot190lo") && args.indexOf ("--polyeditshot190lo") + 2 < args.size())
  3553. {
  3554. // LYNX --polyeditshot190lo prefix audio.wav [key] (round 190lo): the polyphonic note editor's round-2 tools —
  3555. // note assignment, rubber band and moving several notes, stretch handles, modulation / drift / drawn pitch,
  3556. // a dragged note's preview, Edison's buffer mode and its undo, "Prepare edited clips when a project opens" —
  3557. // at 100 % and 150 %, plus <prefix>-checks.txt and <prefix>-notes.txt
  3558. const auto i = args.indexOf ("--polyeditshot190lo");
  3559. const auto ok = runPolyEditShot190lo (args[i + 1].unquoted(), args[i + 2].unquoted(),
  3560. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].getDoubleValue() : 64.0);
  3561. setApplicationReturnValue (ok ? 0 : 1);
  3562. quit();
  3563. return;
  3564. }
  3565. if (args.contains ("--newtoneshot190kx"))
  3566. {
  3567. // LYNX --newtoneshot190kx prefix audio.wav (round 190kx): Newtone with FL's analysis and with "Separate close
  3568. // notes", each as analysed and after Center 100 % (Melodyne's Correct Pitch), for the Melodyne | LYNX pairs
  3569. const auto i = args.indexOf ("--newtoneshot190kx");
  3570. runNewtoneShot190kx (args[i + 1].unquoted(), args[i + 2].unquoted());
  3571. quit();
  3572. return;
  3573. }
  3574. if (args.contains ("--newtoneshot"))
  3575. {
  3576. // LYNX --newtoneshot prefix audio.wav (round natives190kj): FL's Newtone window with the sample analysed, in a
  3577. // few states (-plain, -selected, -advanced, -cut, -timesel, -moved) and the paint time of the FL look against
  3578. // the round-165g layout (-paint.txt)
  3579. const auto i = args.indexOf ("--newtoneshot");
  3580. runNewtoneShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  3581. quit();
  3582. return;
  3583. }
  3584. if (args.contains ("--edisonslottest"))
  3585. {
  3586. // LYNX.exe --edisonslottest folder [project.flp]: round 190cd — the audio editor as a mixer-slot plugin through
  3587. // the engine and the project file (report.txt: one "name=ok|FAIL" per check), its window as slot-*.png, and
  3588. // the Edison slots of an FL project (what was read of each)
  3589. const auto i = args.indexOf ("--edisonslottest");
  3590. const auto ok = runEdisonSlotTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  3591. setApplicationReturnValue (ok ? 0 : 1);
  3592. quit();
  3593. return;
  3594. }
  3595. if (args.contains ("--danceshot"))
  3596. {
  3597. // LYNX.exe --danceshot prefix: LYNX Dance (round 165e) — every move as a contact sheet, the channel's editor,
  3598. // and a demo project with two dance channels (for --snapshot)
  3599. const auto i = args.indexOf ("--danceshot");
  3600. runDanceShot (args[i + 1].unquoted());
  3601. quit();
  3602. return;
  3603. }
  3604. if (args.contains ("--videoshot") && args.indexOf ("--videoshot") + 2 < args.size())
  3605. {
  3606. // LYNX.exe --videoshot prefix video: the Video Player's editor (round 165g) at a few song positions, with
  3607. // the user's ffmpeg, as PNGs + report.txt (frames decoded, the sound track)
  3608. const auto i = args.indexOf ("--videoshot");
  3609. runVideoShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  3610. return;
  3611. }
  3612. if (args.contains ("--videotrackshot") && args.indexOf ("--videotrackshot") + 2 < args.size())
  3613. {
  3614. // LYNX.exe --videotrackshot prefix video [video2]: round 174d — the Playlist with video tracks (filmstrips,
  3615. // timecode row) and the video window at a few song positions, as PNGs + report.txt (the decoder, the
  3616. // frame shown for each wanted time: frame accuracy, frames dropped)
  3617. const auto i = args.indexOf ("--videotrackshot");
  3618. runVideoTrackShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  3619. return;
  3620. }
  3621. if (args.contains ("--vfxshot"))
  3622. {
  3623. // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
  3624. const auto i = args.indexOf ("--vfxshot");
  3625. runVfxShot (args[i + 1].unquoted());
  3626. quit();
  3627. return;
  3628. }
  3629. if (args.contains ("--patchershot"))
  3630. {
  3631. // LYNX.exe --patchershot prefix [project]: every Patcher's editor (round 141) as PNGs (a demo one without a project)
  3632. const auto i = args.indexOf ("--patchershot");
  3633. runPatcherShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  3634. quit();
  3635. return;
  3636. }
  3637. if (args.contains ("--audioxshot"))
  3638. {
  3639. // LYNX.exe --audioxshot prefix (round 190aq): the pre-fader send, the "Low latency while recording" mark on a
  3640. // bypassed slot and the Browser's "Preview in time", drawn off-screen
  3641. runAudioXShot (args[args.indexOf ("--audioxshot") + 1].unquoted());
  3642. quit();
  3643. return;
  3644. }
  3645. if (args.contains ("--comp177shot"))
  3646. {
  3647. // LYNX.exe --comp177shot prefix project (round 177c): a project of loop takes in the maximised
  3648. // Playlist as it opened; every group after "Comp these takes", with a swipe on the first; the track and record menus
  3649. const auto i = args.indexOf ("--comp177shot");
  3650. runComp177Shot (args[i + 1].unquoted(), args[i + 2].unquoted());
  3651. quit();
  3652. return;
  3653. }
  3654. if (args.contains ("--evpaneshot"))
  3655. {
  3656. // LYNX --evpaneshot prefix [project] (round 190fz): the Piano roll's event editor divider driven with the mouse
  3657. // handlers (drag, right-click = alternate size and back, middle-click = default, a drag into the snap zone),
  3658. // a picture of each state and prefix-report.txt with the heights and the remembered settings file
  3659. const auto i = args.indexOf ("--evpaneshot");
  3660. setApplicationReturnValue (runEvPaneShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3661. quit();
  3662. return;
  3663. }
  3664. if (args.contains ("--feat166shot"))
  3665. {
  3666. // LYNX.exe --feat166shot prefix [project]: round 166d (issue #14) — the Piano Roll with a scale, folded to
  3667. // it, with one ghost channel, the ghost channels menu, and the Mixer filled to 500 inserts (its start and
  3668. // its end, and the time a full repaint takes)
  3669. const auto i = args.indexOf ("--feat166shot");
  3670. runFeat166Shot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  3671. quit();
  3672. return;
  3673. }
  3674. if (args.contains ("--pickerdropshot"))
  3675. {
  3676. // LYNX --pickerdropshot prefix: round 190hm (issue #177) — Picker panel entries dropped on the Playlist as FL
  3677. // places them (plain drop: one track per entry at the snapped time; Shift: one after another), off-screen,
  3678. // with <prefix>-checks.txt (OK / FAIL per placement)
  3679. setApplicationReturnValue (runPickerDropShot (args[args.indexOf ("--pickerdropshot") + 1].unquoted()) ? 0 : 1);
  3680. quit();
  3681. return;
  3682. }
  3683. if (args.contains ("--trackmodeshot"))
  3684. {
  3685. // LYNX --trackmodeshot prefix: rollup 190cv (UI gate of PR #151) — Playlist track header › Track mode › Audio
  3686. // track, off-screen, in three states of FL's live check 190cu (q1-01 fresh, q1-02 one insert linked
  3687. // elsewhere and one renamed, q1-07 the full state), plus a report that compares each list with FL's
  3688. setApplicationReturnValue (runTrackModeShot (args[args.indexOf ("--trackmodeshot") + 1].unquoted()) ? 0 : 1);
  3689. quit();
  3690. return;
  3691. }
  3692. if (args.contains ("--curveshot"))
  3693. {
  3694. // LYNX.exe --curveshot prefix: round 190bw — an automation clip with one segment per FL curve mode in the
  3695. // point editor and in the Playlist, and FL's point menu, off-screen
  3696. runCurveShot (args[args.indexOf ("--curveshot") + 1].unquoted());
  3697. quit();
  3698. return;
  3699. }
  3700. if (args.contains ("--remoteshot"))
  3701. {
  3702. // LYNX.exe --remoteshot prefix: Online Sessions P5-A1 (round 190ai) — the host's "Share plugins with guests"
  3703. // list and a guest's parameter editor of a plugin the host plays, off-screen with sample data
  3704. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3705. lynx::liveui::saveRemoteShots (args[args.indexOf ("--remoteshot") + 1].unquoted());
  3706. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  3707. quit();
  3708. return;
  3709. }
  3710. if (args.contains ("--settingsshot") && ! args.contains ("--rtstress")) // (--rtstress has its own --settingsshot file.png option, round 161)
  3711. {
  3712. // LYNX.exe --settingsshot prefix: round 190bx — every Settings page off-screen at the window's size, in a
  3713. // small window (390 x 390) and, for the long pages, whole (see runSettingsShot)
  3714. runSettingsShot (args[args.indexOf ("--settingsshot") + 1].unquoted());
  3715. quit();
  3716. return;
  3717. }
  3718. if (args.contains ("--perfshot"))
  3719. {
  3720. // LYNX.exe --perfshot prefix project: the Playlist in Performance mode with a few clips launched and waiting,
  3721. // then the project patcherized (every insert's effects, the first channels) saved as prefix-patcherized.lynx
  3722. // for --patchershot (round 165m)
  3723. const auto i = args.indexOf ("--perfshot");
  3724. runPerfShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  3725. quit();
  3726. return;
  3727. }
  3728. if (args.contains ("--freezetest"))
  3729. {
  3730. // LYNX.exe --freezetest prefix [project]: round 190ay's Freeze end to end, off-screen (see runFreezeTest)
  3731. const auto i = args.indexOf ("--freezetest");
  3732. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3733. // a word after the project: "keep" = freeze, save prefix-frozen.lynx and stop (the audio stays);
  3734. // "measure" = only load and render the project, for the memory and time of a process of its own
  3735. const auto mode = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  3736. setApplicationReturnValue (runFreezeTest (args[i + 1].unquoted(), project, mode) ? 0 : 1);
  3737. quit();
  3738. return;
  3739. }
  3740. if (args.contains ("--trackfreezetest"))
  3741. {
  3742. // LYNX --trackfreezetest prefix: round 190ff's Freeze Track, Flatten / Bounce Track in Place, Bounce to New
  3743. // Track and Consolidate end to end in the Clip-launch workflow, off-screen (see runTrackFreezeTest)
  3744. const auto i = args.indexOf ("--trackfreezetest");
  3745. setApplicationReturnValue (runTrackFreezeTest (args[i + 1].unquoted()) ? 0 : 1);
  3746. quit();
  3747. return;
  3748. }
  3749. if (args.contains ("--details190ihshot"))
  3750. {
  3751. // LYNX --details190ihshot prefix: round 190ih's live states off screen (no window, no audio device) — Gross
  3752. // Beat's locator and slots from its real engine, the rack's activity light, Play / Pause, the Record blink,
  3753. // the "Note on" hint, the save reminder, the Simple dock's input level, the Envelope Controller's key line
  3754. const auto i = args.indexOf ("--details190ihshot");
  3755. runDetails190ihShot (args[i + 1].unquoted());
  3756. quit();
  3757. return;
  3758. }
  3759. if (args.contains ("--paintbench"))
  3760. {
  3761. // LYNX --paintbench project.(flp|lynx|als) report.txt (round 190ge): each main view drawn off screen, whole, many
  3762. // times (the message thread's CPU per frame), with the playhead mid-song; no window, no audio device
  3763. const auto i = args.indexOf ("--paintbench");
  3764. runPaintBench (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  3765. quit();
  3766. return;
  3767. }
  3768. if (args.contains ("--design190igshot"))
  3769. {
  3770. // LYNX --design190igshot prefix project.flp: round 190ig off-screen (design190ia slice 3) — the Pattern layout's
  3771. // 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),
  3772. // at FL's "zoom 17" (50 px tracks, 39.75 px a bar), and playing (the activity column), as FL's reference shots
  3773. const auto i = args.indexOf ("--design190igshot");
  3774. runDesign190igShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  3775. quit();
  3776. return;
  3777. }
  3778. if (args.contains ("--cliplaunch190kcshot"))
  3779. {
  3780. // LYNX --cliplaunch190kcshot prefix set.als: round 190kc off screen (Live's return tracks, Sends rows, Pre / Post,
  3781. // the crossfader, the map modes' crossfader positions and relative strip, Commit / Extract on audio); prefix-checks.txt
  3782. const auto i = args.indexOf ("--cliplaunch190kcshot");
  3783. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3784. runClipLaunch190kcShot (args[i + 1].unquoted(), set);
  3785. quit();
  3786. return;
  3787. }
  3788. if (args.contains ("--livelook190jnshot"))
  3789. {
  3790. // LYNX --livelook190jnshot prefix [set.als]: round 190jn off screen (design190ia slices 13, 17, 18, 19, 25: the
  3791. // Clip-launch layout in Live's look, and the classic look); prefix-checks.txt
  3792. const auto i = args.indexOf ("--livelook190jnshot");
  3793. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3794. runLiveLook190jnShot (args[i + 1].unquoted(), set);
  3795. quit();
  3796. return;
  3797. }
  3798. if (args.contains ("--fllook190joshot"))
  3799. {
  3800. // LYNX --fllook190joshot prefix project.flp: round 190jo off screen (design190ia slices 12, 21, 23): the Pattern
  3801. // toolbar's tiles in every state, time / tempo / hint / menu bar, at 1920 / 1600 / 1366 / 1280; the Piano roll
  3802. // (FL's rows, notes, keys, grid, ghosts); the audio editor in Edison's layout with FL's "DL Breaker.wav";
  3803. // prefix-checks.txt (note label contrast)
  3804. const auto i = args.indexOf ("--fllook190joshot");
  3805. runFllook190joShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String());
  3806. quit();
  3807. return;
  3808. }
  3809. if (args.contains ("--capfix190jjshot"))
  3810. {
  3811. // LYNX --capfix190jjshot prefix project.flp [set.als]: round 190jj off screen (capture190ji's changes: Simple
  3812. // capsule states, master meter, pads press, held keys, drop lane ghosts; Live's control bar; FL's C-11 drop ghost
  3813. // and the picker's playing mark); prefix-checks.txt
  3814. const auto i = args.indexOf ("--capfix190jjshot");
  3815. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  3816. runCapfix190jjShot (args[i + 1].unquoted(), args[i + 2].unquoted(), set);
  3817. quit();
  3818. return;
  3819. }
  3820. if (args.contains ("--demo190qxcheck"))
  3821. {
  3822. // LYNX --demo190qxcheck prefix: round 190qx, the --demo targets of tutorial batch 3 (src/Demo190qxCheck.inc)
  3823. const auto i = args.indexOf ("--demo190qxcheck");
  3824. setApplicationReturnValue (runDemoCheck190qx (args[i + 1].unquoted()) ? 0 : 1);
  3825. quit();
  3826. return;
  3827. }
  3828. if (args.contains ("--demo190plcheck"))
  3829. {
  3830. // LYNX --demo190plcheck prefix: round 190pl, the --demo operations of tutorial batch 2 (src/Demo190plCheck.inc)
  3831. const auto i = args.indexOf ("--demo190plcheck");
  3832. setApplicationReturnValue (runDemoCheck190pl (args[i + 1].unquoted()) ? 0 : 1);
  3833. quit();
  3834. return;
  3835. }
  3836. if (args.contains ("--demo190pgcheck"))
  3837. {
  3838. // LYNX --demo190pgcheck prefix project.lynx: round 190pg, the --demo operations of the tutorial videos (src/Demo190pgCheck.inc)
  3839. const auto i = args.indexOf ("--demo190pgcheck");
  3840. setApplicationReturnValue (runDemoCheck190pg (args[i + 1].unquoted(), juce::File (i + 2 < args.size() ? args[i + 2].unquoted() : juce::String())) ? 0 : 1);
  3841. quit();
  3842. return;
  3843. }
  3844. if (args.contains ("--onboard190npshot"))
  3845. {
  3846. // LYNX --onboard190npshot prefix: round 190np off screen (src/OnboardShot190np.inc): the welcome card, the choices,
  3847. // the Next-3 card, the empty-state hints, the tips and the Help menu, 100 % and @150, with <prefix>-checks.txt
  3848. const auto i = args.indexOf ("--onboard190npshot");
  3849. setApplicationReturnValue (runOnboardShot190np (args[i + 1].unquoted()) ? 0 : 1);
  3850. quit();
  3851. return;
  3852. }
  3853. if (args.contains ("--details190tbshot"))
  3854. {
  3855. // LYNX --details190tbshot prefix project.flp: round 190tb's hint-bar pictures (src/DetailsSweep190tb.inc)
  3856. const auto i = args.indexOf ("--details190tbshot");
  3857. setApplicationReturnValue (runDetailsShot190tb (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3858. quit();
  3859. return;
  3860. }
  3861. if (args.contains ("--details190tbsweep"))
  3862. {
  3863. // LYNX --details190tbsweep prefix project.flp: round 190tb's hover sweep (src/DetailsSweep190tb.inc)
  3864. const auto i = args.indexOf ("--details190tbsweep");
  3865. setApplicationReturnValue (runDetailsSweep190tb (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3866. quit();
  3867. return;
  3868. }
  3869. if (args.contains ("--details190oashot"))
  3870. {
  3871. // LYNX --details190oashot prefix project.flp: round 190oa off screen (src/DetailsShot190oa.inc)
  3872. const auto i = args.indexOf ("--details190oashot");
  3873. setApplicationReturnValue (runDetailsShot190oa (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3874. quit();
  3875. return;
  3876. }
  3877. if (args.contains ("--details190myshot"))
  3878. {
  3879. // LYNX --details190myshot prefix project.flp: round 190my off screen (src/DetailsShot190my.inc)
  3880. const auto i = args.indexOf ("--details190myshot");
  3881. setApplicationReturnValue (runDetailsShot190my (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3882. quit();
  3883. return;
  3884. }
  3885. if (args.contains ("--details190mvshot"))
  3886. {
  3887. // LYNX --details190mvshot prefix project.flp: round 190mv off screen (src/DetailsShot190mv.inc)
  3888. const auto i = args.indexOf ("--details190mvshot");
  3889. setApplicationReturnValue (runDetailsShot190mv (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3890. quit();
  3891. return;
  3892. }
  3893. if (args.contains ("--details190mrshot"))
  3894. {
  3895. // LYNX --details190mrshot prefix project.flp: round 190mr off screen (src/DetailsShot190mr.inc)
  3896. const auto i = args.indexOf ("--details190mrshot");
  3897. setApplicationReturnValue (runDetailsShot190mr (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3898. quit();
  3899. return;
  3900. }
  3901. if (args.contains ("--rack190ncshot") && args.indexOf ("--rack190ncshot") + 1 < args.size())
  3902. {
  3903. // LYNX --rack190ncshot prefix: round 190nc off screen (src/RackShot190nc.inc): Live's rack with its devices
  3904. // inline and the Macro Map overlay (DL-95), the Session mixer's Solo / Cue (DL-110)
  3905. setApplicationReturnValue (runRackShot190nc (args[args.indexOf ("--rack190ncshot") + 1].unquoted()) ? 0 : 1);
  3906. quit();
  3907. return;
  3908. }
  3909. if (args.contains ("--details190mpshot"))
  3910. {
  3911. // LYNX --details190mpshot prefix project.flp: round 190mp off screen (src/DetailsShot190mp.inc)
  3912. const auto i = args.indexOf ("--details190mpshot");
  3913. setApplicationReturnValue (runDetailsShot190mp (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3914. quit();
  3915. return;
  3916. }
  3917. if (args.contains ("--details190mkshot"))
  3918. {
  3919. // LYNX --details190mkshot prefix project.flp: round 190mk off screen (src/DetailsShot190mk.inc)
  3920. const auto i = args.indexOf ("--details190mkshot");
  3921. setApplicationReturnValue (runDetailsShot190mk (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3922. quit();
  3923. return;
  3924. }
  3925. if (args.contains ("--details190mfshot"))
  3926. {
  3927. // LYNX --details190mfshot prefix project.flp: round 190mf off screen (src/DetailsShot190mf.inc)
  3928. const auto i = args.indexOf ("--details190mfshot");
  3929. setApplicationReturnValue (runDetailsShot190mf (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3930. quit();
  3931. return;
  3932. }
  3933. if (args.contains ("--details190lxshot"))
  3934. {
  3935. // LYNX --details190lxshot prefix project.flp [set.als]: round 190lx off screen (src/DetailsShot190lx.inc)
  3936. const auto i = args.indexOf ("--details190lxshot");
  3937. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  3938. setApplicationReturnValue (runDetailsShot190lx (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  3939. quit();
  3940. return;
  3941. }
  3942. if (args.contains ("--details190lrshot"))
  3943. {
  3944. // LYNX --details190lrshot prefix project.flp [set.als]: round 190lr off screen (src/DetailsShot190lr.inc)
  3945. const auto i = args.indexOf ("--details190lrshot");
  3946. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  3947. setApplicationReturnValue (runDetailsShot190lr (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  3948. quit();
  3949. return;
  3950. }
  3951. if (args.contains ("--details190ldshot"))
  3952. {
  3953. // LYNX --details190ldshot prefix project.flp [set.als]: round 190ld off screen (src/DetailsShot190ld.inc)
  3954. const auto i = args.indexOf ("--details190ldshot");
  3955. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  3956. setApplicationReturnValue (runDetailsShot190ld (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  3957. quit();
  3958. return;
  3959. }
  3960. if (args.contains ("--details190knshot"))
  3961. {
  3962. // LYNX --details190knshot prefix project.flp [set.als]: round 190kn off screen (src/DetailsShot190kn.inc)
  3963. const auto i = args.indexOf ("--details190knshot");
  3964. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  3965. setApplicationReturnValue (runDetailsShot190kn (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  3966. quit();
  3967. return;
  3968. }
  3969. if (args.contains ("--details190imshot"))
  3970. {
  3971. // LYNX --details190imshot prefix project.flp [set.als]: round 190im off-screen (details190if R1, R5, R6, R11, R12,
  3972. // R13, R15) — the automation hints, the Playlist playing (picker marks, glow, overview, activity levels), a drop
  3973. // preview, Follow's pause, the Sampler's handles, and with the Live set the grid's one-shot / follow / queued
  3974. // scene / deactivated clip / hints and the Clip View's launched position; prefix-checks.txt
  3975. const auto i = args.indexOf ("--details190imshot");
  3976. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  3977. runDetails190imShot (args[i + 1].unquoted(), args[i + 2].unquoted(), set);
  3978. quit();
  3979. return;
  3980. }
  3981. if (args.contains ("--toolbarshot190qg"))
  3982. {
  3983. // LYNX --toolbarshot190qg prefix [project]: round 190qg off screen — the toolbar walk (every preset, icon size,
  3984. // Interface size and window width: each item on the toolbar or in its overflow), every preset's toolbar at
  3985. // 80-175 % on 1280 / 1920 px screens, the overflow menus; exit 0 = the walk passed (src/ToolbarShot190qg.inc)
  3986. const auto i = args.indexOf ("--toolbarshot190qg");
  3987. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3988. setApplicationReturnValue (runToolbarShot190qg (args[i + 1].unquoted(), project) ? 0 : 1);
  3989. quit();
  3990. return;
  3991. }
  3992. if (args.contains ("--toolbarshot190iv"))
  3993. {
  3994. // LYNX --toolbarshot190iv prefix [project.als]: round 190iv off screen — the toolbar of each layout style (Pattern,
  3995. // Simple, Clip-launch) at 1920 / 1366 / 1280, the Simple transport capsule idle / hover / pressed / playing /
  3996. // recording, the "Last saved" status in its four states, Live's control bar with every button idle / hover /
  3997. // pressed / lit, the "⋯" menus, and a report of the parts' bounds
  3998. const auto i = args.indexOf ("--toolbarshot190iv");
  3999. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  4000. runToolbarShot190iv (args[i + 1].unquoted(), project);
  4001. quit();
  4002. return;
  4003. }
  4004. if (args.contains ("--gridshot"))
  4005. {
  4006. // LYNX.exe --gridshot prefix [project]: the Clip-launch workflow's layout off-screen, with a grid of sample
  4007. // clips, some playing and waiting, at the size of LYNX_SNAPSHOT_SIZE (round 181a); with a project (.lynx,
  4008. // .flp, .als), that project's grid instead (round 181c: a Live set's Session view as LYNX imports it)
  4009. const auto i = args.indexOf ("--gridshot");
  4010. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  4011. runGridShot (args[i + 1].unquoted(), project);
  4012. quit();
  4013. return;
  4014. }
  4015. if (args.contains ("--tour190dvshot"))
  4016. {
  4017. // LYNX.exe --tour190dvshot prefix: round 190dv off-screen — the Simple workflow's Welcome screen, every step of
  4018. // the first-song tour done with its "Do it for me" (a loop dropped for the loop step), the end card, Back /
  4019. // Next / close, the Help menu, the chooser's tour button, Start from with the three demo songs, a demo
  4020. // opened in Simple — and a text report of the checks (incl. resources/demos/*.lynx = the generated songs)
  4021. const auto i = args.indexOf ("--tour190dvshot");
  4022. runTour190dvShot (args[i + 1].unquoted());
  4023. quit();
  4024. return;
  4025. }
  4026. if (args.contains ("--donateshot"))
  4027. {
  4028. // LYNX --donateshot prefix: round 190fq off-screen (no window) — Help › Support LYNX SHARE... in the three
  4029. // layouts, the Support window, the About window's Support button, the start-up support note in the main
  4030. // window, and the note's rules end to end on its saved state (run it with LYNX_PROFILE_DIR: it writes
  4031. // support-note.txt there, and puts the old one back at the end); report prefix-report.txt, exit 0 = OK
  4032. const auto i = args.indexOf ("--donateshot");
  4033. setApplicationReturnValue (runDonateShot (args[i + 1].unquoted()) ? 0 : 1);
  4034. quit();
  4035. return;
  4036. }
  4037. if (args.contains ("--simpleclosetest"))
  4038. {
  4039. // LYNX --simpleclosetest <report.txt>: round 190fc off-screen (no window) — the main window in the Simple
  4040. // layout with Welcome, the tour, Start from, a demo, the dock's tabs, Finish and Lyrics open, then closed as at
  4041. // shutdown (the 0.1.27 RC crashed on every such close); exit code 0 = OK
  4042. const auto i = args.indexOf ("--simpleclosetest");
  4043. setApplicationReturnValue (runSimpleCloseTest (args[i + 1].unquoted()) ? 0 : 1);
  4044. quit();
  4045. return;
  4046. }
  4047. if (args.contains ("--patterns190ea"))
  4048. {
  4049. // LYNX --patterns190ea <report.txt>: round 190ea off-screen (no window) — a song with no pattern at all
  4050. // reaching the engine in every layout (the Simple dock's Editor tab, the Piano roll panel of the Pattern
  4051. // layout, the Clip-launch layout), the last pattern deleted, all patterns cleared by an edit, undo / redo,
  4052. // a live session's remote song and an out-of-range current pattern; each must leave one pattern and not crash
  4053. const auto i = args.indexOf ("--patterns190ea");
  4054. setApplicationReturnValue (runPatterns190ea (args[i + 1].unquoted()) ? 0 : 1);
  4055. quit();
  4056. return;
  4057. }
  4058. if (args.contains ("--reabl190foshot"))
  4059. {
  4060. // LYNX --reabl190foshot prefix: round 190fo off-screen — the Simple Sampler track's 16 pads in the dock, its
  4061. // menus and kits, the typing keys, the .lynx round trip, a folder of stems and MIDI files — and a report
  4062. const auto i = args.indexOf ("--reabl190foshot");
  4063. runReabl190foShot (args[i + 1].unquoted());
  4064. quit();
  4065. return;
  4066. }
  4067. if (args.contains ("--simple190dsshot"))
  4068. {
  4069. // LYNX.exe --simple190dsshot prefix: round 190ds off-screen, at 1x and 2x — loops dropped in the Simple
  4070. // workflow following the project key (the dock's switch, the clip menu), the docked Piano roll in the Editor
  4071. // tab, the keyboard's modes Keys / Scale keys / Chord pad with the scale selector — and a text report
  4072. const auto i = args.indexOf ("--simple190dsshot");
  4073. runSimple190dsShot (args[i + 1].unquoted());
  4074. quit();
  4075. return;
  4076. }
  4077. if (args.contains ("--simple190dgshot"))
  4078. {
  4079. // LYNX.exe --simple190dgshot prefix: round 190dg's additions to the Simple dock off-screen, at 1x and 2x —
  4080. // the Effects tab with all eight one-knob cards and each card alone, a chain preset with Blend, the
  4081. // favourites in the Preset menu, the sound picker (a search, My plugins with a made-up plugin list) — and a
  4082. // text report of the checks
  4083. const auto i = args.indexOf ("--simple190dgshot");
  4084. runSimple190dgShot (args[i + 1].unquoted());
  4085. quit();
  4086. return;
  4087. }
  4088. if (args.contains ("--simplefxshot"))
  4089. {
  4090. // LYNX.exe --simplefxshot prefix: round 190bu's track dock of the Simple workflow off-screen, at 1x and 2x —
  4091. // the Instrument tab (LYNX sounds, My SoundFonts), the Effects tab (empty, a preset, its menus), and a text
  4092. // report: the dock's edits, a user preset saved and loaded, the same slots in the Pattern workflow's Mixer
  4093. const auto i = args.indexOf ("--simplefxshot");
  4094. runSimpleFxShot (args[i + 1].unquoted());
  4095. quit();
  4096. return;
  4097. }
  4098. if (args.contains ("--simple190jcshot"))
  4099. {
  4100. // LYNX.exe --simple190jcshot prefix: round 190jc's Simple layout look (design190ia slices 5, 14, 15, 22, 24 and
  4101. // Large controls) off-screen, at 1x and 2x, with a text report
  4102. const auto i = args.indexOf ("--simple190jcshot");
  4103. runSimple190jcShot (args[i + 1].unquoted());
  4104. quit();
  4105. return;
  4106. }
  4107. if (args.contains ("--simpleshot"))
  4108. {
  4109. // LYNX.exe --simpleshot prefix: round 184a's Simple workflow off-screen — View › Layout style with each style
  4110. // chosen, Settings › General (Pattern, then Simple selected) with its style list, the window in Pattern, then
  4111. // Simple, then Pattern again, and how many Simple workflow objects existed before and after (0 before)
  4112. const auto i = args.indexOf ("--simpleshot");
  4113. runSimpleShot (args[i + 1].unquoted());
  4114. quit();
  4115. return;
  4116. }
  4117. // --versionsshot <prefix> (round 190ap): the Versions panel, File's new items, a project opened without its
  4118. // third-party plugins (window, list, File menu) and the Export window's additions, offscreen
  4119. if (args.contains ("--versionsshot"))
  4120. {
  4121. runVersionsShot (args[args.indexOf ("--versionsshot") + 1].unquoted());
  4122. quit();
  4123. return;
  4124. }
  4125. // --linkshot <prefix> (round 190bt): FL's Remote control settings / Global link settings windows, the control
  4126. // menu with "Link to controller...", the formula presets and controller menus and the Multilink items,
  4127. // offscreen; prefix-checks.txt holds the round's checks of the engine, the project file and the settings
  4128. if (args.contains ("--linkshot"))
  4129. {
  4130. setApplicationReturnValue (runLinkShot (args[args.indexOf ("--linkshot") + 1].unquoted()) ? 0 : 1);
  4131. quit();
  4132. return;
  4133. }
  4134. // --flctlshot <prefix> (round 190df): FL's multilink menu (on / off), the plugin menu's A/B and "Link all
  4135. // parameters...", the sampler's File row with its Sample history, and the Envelope / instrument page of a sampler
  4136. // running FL's voice with its envelope presets, offscreen; prefix-checks.txt holds the checks
  4137. if (args.contains ("--flctlshot"))
  4138. {
  4139. setApplicationReturnValue (runFlCtlShot (args[args.indexOf ("--flctlshot") + 1].unquoted()) ? 0 : 1);
  4140. quit();
  4141. return;
  4142. }
  4143. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen (shots and checks in prefix-checks.txt)
  4144. if (args.contains ("--samplerpageshot"))
  4145. {
  4146. setApplicationReturnValue (runSamplerPageShot (args[args.indexOf ("--samplerpageshot") + 1].unquoted()) ? 0 : 1);
  4147. quit();
  4148. return;
  4149. }
  4150. // --flplshot <prefix> (round 190dx): the audio clip menu (Preview, Automate › Panning / Volume), the Playlist's "+"
  4151. // and its menu, Track mode › Instrument track, the Channel rack's "Assign to new instrument track", Tools › One-click
  4152. // audio recording and Mixer › Disk recording › Latency compensation, offscreen; prefix-checks.txt holds the checks
  4153. // --hdrshot190ft <prefix> (round 190ft, issues #163 / #164): FL's track-header selection and resize rules driven
  4154. // with synthetic mouse events on the Playlist headers and the mixer strips, offscreen; prefix-checks.txt
  4155. if (args.contains ("--hdrshot190ft"))
  4156. {
  4157. setApplicationReturnValue (runHdrShot190ft (args[args.indexOf ("--hdrshot190ft") + 1].unquoted()) ? 0 : 1);
  4158. quit();
  4159. return;
  4160. }
  4161. // --dawprojcheck190jf <prefix> <project> (round 190jf, slice B22): export to DAWproject and open it again
  4162. if (args.contains ("--dawprojcheck190jf") && args.indexOf ("--dawprojcheck190jf") + 2 < args.size())
  4163. {
  4164. const auto at = args.indexOf ("--dawprojcheck190jf");
  4165. setApplicationReturnValue (runDawProjectCheck190jf (args[at + 1].unquoted(), juce::File (args[at + 2].unquoted())) ? 0 : 1);
  4166. quit();
  4167. return;
  4168. }
  4169. // --foldersshot190jf <prefix> <thief.flp> (round 190jf, slice B17): the Playlist's folders; prefix-checks.txt
  4170. if (args.contains ("--foldersshot190jf") && args.indexOf ("--foldersshot190jf") + 2 < args.size())
  4171. {
  4172. const auto at = args.indexOf ("--foldersshot190jf");
  4173. setApplicationReturnValue (runFoldersShot190jf (args[at + 1].unquoted(), juce::File (args[at + 2].unquoted())) ? 0 : 1);
  4174. quit();
  4175. return;
  4176. }
  4177. // --userfixshot190ib <prefix> (round 190ib): issue #182's type-to-jump in a real popup menu (the Playlist's Edit menu
  4178. // of the issue's screenshot, typed into), #183's Piano roll item, #181's Ctrl+, through the main window's keys;
  4179. // prefix-checks.txt
  4180. if (args.contains ("--userfixshot190ib"))
  4181. {
  4182. setApplicationReturnValue (runUserFixShot190ib (args[args.indexOf ("--userfixshot190ib") + 1].unquoted()) ? 0 : 1);
  4183. quit();
  4184. return;
  4185. }
  4186. // --issuesshot190ht <prefix> (round 190ht): issue #127's other tools on Pattern Blocks (Mute, Select + group move,
  4187. // Slice, Zoom) and issue #154's insert effects list on linked headers, driven with synthetic mouse events,
  4188. // offscreen; prefix-checks.txt and pictures
  4189. if (args.contains ("--issuesshot190ht"))
  4190. {
  4191. setApplicationReturnValue (runIssuesShot190ht (args[args.indexOf ("--issuesshot190ht") + 1].unquoted()) ? 0 : 1);
  4192. quit();
  4193. return;
  4194. }
  4195. // --chordlane190pfshot <prefix> (round 190pf, research190oe P13 / P12): src/ChordLaneShot190pf.inc
  4196. if (args.contains ("--chordlane190pfshot"))
  4197. {
  4198. setApplicationReturnValue (runChordLaneShot190pf (args[args.indexOf ("--chordlane190pfshot") + 1].unquoted()) ? 0 : 1);
  4199. quit();
  4200. return;
  4201. }
  4202. // --sections190olshot <prefix> (round 190ol, research190oe P1 / P6): src/SectionsShot190ol.inc
  4203. if (args.contains ("--sections190olshot"))
  4204. {
  4205. setApplicationReturnValue (runSectionsShot190ol (args[args.indexOf ("--sections190olshot") + 1].unquoted()) ? 0 : 1);
  4206. quit();
  4207. return;
  4208. }
  4209. // --playlistshot190jq <prefix> (round 190jq, issues #164 and #191): src/PlaylistShot190jq.inc
  4210. if (args.contains ("--playlistshot190jq"))
  4211. {
  4212. setApplicationReturnValue (runPlaylistShot190jq (args[args.indexOf ("--playlistshot190jq") + 1].unquoted()) ? 0 : 1);
  4213. quit();
  4214. return;
  4215. }
  4216. // --focus218shot190ng <prefix> (round 190ng, issue #218): src/Focus218Shot190ng.inc
  4217. if (args.contains ("--focus218shot190ng"))
  4218. {
  4219. setApplicationReturnValue (runFocus218Shot190ng (args[args.indexOf ("--focus218shot190ng") + 1].unquoted()) ? 0 : 1);
  4220. quit();
  4221. return;
  4222. }
  4223. // --mixerqolshot190qh <prefix> [project.flp] (round 190qh, research190qa R5 Mixer QoL): src/MixerQolShot190qh.inc
  4224. if (args.contains ("--mixerqolshot190qh"))
  4225. {
  4226. const auto i = args.indexOf ("--mixerqolshot190qh");
  4227. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  4228. setApplicationReturnValue (runMixerQolShot190qh (args[i + 1].unquoted(), project) ? 0 : 1);
  4229. quit();
  4230. return;
  4231. }
  4232. // --slots260shot <prefix> (round 190qf, PR #260: FL 2026.2's mixer slots): src/Slots260Shot190qf.inc
  4233. if (args.contains ("--slots260shot"))
  4234. {
  4235. setApplicationReturnValue (runSlots260Shot (args[args.indexOf ("--slots260shot") + 1].unquoted()) ? 0 : 1);
  4236. quit();
  4237. return;
  4238. }
  4239. // --mixer221shot190ng <prefix> (round 190ng, issue #221): src/Mixer221Shot190ng.inc
  4240. if (args.contains ("--mixer221shot190ng"))
  4241. {
  4242. setApplicationReturnValue (runMixer221Shot190ng (args[args.indexOf ("--mixer221shot190ng") + 1].unquoted()) ? 0 : 1);
  4243. quit();
  4244. return;
  4245. }
  4246. // --research190onshot <prefix> (round 190on: research190oe P2, P8, P10): src/Research190onShot.inc
  4247. if (args.contains ("--research190onshot"))
  4248. {
  4249. setApplicationReturnValue (runResearchShot190on (args[args.indexOf ("--research190onshot") + 1].unquoted()) ? 0 : 1);
  4250. quit();
  4251. return;
  4252. }
  4253. // --issuesshot190nq <prefix> (round 190nq, issues #193, #225-#230): src/IssuesShot190nq.inc
  4254. if (args.contains ("--issuesshot190nq"))
  4255. {
  4256. setApplicationReturnValue (runIssuesShot190nq (args[args.indexOf ("--issuesshot190nq") + 1].unquoted()) ? 0 : 1);
  4257. quit();
  4258. return;
  4259. }
  4260. // --design190ojshot <prefix> [project] (round 190oj, design review): src/Design190ojShot.inc
  4261. if (args.contains ("--design190ojshot"))
  4262. {
  4263. const auto i = args.indexOf ("--design190ojshot");
  4264. setApplicationReturnValue (runDesign190ojShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  4265. quit();
  4266. return;
  4267. }
  4268. // --rackauto190owshot <prefix> [project.flp] [probe.flp] (round 190ow, PAT-7 rest / DE-123): src/RackAuto190owShot.inc
  4269. if (args.contains ("--rackauto190owshot"))
  4270. {
  4271. const auto i = args.indexOf ("--rackauto190owshot");
  4272. const auto arg = [&args] (int k) { return k < args.size() && ! args[k].startsWith ("--") ? args[k].unquoted() : juce::String(); };
  4273. setApplicationReturnValue (runRackAuto190owShot (args[i + 1].unquoted(), arg (i + 2), arg (i + 3)) ? 0 : 1);
  4274. quit();
  4275. return;
  4276. }
  4277. // --settingsshots190qx <prefix> (round 190qx): the Settings pages at 100 % and @150 (src/SettingsShots190qx.inc)
  4278. if (args.contains ("--settingsshots190qx"))
  4279. {
  4280. runSettingsShots190qx (args[args.indexOf ("--settingsshots190qx") + 1].unquoted());
  4281. quit();
  4282. return;
  4283. }
  4284. // --copy0132test190tf <folder> (round 190tf): the Save-a-copy-for-0.1.32 check, leaving the round trip's files
  4285. // (original / copy / expected .lynx) in <folder>: src/Downgrade0132_190tfCheck.inc
  4286. if (args.contains ("--copy0132test190tf"))
  4287. {
  4288. setApplicationReturnValue (runCopy0132Test190tf (args[args.indexOf ("--copy0132test190tf") + 1].unquoted()));
  4289. quit();
  4290. return;
  4291. }
  4292. if (args.contains ("--nofl190rhlynx"))
  4293. {
  4294. const auto i = args.indexOf ("--nofl190rhlynx");
  4295. setApplicationReturnValue (runNoFl190rhLynx (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].unquoted()) ? 0 : 1);
  4296. quit();
  4297. return;
  4298. }
  4299. // --nofl190rhshot <prefix> (round 190rh: Settings > Files > FL Studio folder): src/NoFl190rhCheck.inc
  4300. if (args.contains ("--nofl190rhshot"))
  4301. {
  4302. runNoFl190rhShot (args[args.indexOf ("--nofl190rhshot") + 1].unquoted());
  4303. return;
  4304. }
  4305. // --optionsux190qxshot <prefix> (round 190qx: Settings reset / grouping / palette index, How-to guides, tips, notices)
  4306. if (args.contains ("--optionsux190qxshot"))
  4307. {
  4308. setApplicationReturnValue (runOptionsux190qxShot (args[args.indexOf ("--optionsux190qxshot") + 1].unquoted()) ? 0 : 1);
  4309. quit();
  4310. return;
  4311. }
  4312. // --emptyhint313shot <prefix> (issue #313, round 190rs): the empty-state card while the view zooms: src/Q5fix190rsShot.inc
  4313. if (args.contains ("--emptyhint313shot"))
  4314. {
  4315. setApplicationReturnValue (runEmptyHint313Shot (args[args.indexOf ("--emptyhint313shot") + 1].unquoted()) ? 0 : 1);
  4316. quit();
  4317. return;
  4318. }
  4319. // --q5fix190rsshot <prefix> <project.flp> (round 190rs, 0.1.32 stage Q5 fixes): src/Q5fix190rsShot.inc
  4320. if (args.contains ("--q5fix190rsshot"))
  4321. {
  4322. const auto at = args.indexOf ("--q5fix190rsshot");
  4323. setApplicationReturnValue (runQ5fix190rsShot (args[at + 1].unquoted(), args[at + 2].unquoted()) ? 0 : 1);
  4324. quit();
  4325. return;
  4326. }
  4327. // --playlistview190soshot <prefix> [project] (round 190so, 0.1.33 block A3: the Playlist view group): src/PlaylistView190soShot.inc
  4328. // --custom190ssshot <prefix> (round 190ss, 0.1.33 block C: toolbar presets, pinned actions, track header elements):
  4329. // src/Custom190ssShot.inc
  4330. if (args.contains ("--custom190ssshot"))
  4331. {
  4332. setApplicationReturnValue (runCustom190ssShot (args[args.indexOf ("--custom190ssshot") + 1].unquoted()) ? 0 : 1);
  4333. quit();
  4334. return;
  4335. }
  4336. if (args.contains ("--playlistview190soshot"))
  4337. {
  4338. const auto i = args.indexOf ("--playlistview190soshot");
  4339. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  4340. setApplicationReturnValue (runPlaylistView190soShot (args[i + 1].unquoted(), project) ? 0 : 1);
  4341. quit();
  4342. return;
  4343. }
  4344. // --extras190roshot <prefix> (round 190ro: LYNX extras review 2, the gain handle in view, the Mixer at FL's height, the
  4345. // Clip-launch strips of new projects): src/Extras190roShot.inc
  4346. if (args.contains ("--extras190roshot"))
  4347. {
  4348. setApplicationReturnValue (runExtras190roShot (args[args.indexOf ("--extras190roshot") + 1].unquoted()) ? 0 : 1);
  4349. quit();
  4350. return;
  4351. }
  4352. // --extras190qkshot <prefix> (round 190qk: the LYNX extras on by default, FL-exact / Recommended): src/Extras190qkShot.inc
  4353. if (args.contains ("--extras190qkshot"))
  4354. {
  4355. setApplicationReturnValue (runExtras190qkShot (args[args.indexOf ("--extras190qkshot") + 1].unquoted()) ? 0 : 1);
  4356. quit();
  4357. return;
  4358. }
  4359. // --polish190qwshot <prefix> [project] (round 190qw, design polish + the Soft look): src/Polish190qwShot.inc
  4360. if (args.contains ("--polish190qwshot"))
  4361. {
  4362. const auto i = args.indexOf ("--polish190qwshot");
  4363. setApplicationReturnValue (runPolish190qwShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  4364. quit();
  4365. return;
  4366. }
  4367. // --design190ooshot <prefix> [project] (round 190oo, design review 2): src/Design190ooShot.inc
  4368. if (args.contains ("--design190ooshot"))
  4369. {
  4370. const auto i = args.indexOf ("--design190ooshot");
  4371. setApplicationReturnValue (runDesign190ooShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  4372. quit();
  4373. return;
  4374. }
  4375. // --rollup031s3shot <prefix> (rollup 0.1.31 step 3, round 190ny): src/Rollup031S3Shot.inc
  4376. if (args.contains ("--rollup031s3shot"))
  4377. {
  4378. setApplicationReturnValue (runRollup031S3Shot (args[args.indexOf ("--rollup031s3shot") + 1].unquoted()) ? 0 : 1);
  4379. quit();
  4380. return;
  4381. }
  4382. // --tabs2test190nz <a|b> <folder> (round 190nz, issue #232 stage 2: copy and paste between two LYNX windows):
  4383. // src/Tabs2Test190nz.inc
  4384. if (args.contains ("--tabs2test190nz"))
  4385. {
  4386. const auto i = args.indexOf ("--tabs2test190nz");
  4387. setApplicationReturnValue (runTabs2Test190nz (args[i + 1].unquoted(), juce::File (args[i + 2].unquoted())) ? 0 : 1);
  4388. quit();
  4389. return;
  4390. }
  4391. // --headergearshot248 <prefix> (rollup 0.1.31 step 7, PRs #248 / #256): src/HeaderGearShot248.inc
  4392. if (args.contains ("--headergearshot248"))
  4393. {
  4394. setApplicationReturnValue (runHeaderGearShot (args[args.indexOf ("--headergearshot248") + 1].unquoted()) ? 0 : 1);
  4395. quit();
  4396. return;
  4397. }
  4398. // --hotfix190qpwfshot <prefix> (round 190qp, 0.1.31.1 hotfix): src/Hotfix190qpWf.inc, its checks and pictures
  4399. if (args.contains ("--hotfix190qpwfshot"))
  4400. {
  4401. const auto prefix = args[args.indexOf ("--hotfix190qpwfshot") + 1].unquoted();
  4402. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4403. const auto r = hotfix190qpWfCheck (prefix);
  4404. juce::File (prefix + "-checks.txt").replaceWithText ("hotfix190qp_wf=" + r + "\n");
  4405. setApplicationReturnValue (r == "OK" ? 0 : 1);
  4406. quit();
  4407. return;
  4408. }
  4409. // --pickerpaint190qi <report> (round 190qi): the plugin lists' and the Browser's paint cost, src/PickerPaintBench190qi.inc
  4410. if (args.contains ("--pickerpaint190qi"))
  4411. {
  4412. runPickerPaint190qi (juce::File (args[args.indexOf ("--pickerpaint190qi") + 1].unquoted()));
  4413. setApplicationReturnValue (0);
  4414. quit();
  4415. return;
  4416. }
  4417. // --picker190qishot <folder> (round 190qi, picker and Browser quality of life): src/Picker190qiShot.inc
  4418. if (args.contains ("--picker190qishot"))
  4419. {
  4420. setApplicationReturnValue (runPicker190qiShot (juce::File (args[args.indexOf ("--picker190qishot") + 1].unquoted())) ? 0 : 1);
  4421. quit();
  4422. return;
  4423. }
  4424. // --issuesshot190qo <prefix> (round 190qo, issues #239, #215, #251, #270): src/IssuesShot190qo.inc
  4425. if (args.contains ("--issuesshot190qo"))
  4426. {
  4427. setApplicationReturnValue (runIssuesShot190qo (args[args.indexOf ("--issuesshot190qo") + 1].unquoted()) ? 0 : 1);
  4428. quit();
  4429. return;
  4430. }
  4431. // --issuesshot190qb <prefix> (round 190qb, follow-ups of issues #206 and #215): src/IssuesShot190qb.inc
  4432. if (args.contains ("--issuesshot190qb"))
  4433. {
  4434. setApplicationReturnValue (runIssuesShot190qb (args[args.indexOf ("--issuesshot190qb") + 1].unquoted()) ? 0 : 1);
  4435. quit();
  4436. return;
  4437. }
  4438. // --issuesshot190oq <prefix> (round 190oq, issues #243-#252): src/IssuesShot190oq.inc
  4439. if (args.contains ("--issuesshot190oq"))
  4440. {
  4441. setApplicationReturnValue (runIssuesShot190oq (args[args.indexOf ("--issuesshot190oq") + 1].unquoted()) ? 0 : 1);
  4442. quit();
  4443. return;
  4444. }
  4445. // --issuesshot190od <prefix> (round 190od, issues #236-#242): src/IssuesShot190od.inc
  4446. if (args.contains ("--issuesshot190od"))
  4447. {
  4448. setApplicationReturnValue (runIssuesShot190od (args[args.indexOf ("--issuesshot190od") + 1].unquoted()) ? 0 : 1);
  4449. quit();
  4450. return;
  4451. }
  4452. // --issuesshot190ns <prefix> (round 190ns, issues #231-#235): src/IssuesShot190ns.inc
  4453. if (args.contains ("--issuesshot190ns"))
  4454. {
  4455. setApplicationReturnValue (runIssuesShot190ns (args[args.indexOf ("--issuesshot190ns") + 1].unquoted()) ? 0 : 1);
  4456. quit();
  4457. return;
  4458. }
  4459. // --issuesshot190ng <prefix> (round 190ng, issues #215, #217, #219, #220, #222): src/IssuesShot190ng.inc
  4460. if (args.contains ("--issuesshot190ng"))
  4461. {
  4462. setApplicationReturnValue (runIssuesShot190ng (args[args.indexOf ("--issuesshot190ng") + 1].unquoted()) ? 0 : 1);
  4463. quit();
  4464. return;
  4465. }
  4466. // --tracker190nwshot <prefix> [module] (round 190nw, 0.1.31: the built-in tracker): src/TrackerShot190nw.inc
  4467. if (args.contains ("--tracker190nwshot"))
  4468. {
  4469. const auto i = args.indexOf ("--tracker190nwshot");
  4470. setApplicationReturnValue (runTrackerShot190nw (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  4471. quit();
  4472. return;
  4473. }
  4474. // --automodes190pashot <prefix> (round 190pa, 0.1.32: automation write modes, range edits on chosen tracks): src/AutoModesShot190pa.inc
  4475. if (args.contains ("--automodes190pashot"))
  4476. {
  4477. setApplicationReturnValue (runAutoModesShot190pa (args[args.indexOf ("--automodes190pashot") + 1].unquoted()) ? 0 : 1);
  4478. quit();
  4479. return;
  4480. }
  4481. // --trackstates190opshot <prefix> (round 190op, 0.1.31: Hide / Deactivate tracks, Capture automation): src/TrackStatesShot190op.inc
  4482. // --tracks190peshot <prefix> (round 190pe, 0.1.32: Track versions, Import tracks from another project): src/Tracks190peShot.inc
  4483. if (args.contains ("--tracks190peshot"))
  4484. {
  4485. setApplicationReturnValue (runTracks190peShot (args[args.indexOf ("--tracks190peshot") + 1].unquoted()) ? 0 : 1);
  4486. quit();
  4487. return;
  4488. }
  4489. if (args.contains ("--trackstates190opshot"))
  4490. {
  4491. setApplicationReturnValue (runTrackStatesShot190op (args[args.indexOf ("--trackstates190opshot") + 1].unquoted()) ? 0 : 1);
  4492. quit();
  4493. return;
  4494. }
  4495. // --trackclips190neshot <prefix> (round 190ne, 0.1.31: track clips): src/TrackClipsShot190ne.inc
  4496. if (args.contains ("--trackclips190neshot"))
  4497. {
  4498. setApplicationReturnValue (runTrackClipsShot190ne (args[args.indexOf ("--trackclips190neshot") + 1].unquoted()) ? 0 : 1);
  4499. quit();
  4500. return;
  4501. }
  4502. // --issueshot190mq <prefix> (round 190mq, issues #211, #212, #213): src/IssuesShot190mq.inc
  4503. if (args.contains ("--issueshot190mq"))
  4504. {
  4505. setApplicationReturnValue (runIssuesShot190mq (args[args.indexOf ("--issueshot190mq") + 1].unquoted()) ? 0 : 1);
  4506. quit();
  4507. return;
  4508. }
  4509. // --issueshot190lw <prefix> (round 190lw, issues #205, #206, #207): src/IssuesShot190lw.inc
  4510. if (args.contains ("--issueshot190lw"))
  4511. {
  4512. setApplicationReturnValue (runIssuesShot190lw (args[args.indexOf ("--issueshot190lw") + 1].unquoted()) ? 0 : 1);
  4513. quit();
  4514. return;
  4515. }
  4516. // --audioedit190stshot <prefix> <project.lynx> [pixelsPerBar] [trackHeight] (round 190st): src/AudioEdit190stShot.inc
  4517. if (args.contains ("--audioedit190stshot"))
  4518. {
  4519. const auto i = args.indexOf ("--audioedit190stshot");
  4520. const auto bar = args.size() > i + 3 ? args[i + 3].getDoubleValue() : 0.0;
  4521. const auto height = args.size() > i + 4 ? args[i + 4].getIntValue() : 0;
  4522. setApplicationReturnValue (runAudioEdit190stShot (args[i + 1].unquoted(), juce::File (args[i + 2].unquoted()), bar > 0.0 ? bar : 280.0,
  4523. height > 0 ? height : 90) ? 0 : 1);
  4524. quit();
  4525. return;
  4526. }
  4527. // --issueshot190jz <prefix> (round 190jz, issues #192, #194, #195): src/IssuesShot190jz.inc
  4528. if (args.contains ("--issueshot190jz"))
  4529. {
  4530. setApplicationReturnValue (runIssuesShot190jz (args[args.indexOf ("--issueshot190jz") + 1].unquoted()) ? 0 : 1);
  4531. quit();
  4532. return;
  4533. }
  4534. // --workflowshot190iu <prefix> (round 190iu, issues #186 and #191): src/WorkflowShot190iu.inc
  4535. if (args.contains ("--workflowshot190iu"))
  4536. {
  4537. setApplicationReturnValue (runWorkflowShot190iu (args[args.indexOf ("--workflowshot190iu") + 1].unquoted()) ? 0 : 1);
  4538. quit();
  4539. return;
  4540. }
  4541. // --trackautoshot190gz <prefix> (round 190gz, issue #170): LYNX's "Link Playlist tracks to mixer tracks" — the
  4542. // switch, the linked headers' M / S / volume / pan driven with synthetic mouse events, row sizes, undo and the
  4543. // .lynx round trip, offscreen; prefix-checks.txt
  4544. if (args.contains ("--trackautoshot190gz"))
  4545. {
  4546. setApplicationReturnValue (runTrackAutoShot190gz (args[args.indexOf ("--trackautoshot190gz") + 1].unquoted()) ? 0 : 1);
  4547. quit();
  4548. return;
  4549. }
  4550. if (args.contains ("--flplshot"))
  4551. {
  4552. setApplicationReturnValue (runFlPlShot (args[args.indexOf ("--flplshot") + 1].unquoted()) ? 0 : 1);
  4553. quit();
  4554. return;
  4555. }
  4556. // --genpresetshot <prefix> (round 190fs): the channel window's preset box with the user's own presets (Save
  4557. // preset..., Your presets, Delete preset, Show the presets folder) for Fruity DX10, 3x Osc and LYNX's synth, the
  4558. // name box, a load (one undo step) and the Browser's new channel, offscreen; prefix-checks.txt holds the checks
  4559. if (args.contains ("--genpresetshot"))
  4560. {
  4561. setApplicationReturnValue (runGenPresetShot (args[args.indexOf ("--genpresetshot") + 1].unquoted()) ? 0 : 1);
  4562. quit();
  4563. return;
  4564. }
  4565. // --flfixshot <prefix> (round 190ey): what the live FL session 190ew found different (the Sampler page, the
  4566. // Multilink menu, the Playlist, issue #152's question), offscreen; prefix-checks.txt holds the checks
  4567. if (args.contains ("--flfixshot"))
  4568. {
  4569. setApplicationReturnValue (runFlFixShot (args[args.indexOf ("--flfixshot") + 1].unquoted()) ? 0 : 1);
  4570. quit();
  4571. return;
  4572. }
  4573. // --flclipshot <prefix> (round 190dz): FL's audio clip menu layout (two columns, FL's sections, LYNX's own items at
  4574. // the end) and the channel's Misc › Levels adjustment, offscreen; prefix-checks.txt holds the checks
  4575. if (args.contains ("--flclipshot"))
  4576. {
  4577. setApplicationReturnValue (runFlClipShot (args[args.indexOf ("--flclipshot") + 1].unquoted()) ? 0 : 1);
  4578. quit();
  4579. return;
  4580. }
  4581. if (args.contains ("--warpshot"))
  4582. {
  4583. // LYNX.exe --warpshot prefix: round 190cg's pictures (warp commands in the audio editor, the Clip page's
  4584. // Audio panel, the arrangement with the loop switched off, a folded track, signature changes), off-screen
  4585. const auto i = args.indexOf ("--warpshot");
  4586. runWarpShot (args[i + 1].unquoted());
  4587. quit();
  4588. return;
  4589. }
  4590. // --bandlab190jrshot <prefix> (round 190jr): a .blx imported as Simple tracks, the region loop handle, the Simple
  4591. // automation view and its menu, the Extract stems form; <prefix>-report.txt with ok / FAIL lines
  4592. if (args.contains ("--bandlab190jrshot"))
  4593. {
  4594. runBandlab190jrShot (args[args.indexOf ("--bandlab190jrshot") + 1].unquoted());
  4595. quit();
  4596. return;
  4597. }
  4598. // --bandlabshot <prefix> (round 190ch): Lyrics / Notes, Reference match, Start from and Clean voice, offscreen
  4599. if (args.contains ("--notes190tjshot"))
  4600. {
  4601. // LYNX --notes190tjshot <prefix> (round 190tj, issue #358): the Notes window's pictures (src/Notes190tjCheck.inc)
  4602. runNotes190tjShot (args[args.indexOf ("--notes190tjshot") + 1].unquoted());
  4603. quit();
  4604. return;
  4605. }
  4606. if (args.contains ("--bandlabshot"))
  4607. {
  4608. runBandlabShot (args[args.indexOf ("--bandlabshot") + 1].unquoted());
  4609. quit();
  4610. return;
  4611. }
  4612. if (args.contains ("--mpeshot190hy"))
  4613. {
  4614. // LYNX --mpeshot190hy prefix: round 190hy (issue #108, MPE stage 2) off-screen: the Piano roll's MPE lanes (pitch
  4615. // bend, slide, pressure) over notes with curves in Pattern workflow, then the Clip-launch layout's Clip page with
  4616. // its Notes and MPE tabs. Writes prefix-checks.txt.
  4617. runMpeShot190hy (args[args.indexOf ("--mpeshot190hy") + 1].unquoted());
  4618. quit();
  4619. return;
  4620. }
  4621. if (args.contains ("--detailshot"))
  4622. {
  4623. // LYNX.exe --detailshot prefix: the Clip-launch workflow's detail view off-screen (round 183a): a track's chain
  4624. // (instrument, effects, one off, one folded), its clip page, and Pattern workflow before / after, at
  4625. // LYNX_SNAPSHOT_SIZE. Writes prefix-counts.txt with what the chain shows.
  4626. const auto i = args.indexOf ("--detailshot");
  4627. runDetailShot (args[i + 1].unquoted());
  4628. quit();
  4629. return;
  4630. }
  4631. if (args.contains ("--meldshot190ko"))
  4632. {
  4633. // LYNX.exe --meldshot190ko prefix meld.adv spectraltime.adv spectralresonator.adv: round 190ko off-screen, in the
  4634. // Clip-launch layout: a track whose instrument is what a Live Meld preset imports onto (Braid) and whose insert
  4635. // holds what Spectral Time and Spectral Resonator presets import onto (Timeprism, Harmonia), on the Device View.
  4636. // Writes prefix-devices.png and prefix-checks.txt.
  4637. const auto i = args.indexOf ("--meldshot190ko");
  4638. runMeldShot190ko (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].unquoted(), args[i + 4].unquoted());
  4639. quit();
  4640. return;
  4641. }
  4642. if (args.contains ("--livedevshot190kk"))
  4643. {
  4644. // LYNX.exe --livedevshot190kk prefix: round 190kk off-screen, in the Clip-launch layout: a track whose insert holds
  4645. // what Live's Erosion, Vinyl Distortion and Corpus (Core Library presets) import onto — Corrode, Platter,
  4646. // Soundboard — on the Device View as ordinary effect cards. Writes prefix-devices.png and prefix-checks.txt.
  4647. runLiveDevShot190kk (args[args.indexOf ("--livedevshot190kk") + 1].unquoted());
  4648. quit();
  4649. return;
  4650. }
  4651. if (args.contains ("--liverackshot190hr"))
  4652. {
  4653. // LYNX.exe --liverackshot190hr prefix: round 190hr off-screen, in the Ableton-style layout: the Device View's
  4654. // instrument menu with Group / Ungroup, an instrument grouped into an Instrument Rack and back, a rack's Save
  4655. // Preset button and drop area (a device dropped in, an instrument refused), Live's own .adg presets opened
  4656. // with their chains, and a saved .adg read back. Writes prefix-checks.txt.
  4657. runLiveRackShot190hr (args[args.indexOf ("--liverackshot190hr") + 1].unquoted());
  4658. quit();
  4659. return;
  4660. }
  4661. if (args.contains ("--helixshot190mi"))
  4662. {
  4663. // LYNX --helixshot190mi prefix [bank preset name]: round 190mi off-screen, the Pattern layout's Helix channel
  4664. // window with Helix+'s strip, from a factory preset (default "Growl FM"): the device + strip, LFO 1 (drawn),
  4665. // the Matrix page (macros, Helix+'s rows); --shot-scale 1.5 --shot-suffix @150 for the 150 % pictures.
  4666. const auto i = args.indexOf ("--helixshot190mi");
  4667. runHelixShot190mi (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("Growl FM"));
  4668. quit();
  4669. return;
  4670. }
  4671. if (args.contains ("--helixshot190oc"))
  4672. {
  4673. // LYNX --helixshot190oc prefix: round 190oc off-screen: the Pattern layout's Helix channel window with round 4's
  4674. // row (Grain Swarm, Spectral Ensemble; Frozen Choir and Triple Stack for the side by side with 190mt), the strip's
  4675. // row alone; paint costs in prefix-checks.txt
  4676. runHelixShot190oc (args[args.indexOf ("--helixshot190oc") + 1].unquoted());
  4677. quit();
  4678. return;
  4679. }
  4680. if (args.contains ("--helixshot190mt"))
  4681. {
  4682. // LYNX --helixshot190mt prefix: round 190mt off-screen: the Pattern layout's Helix channel window with round 3's
  4683. // row (Grain Cloud, Frozen Choir, Spectral Glass; Triple Stack for the side by side with 190ml), the Matrix page with
  4684. // the new rows, and the Clip-launch Device View card's Helix+ panel; paint costs in prefix-checks.txt.
  4685. runHelixShot190mt (args[args.indexOf ("--helixshot190mt") + 1].unquoted());
  4686. quit();
  4687. return;
  4688. }
  4689. if (args.contains ("--helixshot190ml"))
  4690. {
  4691. // LYNX --helixshot190ml prefix: round 190ml off-screen: the Pattern layout's Helix channel window with Helix+ 2's
  4692. // rows (Triple Stack, Vowel Sync), the Matrix page's Macros tab, the table editor (Draw, Harmonics) and the
  4693. // Clip-launch Device View card without / with its Helix+ panel; paint costs in prefix-checks.txt.
  4694. runHelixShot190ml (args[args.indexOf ("--helixshot190ml") + 1].unquoted());
  4695. quit();
  4696. return;
  4697. }
  4698. if (args.contains ("--helixshot190ja"))
  4699. {
  4700. // LYNX --helixshot190ja prefix [Wavetable preset .adv]: round 190ja off-screen, the Clip-launch layout's Device
  4701. // View with a Helix track (the preset's values imported as a Live set would bring them, else Helix's defaults):
  4702. // the device and its pages (Matrix, MIDI, MPE, Env 2, LFO 1, Osc 2), then the Pattern layout's channel window.
  4703. const auto i = args.indexOf ("--helixshot190ja");
  4704. runHelixShot190ja (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String());
  4705. quit();
  4706. return;
  4707. }
  4708. if (args.contains ("--liveshot190ce"))
  4709. {
  4710. // LYNX.exe --liveshot190ce prefix: round 190ce off-screen, in the Ableton-style layout: the Device View's cards
  4711. // with their hot-swap and save buttons, a device's menu, hot-swap on (the Browser's bar, the lit button), a
  4712. // swap and its undo, a duplicate, and the Browser's collections (STARRED tab, the Collections menu, a search
  4713. // by a collection's name). Writes prefix-checks.txt.
  4714. runLiveShot190ce (args[args.indexOf ("--liveshot190ce") + 1].unquoted());
  4715. quit();
  4716. return;
  4717. }
  4718. if (args.contains ("--missingsearchshot190eo"))
  4719. {
  4720. // LYNX --missingsearchshot190eo prefix folder...: round 190eo (integration of issue #159's fix) off-screen: the
  4721. // Missing files window's Samples page while a real search of the folders runs (matches streamed in, Stop
  4722. // shown, Apply usable). Writes prefix-searching.png and prefix-checks.txt; the search is let go at the end.
  4723. const auto i = args.indexOf ("--missingsearchshot190eo");
  4724. const auto prefix = args[i + 1].unquoted();
  4725. juce::StringArray folders;
  4726. for (int k = i + 2; k < args.size(); ++k)
  4727. folders.add (args[k].unquoted());
  4728. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4729. std::shared_ptr<juce::Component> panel = lynx::makeMissingFilesPanelSearching (lynx::missingFilesSnapshotInfo(), folders);
  4730. juce::Timer::callAfterDelay (700, [this, panel, prefix] {
  4731. juce::String status;
  4732. bool stopShown = false, applyEnabled = false;
  4733. const auto searching = lynx::missingFilesSearchState (*panel, status, stopShown, applyEnabled);
  4734. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  4735. const auto file = juce::File (prefix + "-searching.png");
  4736. file.deleteFile();
  4737. if (auto out = file.createOutputStream())
  4738. juce::PNGImageFormat().writeImageToStream (image, *out);
  4739. juce::String checks;
  4740. auto check = [&checks] (const char* name, bool ok, const juce::String& detail) {
  4741. checks << name << "=" << (ok ? "OK" : "FAIL") << " " << detail << "\n";
  4742. };
  4743. check ("still_searching_at_the_shot", searching, {});
  4744. check ("status_shows_the_walk", status.contains (lynx::tr ("Searching {0}... {1} files looked at").upToFirstOccurrenceOf ("{0}", false, false)), status);
  4745. check ("stop_shown", stopShown, {});
  4746. check ("apply_usable_during_the_search", applyEnabled, {});
  4747. lynx::stopMissingFilesSearch (*panel);
  4748. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  4749. quit();
  4750. });
  4751. return;
  4752. }
  4753. // --grooveshot190fm <prefix> (round 190fm): a Playlist pattern clip's menu with its Groove items (the chooser, Commit,
  4754. // Extract) and the "Classic swing" folder, and a Groove Pool holding classic swing grooves, offscreen;
  4755. // prefix-checks.txt holds the checks (also the .lynx round trip of a Playlist clip's groove)
  4756. if (args.contains ("--grooveshot190fm"))
  4757. {
  4758. setApplicationReturnValue (runGrooveShot190fm (args[args.indexOf ("--grooveshot190fm") + 1].unquoted()) ? 0 : 1);
  4759. quit();
  4760. return;
  4761. }
  4762. if (args.contains ("--mtshot190fm"))
  4763. {
  4764. // LYNX --mtshot190fm prefix: round 190fm off-screen: the MIDI Tools panel's Generate tab with each generator
  4765. // (prefix-generate-rhythm.png … -euclidean.png), the five side by side as Live's picture shows them
  4766. // (prefix-generate-panels.png; Live's: ableton190o/shots/live-04-generate-panels.png), then each generator
  4767. // written into a one-bar pattern and undone again: prefix-checks.txt.
  4768. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4769. runMtShot190fm (args[args.indexOf ("--mtshot190fm") + 1].unquoted());
  4770. quit();
  4771. return;
  4772. }
  4773. if (args.contains ("--drumshot190ec"))
  4774. {
  4775. // LYNX.exe --drumshot190ec prefix: round 190ec off-screen: a demo Drum Rack's pad view (default and scrolled), its
  4776. // chain list with I-O, sends and return chains, a new empty Drum Rack and the Piano roll's pad names. Writes
  4777. // prefix-checks.txt (hit tests: C1 bottom-left, overview scroll, a pad dragged onto another swaps them).
  4778. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4779. lynx::drumshot::run (args[args.indexOf ("--drumshot190ec") + 1].unquoted());
  4780. quit();
  4781. return;
  4782. }
  4783. if (args.contains ("--linkshot190gl"))
  4784. {
  4785. // LYNX --linkshot190gl prefix (round 190gl): Ableton Link off-screen with a second Link peer in this process —
  4786. // the toolbar in FL's Pattern layout (hidden by default, then shown, off and on) and in the Clip-launch layout
  4787. // ("1 Link", the position display's progress bar, Play waiting), Settings › Ableton Link, the toggle's
  4788. // drop-down and the Options menu. Writes prefix-checks.txt.
  4789. runLinkShot190gl (args[args.indexOf ("--linkshot190gl") + 1].unquoted());
  4790. quit();
  4791. return;
  4792. }
  4793. if (args.contains ("--communityshot190hp"))
  4794. {
  4795. // LYNX --communityshot190hp prefix (round 190hp): global MIDI mappings, Mix snapshots and Split at silence
  4796. // off-screen; writes prefix-checks.txt
  4797. runCommunityShot190hp (args[args.indexOf ("--communityshot190hp") + 1].unquoted());
  4798. quit();
  4799. return;
  4800. }
  4801. if (args.contains ("--mapshot190ef"))
  4802. {
  4803. // LYNX.exe --mapshot190ef prefix: round 190ef's map modes off-screen, in the Clip-launch workflow: MIDI Map Mode
  4804. // (the overlay over the grid, the Session mixer, the Device View and the transport; the Mapping Browser with
  4805. // Min / Max), Key Map Mode, the row menu, the title bar's Draw / Key / MIDI switches, Ctrl+M / Ctrl+K and the
  4806. // Pattern layout keeping Ctrl+M. Writes prefix-checks.txt.
  4807. runMapShot190ef (args[args.indexOf ("--mapshot190ef") + 1].unquoted());
  4808. quit();
  4809. return;
  4810. }
  4811. if (args.contains ("--sceneshot190ef"))
  4812. {
  4813. // LYNX.exe --sceneshot190ef prefix: round 190ef's scene work off-screen, in the Clip-launch workflow: the scene
  4814. // column with its tempo / time signature fields, the scene menu, a scene field's menu, the column title's menu
  4815. // (Rename, colours), a duplicated scene and a captured scene. Writes prefix-checks.txt.
  4816. runSceneShot190ef (args[args.indexOf ("--sceneshot190ef") + 1].unquoted());
  4817. quit();
  4818. return;
  4819. }
  4820. if (args.contains ("--drawshot190ef"))
  4821. {
  4822. // LYNX.exe --drawshot190ef prefix: round 190ef off-screen, in the Clip-launch workflow: Draw Mode in an
  4823. // automation lane, steps at the grid width and an Alt (no grid) freehand stroke drawn through the Playlist's
  4824. // own mouse handlers, and the Options menu with "Draw Mode". Writes prefix-checks.txt.
  4825. runDrawShot190ef (args[args.indexOf ("--drawshot190ef") + 1].unquoted());
  4826. quit();
  4827. return;
  4828. }
  4829. if (args.contains ("--clipenvshot190gi"))
  4830. {
  4831. // LYNX.exe --clipenvshot190gi prefix: round 190gi off-screen: audio clip envelopes on the Playlist (volume and
  4832. // pan lanes, edited through the Playlist's own mouse handlers), the clip menu's LYNX extras (Clip envelope ›,
  4833. // Auto-warp, Quantize audio, run from the menu), warp flags added on the flag strip and moved with Alt + drag,
  4834. // and the Clip-launch Clip View's Envelopes tab (Clip › Gain, Mixer › Track Panning). Writes prefix-checks.txt.
  4835. runClipEnvShot190gi (args[args.indexOf ("--clipenvshot190gi") + 1].unquoted());
  4836. quit();
  4837. return;
  4838. }
  4839. if (args.contains ("--gapsshot190kf"))
  4840. {
  4841. // LYNX.exe --gapsshot190kf prefix [file.wav]: round gaps190kf off-screen: the Clip View's warp time line (Live's
  4842. // loop brace and Start / End markers under the beat-time ruler, the seconds ruler of an unwarped clip) on the
  4843. // probe of gaps190kf/live/cv-clipview.als (voice.wav, warp markers at 30 % / 55 %, Loop 1.3 … 3.3, Start 1.4).
  4844. const auto i = args.indexOf ("--gapsshot190kf");
  4845. runGapsShot190kf (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  4846. quit();
  4847. return;
  4848. }
  4849. if (args.contains ("--livefactsshot190gx"))
  4850. {
  4851. // LYNX.exe --livefactsshot190gx prefix: round 190gx off-screen: the Clip page's Audio panel in Live's 190gu
  4852. // layout (Beats: Preserve label + chooser, the loop-mode icon chooser beside the Transient Envelope box;
  4853. // Tones / Texture: Grain Size [+ Flux]; Complex [Pro]), the Envelopes tab with a Clip Gain staircase on Live's
  4854. // axis, choosers at the bottom left, and an unwarped clip without the Envelopes tab. Writes prefix-checks.txt.
  4855. runLiveFactsShot190gx (args[args.indexOf ("--livefactsshot190gx") + 1].unquoted());
  4856. quit();
  4857. return;
  4858. }
  4859. if (args.contains ("--dvshot190hr"))
  4860. {
  4861. // LYNX.exe --dvshot190hr prefix: round 190hr off-screen, the Clip-launch Clip View: a MIDI clip whose Start
  4862. // marker sits inside its loop, with its own scale and a follow action (Launch panel controls), the docked
  4863. // editor's grid value and menu, Ctrl+1 / Ctrl+3 / Ctrl+U on it, the Quantize Settings panel, and an audio clip
  4864. // transposed past ±12. Writes prefix-checks.txt.
  4865. runDvShot190hr (args[args.indexOf ("--dvshot190hr") + 1].unquoted());
  4866. quit();
  4867. return;
  4868. }
  4869. if (args.contains ("--warpshot190fm"))
  4870. {
  4871. // LYNX.exe --warpshot190fm prefix: round 190fm off-screen: the Clip page's Audio panel of a grid audio clip in
  4872. // Beats (Preserve, Transient Loop Mode, Envelope), Tones and Texture (Grain Size), Complex (none), and the clip
  4873. // made unique by a mode change while another clip shares its channel (O16). Writes prefix-checks.txt.
  4874. runWarpShot190fm (args[args.indexOf ("--warpshot190fm") + 1].unquoted());
  4875. quit();
  4876. return;
  4877. }
  4878. if (args.contains ("--liveshot190dr"))
  4879. {
  4880. // LYNX.exe --liveshot190dr prefix: round 190dr off-screen, in the Clip-launch workflow: the Session mixer
  4881. // under the clip grid (default sections, Track Options, Volume only, hidden, its View menu), the Clip page's
  4882. // Sample panel of an audio clip (Warp on / off, the Set buttons while it plays, the sample's title) and a
  4883. // device dragged from one track's Device View to another track. Writes prefix-checks.txt.
  4884. runLiveShot190dr (args[args.indexOf ("--liveshot190dr") + 1].unquoted());
  4885. quit();
  4886. return;
  4887. }
  4888. if (args.contains ("--modshot190ox"))
  4889. {
  4890. // LYNX.exe --modshot190ox prefix [--shot-scale 1.5 --shot-suffix @150] (round 190ox, modulators stage 2): the
  4891. // Modulators window, rings on knobs, the Modulate with menu; checks in prefix-checks.txt
  4892. runModShot190ox (args[args.indexOf ("--modshot190ox") + 1].unquoted());
  4893. quit();
  4894. return;
  4895. }
  4896. if (args.contains ("--gapshot190og"))
  4897. {
  4898. // LYNX.exe --gapshot190og prefix [--shot-scale 1.5 --shot-suffix @150] (round gap190og, coverage rows still open on
  4899. // 0.1.31): in the Clip-launch layout, the Edit menu's Live block on the Device View (deviceview-0012), the Clip
  4900. // panel's Duplicate (Loop) button (detail-019), the clip menu's Crop Clip and Ctrl+Shift+J (detail-020), the
  4901. // Velocity lane's Randomize footer (detail-047), Key Map Mode on the transport switches (mapping-0028);
  4902. // checks in prefix-checks.txt
  4903. runGapShot190og (args[args.indexOf ("--gapshot190og") + 1].unquoted());
  4904. quit();
  4905. return;
  4906. }
  4907. if (args.contains ("--undoshot190mz"))
  4908. {
  4909. // LYNX.exe --undoshot190mz prefix [--shot-scale 1.5 --shot-suffix @150] (round 190mz, issue #214): the main
  4910. // window's undo keys with three edits, in both "Alternate undo mode" settings, and the Edit menu after each
  4911. // step in the Pattern, Clip-launch and Simple layouts (prefix-menu-*.png); checks in prefix-checks.txt
  4912. runUndoShot190mz (args[args.indexOf ("--undoshot190mz") + 1].unquoted());
  4913. quit();
  4914. return;
  4915. }
  4916. if (args.contains ("--design190igs4shot"))
  4917. {
  4918. // LYNX.exe --design190igs4shot prefix [set.als]: round 190ig slice 4 off-screen, in the Clip-launch layout with the
  4919. // set imported there (Live's colours, CL-6): the Session grid in Live's look idle, then the launch states —
  4920. // playing, a launch waiting (both blink phases), a stop waiting, recording, the status pie at 25 / 50 / 75 % —
  4921. // and the same with Animations off, then round 181a's look (the option); prefix-checks.txt
  4922. const auto i = args.indexOf ("--design190igs4shot");
  4923. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  4924. runDesign190igS4Shot (args[i + 1].unquoted(), project);
  4925. quit();
  4926. return;
  4927. }
  4928. if (args.contains ("--typeaheadtest"))
  4929. {
  4930. // LYNX.exe --typeaheadtest out.txt: issue #64 — a real popup menu (headings, a submenu) driven by key presses
  4931. // through its window's peer, as the OS delivers them; writes what got the highlight and what was picked
  4932. const auto i = args.indexOf ("--typeaheadtest");
  4933. runTypeAheadTest (juce::File (args[i + 1].unquoted()));
  4934. return;
  4935. }
  4936. if (args.contains ("--choosertest"))
  4937. {
  4938. // LYNX --choosertest out.txt file: issue #72 — opens LYNX's file chooser as the UI does (makeFileChooser +
  4939. // launchChooser) and reports which dialog came up and what reached the callback. A built-in dialog is shot
  4940. // (out.txt.png), `file` typed into it and confirmed; a native one (zenity / kdialog) is left to answer.
  4941. const auto i = args.indexOf ("--choosertest");
  4942. runChooserTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  4943. return;
  4944. }
  4945. if (args.contains ("--stabilityshot"))
  4946. {
  4947. // LYNX --stabilityshot <folder> (round 190gg): offscreen PNGs of the crash prompt, the plugin window's crash
  4948. // notice, the Plugin manager's "Separate process" column and the monitor's dropout line (no window opens)
  4949. const auto i = args.indexOf ("--stabilityshot");
  4950. runStabilityShot (args[i + 1].unquoted());
  4951. return;
  4952. }
  4953. if (args.contains ("--repeats190pmshot"))
  4954. {
  4955. // LYNX --repeats190pmshot <folder> (round 190pm, research190oe P19 / P23): Note Repeats and Conditions, Touch mode
  4956. setApplicationReturnValue (runRepeatsShot190pm (args[args.indexOf ("--repeats190pmshot") + 1].unquoted()) ? 0 : 1);
  4957. quit();
  4958. return;
  4959. }
  4960. if (args.contains ("--discord190qushot"))
  4961. {
  4962. // LYNX --discord190qushot <folder> [lanes.flp] (round 190qu, Discord 11-24): keys, Clip View, lanes, Simple, Track-only
  4963. const auto i = args.indexOf ("--discord190qushot");
  4964. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  4965. setApplicationReturnValue (runDiscordShot190qu (args[i + 1].unquoted(), project) ? 0 : 1);
  4966. quit();
  4967. return;
  4968. }
  4969. if (args.contains ("--simpleduck190otshot"))
  4970. {
  4971. // LYNX --simpleduck190otshot <folder> (round 190ot, research190oe P5): "Duck under..." and the Echo send at 100 / 150 %
  4972. setApplicationReturnValue (runSimpleDuckShot190ot (args[args.indexOf ("--simpleduck190otshot") + 1].unquoted()) ? 0 : 1);
  4973. quit();
  4974. return;
  4975. }
  4976. if (args.contains ("--smarttipshot190ok"))
  4977. {
  4978. // LYNX --smarttipshot190ok <folder> [project.flp] (round 190ok, D1): the smart-disable tip at 100 / 150 %
  4979. const auto i = args.indexOf ("--smarttipshot190ok");
  4980. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  4981. setApplicationReturnValue (runSmartTipShot190ok (args[i + 1].unquoted(), project) ? 0 : 1);
  4982. quit();
  4983. return;
  4984. }
  4985. if (args.contains ("--monitorshot190of"))
  4986. {
  4987. // LYNX --monitorshot190of <folder> (round 190of): the Plugin performance monitor with its sample numbers
  4988. // (Longest, Spikes) at 100 % and 150 %, off screen
  4989. const juce::File dir (args[args.indexOf ("--monitorshot190of") + 1].unquoted());
  4990. dir.createDirectory();
  4991. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4992. {
  4993. lynx::AudioEngine offline (false);
  4994. lynx::MainComponent ui (offline, false);
  4995. offline.dispatchPendingMessages();
  4996. for (const auto scale : { 1.0f, 1.5f })
  4997. {
  4998. auto panel = lynx::makePluginMonitorPanel (offline);
  4999. juce::Component frame;
  5000. frame.setSize (panel->getWidth(), panel->getHeight());
  5001. frame.setOpaque (true);
  5002. frame.addAndMakeVisible (*panel);
  5003. savePng (frame.createComponentSnapshot (frame.getLocalBounds(), true, scale),
  5004. dir.getChildFile (scale > 1.0f ? "plugin-monitor@150.png" : "plugin-monitor.png").getFullPathName());
  5005. }
  5006. }
  5007. setApplicationReturnValue (0);
  5008. quit();
  5009. return;
  5010. }
  5011. if (args.contains ("--jsfxshots"))
  5012. {
  5013. // LYNX --jsfxshots <folder> [--shot-scale 1.5 --shot-suffix @150] (round 190pj): the JSFX slider panels of
  5014. // bundled scripts, the Browser's JSFX category and Settings › File with the JSFX folders, off screen
  5015. const auto i = args.indexOf ("--jsfxshots");
  5016. runJsfxShots (args[i + 1].unquoted());
  5017. return;
  5018. }
  5019. if (args.contains ("--snapshot"))
  5020. {
  5021. const auto i = args.indexOf ("--snapshot");
  5022. runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
  5023. return;
  5024. }
  5025. if (args.contains ("--stemsplit"))
  5026. {
  5027. // LYNX.exe --stemsplit input.wav folder ["stems=111100 model=2 ..."]: the stem separation of the clip menu,
  5028. // without the window (round 190jr: the options as the settings file writes them; none = every stem, Standard)
  5029. const auto i = args.indexOf ("--stemsplit");
  5030. lynx::AudioEngine loader (false);
  5031. const auto options = i + 3 < args.size() && args[i + 3].unquoted().containsChar ('=') ? lynx::stemsplit::optionsFromText (args[i + 3].unquoted().toStdString())
  5032. : lynx::stemsplit::Options {};
  5033. const auto started = juce::Time::getMillisecondCounterHiRes();
  5034. const auto error = lynx::extractStemsToFolder (loader, juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), options);
  5035. std::fprintf (stderr, "stemsplit: %.0f ms\n", juce::Time::getMillisecondCounterHiRes() - started);
  5036. juce::File (args[i + 2].unquoted()).getSiblingFile ("stemsplit.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  5037. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  5038. quit();
  5039. return;
  5040. }
  5041. if (args.contains ("--audio2midi"))
  5042. {
  5043. // LYNX.exe --audio2midi input.wav melody|harmony|drums notes.csv: the clip menu's Convert to MIDI, without the
  5044. // window (round a2m189b's measurements)
  5045. // Round 190lj: mode "poly" = the "Convert to MIDI (polyphonic)" dialog's path, settings after the CSV as
  5046. // 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
  5047. // seconds spent resampling, in the model and making the notes.
  5048. const auto i = args.indexOf ("--audio2midi");
  5049. const auto mode = args[i + 2] == "drums" ? lynx::a2m::Mode::drums : args[i + 2] == "harmony" ? lynx::a2m::Mode::harmony : lynx::a2m::Mode::melody;
  5050. lynx::AudioEngine loader (false);
  5051. const juce::File csv (args[i + 3].unquoted());
  5052. juce::String error, timing;
  5053. if (args[i + 2] == "poly")
  5054. {
  5055. lynx::a2m::ConvertOptions options;
  5056. for (int k = i + 4; k < args.size() && args[k].containsChar ('='); ++k)
  5057. {
  5058. const auto key = args[k].upToFirstOccurrenceOf ("=", false, false);
  5059. const auto value = args[k].fromFirstOccurrenceOf ("=", false, false);
  5060. if (key == "poly") options.polyphonic = value.getIntValue() != 0;
  5061. else if (key == "note") options.noteSensitivity = value.getFloatValue();
  5062. else if (key == "split") options.splitSensitivity = value.getFloatValue();
  5063. else if (key == "minms") options.minNoteMs = value.getDoubleValue();
  5064. else if (key == "low") options.minKey = value.getIntValue();
  5065. else if (key == "high") options.maxKey = value.getIntValue();
  5066. else if (key == "bends") options.pitchBends = value.getIntValue() != 0;
  5067. }
  5068. error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), options, csv, &timing);
  5069. }
  5070. else
  5071. error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), mode, csv);
  5072. csv.getSiblingFile ("audio2midi.txt").replaceWithText (error.isEmpty() ? "result=OK\n" + (timing.isEmpty() ? juce::String() : "seconds=" + timing + "\n")
  5073. : "result=FAIL " + error + "\n");
  5074. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  5075. quit();
  5076. return;
  5077. }
  5078. if (args.contains ("--stems") || args.contains ("--stemexport"))
  5079. {
  5080. // LYNX.exe --stems project.(flp|als|lynx) base.wav [--separate]: one WAV per insert that has sound (like
  5081. // "Export stems"), in one render of the song (round 190gj; --separate: one render per insert, as before).
  5082. // LYNX.exe --stemexport project base.ext options.txt [--separate]: what the Export window writes with these
  5083. // options (exportopts::toText lines: stems, sections, the full mix, formats...), the same code.
  5084. // Both write <base>.txt: the files with their peaks, the renders, the wall and CPU time.
  5085. const auto full = args.contains ("--stemexport");
  5086. const auto i = args.indexOf (full ? "--stemexport" : "--stems");
  5087. const auto separate = args.contains ("--separate");
  5088. juce::String error, report;
  5089. int written = 0;
  5090. {
  5091. lynx::AudioEngine loader (false);
  5092. const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
  5093. // an .flp or a Live set (.als) opens through the import, as File › Open does (round 182b)
  5094. auto ok = input.hasFileExtension ("flp;als") ? loader.importFlpFile (input, error) : false;
  5095. if (! input.hasFileExtension ("flp;als"))
  5096. if (auto song = lynx::ProjectFile::load (input, error))
  5097. {
  5098. loader.setSong (std::move (*song));
  5099. ok = true;
  5100. }
  5101. const auto& song = loader.getSong();
  5102. lynx::StemPlan plan;
  5103. if (full && ok)
  5104. plan = lynx::planStemExport (song, lynx::exportopts::fromText (juce::File (args[i + 3].unquoted()).loadFileAsString().toStdString()), base);
  5105. else if (ok)
  5106. {
  5107. // every insert a channel goes to, as "<base> - <insert>.wav", 24-bit, 6 s of tail at most
  5108. lynx::ExportSettings settings;
  5109. plan.sets.push_back ({ song, settings.toOptions() });
  5110. for (int t = 1; t < (int) song.mixer.size(); ++t)
  5111. if (std::any_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  5112. plan.items.push_back ({ juce::String (t), base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav"), 0, t,
  5113. lynx::makeBounceSong (song, t), settings.toOptions() });
  5114. }
  5115. const auto wallStart = juce::Time::getMillisecondCounterHiRes();
  5116. const auto cpuStart = std::clock();
  5117. lynx::StemRunStats stats;
  5118. std::vector<juce::String> lines (plan.items.size());
  5119. auto previous = wallStart; // (one render per file: the time since the file before is its render's)
  5120. written = lynx::runStemExport (
  5121. plan, [] (std::function<void()> f) { f(); }, {}, {}, {},
  5122. [&] (std::size_t k, bool done, float peak) {
  5123. const auto now = juce::Time::getMillisecondCounterHiRes();
  5124. if (done)
  5125. lines[k] = plan.items[k].file.getFileName() + " peak=" + juce::String (peak) + " ms=" + juce::String (now - previous, 0) + "\n";
  5126. previous = now;
  5127. },
  5128. separate, full, &stats);
  5129. const auto wallMs = juce::Time::getMillisecondCounterHiRes() - wallStart;
  5130. const auto cpuMs = 1000.0 * (double) (std::clock() - cpuStart) / (double) CLOCKS_PER_SEC;
  5131. for (const auto& line : lines)
  5132. report << line;
  5133. report << "renders=" << (stats.passes + stats.alone) << " shared=" << stats.passes << " inshared=" << stats.inPass
  5134. << " alone=" << stats.alone << "\n";
  5135. for (const auto& why : stats.why)
  5136. report << "alone: " << why << "\n";
  5137. report << "wall_ms=" << juce::String (wallMs, 0) << " cpu_ms=" << juce::String (cpuMs, 0) << " make_ms=" << juce::String (stats.makeMs, 0)
  5138. << " render_ms=" << juce::String (stats.renderMs, 0) << "\n";
  5139. }
  5140. report << "stems=" << written << "\n";
  5141. juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
  5142. setApplicationReturnValue (written > 0 ? 0 : 1);
  5143. quit();
  5144. return;
  5145. }
  5146. // --export-als <in.lynx|.flp|.als> <folder> [--live11] [--reference] [--scan]: "<folder>/<name> Project/<name>.als" (round 175a)
  5147. if (args.contains ("--export-als"))
  5148. {
  5149. const auto i = args.indexOf ("--export-als");
  5150. runAlsExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--live11"), args.contains ("--reference"));
  5151. return;
  5152. }
  5153. // --export-dawproject <in> <out.dawproject> [--stress] (round 190ri, kainproctor's "Doesn't work"): File › Export ›
  5154. // DAWproject without the window; the time, the size, the notes and the result to "<out>.txt". --stress makes the song
  5155. // like his: the arrangement repeated to 1,200+ bars, the automation clips as lanes, every kind of marker, some clips
  5156. // muted, a sample and a plugin that are not on this computer
  5157. if (args.contains ("--export-dawproject"))
  5158. {
  5159. const auto i = args.indexOf ("--export-dawproject");
  5160. const juce::File input (args[i + 1].unquoted()), output (args[i + 2].unquoted());
  5161. juce::String error, report;
  5162. auto ok = false;
  5163. {
  5164. lynx::AudioEngine loader (false);
  5165. if (input.hasFileExtension ("flp;als;flm;songtmpl;band;blx;mod;xm;s3m;it;dawproject"))
  5166. ok = loader.importFlpFile (input, error);
  5167. else if (auto song = lynx::ProjectFile::load (input, error))
  5168. {
  5169. loader.setSong (std::move (*song));
  5170. ok = true;
  5171. }
  5172. if (ok && args.contains ("--stress"))
  5173. loader.editSong ([] (lynx::Song& s) { community190riStressSong (s); });
  5174. if (ok)
  5175. {
  5176. loader.capturePluginStates();
  5177. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  5178. juce::StringArray notes;
  5179. ok = lynx::writeDawProjectFile (loader.getSong(), &loader.getPluginHost(), output, notes, error);
  5180. report << "ms=" << juce::String (juce::Time::getMillisecondCounterHiRes() - t0, 0) << "\nbytes=" << output.getSize()
  5181. << "\nbars=" << loader.getSong().barAt (loader.getSong().songLength()).number << "\nclips=" << (int) loader.getSong().playlist.size()
  5182. << "\nnotes=" << notes.size() << "\n" << notes.joinIntoString ("\n") << "\n";
  5183. }
  5184. }
  5185. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  5186. juce::File (output.getFullPathName() + ".txt").replaceWithText (report);
  5187. setApplicationReturnValue (ok ? 0 : 1);
  5188. quit();
  5189. return;
  5190. }
  5191. // --export-flm <in.lynx|.flp|.als|.flm|...> <out.flm> (round 190og, FLM coverage app-0003): File › "Save a copy as FL
  5192. // Studio Mobile project" without the window; the samples go beside it, the losses and the result to "<out>.txt".
  5193. // --flmexportshot <prefix> <project> [--shot-scale 1.5 --shot-suffix @150]: the window with that project's losses
  5194. if (args.contains ("--export-flm") || args.contains ("--flmexportshot"))
  5195. {
  5196. const auto shot = args.contains ("--flmexportshot");
  5197. const auto i = args.indexOf (shot ? "--flmexportshot" : "--export-flm");
  5198. const juce::File input (args[i + (shot ? 2 : 1)].unquoted());
  5199. juce::String error, report;
  5200. auto ok = false;
  5201. {
  5202. lynx::AudioEngine loader (false);
  5203. if (input.hasFileExtension ("flp;als;flm;songtmpl;band;blx;mod;xm;s3m;it;dawproject"))
  5204. ok = loader.importFlpFile (input, error);
  5205. else if (auto song = lynx::ProjectFile::load (input, error))
  5206. {
  5207. loader.setSong (std::move (*song));
  5208. ok = true;
  5209. }
  5210. if (ok && shot)
  5211. {
  5212. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5213. lynx::FlmExportOptions o;
  5214. o.title = input.getFileNameWithoutExtension().toStdString();
  5215. const auto dry = lynx::exportFlm (loader.getSong(), o);
  5216. auto list = std::make_shared<juce::TextEditor>();
  5217. std::unique_ptr<juce::AlertWindow> w (lynx::buildFlmExportWindow (dry, list));
  5218. saveSnapshot (*w, args[i + 1].unquoted() + "-flmexport.png");
  5219. report << lynx::flmExportLossText (dry) << "\n";
  5220. }
  5221. else if (ok)
  5222. {
  5223. loader.capturePluginStates();
  5224. lynx::FlmExportResult result;
  5225. const juce::File out (args[i + 2].unquoted());
  5226. ok = lynx::writeFlmCopy (loader.getSong(), out, result, error);
  5227. report << "bytes=" << (int) result.bytes.size() << "\nsamples=" << (int) result.samples.size() << "\n";
  5228. for (const auto& l : result.lost)
  5229. report << (l.sound ? "sound: " : "other: ") << juce::String::fromUTF8 (l.text.c_str()).replace ("{0}", juce::String::fromUTF8 (l.detail.c_str())) << "\n";
  5230. }
  5231. }
  5232. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  5233. juce::File (args[i + (shot ? 1 : 2)].unquoted() + (shot ? "-flmexport.txt" : ".txt")).replaceWithText (report);
  5234. setApplicationReturnValue (ok ? 0 : 1);
  5235. quit();
  5236. return;
  5237. }
  5238. // --gamepadshot <prefix> (round 184a, S16): the game controller's hints overlay and the MIDI settings page with
  5239. // the option on, offscreen, plus the poller fed fake pad states ("<prefix>-gamepad.txt")
  5240. if (args.contains ("--gamepadshot"))
  5241. {
  5242. runGamepadShot (args[args.indexOf ("--gamepadshot") + 1].unquoted());
  5243. return;
  5244. }
  5245. // --midioutshot <prefix> [--shot-scale 1.5] (round 190jl): Settings › MIDI with the output devices' Port boxes
  5246. // (the snapshot's sample devices: the volca on port 1 of its own, the drum machine with master sync), offscreen
  5247. if (args.contains ("--midioutshot"))
  5248. {
  5249. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5250. {
  5251. lynx::AudioEngine engine (false);
  5252. auto page = lynx::makeMidiPage (engine, {}, false);
  5253. page->setSize (1000, 1300);
  5254. savePng (lynx::shot::snapshot (*page), args[args.indexOf ("--midioutshot") + 1].unquoted() + "-settings-midi.png");
  5255. }
  5256. setApplicationReturnValue (0);
  5257. quit();
  5258. return;
  5259. }
  5260. // --export-bundle <in.lynx|.flp|.als> <folder> [--zip] [--no-mixdown] [--shot <prefix>] (round 184a, S9): File ›
  5261. // Export › "For other apps..." without the window; the report goes to "<folder>/export-bundle.txt"
  5262. if (args.contains ("--export-bundle"))
  5263. {
  5264. const auto i = args.indexOf ("--export-bundle");
  5265. runBundleExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--zip"), ! args.contains ("--no-mixdown"),
  5266. args.contains ("--shot") ? args[args.indexOf ("--shot") + 1].unquoted() : juce::String());
  5267. return;
  5268. }
  5269. if (args.contains ("--export-flp"))
  5270. {
  5271. const auto i = args.indexOf ("--export-flp");
  5272. runFlExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--substitute"));
  5273. return;
  5274. }
  5275. if (args.contains ("--export"))
  5276. {
  5277. const auto i = args.indexOf ("--export");
  5278. const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
  5279. // (round 190te, issue #356: --latency356on renders with the LYNX extra "Tempo-synced effects follow the latency
  5280. // before them" on, to measure what it changes in FL projects; the export never reads ui-options.txt)
  5281. if (args.contains ("--latency356on"))
  5282. lynx::latencytransport::patternOn = true;
  5283. lynx::SampleLibrary::setInlineCacheChecks (true); // (round 190tg: an export reads only checked cache files)
  5284. runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
  5285. return;
  5286. }
  5287. if (args.contains ("--tempomarkershot"))
  5288. {
  5289. // LYNX --tempomarkershot <prefix> <project.lynx> (round 190hq): the Playlist of the project with its tempo
  5290. // markers on the ruler (-playlist.png) and the "Save a copy for an older LYNX" window for each release
  5291. // (-savecopy-<release>.png); no window, nothing saved
  5292. const auto i = args.indexOf ("--tempomarkershot");
  5293. const auto prefix = args[i + 1].unquoted();
  5294. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5295. lynx::AudioEngine shotEngine (false);
  5296. juce::String error;
  5297. auto ok = false;
  5298. if (auto song = lynx::ProjectFile::load (juce::File (args[i + 2].unquoted()), error))
  5299. shotEngine.setSong (std::move (*song)), ok = true;
  5300. if (ok)
  5301. {
  5302. {
  5303. lynx::PlaylistComponent playlist (shotEngine);
  5304. playlist.setBounds (0, 0, 1400, 420);
  5305. playlist.setVisible (true);
  5306. playlist.setViewForSnapshot (70.0, 0, 0);
  5307. shotEngine.dispatchPendingMessages();
  5308. saveSnapshot (playlist, prefix + "-playlist.png");
  5309. }
  5310. auto list = std::make_shared<juce::TextEditor>();
  5311. std::unique_ptr<juce::AlertWindow> w (lynx::MainComponent::buildSaveCopyWindow (lynx::ProjectFile::toJson (shotEngine.getSong()), list));
  5312. const auto releases = lynx::olderlynx::releases();
  5313. for (int k = 0; k < releases.size(); ++k)
  5314. {
  5315. w->getComboBoxComponent ("release")->setSelectedItemIndex (k, juce::sendNotificationSync);
  5316. saveSnapshot (*w, prefix + "-savecopy-" + releases[k] + ".png");
  5317. }
  5318. }
  5319. setApplicationReturnValue (ok ? 0 : 1);
  5320. quit();
  5321. return;
  5322. }
  5323. // --convert190rm <in> <out> [--savecopyfor <release>] (round 190rm): open as File › Open does, write as the export
  5324. // does (src/Iox190rmCheck.inc); before --savecopyfor, which it can take as an option
  5325. if (args.contains ("--convert190rm"))
  5326. {
  5327. const auto i = args.indexOf ("--convert190rm");
  5328. runConvert190rm (args[i + 1].unquoted(), args[i + 2].unquoted());
  5329. return;
  5330. }
  5331. if (args.contains ("--savecopyfor"))
  5332. {
  5333. // LYNX --savecopyfor <in.lynx> <release> <out.lynx> (round 190hq, B20): File › "Save a copy for an older
  5334. // LYNX..." without the window; what the copy loses goes to <out.lynx>.txt (English), then result=OK
  5335. const auto i = args.indexOf ("--savecopyfor");
  5336. const juce::File input (args[i + 1].unquoted()), output (args[i + 3].unquoted());
  5337. const auto release = args[i + 2].unquoted();
  5338. juce::String report, error;
  5339. auto ok = false;
  5340. if (const auto song = lynx::ProjectFile::load (input, error))
  5341. {
  5342. const auto copy = lynx::olderlynx::forRelease (*song, release);
  5343. for (const auto& l : copy.lost)
  5344. report << (l.sound ? "sound: " : "view: ") << juce::String::fromUTF8 (l.text).replace ("{0}", l.detail) << "\n";
  5345. ok = copy.ok && output.replaceWithText (copy.json, false, false, nullptr);
  5346. if (! copy.ok)
  5347. error = copy.error;
  5348. }
  5349. report << "result=" << (ok ? juce::String ("OK") : "ERROR " + error) << "\n";
  5350. juce::File (output.getFullPathName() + ".txt").replaceWithText (report);
  5351. setApplicationReturnValue (ok ? 0 : 1);
  5352. quit();
  5353. return;
  5354. }
  5355. if (args.contains ("--render"))
  5356. {
  5357. const auto i = args.indexOf ("--render");
  5358. runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
  5359. return;
  5360. }
  5361. // session breadcrumb: a fail-fast (no crash handler runs) still leaves the last steps behind (round 111)
  5362. uncleanLastStep = collectUncleanSessions();
  5363. // round 190rp: the saved audio device hung (or crashed) the last start: not this time (see AudioEngine::skipSavedDevice)
  5364. if (uncleanLastStep.isNotEmpty())
  5365. if (uncleanDevice = uncleanDeviceOpen(); uncleanDevice.isNotEmpty())
  5366. lynx::AudioEngine::skipSavedDevice = true;
  5367. sessionsFolder().createDirectory();
  5368. lynx::crashguard::beginSession (
  5369. sessionsFolder().getChildFile ("session-" + juce::String (lynx::crashguard::processId()) + ".txt").getFullPathName().toStdString(),
  5370. ("LYNX session\nversion=" + getApplicationVersion() + "\npid=" + juce::String (lynx::crashguard::processId())
  5371. + "\nstart=" + juce::String ((juce::int64) lynx::crashguard::processStartTime())
  5372. + "\nstarted=" + juce::Time::getCurrentTime().toISO8601 (true) + "\n").toStdString());
  5373. startHangWatch();
  5374. // LYNX_PROFILE_MAIN=<file> (round 174f): the message thread sampled every millisecond, 5-second windows
  5375. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  5376. lynx::crashguard::startMainProfiler (profile.toStdString());
  5377. startupTrace.mark ("initialise (normal start)");
  5378. // (round 190hd, Windows) how long before the trace's 0 the process was made: the loader (the exe, its DLLs,
  5379. // relocations) and the static initialisers that ran before this file's
  5380. if (const auto created = lynx::crashguard::processStartTime(); created != 0)
  5381. {
  5382. const auto t0 = (std::uint64_t) std::chrono::duration_cast<std::chrono::microseconds> (startupTrace.t0System.time_since_epoch()).count() * 10u
  5383. + 116444736000000000ull; // (FILETIME: 100 ns since 1601)
  5384. if (t0 > created)
  5385. startupTrace.mark ((" (the process was made " + juce::String ((double) (t0 - created) / 10000.0, 1)
  5386. + " ms before this trace's 0: the loader, the DLLs, the first static initialisers)").toRawUTF8());
  5387. }
  5388. prepareGraphicsDevice();
  5389. if (startupTrace.on)
  5390. lynx::startupMark = startupMarkHook;
  5391. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  5392. lynx::themeui::loadSaved(); // the user's theme (Options › Theme, round 162d)
  5393. startupOptions = lynx::StartupOptions::load();
  5394. if (lynx::demo::active()) // (round 190np: --demo records from the first frame: no splash card, no start-up sound)
  5395. startupOptions.splash = startupOptions.sound = false;
  5396. lynx::registerFileTypes();
  5397. startupTrace.mark ("options + file types");
  5398. // Double-clicking a .lynx/.flp opens LYNX with the file as an argument; a path typed in a terminal may be relative
  5399. // (D#92, round 180a: it was ignored, leaving the blank project with no message). A missing file gets "Could not open".
  5400. // Issue #346 (round 190sq): a desktop-entry field code left in the command ("<AppImage> %F" run from a keyboard
  5401. // shortcut) is no file, and an escaped "%%" is a "%" when only that names a file
  5402. const auto startupFile = [] (const juce::String& argument) {
  5403. const auto cwd = juce::File::getCurrentWorkingDirectory();
  5404. const auto path = lynx::safety::fileArgumentPath (argument.unquoted().toStdString(), [&cwd] (const std::string& p) {
  5405. return cwd.getChildFile (juce::String::fromUTF8 (p.c_str())).exists();
  5406. });
  5407. return cwd.getChildFile (juce::String::fromUTF8 (path.c_str()));
  5408. };
  5409. {
  5410. std::vector<std::string> unquoted;
  5411. for (const auto& a : args)
  5412. unquoted.push_back (a.unquoted().toStdString());
  5413. if (const auto i = lynx::safety::startupFileArgument (unquoted); i >= 0)
  5414. fileToOpen = startupFile (args[i]);
  5415. }
  5416. // LYNX --no-plugins project.lynx (round 190ap): File › "Open without third-party plugins..." from the command
  5417. // line, for a project a plugin keeps from opening — no hosted plugin is created, each keeps its settings
  5418. if (const auto i = args.indexOf ("--no-plugins"); i >= 0)
  5419. {
  5420. if (i + 1 < args.size() && lynx::safety::isFileArgument (args[i + 1].unquoted().toStdString()))
  5421. fileToOpen = startupFile (args[i + 1]);
  5422. startWithoutPlugins = fileToOpen.hasFileExtension ("lynx");
  5423. }
  5424. // LYNX_TEST_MODE=1 LYNX --open-event-test <ms> <file>: the file arrives the way macOS's Finder delivers it (a Linux
  5425. // or Windows run can exercise that path): 0 ms = at once, before the window exists
  5426. if (lynx::platform::testMode() && args[0] == "--open-event-test" && args.size() > 2)
  5427. {
  5428. const auto file = args[2].unquoted().quoted();
  5429. if (args[1].getIntValue() == 0)
  5430. anotherInstanceStarted (file);
  5431. else
  5432. juce::Timer::callAfterDelay (args[1].getIntValue(), [this, file] { anotherInstanceStarted (file); });
  5433. }
  5434. // LYNX --opentime project.(flp|lynx)|- report.txt [idle seconds] (round 165i): the normal start-up (splash, audio
  5435. // device, window) opens the project, waits until it is loaded and LYNX has gone quiet, measures the idle CPU and
  5436. // memory, writes the times and quits normally (a benchmark that killed LYNX left "closed unexpectedly" behind)
  5437. if (args.contains ("--opentime"))
  5438. {
  5439. const auto i = args.indexOf ("--opentime");
  5440. const auto project = args[i + 1].unquoted();
  5441. fileToOpen = project != "-" && juce::File::isAbsolutePath (project) ? juce::File (project) : juce::File();
  5442. openTimeReport = juce::File (args[i + 2].unquoted());
  5443. if (args.size() > i + 3 && ! args[i + 3].startsWith ("--"))
  5444. openTimeIdleSeconds = juce::jlimit (1, 120, args[i + 3].getIntValue());
  5445. }
  5446. // round 190go: the ASIO device of the last session is made and opened from now on, while the splash and the
  5447. // window come up (see below)
  5448. lynx::AudioEngine::prewarmAudioDevice();
  5449. // round 190go: the built-in start-up sound is made while the splash and the window come up (pure maths)
  5450. if (startupOptions.sound && lynx::themeui::current().startupSound.empty())
  5451. startupSampleJob = std::async (std::launch::async, [] { return lynx::makeStartupSample(); });
  5452. // Round 190go (start-up faster than FL Studio): the main window is built first, with the engine ready but no
  5453. // audio device open; the device opens after it. An ASIO device of the last session was made and opened ahead,
  5454. // on a worker, while the window was built (AudioEngine::prewarmAudioDevice; the driver itself only ever runs on
  5455. // JUCE's ASIO thread, as COM wants). Play pressed before the device is open starts with it.
  5456. if (! startupOptions.splash)
  5457. {
  5458. startEngine();
  5459. createMainWindow();
  5460. mainWindow->reveal();
  5461. startupTrace.mark ("window revealed");
  5462. // the device (and the start-up sound) once the window's first frame is on screen
  5463. mainWindow->whenPainted ([this] {
  5464. openAudioDevice();
  5465. openMidiDevices();
  5466. startAfterWindow (lynx::demo::active()); // (round 190np: --demo has no splash; its first run still gets the welcome card)
  5467. });
  5468. return;
  5469. }
  5470. // the splash first; the main window is built behind its card (still: the logo has not started to drop; building
  5471. // it during the drop would stop the animation, both run on the message thread), then the audio device opens
  5472. // (the start-up sound needs it), and the drop starts with its sound. The window shows the moment the logo has
  5473. // landed (round 190go, A4: before, the window was built only after the drop: the drop, then ~0.6 s of build).
  5474. // Round 190hd (Windows): the card draws on a thread of its own, so the main window is built DURING the drop
  5475. // (startOnItsOwnThread below).
  5476. splash = lynx::makeStartupSplash();
  5477. startupTrace.mark ("splash made");
  5478. splash->showOnDesktop();
  5479. startupTrace.mark ("splash on the desktop");
  5480. if (splash->drawsOnItsOwnThread())
  5481. {
  5482. startWithThreadedSplash();
  5483. return;
  5484. }
  5485. // the rest once the card's first frame is on the screen (round 190go: before, a fixed 40 ms), at the latest
  5486. // after 40 ms
  5487. const auto goOn = [this, started = std::make_shared<bool> (false)] {
  5488. if (std::exchange (*started, true) || splash == nullptr) // (once; or quit meanwhile)
  5489. return;
  5490. startEngine();
  5491. if (splash == nullptr) // quit meanwhile
  5492. return;
  5493. createMainWindow();
  5494. if (splash == nullptr || mainWindow == nullptr)
  5495. return;
  5496. if (startupOptions.sound)
  5497. openAudioDevice (false); // (else after the splash: nothing waits for it)
  5498. // one turn of the message loop before the drop: what fell due while the window was built (JUCE's timers,
  5499. // the window's own async work) runs now, on the still card, not in the drop's first frames
  5500. juce::MessageManager::callAsync ([this] { startDrop(); });
  5501. };
  5502. splash->onFirstFrame = goOn;
  5503. juce::Timer::callAfterDelay (40, goOn);
  5504. }
  5505. // Round 190hd (start-up faster than FL Studio, Windows): the card draws on a thread of its own (ui/Splash.cpp), so
  5506. // nothing the message thread does stops the drop. The card shows at once (no Direct2D device is made for it); the
  5507. // engine starts and the audio device opens behind the still card (an ASIO device of the last session was made and
  5508. // opened ahead on its own thread meanwhile), the drop starts with its sound, and the main window is built while
  5509. // 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
  5510. // fades the moment the logo has landed. The card stays for the drop only (the JUCE card's
  5511. // 2.1 s from the process start was there to keep a fast start from flashing; the drop alone is 1.05 s).
  5512. void startWithThreadedSplash()
  5513. {
  5514. splash->onFirstFrame = [this] {
  5515. if (splash != nullptr && startupTrace.on)
  5516. startupTrace.mark ((" splash: first frame on the screen at "
  5517. + juce::String (std::chrono::duration<double, std::milli> (splash->getFirstFrameTime() - startupTrace.t0).count(), 1) + " ms (its own thread)")
  5518. .toRawUTF8());
  5519. };
  5520. juce::MessageManager::callAsync ([this] {
  5521. if (splash == nullptr) // (quit meanwhile)
  5522. return;
  5523. startEngine();
  5524. if (splash == nullptr)
  5525. return;
  5526. if (startupOptions.sound)
  5527. openAudioDevice (false); // (else after the splash: nothing waits for it)
  5528. startDrop();
  5529. // the main window while the logo drops (one more message, so the drop's start is not held by it)
  5530. juce::MessageManager::callAsync ([this] {
  5531. if (splash == nullptr || mainWindow != nullptr || engine == nullptr)
  5532. return;
  5533. createMainWindow();
  5534. // shown as soon as it is built, behind the card: the logo goes on dropping above it and the card fades at
  5535. // the landing as before (LYNX_REVEAL_AT_LANDING=1: the window shows at the landing, as in round 190go)
  5536. if (mainWindow != nullptr && splash != nullptr
  5537. && juce::SystemStats::getEnvironmentVariable ("LYNX_REVEAL_AT_LANDING", {}) != "1")
  5538. {
  5539. mainWindow->reveal();
  5540. windowRevealed = true;
  5541. startupTrace.mark ("window revealed (behind the card, while the logo drops)");
  5542. splash->raise();
  5543. }
  5544. });
  5545. });
  5546. }
  5547. // the logo's drop and the start-up sound together; the window shows the moment the logo has landed
  5548. void startDrop()
  5549. {
  5550. const auto ownThread = splash != nullptr && splash->drawsOnItsOwnThread(); // (the window is built during the drop)
  5551. if (splash == nullptr || (mainWindow == nullptr && ! ownThread) || engine == nullptr)
  5552. return;
  5553. if (startupOptions.sound)
  5554. playStartupSound();
  5555. splash->setStatus (lynx::tr ("Loading the workspace..."));
  5556. splash->startClock();
  5557. // the card stays for the logo's drop, then the window shows (round 190hd: a card on its own thread; round 190rn:
  5558. // the card on the message thread too, so Linux and macOS no longer hold a window that is ready for a 2.1 s
  5559. // minimum counted from the process start: the window was built at 0.15 s and the audio device open at 0.87 s)
  5560. splashDuration = landingSeconds;
  5561. splash->setBarDuration (splashDuration);
  5562. splash->whenLanded (splashDuration, [this] {
  5563. if (splash == nullptr || mainWindow == nullptr)
  5564. return;
  5565. if (startupTrace.on)
  5566. startupTrace.mark (("splash: the drop in " + juce::String (splash->getDropFrames()) + " frames, longest gap "
  5567. + juce::String (splash->getLongestDropGapMs(), 1) + " ms"
  5568. + (splash->getLongestDropGapAt() >= 0.0 ? " (at " + juce::String (splash->getLongestDropGapAt(), 3) + " s of its clock; the frame before: "
  5569. + splash->getLongestDropGapDetail() + ")"
  5570. : juce::String()))
  5571. .toRawUTF8());
  5572. if (! std::exchange (windowRevealed, true))
  5573. {
  5574. mainWindow->reveal();
  5575. startupTrace.mark ("window revealed (after the splash)");
  5576. }
  5577. splash->raise();
  5578. const auto deviceOpen = ! engine->isAudioDeviceOpenPending();
  5579. splash->finish ([this, deviceOpen] {
  5580. splash = nullptr;
  5581. // without the start-up sound the device opens now, once the card has faded (the window is up)
  5582. if (! deviceOpen)
  5583. openAudioDevice();
  5584. openMidiDevices();
  5585. if (! deviceOpen)
  5586. startAfterWindow (true);
  5587. });
  5588. if (deviceOpen)
  5589. mainWindow->whenPainted ([this] { startAfterWindow (true); });
  5590. });
  5591. }
  5592. // what follows the window's first frame (the audio device is open): the notice of an unclean end, the start-up
  5593. // project, the probes and the update check; on a first run (with the splash) the setup wizard
  5594. void startAfterWindow (bool offerSetupWizard)
  5595. {
  5596. if (std::exchange (startedAfterWindow, true) || mainWindow == nullptr)
  5597. return;
  5598. // (round 190go) each step after the window is a timed line of the start-up trace
  5599. showUncleanNotice();
  5600. startupTrace.mark ("after the window: unclean-session notice");
  5601. openStartupFile();
  5602. startupTrace.mark ("startup file opened");
  5603. startOpenTimeProbe();
  5604. if (! lynx::demo::active()) // (round 190np: --demo records videos: no update prompt, no support note)
  5605. {
  5606. startUpdateCheck();
  5607. startSupportNote(); // (round 190fq)
  5608. }
  5609. startupTrace.mark ("after the window: probes, update check scheduled");
  5610. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  5611. markSettled(); // (round 190gd)
  5612. // first run: language, audio, plugin folders (FL Studio's included) and a background scan
  5613. if (! offerSetupWizard)
  5614. return;
  5615. // round 190np: a fresh profile gets the welcome card ("Where are you coming from?"); a profile that had LYNX's
  5616. // settings and never finished the old wizard keeps the old wizard; an answered one gets nothing (core/Onboarding.h)
  5617. const auto action = lynx::onboarding::startAction (lynx::setupWizardDone(), lynx::onboardui::profileExistedAtStart(),
  5618. mainWindow->getContent().onboardingStateForCheck().pending);
  5619. using StartAction = lynx::onboarding::StartAction;
  5620. if (action != StartAction::none && lynx::platform::testMode())
  5621. lynx::platform::testModeLog (action == StartAction::welcomeCard ? "setup wizard: welcome card" : "setup wizard");
  5622. else if (action == StartAction::welcomeCard)
  5623. {
  5624. mainWindow->getContent().showWelcomeCard (true);
  5625. startupTrace.mark ("after the window: welcome card shown");
  5626. }
  5627. else if (action == StartAction::setupWizard)
  5628. {
  5629. mainWindow->showSetupWizard();
  5630. startupTrace.mark ("after the window: setup wizard shown");
  5631. }
  5632. // 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
  5633. // first run's card, never when a file was given to open
  5634. if (lynx::startpage::showAtStart (lynx::startpage::enabled(), fileToOpen != juce::File(), action != StartAction::none,
  5635. openTimeReport != juce::File() || lynx::platform::testMode()))
  5636. {
  5637. mainWindow->getContent().showStartPage();
  5638. startupTrace.mark ("after the window: start page shown");
  5639. }
  5640. }
  5641. // round 190fq: the start-up support note (ui/SupportLynx.h) counts this start and, from the 10th on, may show its
  5642. // card once at a quiet moment. Only here, on the normal start path (the command-line modes returned earlier); test
  5643. // mode and CI machines neither count nor show it.
  5644. void startSupportNote()
  5645. {
  5646. if (mainWindow == nullptr)
  5647. return;
  5648. const auto env = [] (const char* name) { return juce::SystemStats::getEnvironmentVariable (name, {}).toStdString(); };
  5649. const auto quiet = lynx::supportnote::quietEnvironment (lynx::platform::testMode(), env ("CI"), env ("GITHUB_ACTIONS"), env ("LYNX_NO_SUPPORT_NOTE"));
  5650. if (quiet && lynx::platform::testMode())
  5651. lynx::platform::testModeLog ("support note: not counted (test mode)");
  5652. mainWindow->getContent().startSupportNote (quiet);
  5653. }
  5654. // the start-up trace's last lines: what the first seconds after the window add (lazy work, caches, the first paints)
  5655. static void markSettled()
  5656. {
  5657. if (! startupTrace.on)
  5658. return;
  5659. juce::Timer::callAfterDelay (5000, [] { startupTrace.mark ("5 s after the window"); startupTrace.write(); });
  5660. juce::Timer::callAfterDelay (15000, [] { startupTrace.mark ("15 s after the window"); startupTrace.write(); });
  5661. }
  5662. // Round 190hd (Windows): the Direct3D 11 + Direct2D device (~0.35 s: the graphics driver loads) is made once, on a
  5663. // worker, while the splash card, the engine and the audio device come up, and kept until LYNX closes: a 1 x 1
  5664. // Direct2D image holds JUCE's shared DirectX object (its devices), so the main window finds them made and nothing
  5665. // makes them again (before, every holder going away -- the splash's logo, a temporary one -- could mean a new device
  5666. // at its next use). Other systems: nothing to do.
  5667. void prepareGraphicsDevice()
  5668. {
  5669. #if JUCE_WINDOWS
  5670. if (juce::SystemStats::getEnvironmentVariable ("LYNX_GPU_PREWARM", {}) == "0")
  5671. return;
  5672. graphicsDeviceJob = std::async (std::launch::async, [] {
  5673. const auto from = std::chrono::steady_clock::now();
  5674. juce::Image holder (juce::Image::ARGB, 1, 1, false); // (NativeImageType: Direct2D, the shared device)
  5675. return std::make_pair (holder, std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - from).count());
  5676. });
  5677. #endif
  5678. }
  5679. void markGraphicsDevice()
  5680. {
  5681. if (! graphicsDeviceJob.valid() || ! startupTrace.on || std::exchange (graphicsDeviceMarked, true))
  5682. return;
  5683. const auto ready = graphicsDeviceJob.wait_for (std::chrono::seconds (0)) == std::future_status::ready;
  5684. startupTrace.mark (ready ? (" graphics device made on a worker in " + juce::String (graphicsDeviceJob.get().second, 1) + " ms").toRawUTF8()
  5685. : " graphics device: still being made on its worker");
  5686. }
  5687. void startEngine()
  5688. {
  5689. startupTrace.mark ("before the audio engine");
  5690. lynx::BrowserComponent::allowIndexerProcess = true; // (round 190hd: the normal window only)
  5691. // (round 190go) ready to play, no device open yet: see openAudioDevice
  5692. engine = std::make_unique<lynx::AudioEngine> (true, -1, true, true);
  5693. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  5694. startupTrace.mark ("audio engine (no device yet)");
  5695. crashEngine = engine.get();
  5696. lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
  5697. // a project given on the command line: its slow plugin modules (a Waves shell) start now, on their own
  5698. // thread, while the splash and the main window come up (round 121)
  5699. if (fileToOpen.hasFileExtension ("flp"))
  5700. if (juce::MemoryBlock data; fileToOpen.loadFileAsData (data))
  5701. try
  5702. {
  5703. engine->getPluginHost().startModulesFor (lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  5704. startupTrace.mark ("plugin modules started ahead");
  5705. }
  5706. catch (const flp::Error&)
  5707. {
  5708. }
  5709. }
  5710. // The audio device of the last session, then (withSound) the start-up sound on it (once; message thread)
  5711. void openAudioDevice (bool withSound = true)
  5712. {
  5713. if (engine == nullptr || ! engine->isAudioDeviceOpenPending())
  5714. return;
  5715. engine->openAudioDevice();
  5716. if (const auto prewarmed = lynx::asioPrewarmReport(); prewarmed.isNotEmpty() && startupTrace.on)
  5717. startupTrace.mark ((" " + prewarmed).toRawUTF8());
  5718. startupTrace.mark ("audio device opened");
  5719. addDriverFileDeviceType();
  5720. if (withSound)
  5721. playStartupSound();
  5722. }
  5723. // issue #280 (round 190qr): the LYNX extra "Play a sound when an export finishes" (core/ExportDone.h)
  5724. void bindExportDoneSound()
  5725. {
  5726. lynx::exportdone::playSound = [this] {
  5727. if (engine != nullptr)
  5728. {
  5729. auto sound = lynx::startup::makeDoneSound (48000.0);
  5730. auto sample = std::make_shared<lynx::SampleData>();
  5731. sample->left = std::move (sound.left);
  5732. sample->right = std::move (sound.right);
  5733. sample->sampleRate = sound.sampleRate;
  5734. engine->previewSample (sample);
  5735. }
  5736. };
  5737. }
  5738. void playStartupSound()
  5739. {
  5740. if (startupOptions.sound && ! std::exchange (startupSoundPlayed, true) && engine != nullptr)
  5741. {
  5742. // Options › Theme › Startup sound (issue #12): the user's file, else (or when it can't be read) LYNX's own
  5743. std::shared_ptr<const lynx::SampleData> sound;
  5744. if (const auto& own = lynx::themeui::current().startupSound; ! own.empty() && juce::File (juce::String::fromUTF8 (own.c_str())).existsAsFile())
  5745. sound = engine->getSampleLibrary().load (juce::String::fromUTF8 (own.c_str()));
  5746. if (sound == nullptr && startupSampleJob.valid())
  5747. sound = startupSampleJob.get();
  5748. engine->previewSample (sound != nullptr ? sound : lynx::makeStartupSample());
  5749. }
  5750. startupTrace.mark ("startup sound");
  5751. }
  5752. void openMidiDevices()
  5753. {
  5754. if (engine != nullptr)
  5755. engine->openMidiDevices(); // (its own line in the start-up trace: "engine: MIDI inputs")
  5756. }
  5757. void createMainWindow()
  5758. {
  5759. bindExportDoneSound(); // (round 190qr, #280)
  5760. mainWindow = std::make_unique<MainWindow> ("LYNX SHARE", *engine); // the brand; getApplicationName() stays "LYNX" (an id: instance lock, X11 WM_CLASS, ALSA client)
  5761. // round 190rp (decision O-2): the recovery box (MainComponent::checkPreviousSession, 2.5 s after the session
  5762. // starts) names the plugin whose window was open when the last session ended and opens the backup without
  5763. // third-party plugins by default
  5764. if (uncleanLastStep.isNotEmpty())
  5765. mainWindow->getContent().setRecoveryPlugin (uncleanCause().editorPlugin);
  5766. lynx::setMainWindowForOwnership (mainWindow.get());
  5767. lynx::crashguard::watchDisplayConnection (onDisplayLost); // (round 190rf, Linux: the display is open now)
  5768. lynx::applyRenderingChoice (*mainWindow); // (GPU rendering off: GDI; round 157a)
  5769. lynx::startRenderingWatch();
  5770. startupTrace.mark ("main window built");
  5771. lynx::remoteui::install ([this] (bool enabled) {
  5772. remoteControl = nullptr;
  5773. if (enabled)
  5774. remoteControl = lynx::RemoteControl::create (*engine, true, [this] {
  5775. const auto title = mainWindow != nullptr ? mainWindow->getName() : juce::String ("Untitled");
  5776. const auto separator = title.indexOf (" - ");
  5777. return separator >= 0 ? title.substring (separator + 3) : title;
  5778. }, [this] {
  5779. const auto file = mainWindow != nullptr ? mainWindow->getContent().getCurrentProjectFile() : juce::File();
  5780. return file == juce::File() ? juce::String() : file.getFullPathName();
  5781. });
  5782. lynx::remoteui::setRuntimeStatus (remoteControl != nullptr && remoteControl->active());
  5783. });
  5784. if (lynx::demo::active()) // round 190np: --demo's view operations (ui.find, ui.click, ui.layout...) on the API
  5785. lynx::RemoteControl::setExtension (lynx::demo::operations(), [this] (const juce::String& op, const juce::var& args) -> juce::var {
  5786. if (mainWindow == nullptr)
  5787. throw std::runtime_error ("No main window");
  5788. return mainWindow->getContent().handleDemoOp (op, args);
  5789. });
  5790. markGraphicsDevice();
  5791. }
  5792. // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
  5793. // Settings › General › "Crash reports" says (round 159), ask whether to send a report, send it unasked, or not
  5794. void showUncleanNotice()
  5795. {
  5796. if (uncleanDevice.isNotEmpty())
  5797. lynx::platform::testModeLog ("saved audio device skipped: the last session ended while it opened (" + uncleanDevice + ")");
  5798. if (lynx::platform::testMode()) // LYNX_TEST_MODE: no prompt, no report sent (written to test-mode.log)
  5799. {
  5800. if (uncleanLastStep.isNotEmpty())
  5801. lynx::platform::testModeLog ("\"closed unexpectedly\" notice (last step: " + uncleanLastStep + ")");
  5802. return;
  5803. }
  5804. if (uncleanLastStep.isEmpty())
  5805. {
  5806. lynx::crashreporter::retryPending(); // (reports an earlier run could not send: once more)
  5807. return;
  5808. }
  5809. auto message = lynx::tr ("The last session ended without closing normally. Last step: {0}. Backup copies of your project are in "
  5810. "LYNX SHARE's autosave folder; details in crash-history.log.",
  5811. { uncleanLastStep });
  5812. uncleanLastStep.clear();
  5813. if (uncleanDevice.isNotEmpty()) // (round 190rp)
  5814. message << "\n\n"
  5815. << lynx::tr ("It stopped while the audio device {0} was opening, so LYNX SHARE started with the default device this time. "
  5816. "Choose {0} again in Options > Audio settings when its driver works (after an update or a restart, for example).",
  5817. { uncleanDevice.fromFirstOccurrenceOf (": ", false, false) });
  5818. const auto cause = uncleanCause();
  5819. // round 157a: a plugin's editor was opening — it crashed (often in the graphics driver, inside the plugin's own
  5820. // OpenGL window): offer to keep that plugin in its own process, where a crash takes only the plugin down
  5821. juce::String separatePlugin;
  5822. if (cause.editorPlugin.isNotEmpty() && ! lynx::pluginSandboxEnabled() && ! lynx::pluginAlwaysSeparate (cause.editorPlugin))
  5823. separatePlugin = cause.editorPlugin;
  5824. // LYNX's own drawing crashed in the graphics driver (Direct2D / Direct3D): draw with the CPU from now on
  5825. else if (cause.gpuDriver && lynx::gpuRenderingEnabled())
  5826. {
  5827. lynx::setGpuRenderingEnabled (false);
  5828. message << "\n\n"
  5829. << lynx::tr ("The crash was in the graphics driver ({0}). LYNX SHARE now draws its windows without the GPU; you can turn GPU "
  5830. "rendering back on in Options > General settings (after a driver update, for example).",
  5831. { cause.driverModule });
  5832. }
  5833. // round 165e: the Visualizer's GPU view was drawing when the session ended (a driver crash, a hang, the machine
  5834. // going down): the Visualizer draws with the 2D renderer from now on (its GPU button turns it back on)
  5835. for (int i = uncleanSteps.size(); --i >= 0;)
  5836. {
  5837. if (uncleanSteps[i].contains (lynx::visualgl::stopNote))
  5838. break;
  5839. if (uncleanSteps[i].contains (lynx::visualgl::startNote))
  5840. {
  5841. if (lynx::visualgl::enabled())
  5842. {
  5843. lynx::visualgl::setEnabled (false);
  5844. message << "\n\n"
  5845. << lynx::tr ("The Visualizer was drawing with the GPU (OpenGL) when it happened. It now draws without the GPU; its GPU "
  5846. "button turns it back on.");
  5847. }
  5848. break;
  5849. }
  5850. }
  5851. const auto session = lynx::crashreporter::parseSession (uncleanSessionText);
  5852. auto* devices = engine != nullptr ? &engine->getDeviceManager() : nullptr;
  5853. const auto action = lynx::crashreport::actionFor (lynx::crashreporter::consent());
  5854. lynx::crashreporter::retryPending();
  5855. if (action == lynx::crashreport::Action::askUser)
  5856. {
  5857. if (separatePlugin.isNotEmpty())
  5858. message << "\n\n"
  5859. << lynx::tr ("It happened while the window of {0} was opening{1}.",
  5860. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() });
  5861. lynx::crashreporter::showStartupDialog (session, message, separatePlugin, [separatePlugin] { lynx::setPluginAlwaysSeparate (separatePlugin, true); },
  5862. devices);
  5863. return;
  5864. }
  5865. if (action == lynx::crashreport::Action::sendSilently)
  5866. {
  5867. const auto input = lynx::crashreporter::makeInput (session, session.kind(), devices);
  5868. lynx::crashreporter::send (lynx::crashreporter::buildJson (input, false), juce::String::fromUTF8 (input.id.c_str()));
  5869. message << "\n\n" << lynx::tr ("A crash report is being sent to help fix it (Options > General settings > Crash reports).");
  5870. }
  5871. if (separatePlugin.isNotEmpty())
  5872. {
  5873. juce::AlertWindow::showOkCancelBox (
  5874. juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"),
  5875. message + "\n\n"
  5876. + lynx::tr ("It happened while the window of {0} was opening{1}. Run {0} in a separate process from now on? If it "
  5877. "crashes again, only the plugin stops and LYNX SHARE keeps running (Plugin wrapper menu: \"Always run in a "
  5878. "separate process\").",
  5879. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() }),
  5880. lynx::tr ("Run separately"), lynx::tr ("No"), nullptr,
  5881. juce::ModalCallbackFunction::create ([separatePlugin] (int result) {
  5882. if (result != 0)
  5883. lynx::setPluginAlwaysSeparate (separatePlugin, true);
  5884. }));
  5885. return;
  5886. }
  5887. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"), message);
  5888. }
  5889. // --opentime: after the start-up file was handed to the window
  5890. void startOpenTimeProbe()
  5891. {
  5892. if (openTimeReport == juce::File())
  5893. return;
  5894. struct Probe final : juce::Timer
  5895. {
  5896. LynxApplication& app;
  5897. juce::File report, project;
  5898. int idleSeconds;
  5899. int phase = 0; // 0 loading, 1 settling, 2 idle measurement
  5900. double revealedS = 0.0, loadedS = -1.0, settledS = -1.0, cpuAtLoaded = 0.0;
  5901. double lastCpu = 0.0, lastT = 0.0, quietSince = -1.0, idleCpu0 = 0.0, idleT0 = 0.0;
  5902. Probe (LynxApplication& a, juce::File r, juce::File p, int idle)
  5903. : app (a), report (std::move (r)), project (std::move (p)), idleSeconds (idle)
  5904. {
  5905. revealedS = startupTrace.seconds();
  5906. startTimer (250);
  5907. }
  5908. bool loaded() const
  5909. {
  5910. if (project == juce::File())
  5911. return true;
  5912. return app.mainWindow != nullptr
  5913. && app.mainWindow->getName().containsIgnoreCase (project.getFileNameWithoutExtension());
  5914. }
  5915. void finish (const juce::String& result)
  5916. {
  5917. stopTimer();
  5918. const auto now = startupTrace.seconds();
  5919. const auto cpu = lynx::processCpuSeconds();
  5920. juce::String text;
  5921. text << "project=" << (project == juce::File() ? juce::String ("-") : project.getFullPathName()) << "\n"
  5922. << "window_s=" << juce::String (revealedS, 3) << "\n"
  5923. << "loaded_s=" << juce::String (loadedS, 3) << "\n"
  5924. << "settled_s=" << juce::String (settledS, 3) << "\n"
  5925. << "cpu_at_loaded_s=" << juce::String (cpuAtLoaded, 3) << "\n"
  5926. << "idle_s=" << juce::String (now - idleT0, 2) << "\n"
  5927. << "idle_cpu_pct=" << juce::String (phase == 2 && now > idleT0 ? 100.0 * (cpu - idleCpu0) / (now - idleT0) : -1.0, 1) << "\n"
  5928. << "working_set_mb=" << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << "\n"
  5929. << "cpu_total_s=" << juce::String (cpu, 3) << "\n"
  5930. << "result=" << result << "\n";
  5931. report.replaceWithText (text);
  5932. app.setApplicationReturnValue (result == "OK" ? 0 : 1);
  5933. app.quit();
  5934. }
  5935. void timerCallback() override
  5936. {
  5937. const auto now = startupTrace.seconds();
  5938. const auto cpu = lynx::processCpuSeconds();
  5939. if (phase == 0)
  5940. {
  5941. if (loaded())
  5942. {
  5943. loadedS = now;
  5944. cpuAtLoaded = cpu;
  5945. phase = 1;
  5946. lastCpu = cpu;
  5947. lastT = now;
  5948. }
  5949. else if (now - revealedS > 240.0)
  5950. finish ("TIMEOUT loading");
  5951. return;
  5952. }
  5953. if (phase == 1)
  5954. {
  5955. // quiet = under 10 % of one core for 1.5 s (the harness's rule), at most 30 s after loading
  5956. const auto use = now > lastT ? 100.0 * (cpu - lastCpu) / (now - lastT) : 0.0;
  5957. lastCpu = cpu;
  5958. lastT = now;
  5959. if (use < 10.0)
  5960. {
  5961. if (quietSince < 0.0)
  5962. quietSince = now - 0.25;
  5963. if (now - quietSince >= 1.5)
  5964. settledS = quietSince;
  5965. }
  5966. else
  5967. quietSince = -1.0;
  5968. if (settledS >= 0.0 || now - loadedS > 30.0)
  5969. {
  5970. phase = 2;
  5971. idleCpu0 = cpu;
  5972. idleT0 = now;
  5973. }
  5974. return;
  5975. }
  5976. if (now - idleT0 >= (double) idleSeconds)
  5977. finish ("OK");
  5978. }
  5979. };
  5980. perf = std::make_unique<Probe> (*this, openTimeReport, fileToOpen, openTimeIdleSeconds);
  5981. }
  5982. // round 166b: the update check of a normal start (never in --opentime and the other command-line modes), a few
  5983. // seconds after the window is up so it never competes with the start-up; and the result of an update just installed
  5984. void startUpdateCheck()
  5985. {
  5986. if (openTimeReport != juce::File())
  5987. return;
  5988. lynx::updater::afterStart();
  5989. juce::Timer::callAfterDelay (3000, [] { lynx::updater::startAutomaticCheck(); });
  5990. }
  5991. void openStartupFile()
  5992. {
  5993. startupFileHandled = true;
  5994. if (fileToOpen != juce::File() && mainWindow != nullptr)
  5995. {
  5996. if (std::exchange (startWithoutPlugins, false)) // --no-plugins (round 190ap)
  5997. mainWindow->getContent().openNextWithoutPlugins (true);
  5998. mainWindow->openFile (fileToOpen);
  5999. mainWindow->getContent().openNextWithoutPlugins (false); // (a file that did not open leaves nothing behind)
  6000. }
  6001. else if (mainWindow != nullptr && openTimeReport == juce::File())
  6002. mainWindow->getContent().openStartupProject(); // issue #123 (FL's Startup project)
  6003. }
  6004. void shutdown() override
  6005. {
  6006. parityShow.reset(); // (LYNX_PARITYSHOT_SHOW's window, before the engine it shows)
  6007. if (relaunched || updateHelper)
  6008. return; // the copy that ran owns the session (its crash notes stay for the next start)
  6009. lynx::crashguard::note ("closing");
  6010. // round 190rn: with LYNX_TRACE_STARTUP the quit's steps go to startup.log too (where a slow quit's time goes)
  6011. const auto quitMark = [] (const char* step) { if (startupTrace.eachStep) startupTrace.mark (step); };
  6012. quitMark ("quit: starts");
  6013. lynx::shutdownPluginSandboxWorker();
  6014. splash = nullptr;
  6015. lynx::shutdownStemExtraction(); // (a separation in flight stops before its window and the engine go)
  6016. lynx::shutdownAudioToMidi(); // (the same for a conversion to MIDI)
  6017. if (mainWindow != nullptr && mainWindow->isVisible())
  6018. mainWindow->saveState();
  6019. lynx::remoteui::shutdown();
  6020. lynx::closeModalWindows(); // (round 190rf: a call-out box or dialog still open goes before the UI and the engine)
  6021. remoteControl = nullptr; // cancels queued control work before its engine and UI go
  6022. quitMark ("quit: window state saved, remote control closed");
  6023. mainWindow = nullptr; // the UI goes before the engine
  6024. quitMark ("quit: main window deleted");
  6025. graphicsDeviceJob = {}; // (round 190hd: the graphics device's holder, after every window)
  6026. lynx::updater::shutdown(); // (a check or download in flight stops)
  6027. crashEngine = nullptr;
  6028. engine = nullptr;
  6029. quitMark ("quit: engine deleted");
  6030. // separate-process plugins end on threads of their own (issue #159): a moment for them, never the 10 s a dead
  6031. // child's pipe can take
  6032. lynx::finishSandboxTeardowns (2000);
  6033. // CLAP plugins whose instance another thread deleted while this one was busy: deactivated and destroyed now
  6034. lynx::ClapPluginFormat::finishPendingTeardowns();
  6035. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  6036. heartbeat.stopTimer();
  6037. lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
  6038. lynx::crashguard::stopHangWatch();
  6039. lynx::crashguard::stopMainProfiler();
  6040. lynx::crashguard::endSession(); // a clean exit: no breadcrumb left behind
  6041. quitMark ("quit: done");
  6042. // everything is saved and closed: a process that loaded third-party plugins ends here, before the DLLs' own
  6043. // teardown runs (some crash in it at exit, round 111)
  6044. if (sandboxChild || lynx::PluginHost::pluginsWereLoaded())
  6045. lynx::crashguard::exitNow (getApplicationReturnValue());
  6046. }
  6047. void systemRequestedQuit() override
  6048. {
  6049. if (mainWindow != nullptr)
  6050. mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
  6051. else
  6052. quit();
  6053. }
  6054. private:
  6055. // round 157a: a frozen UI (Windows' "not responding") writes the message thread's stack to autosave\hang <time>.txt
  6056. // and a session step, so a freeze can be told apart from a crash and located. The timer is the heartbeat.
  6057. struct Heartbeat final : juce::Timer
  6058. {
  6059. void timerCallback() override { lynx::crashguard::heartbeat(); }
  6060. } heartbeat;
  6061. void startHangWatch()
  6062. {
  6063. const auto folder = lynx::platform::settingsFile ("autosave");
  6064. folder.createDirectory();
  6065. // keep the newest hang files only
  6066. auto old = folder.findChildFiles (juce::File::findFiles, false, "hang *.txt");
  6067. lynx::filesort::byTime (old, lynx::filesort::By::modificationTime, true);
  6068. for (int i = 20; i < old.size(); ++i)
  6069. old.getReference (i).deleteFile();
  6070. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString());
  6071. heartbeat.startTimerHz (5);
  6072. }
  6073. bool sandboxChild = false;
  6074. bool relaunched = false; // relaunchFromAsciiPath ran LYNX from its short path: this process only waited
  6075. bool updateHelper = false; // --apply-update (round 166b)
  6076. juce::String uncleanLastStep; // last step of a previous run that ended without closing
  6077. // LYNX_PROFILE_DIR=<folder> LYNX --lv2scantest report.txt (Linux, issue #85): the LV2 scan's promise, with real child
  6078. // processes. A new PluginHost per step, as every start of LYNX has. The LV2 folders of the machine are read too.
  6079. void runLv2ScanTest (const juce::String& reportPath)
  6080. {
  6081. juce::String report;
  6082. auto ok = lynx::platform::profileOverride() != juce::File();
  6083. #if JUCE_LINUX
  6084. const auto folder = lynx::platform::profileOverride().getChildFile ("lv2-test");
  6085. const juce::FileSearchPath paths (folder.getFullPathName());
  6086. const auto check = [&] (const juce::String& name, bool passed) {
  6087. report << name << "=" << (passed ? "ok" : "FAILED") << "\n";
  6088. ok = ok && passed;
  6089. };
  6090. const auto install = [&] (const juce::String& name) {
  6091. const auto bundle = folder.getChildFile (name + ".lv2");
  6092. bundle.createDirectory();
  6093. bundle.getChildFile ("manifest.ttl").replaceWithText ("@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
  6094. "<urn:lynx-test:" + name + "> a lv2:Plugin ; lv2:binary <" + name + ".so> ; rdfs:seeAlso <plugin.ttl> .\n");
  6095. bundle.getChildFile ("plugin.ttl").replaceWithText ("@prefix doap: <http://usefulinc.com/ns/doap#> .\n<urn:lynx-test:" + name + "> doap:name \"" + name + "\" .\n");
  6096. };
  6097. auto date = juce::Time::getCurrentTime();
  6098. const auto touch = [&] { // the next date, whatever the file system's date resolution
  6099. date += juce::RelativeTime::seconds (2.0);
  6100. folder.getChildFile ("a.lv2/plugin.ttl").setLastModificationTime (date);
  6101. };
  6102. const auto listed = [] (lynx::PluginHost& host, const juce::String& name) {
  6103. for (const auto& d : host.getKnownPlugins().getTypes())
  6104. if (d.fileOrIdentifier == "urn:lynx-test:" + name)
  6105. return true;
  6106. return false;
  6107. };
  6108. const auto step = [&] (const juce::String& name, int children, const std::function<void (lynx::PluginHost&)>& prepare = {}) {
  6109. lynx::PluginHost host (true);
  6110. if (prepare)
  6111. prepare (host);
  6112. host.scan (paths, {});
  6113. check (name, host.scanChildrenStarted() == children && listed (host, "a"));
  6114. };
  6115. install ("a");
  6116. step ("first_scan_one_child", 1);
  6117. step ("nothing_changed_no_child", 0);
  6118. touch();
  6119. step ("ttl_updated", 1);
  6120. install ("b");
  6121. step ("bundle_installed", 1);
  6122. step ("forget_file", 1, [] (lynx::PluginHost& host) { host.forgetFile ("urn:lynx-test:a"); });
  6123. step ("forget_all", 1, [] (lynx::PluginHost& host) { host.forgetAll(); });
  6124. lynx::platform::settingsFile ("plugins.xml").deleteFile();
  6125. step ("list_lost", 1);
  6126. step ("nothing_changed_again", 0);
  6127. // cancelled while the child works: stopped at once, and nothing is taken for done
  6128. touch();
  6129. setenv ("LYNX_TEST_CRASH", "lv2-batch-hang", 1);
  6130. {
  6131. lynx::PluginHost host (true);
  6132. const auto started = juce::Time::getMillisecondCounter();
  6133. host.scan (paths, [] (float, const juce::String&) { return false; });
  6134. check ("cancel_stops_the_child", host.scanChildrenStarted() == 1 && juce::Time::getMillisecondCounter() - started < 20000);
  6135. }
  6136. unsetenv ("LYNX_TEST_CRASH");
  6137. step ("described_after_cancel", 1);
  6138. // the child dies: plugin by plugin takes over (stopped after two of them: a machine may have hundreds)
  6139. touch();
  6140. setenv ("LYNX_TEST_CRASH", "lv2-batch", 1);
  6141. {
  6142. lynx::PluginHost host (true);
  6143. host.scan (paths, [&host] (float, const juce::String&) { return host.scanChildrenStarted() < 3; });
  6144. check ("crash_falls_back_plugin_by_plugin", host.scanChildrenStarted() == 3);
  6145. auto blamed = false;
  6146. for (const auto& file : host.getKnownPlugins().getBlacklistedFiles())
  6147. blamed = blamed || file.startsWith ("lv2-folders:");
  6148. check ("crash_blacklists_nothing", ! blamed);
  6149. }
  6150. unsetenv ("LYNX_TEST_CRASH");
  6151. step ("described_after_crash", 1);
  6152. // round 190fw: past the first limit, a child that still works is waited for (FL Studio's own VST plugin boots
  6153. // the FL engine), one that sits still is killed as before, and a busy one only up to the cap. Limits are
  6154. // shortened for the test: 2 s first limit, 2 s without work, 8 s cap (real: 30 s, 30 s, 5 min).
  6155. setenv ("LYNX_TEST_SCAN_MS", "2000,2000,8000", 1);
  6156. const auto timed = [&] (const char* fault, const std::function<bool (lynx::PluginHost&)>& progress) {
  6157. touch();
  6158. setenv ("LYNX_TEST_CRASH", fault, 1);
  6159. lynx::PluginHost host (true);
  6160. const auto started = juce::Time::getMillisecondCounter();
  6161. host.scan (paths, [&] (float, const juce::String&) { return ! progress || progress (host); });
  6162. unsetenv ("LYNX_TEST_CRASH");
  6163. const auto took = (int) (juce::Time::getMillisecondCounter() - started);
  6164. report << " " << fault << ": " << took << " ms, children " << host.scanChildrenStarted() << "\n";
  6165. return std::make_pair (took, host.scanChildrenStarted());
  6166. };
  6167. // (after a failed batch, one plugin-by-plugin child and no more: it describes quickly)
  6168. const auto stopAfterBatch = [] (lynx::PluginHost& host) { return host.scanChildrenStarted() < 2; };
  6169. {
  6170. const auto [took, children] = timed ("lv2-batch-busy:5000", {});
  6171. check ("busy_child_is_waited_for", children == 1 && took >= 4500);
  6172. }
  6173. {
  6174. const auto [took, children] = timed ("lv2-batch-hang", stopAfterBatch);
  6175. check ("idle_child_ends_near_the_first_limit", children == 2 && took >= 1900 && took < 9000);
  6176. }
  6177. {
  6178. const auto [took, children] = timed ("lv2-batch-busy:60000", stopAfterBatch);
  6179. check ("busy_child_ends_at_the_cap", children == 2 && took >= 7500 && took < 20000);
  6180. }
  6181. unsetenv ("LYNX_TEST_SCAN_MS");
  6182. step ("described_after_slow_children", 1);
  6183. #endif
  6184. juce::File (reportPath).replaceWithText (report + "result=" + (ok ? "OK" : "FAILED") + "\n");
  6185. setApplicationReturnValue (ok ? 0 : 1);
  6186. quit();
  6187. }
  6188. // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
  6189. // Exit code 0 = audio came out, 1 = silence.
  6190. // --selftest (round 190ci): two more copies of LYNX end by a fault on purpose (--faulttest), one on a normal stack
  6191. // (the top-level filter) and one on a stack Windows cannot walk (the first-chance hook); each must leave
  6192. // "crash <time>.txt" with the access violation in the folder it is given.
  6193. // Round 190dt (Linux / macOS): a plain fault, and LYNX's own fault inside a guarded plugin call (in its code, and in
  6194. // the C library called from its code), must each leave the crash file with the signal: the plugin guard passes
  6195. // LYNX's own faults on to the crash handler instead of swallowing them ("swallowed.txt" = it did).
  6196. // Round 190gj (P9): the inserts' stems from one render are the files each stem's own render writes, byte for byte
  6197. // (a short song with a bus, a send return, delay compensation, a channel on the Master, an automated insert and a
  6198. // side-chained insert), streamed (24-bit WAV with the full mix) and buffered (normalised float).
  6199. static juce::String stemsSinglePassSelfTest()
  6200. {
  6201. auto s = lynx::Song::makeDefault();
  6202. s.mixer = lynx::Song::defaultMixer (7);
  6203. for (std::size_t c = 0; c < s.channels.size(); ++c)
  6204. s.channels[c].mixerTrack = (int) c + 1;
  6205. auto onMaster = s.channels[2];
  6206. onMaster.mixerTrack = 0;
  6207. onMaster.pan = -0.4f;
  6208. s.channels.push_back (onMaster);
  6209. for (int step : { 1, 5, 9, 13 })
  6210. s.patterns[0].toggleStep ((int) s.channels.size() - 1, step);
  6211. for (int step : { 4, 12 })
  6212. s.patterns[0].toggleStep (3, step); // the snare
  6213. for (int k = 0; k < 4; ++k) // the synth under the kick (its compressor listens to it)
  6214. s.patterns[0].notes.push_back ({ (std::int64_t) k * lynx::ppq, lynx::ppq - 60, 4, 57 + 3 * k, 0.9f });
  6215. s.patterns[0].sortNotes();
  6216. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  6217. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::compressor));
  6218. s.mixer[2].toMaster = false;
  6219. s.mixer[2].sends = { lynx::MixerSend { 6, 1.0f } };
  6220. s.mixer[3].sends = { lynx::MixerSend { 7, 0.5f } };
  6221. s.mixer[3].latencyMs = 3.0f;
  6222. s.mixer[4].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  6223. s.mixer[4].latencyMs = 5.0f;
  6224. s.mixer[4].sends = { lynx::MixerSend { 6, 0.7f } };
  6225. s.mixer[4].masterLevel = 0.8f;
  6226. auto keyed = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  6227. keyed.params[0] = 0.5f; // (−30 dB: the kick's hits pull the synth down)
  6228. keyed.sidechain = 1;
  6229. s.mixer[5].effects.push_back (keyed);
  6230. s.mixer[6].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::distortion));
  6231. s.mixer[7].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  6232. lynx::Automation a;
  6233. a.target = { lynx::AutomationTargetKind::mixerPan, 3 };
  6234. a.points = { { 0, 0.2f, 0.0f }, { 8 * lynx::ppq, 0.9f, 0.0f } };
  6235. s.automations.push_back (a);
  6236. s.playlist.clear();
  6237. for (int bar = 0; bar < 2; ++bar)
  6238. s.playlist.push_back ({ 0, 0, bar * 4 * lynx::ppq, 4 * lynx::ppq, 0 });
  6239. lynx::Clip automationClip;
  6240. automationClip.kind = lynx::ClipKind::automation;
  6241. automationClip.automation = 0;
  6242. automationClip.length = 8 * lynx::ppq;
  6243. automationClip.track = 1;
  6244. s.playlist.push_back (automationClip);
  6245. s.mode = lynx::PlayMode::song;
  6246. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-stems190gj-" + juce::String (juce::Time::currentTimeMillis()));
  6247. juce::String problems;
  6248. auto run = [&] (lynx::exportopts::Options o, const juce::String& name) {
  6249. o.stems = lynx::exportopts::Stems::mixerTracks;
  6250. o.maxTailSeconds = 3.0;
  6251. const auto alone = dir.getChildFile ("alone"), shared = dir.getChildFile ("shared");
  6252. alone.createDirectory();
  6253. shared.createDirectory();
  6254. const auto ext = juce::String (lynx::exportopts::extension (o.format));
  6255. const auto planAlone = lynx::planStemExport (s, o, alone.getChildFile (name + ext));
  6256. const auto planShared = lynx::planStemExport (s, o, shared.getChildFile (name + ext));
  6257. auto now = [] (std::function<void()> f) { f(); };
  6258. lynx::StemRunStats stats;
  6259. const auto a = lynx::runStemExport (planAlone, now, {}, {}, {}, {}, true);
  6260. const auto b = lynx::runStemExport (planShared, now, {}, {}, {}, {}, false, true, &stats);
  6261. if (a != (int) planAlone.items.size() || b != a)
  6262. problems << name << ": " << a << " / " << b << " files; ";
  6263. // (every insert from the one render, insert 5 with its side-chain too: it stays ducked as in the mix)
  6264. if (stats.passes != 1 || stats.inPass < 6)
  6265. problems << name << ": renders " << stats.passes << " shared, " << stats.inPass << " in it, " << stats.alone << " alone; ";
  6266. for (std::size_t k = 0; k < planShared.items.size() && k < planAlone.items.size(); ++k)
  6267. {
  6268. juce::MemoryBlock x, y;
  6269. planAlone.items[k].file.loadFileAsData (x);
  6270. planShared.items[k].file.loadFileAsData (y);
  6271. if (x.getSize() == 0 || x != y)
  6272. problems << name << ": " << planShared.items[k].file.getFileName() << " differs; ";
  6273. }
  6274. };
  6275. lynx::exportopts::Options streamed;
  6276. streamed.wavBits = 24;
  6277. streamed.stemsIncludeMaster = true;
  6278. run (streamed, "streamed");
  6279. lynx::exportopts::Options buffered;
  6280. buffered.wavBits = 32;
  6281. buffered.normalize = true;
  6282. run (buffered, "buffered");
  6283. dir.deleteRecursively();
  6284. return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems;
  6285. }
  6286. static juce::String faultReportSelfTest()
  6287. {
  6288. #if (JUCE_WINDOWS && (defined (_M_X64) || defined (__x86_64__))) \
  6289. || ((JUCE_LINUX || JUCE_MAC) && (defined (__x86_64__) || defined (__aarch64__)))
  6290. const auto exe = juce::File::getSpecialLocation (juce::File::currentExecutableFile);
  6291. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  6292. .getChildFile ("lynx-faulttest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  6293. juce::StringArray problems;
  6294. // (rollup step 12: + hang = the crash handler's watchdog ends a handler that never returns, within its time limit
  6295. // (3 s here); heap = the C library's heap-corruption abort leaves the allocation-free crash file and no recovered
  6296. // project, at once (before the watchdog: the old handler waited for ever on the allocator's lock); Linux / macOS)
  6297. #if JUCE_WINDOWS
  6298. const char* const kinds[] = { "plain", "unwalkable", "hang" };
  6299. #else
  6300. const char* const kinds[] = { "plain", "guarded", "guarded-libc", "thread", "thread-libc", "hang", "heap" };
  6301. #endif
  6302. for (const auto* kind : kinds)
  6303. {
  6304. const auto folder = root.getChildFile (kind);
  6305. folder.createDirectory();
  6306. const auto watchdogTest = juce::String (kind) == "hang" || juce::String (kind) == "heap";
  6307. #if JUCE_WINDOWS
  6308. _putenv_s ("LYNX_CRASH_WATCHDOG_S", watchdogTest ? "3" : "");
  6309. #else
  6310. if (watchdogTest)
  6311. setenv ("LYNX_CRASH_WATCHDOG_S", "3", 1);
  6312. else
  6313. unsetenv ("LYNX_CRASH_WATCHDOG_S");
  6314. #endif
  6315. juce::ChildProcess child;
  6316. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  6317. const auto started = child.start (juce::StringArray { exe.getFullPathName(), "--faulttest", kind, folder.getFullPathName() }, 0);
  6318. const auto ended = started && child.waitForProcessToFinish (60000);
  6319. const auto seconds = (juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0;
  6320. if (! ended)
  6321. {
  6322. child.kill();
  6323. problems.add (juce::String (kind) + ": " + (started ? "did not end" : "did not start"));
  6324. continue;
  6325. }
  6326. juce::String text;
  6327. for (const auto& file : folder.findChildFiles (juce::File::findFiles, false, "crash *.txt"))
  6328. text = file.loadFileAsString();
  6329. if (watchdogTest)
  6330. {
  6331. const auto recovered = folder.findChildFiles (juce::File::findFiles, false, "recovered *").size();
  6332. if (juce::String (kind) == "hang" && (seconds < 2.5 || seconds > 30.0 || text.isEmpty()))
  6333. problems.add ("hang: ended after " + juce::String (seconds, 1) + " s (the watchdog: 3 s)" + (text.isEmpty() ? ", no crash file" : ""));
  6334. if (juce::String (kind) == "heap" && (seconds > 20.0 || ! text.contains ("heap-corruption abort") || recovered != 0))
  6335. problems.add ("heap: " + juce::String (seconds, 1) + " s, " + (text.isEmpty() ? juce::String ("no crash file") : text.upToFirstOccurrenceOf ("\n", false, false))
  6336. + ", " + juce::String (recovered) + " recovered project(s)");
  6337. continue;
  6338. }
  6339. #if JUCE_WINDOWS
  6340. const auto found = text.contains ("0xc0000005");
  6341. #else
  6342. const auto found = text.contains ("segmentation fault") || text.contains ("bus error");
  6343. #endif
  6344. if (folder.getChildFile ("swallowed.txt").existsAsFile())
  6345. problems.add (juce::String (kind) + ": LYNX's own fault was caught as a plugin's ("
  6346. + folder.getChildFile ("swallowed.txt").loadFileAsString() + ")");
  6347. else if (! found)
  6348. problems.add (juce::String (kind) + ": " + (text.isEmpty() ? "no crash file" : "a crash file without the fault")
  6349. + " (exit code 0x" + juce::String::toHexString ((juce::int64) child.getExitCode()) + ")");
  6350. }
  6351. root.deleteRecursively();
  6352. #if JUCE_WINDOWS
  6353. _putenv_s ("LYNX_CRASH_WATCHDOG_S", "");
  6354. #else
  6355. unsetenv ("LYNX_CRASH_WATCHDOG_S");
  6356. #endif
  6357. return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems.joinIntoString ("; ");
  6358. #else
  6359. return "SKIPPED (Windows x64, Linux / macOS x86-64 / ARM64 only)";
  6360. #endif
  6361. }
  6362. void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
  6363. {
  6364. lynx::AudioEngine offline (false);
  6365. const auto peak = offline.renderOffline (2.0, 48000.0);
  6366. const auto audioOk = peak > 0.01f && peak < 10.0f;
  6367. // round 190qk (core/ExtrasDefaults.h, the owner's policy 11-23): first, before any item switches an option — every
  6368. // 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
  6369. // ui-options.txt keeps what the user changed and takes the new defaults for the rest; a file with the user-set
  6370. // list keeps a choice that differs from the default; the page's two buttons' values
  6371. juce::String extras190qkResult = "OK";
  6372. {
  6373. lynx::SettingsHooks hooks;
  6374. hooks.getGeneral = [] { return lynx::GeneralOptions {}; };
  6375. for (const auto& item : lynx::extras::items)
  6376. {
  6377. const auto now = item.id == "general.stretchedClipsLoop" ? lynx::stretchedClipsLoop()
  6378. : lynx::lynxExtraOn (offline, hooks, item.id);
  6379. if (now != lynx::extras::defaultOn (item.id))
  6380. extras190qkResult = "ERROR default of " + juce::String (std::string (item.id));
  6381. }
  6382. const auto kept = lynx::extras::userSet();
  6383. std::vector<std::string> old { "wheelZones=1", "shadeFadedAudio=0", "hoverValues=0", "escClosesWindows=0", "liveScaleControl=1" };
  6384. lynx::extras::followDefaults (old);
  6385. const std::vector<std::string> expected { "wheelZones=1", "shadeFadedAudio=0", "hoverValues=0", "escClosesWindows=0", "liveScaleControl=1" };
  6386. if (old != expected || lynx::extras::userSet() != std::set<std::string> { "controlBar.liveScale", "general.escCloses", "playlist.wheelZones" })
  6387. extras190qkResult = "ERROR 0.1.31 file";
  6388. std::vector<std::string> mine { "trackInserts=0", "prChordHighlight=0", "extrasUserSet=playlist.trackInserts" };
  6389. lynx::extras::followDefaults (mine);
  6390. if (mine[0] != "trackInserts=0" || mine[1] != "prChordHighlight=1")
  6391. extras190qkResult = "ERROR user-set list";
  6392. if (lynx::extras::noteUserChoices ("\nshadeFadedAudio=0\ntrackInserts=0\nwheelZones=1") != "\nextrasUserSet=playlist.trackInserts,playlist.wheelZones")
  6393. extras190qkResult = "ERROR noting the choices";
  6394. if (! lynx::extras::flExactOn ("general.escCloses") || lynx::extras::flExactOn ("playlist.shadeFadedAudio") || lynx::extras::flExactOn ("general.stretchedClipsLoop"))
  6395. extras190qkResult = "ERROR FL-exact values";
  6396. lynx::extras::userSet() = kept;
  6397. }
  6398. // round 190ro (src/Extras190roShot.inc, no pictures): the defaults it changed, a press on and beside the gain handle
  6399. // that stays in view, the Mixer at FL's height, a new Clip-launch project's strips
  6400. juce::String extras190roResult;
  6401. runExtras190roShot ({}, &extras190roResult);
  6402. // round 190so (src/PlaylistView190soShot.inc, no pictures): pinned tracks, the mixer rows, wide meters, FL's Playlist
  6403. // digits and the marker keys, the toolbar's numbers and second readout, the empty workspace's double click
  6404. juce::String playlistview190soResult;
  6405. runPlaylistView190soShot ({}, {}, &playlistview190soResult);
  6406. // round 190ss (src/Custom190ssShot.inc, no pictures): toolbar presets, pinned actions, the working time panel, widths
  6407. // by hand, the Customize dialog, the linked headers' elements, the keyboard button's middle click
  6408. juce::String custom190ssResult;
  6409. runCustom190ssShot ({}, &custom190ssResult);
  6410. // round 190qx (src/Optionsux190qx.inc): the extras page by area, the Settings options for the palette, tooltips,
  6411. // Reset this page, the window tips, the How-to guides, the notices
  6412. const auto optionsux190qxResult = runOptionsux190qxSelftest (offline);
  6413. // project format round trip, with accents in the name
  6414. auto original = lynx::Song::makeDefault();
  6415. original.channels[0].name = "Bumbo ação";
  6416. original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
  6417. original.mode = lynx::PlayMode::song;
  6418. original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  6419. original.mixer[3].effects[0].params[1] = 0.25f;
  6420. lynx::Automation automation;
  6421. automation.name = "Pan";
  6422. automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
  6423. automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
  6424. original.automations.push_back (automation);
  6425. lynx::Clip automationClip;
  6426. automationClip.kind = lynx::ClipKind::automation;
  6427. automationClip.automation = 0;
  6428. automationClip.track = 4;
  6429. automationClip.length = 3840;
  6430. original.playlist.push_back (automationClip);
  6431. original.loopStart = 960;
  6432. original.loopEnd = 7680;
  6433. original.playlistTracks.resize (3);
  6434. original.playlistTracks[2].colour = 0xFF2A6FDB; // a track colour (round 90)
  6435. { // the clip grid (round 181a)
  6436. lynx::launcher::setClip (original, 1, 2, { 0, 0, 0, 1920, 0 });
  6437. auto& slot = *lynx::launcher::settingsAt (*original.clipGrid, 1, 2);
  6438. slot.name = "Clip ação";
  6439. slot.mode = lynx::LaunchMode::toggle;
  6440. slot.quant = lynx::LaunchQuant::eighthTriplet;
  6441. slot.legato = true;
  6442. slot.loop = false;
  6443. original.clipGrid->scenes[0].name = "Intro";
  6444. original.clipGrid->globalQuant = lynx::LaunchQuant::bars2;
  6445. }
  6446. std::uint32_t savedGroove = 0;
  6447. { // round 190bv: the groove pool, a groove on the slot's clip, and that clip copied and the copy moved
  6448. lynx::Groove g;
  6449. g.name = "Balanço";
  6450. g.base = lynx::GrooveBase::eighth;
  6451. g.quantize = 0.25f;
  6452. g.timing = 0.8f;
  6453. g.random = 0.1f;
  6454. g.velocity = -0.5f;
  6455. g.length = 1920;
  6456. g.points = { { 0, 1.0f }, { 560, 0.5f } };
  6457. savedGroove = lynx::groove::add (original.grooves, g);
  6458. original.grooves.amount = 1.2f;
  6459. lynx::groove::setClipGroove (original, 1, 2, savedGroove);
  6460. lynx::session::moveClip (original, 1, 2, 0, 1, true);
  6461. lynx::session::moveClip (original, 0, 1, 2, 0, false);
  6462. original.playlist[0].groove = savedGroove; // round 190fm: a Playlist pattern clip's groove
  6463. }
  6464. original.playlistTracks[2].grouped = true; // track groups and rack filter groups (round 104)
  6465. original.playlistTracks[1].collapsed = true;
  6466. original.channelGroups = { "Drums", "Keys" };
  6467. original.channels[1].group = 1;
  6468. original.channels[1].cutOthersOnly = original.channels[1].cutAtNoteEnd = true; // FL Studio Mobile's cut rule (round 190fe)
  6469. juce::String error;
  6470. if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
  6471. lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
  6472. const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
  6473. // round 190bw: FL's curve modes of automation points come back from a project, tension whole; a bent point
  6474. // without a mode (a project saved before the modes: [tick, value, tension]) keeps LYNX's older law
  6475. const auto curveModesOk = [&original] {
  6476. auto song = original;
  6477. auto& a = song.automations[0];
  6478. a.points = { { 0, 0.25f, 0.5f, (std::uint8_t) lynx::flcurve::stairs },
  6479. { 960, 1.0f, -0.123456f, (std::uint8_t) lynx::flcurve::smooth },
  6480. { 1920, 0.5f, 0.0f, (std::uint8_t) lynx::flcurve::hold },
  6481. { 2400, 0.75f, 0.7f, lynx::AutomationPoint::legacyCurve },
  6482. { 2880, 0.3f, 0.0f, 0 },
  6483. { 3840, 0.6f, 0.0f, 0 } };
  6484. a.lfo.on = true;
  6485. a.lfo.amp = { { 0, 1.0f, -0.25f, (std::uint8_t) lynx::flcurve::pulse }, { 960, 0.5f, 0.0f, 0 } };
  6486. juce::String e;
  6487. const auto text = lynx::ProjectFile::toJson (song);
  6488. const auto back = lynx::ProjectFile::fromJson (text, e);
  6489. return back && back->automations.size() == 1 && back->automations[0].points == a.points && back->automations[0].lfo.amp == a.lfo.amp
  6490. && back->automations[0].valueAt (700.0) == a.valueAt (700.0) && back->automations[0].valueAt (2600.0) == a.valueAt (2600.0);
  6491. }();
  6492. const auto projectOk = curveModesOk && reloaded && reloaded->channels.size() == original.channels.size()
  6493. && reloaded->channels[0].name == original.channels[0].name
  6494. && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
  6495. && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
  6496. && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
  6497. && reloaded->clipGrid.has_value() && reloaded->clipGrid->globalQuant == lynx::LaunchQuant::bars2
  6498. && reloaded->clipGrid->scenes.size() == 3 && reloaded->clipGrid->scenes[0].name == "Intro"
  6499. && lynx::launcher::clipAt (*reloaded->clipGrid, 1, 2) != nullptr
  6500. && [&reloaded] {
  6501. auto grid = *reloaded->clipGrid;
  6502. const auto* slot = lynx::launcher::settingsAt (grid, 1, 2);
  6503. return slot != nullptr && slot->name == "Clip ação" && slot->mode == lynx::LaunchMode::toggle
  6504. && slot->quant == lynx::LaunchQuant::eighthTriplet && slot->legato && ! slot->loop;
  6505. }()
  6506. && [&reloaded, &original, savedGroove] { // round 190bv
  6507. auto grid = *reloaded->clipGrid;
  6508. const auto* kept = lynx::launcher::settingsAt (grid, 1, 2);
  6509. const auto* moved = lynx::launcher::settingsAt (grid, 2, 0);
  6510. const auto* clip = lynx::launcher::clipAt (grid, 2, 0);
  6511. return reloaded->grooves == original.grooves && reloaded->grooves.grooves.size() == 1
  6512. && reloaded->grooves.amount == 1.2f && reloaded->grooves.grooves[0].name == "Balanço"
  6513. && reloaded->grooves.grooves[0].points.size() == 2 && savedGroove != 0
  6514. && kept != nullptr && kept->groove == savedGroove
  6515. && lynx::launcher::clipAt (grid, 0, 1) == nullptr
  6516. && clip != nullptr && clip->pattern == 0 && clip->length == 1920
  6517. && moved != nullptr && moved->groove == savedGroove && moved->name == "Clip ação"
  6518. && moved->mode == lynx::LaunchMode::toggle && moved->legato && ! moved->loop
  6519. && reloaded->playlist[0].groove == savedGroove && reloaded->playlist[1].groove == 0; // (190fm)
  6520. }()
  6521. && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
  6522. && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
  6523. && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
  6524. && reloaded->automations[0].points[1].tick == 3840
  6525. && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
  6526. && reloaded->playlistTracks.size() == 3 && reloaded->playlistTracks[2].colour == 0xFF2A6FDB
  6527. && reloaded->playlistTracks[1].colour == 0
  6528. && reloaded->playlistTracks[2].grouped && reloaded->playlistTracks[1].collapsed && ! reloaded->playlistTracks[1].grouped
  6529. && reloaded->channelGroups == original.channelGroups && reloaded->channels[1].group == 1 && reloaded->channels[0].group == -1
  6530. && reloaded->channels[1].cutOthersOnly && reloaded->channels[1].cutAtNoteEnd && ! reloaded->channels[0].cutOthersOnly
  6531. && ! reloaded->channels[0].cutAtNoteEnd
  6532. && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
  6533. && reloaded->mixer[3].effects.size() == 1
  6534. && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
  6535. && reloaded->mixer[3].effects[0].params[1] == 0.25f;
  6536. // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
  6537. auto rich = lynx::Song::makeDefault();
  6538. auto& synth = rich.channels[4].synth;
  6539. synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
  6540. synth.filterType = 2;
  6541. synth.mono = true;
  6542. synth.portaBeats = 0.125f;
  6543. synth.am = true;
  6544. synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
  6545. synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
  6546. auto& sampler = rich.channels[0].sampler;
  6547. sampler.cutoff = 1200.0f;
  6548. sampler.resonance = 0.3f;
  6549. sampler.filterType = 1;
  6550. sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
  6551. sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
  6552. rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
  6553. rich.mixer[2].eq.hz[1] = 2200.0f;
  6554. auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  6555. peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
  6556. peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
  6557. rich.mixer[2].effects.push_back (peqSlot);
  6558. auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
  6559. utilitySlot.params[1] = 0.2f;
  6560. rich.mixer[2].effects.push_back (utilitySlot);
  6561. auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
  6562. for (int i = 0; i < 300; ++i)
  6563. vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
  6564. vocodexSlot.sidechain = 1;
  6565. vocodexSlot.sidechain2 = 2;
  6566. rich.mixer[3].effects.push_back (vocodexSlot);
  6567. rich.addMarker ({ 3840, "Refrão", 0, 4 });
  6568. rich.addMarker ({ 7680, {}, 7, 8 });
  6569. const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
  6570. auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
  6571. for (std::size_t i = 0; i < a.size(); ++i)
  6572. if (std::abs (a[i] - b[i]) > 1.0e-3f)
  6573. return false;
  6574. return true;
  6575. };
  6576. // round 190bu: a one-knob effect, the chain's Blend and its preset name travel in the project; a project without
  6577. // them reads as before (no goal, Blend 100 %) and writes none of the new keys
  6578. bool fx190buOk = false;
  6579. {
  6580. auto song = lynx::Song::makeDefault();
  6581. const auto plainJson = lynx::ProjectFile::toJson (song);
  6582. const auto* preset = lynx::chains::find ("Whisper Air");
  6583. if (preset != nullptr && song.mixer.size() > 2)
  6584. {
  6585. lynx::chains::apply (song, 1, *preset);
  6586. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::room, 0.62f));
  6587. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::bass, 0.3f));
  6588. song.mixer[2].chainBlend = 0.4f;
  6589. const auto json = lynx::ProjectFile::toJson (song);
  6590. const auto back = lynx::ProjectFile::fromJson (json, error);
  6591. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  6592. auto same = back && back->mixer.size() == song.mixer.size();
  6593. for (std::size_t t = 1; same && t <= 2; ++t)
  6594. {
  6595. const auto& a = song.mixer[t];
  6596. const auto& b = back->mixer[t];
  6597. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  6598. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  6599. same = a.effects[i].kind == b.effects[i].kind && a.effects[i].goal == b.effects[i].goal
  6600. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f && a.effects[i].row == b.effects[i].row
  6601. && lynx::goals::active (b.effects[i]) == lynx::goals::active (a.effects[i]);
  6602. }
  6603. fx190buOk = same && lynx::chains::unchanged (*back, 1) && back->mixer[2].chainPreset.empty()
  6604. && ! plainJson.contains ("\"goal\"") && ! plainJson.contains ("chainBlend") && ! plainJson.contains ("chainPreset")
  6605. && json.contains ("\"goalAmount\"") && plainBack && plainBack->mixer[1].chainBlend == 1.0f
  6606. && lynx::ProjectFile::toJson (*back) == json;
  6607. // a user's chain preset file: the slots, Blend and name come back; the strip's level is not part of it
  6608. song.mixer[2].volume = 0.31f;
  6609. const auto file = lynx::ProjectFile::mixerTrackStateToJson (lynx::chains::stateOf (song.mixer[2], "Mine"));
  6610. const auto state = lynx::ProjectFile::mixerTrackStateFromJson (file, error);
  6611. fx190buOk = fx190buOk && state && state->effects.size() == 2 && state->effects[0].goal == lynx::goals::room
  6612. && lynx::goals::active (state->effects[1]) && std::abs (state->chainBlend - 0.4f) < 1.0e-6f && state->chainPreset == "Mine"
  6613. && state->volume == lynx::MixerTrack().volume;
  6614. }
  6615. }
  6616. const auto richOk = fx190buOk && richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
  6617. && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
  6618. && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
  6619. && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
  6620. && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
  6621. && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
  6622. && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
  6623. && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
  6624. && richBack->markers() == rich.markers();
  6625. // issue #96's per-plugin option: saved only when on; old projects (no field) read as off
  6626. bool hostKeysOk = false;
  6627. {
  6628. auto song = lynx::Song::makeDefault();
  6629. lynx::ChannelDef plugin;
  6630. plugin.instrument = lynx::InstrumentKind::plugin;
  6631. plugin.plugin.id = "x";
  6632. song.channels.push_back (plugin);
  6633. const auto channel = song.channels.size() - 1;
  6634. const auto off = lynx::ProjectFile::toJson (song);
  6635. song.channels[channel].plugin.allowHostKeys = true;
  6636. song.channels[channel].plugin.hostKeysFirst = true;
  6637. song.channels[channel].plugin.pinned = true; // (round 190ao: Pin on top)
  6638. song.channels[channel].plugin.velocityMode = lynx::prefs::pluginVelocityFixed; // (round 190ao: the plugin's own velocity)
  6639. song.channels[channel].plugin.fixedVelocity = 64;
  6640. const auto on = lynx::ProjectFile::toJson (song);
  6641. const auto offBack = lynx::ProjectFile::fromJson (off, error);
  6642. const auto onBack = lynx::ProjectFile::fromJson (on, error);
  6643. hostKeysOk = ! off.contains ("allowHostKeys") && on.contains ("allowHostKeys") && offBack && onBack
  6644. && ! offBack->channels[channel].plugin.allowHostKeys && onBack->channels[channel].plugin.allowHostKeys
  6645. && ! off.contains ("hostKeysFirst") && ! offBack->channels[channel].plugin.hostKeysFirst && onBack->channels[channel].plugin.hostKeysFirst
  6646. && ! off.contains ("pinnedOnTop") && ! offBack->channels[channel].plugin.pinned && onBack->channels[channel].plugin.pinned
  6647. && ! off.contains ("velocityMode") && ! off.contains ("fixedVelocity") && offBack->channels[channel].plugin.velocityMode == 0
  6648. && offBack->channels[channel].plugin.fixedVelocity == lynx::prefs::defaultFixedVelocity
  6649. && onBack->channels[channel].plugin.velocityMode == lynx::prefs::pluginVelocityFixed && onBack->channels[channel].plugin.fixedVelocity == 64;
  6650. }
  6651. // round 190ad: a new project has FL's plugin levels and keeps them through a save; a project saved before
  6652. // (no "pluginLevels") reads as LYNX's own law, and stays so when it opens
  6653. bool pluginLevelsOk = false;
  6654. {
  6655. const auto fresh = lynx::makeNewProject();
  6656. const auto saved = lynx::ProjectFile::toJson (fresh);
  6657. const auto back = lynx::ProjectFile::fromJson (saved, error);
  6658. auto old = lynx::Song::makeDefault(); // (what every earlier version made)
  6659. const auto oldSaved = lynx::ProjectFile::toJson (old);
  6660. const auto oldBack = lynx::ProjectFile::fromJson (oldSaved, error);
  6661. const auto stripped = lynx::ProjectFile::fromJson (saved.replace ("\"pluginLevels\"", "\"pluginLevelsGone\""), error);
  6662. pluginLevelsOk = fresh.flPluginLevels && saved.contains ("\"pluginLevels\"") && back && back->flPluginLevels
  6663. && ! old.flPluginLevels && ! oldSaved.contains ("pluginLevels") && oldBack && ! oldBack->flPluginLevels
  6664. && stripped && ! stripped->flPluginLevels;
  6665. }
  6666. // hardware output targets (REA round 156): saved only when set; old projects (no field) keep the defaults
  6667. bool hwOutOk = false;
  6668. {
  6669. auto song = lynx::Song::makeDefault();
  6670. const auto plain = lynx::ProjectFile::toJson (song);
  6671. song.mixer[0].outputChannel = lynx::outputNone;
  6672. song.mixer[1].outputChannel = 2;
  6673. song.mixer[1].outputMode = lynx::OutputMode::monoRight;
  6674. song.mixer[2].outputChannel = 6;
  6675. song.mixer[3].outputChannel = 4;
  6676. song.mixer[3].outputMode = lynx::OutputMode::monoSum;
  6677. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  6678. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  6679. hwOutOk = back && back->mixer[0].outputChannel == lynx::outputNone && back->mixer[1].outputChannel == 2
  6680. && back->mixer[1].outputMode == lynx::OutputMode::monoRight && back->mixer[2].outputChannel == 6
  6681. && back->mixer[2].outputMode == lynx::OutputMode::stereo && back->mixer[3].outputMode == lynx::OutputMode::monoSum
  6682. && back->mixer[4].outputChannel == lynx::outputDefault && ! plain.contains ("\"output\"") && plainBack
  6683. && plainBack->mixer[0].outputChannel == lynx::outputDefault && plainBack->mixer[1].outputChannel == lynx::outputDefault;
  6684. }
  6685. // round 168j: FL's icons (channel / mixer track / playlist track), PDC Automatic / Compensate automations, Time
  6686. // settings, scale highlighting and data folder — saved only when set, old projects load with FL's defaults
  6687. bool flp168jOk = false;
  6688. {
  6689. auto song = lynx::Song::makeDefault();
  6690. const auto plain = lynx::ProjectFile::toJson (song);
  6691. song.channels[0].icon = 75;
  6692. song.mixer[2].icon = 71;
  6693. song.playlistTracks.resize (3);
  6694. song.playlistTracks[2].icon = 30;
  6695. song.autoPdc = false;
  6696. song.compensateAutomations = false;
  6697. song.timeSignatureMode = true;
  6698. song.scaleHighlight = { 10, 5 };
  6699. song.dataFolder = "D:\\Projects\\data";
  6700. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  6701. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  6702. flp168jOk = back && back->channels[0].icon == 75 && back->mixer[2].icon == 71 && back->playlistTracks.size() >= 3
  6703. && back->playlistTracks[2].icon == 30 && ! back->autoPdc && ! back->compensateAutomations && back->timeSignatureMode
  6704. && back->scaleHighlight == song.scaleHighlight && back->dataFolder == song.dataFolder && plainBack && plainBack->autoPdc
  6705. && plainBack->compensateAutomations && ! plainBack->timeSignatureMode && plainBack->scaleHighlight == lynx::Song::ScaleHighlight {}
  6706. && plainBack->dataFolder.empty() && plainBack->channels[0].icon == 0 && ! plain.contains ("\"icon\"")
  6707. && ! plain.contains ("autoPdc") && ! plain.contains ("scaleHighlight");
  6708. }
  6709. // round 180d: clip fades take FL's S curve; a project saved before that keeps its straight fades, also after another
  6710. // save, and a clip made in it takes the S curve. FL's fade tensions and stretch mode and PITCH survive a save.
  6711. // issue #122: playlist tracks linked to inserts (audio) and channels (instrument) survive save, load and save
  6712. // again byte for byte (they were read before the mixer and fell back to Unassigned)
  6713. bool trackModes122Ok = false;
  6714. {
  6715. auto song = lynx::Song::makeDefault();
  6716. song.playlistTracks.resize (6);
  6717. song.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  6718. song.playlistTracks[1].mixerTrack = 3;
  6719. song.playlistTracks[4].mode = lynx::PlaylistTrackMode::audio;
  6720. song.playlistTracks[4].mixerTrack = (int) song.mixer.size() - 1;
  6721. song.playlistTracks[5].mode = lynx::PlaylistTrackMode::instrument;
  6722. song.playlistTracks[5].channel = 1;
  6723. song.playlistTracks[5].mixerTrack = 2;
  6724. const auto json = lynx::ProjectFile::toJson (song, false);
  6725. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  6726. const auto again = loaded ? lynx::ProjectFile::toJson (*loaded, false) : juce::String();
  6727. trackModes122Ok = loaded && json.contains ("playlistTrackModes") && again == json && loaded->playlistTracks.size() >= 6
  6728. && loaded->playlistTracks[1].mode == lynx::PlaylistTrackMode::audio && loaded->playlistTracks[1].mixerTrack == 3
  6729. && loaded->playlistTracks[4].mode == lynx::PlaylistTrackMode::audio
  6730. && loaded->playlistTracks[4].mixerTrack == (int) song.mixer.size() - 1
  6731. && loaded->playlistTracks[5].mode == lynx::PlaylistTrackMode::instrument && loaded->playlistTracks[5].channel == 1;
  6732. }
  6733. bool clipFades180dOk = false;
  6734. {
  6735. auto song = lynx::Song::makeDefault();
  6736. lynx::Clip faded;
  6737. faded.kind = lynx::ClipKind::audio;
  6738. faded.channel = 0;
  6739. faded.length = lynx::ppq * 8;
  6740. faded.fadeIn = lynx::ppq;
  6741. faded.fadeOutTension = -812.933f;
  6742. faded.fadeOut = lynx::ppq * 2;
  6743. lynx::Clip plainClip = faded;
  6744. plainClip.fadeIn = plainClip.fadeOut = 0;
  6745. plainClip.fadeOutTension = 0.0f;
  6746. plainClip.start = lynx::ppq * 16;
  6747. song.playlist = { faded, plainClip };
  6748. song.channels[0].sampler.flStretchMode = 5;
  6749. song.channels[0].sampler.flStretchPitch = 247;
  6750. const auto json = lynx::ProjectFile::toJson (song);
  6751. const auto current = lynx::ProjectFile::fromJson (json, error);
  6752. const auto oldJson = json.replace ("\"clipFadesPerClip\"", "\"clipFadesOther\"");
  6753. auto old = lynx::ProjectFile::fromJson (oldJson, error);
  6754. auto resaved = old;
  6755. if (resaved)
  6756. {
  6757. auto added = faded;
  6758. added.start = lynx::ppq * 32;
  6759. added.linearFades = 0;
  6760. resaved->playlist.push_back (added);
  6761. resaved = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*resaved), error);
  6762. }
  6763. clipFades180dOk = current && old && resaved && json.contains ("clipFadesPerClip") && ! oldJson.contains ("clipFadesPerClip")
  6764. && current->playlist.size() == 2 && ! current->playlist[0].linearFades
  6765. && current->playlist[0].fadeOutTension == -812.933f && ! current->playlist[1].linearFades
  6766. && current->channels[0].sampler.flStretchMode == 5 && current->channels[0].sampler.flStretchPitch == 247
  6767. && old->playlist.size() == 2 && old->playlist[0].linearFades && ! old->playlist[1].linearFades
  6768. && resaved->playlist.size() == 3 && resaved->playlist[0].linearFades && ! resaved->playlist[1].linearFades
  6769. && ! resaved->playlist[2].linearFades && resaved->playlist[0].fadeOutTension == -812.933f;
  6770. }
  6771. // FL's legacy Pattern Blocks (round 170f): the option and every arrangement's blocks are saved; a project without
  6772. // them has neither in its file and loads with the option off
  6773. bool blocksOk = false;
  6774. {
  6775. auto song = lynx::Song::makeDefault();
  6776. const auto plain = lynx::ProjectFile::toJson (song);
  6777. song.patternBlocksOn = true;
  6778. lynx::patternblocks::place (song, 0, 0);
  6779. lynx::patternblocks::place (song, 0, 4 * 4 * lynx::ppq);
  6780. lynx::patternblocks::setMuted (song, 1, true); // (round 190ht, issue #127: a muted block keeps its mute)
  6781. song.addArrangement ("Second");
  6782. lynx::patternblocks::place (song, 0, 2 * 4 * lynx::ppq);
  6783. song.selectArrangement (0);
  6784. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  6785. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  6786. blocksOk = back && back->patternBlocksOn && back->blocks == song.blocks && song.blocks.size() == 2 && back->blocks[1].muted
  6787. && back->arrangements.size() == 2 && back->arrangements[1].blocks == song.arrangements[1].blocks
  6788. && song.arrangements[1].blocks.size() == 1 && back->songLength() == song.songLength() && plainBack
  6789. && ! plainBack->patternBlocksOn && plainBack->blocks.empty() && ! plain.contains ("blocks")
  6790. && ! plain.contains ("patternBlocks");
  6791. }
  6792. // FL's pattern clip takeover (issue #158): saved when on; a project saved before it (no key) loads with it off and
  6793. // keeps playing every overlapping clip of a pattern in full; new projects have it on
  6794. bool takeoverOk = false;
  6795. {
  6796. auto song = lynx::Song::makeDefault();
  6797. const auto plain = lynx::ProjectFile::toJson (song);
  6798. song.patternClipTakeover = true;
  6799. const auto json = lynx::ProjectFile::toJson (song);
  6800. const auto back = lynx::ProjectFile::fromJson (json, error);
  6801. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  6802. takeoverOk = back && back->patternClipTakeover && json.contains ("patternClipTakeover") && plainBack
  6803. && ! plainBack->patternClipTakeover && ! plain.contains ("patternClipTakeover")
  6804. && lynx::makeNewProject().patternClipTakeover;
  6805. }
  6806. // comping (round 177c): a comp's equal-power crossfades (Clip::fadeCurve) and the crossfade length are saved; a
  6807. // project without them has neither in its file
  6808. bool compOk = false;
  6809. {
  6810. auto song = lynx::Song::makeDefault();
  6811. const auto plain = lynx::ProjectFile::toJson (song);
  6812. lynx::ChannelDef take;
  6813. take.instrument = lynx::InstrumentKind::audioClip;
  6814. take.samplePath = "take.wav";
  6815. song.channels.push_back (take);
  6816. lynx::Clip a;
  6817. a.kind = lynx::ClipKind::audio;
  6818. a.channel = (int) song.channels.size() - 1;
  6819. a.length = lynx::ppq;
  6820. a.fadeOut = 20;
  6821. a.fadeCurve = 2;
  6822. auto b = a;
  6823. b.start = lynx::ppq - 20;
  6824. b.fadeOut = 0;
  6825. b.fadeIn = 20;
  6826. b.fadeCurve = 1;
  6827. // round 180d's FL fade fields (indices 17..20) and the comp curve (index 21) on one clip, all kept
  6828. auto c = a;
  6829. c.start = 4 * lynx::ppq;
  6830. c.fadeIn = 30;
  6831. c.fadeInTension = -0.75f;
  6832. c.fadeOutTension = 0.5f;
  6833. c.linearFades = 2;
  6834. c.flFadeFlags = 0x1234u;
  6835. c.fadeCurve = 3;
  6836. song.playlist = { a, b, c };
  6837. song.compCrossfadeMs = 12.5f;
  6838. song.playlistTracks.resize (2);
  6839. song.playlistTracks[0].compTrack = true;
  6840. song.playlistTracks[1].grouped = true;
  6841. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  6842. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  6843. const auto* both = back && back->playlist.size() == 3 ? &back->playlist[2] : nullptr;
  6844. compOk = back && back->playlist.size() == 3 && back->playlist[0].fadeCurve == 2 && back->playlist[1].fadeCurve == 1
  6845. && both != nullptr && both->fadeCurve == 3 && both->fadeInTension == -0.75f && both->fadeOutTension == 0.5f
  6846. && both->linearFades == 2 && both->flFadeFlags == 0x1234u && both->fadeIn == 30
  6847. && back->playlist[1].fadeIn == 20 && back->compCrossfadeMs == 12.5f && back->playlistTracks[0].compTrack && ! back->playlistTracks[1].compTrack && plainBack
  6848. && plainBack->compCrossfadeMs == lynx::Song::defaultCompCrossfadeMs && ! plain.contains ("compCrossfadeMs") && ! plain.contains ("playlistCompTracks");
  6849. }
  6850. // Misc › Mono / Porta / Slide on every generator (round 168l): kept in the file; a project saved before (an
  6851. // imported engine's flags in its synth settings) gets them back, a Max polyphony of 1 is not Mono
  6852. bool polyOk = false;
  6853. {
  6854. auto song = lynx::Song::makeDefault();
  6855. lynx::ChannelDef osc;
  6856. osc.instrument = lynx::InstrumentKind::threeosc;
  6857. osc.misc.mono = osc.misc.porta = true;
  6858. osc.misc.portaBeats = 0.25f;
  6859. song.channels.push_back (osc);
  6860. auto old = osc;
  6861. old.misc = {};
  6862. old.synth.mono = old.synth.porta = true;
  6863. old.synth.portaBeats = 0.5f;
  6864. song.channels.push_back (old);
  6865. old.maxPolyphony = 1;
  6866. song.channels.push_back (old);
  6867. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  6868. const auto n = song.channels.size();
  6869. polyOk = back && back->channels.size() == n && back->channels[n - 3].misc.mono && back->channels[n - 3].misc.porta
  6870. && std::abs (back->channels[n - 3].misc.portaBeats - 0.25f) < 1e-6f && back->channels[n - 2].misc.mono
  6871. && back->channels[n - 2].misc.porta && std::abs (back->channels[n - 2].misc.portaBeats - 0.5f) < 1e-6f
  6872. && ! back->channels[n - 1].misc.mono && back->channels[n - 1].maxPolyphony == 1
  6873. && ! back->channels[4].misc.mono; // (the LYNX Synth keeps its own flags)
  6874. }
  6875. // FL's track latency (REA round 165f-mixer): manual ms, bypass mode and master compensation saved only when set
  6876. bool latencyOk = false;
  6877. {
  6878. auto song = lynx::Song::makeDefault();
  6879. const auto plain = lynx::ProjectFile::toJson (song);
  6880. song.mixer[1].latencyMs = -20.0f;
  6881. song.mixer[2].latencyMs = 12.5f;
  6882. song.mixer[2].latencyBypass = lynx::LatencyBypass::always;
  6883. song.mixer[3].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  6884. song.mixer[3].compensateMasterLatency = false;
  6885. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  6886. latencyOk = back && back->mixer[1].latencyMs == -20.0f && back->mixer[2].latencyMs == 12.5f
  6887. && back->mixer[2].latencyBypass == lynx::LatencyBypass::always
  6888. && back->mixer[3].latencyBypass == lynx::LatencyBypass::whenRecordingOrStopped && ! back->mixer[3].compensateMasterLatency
  6889. && back->mixer[4].latencyMs == 0.0f && back->mixer[4].compensateMasterLatency
  6890. && ! plain.contains ("latencyMs") && ! plain.contains ("latencyBypass") && ! plain.contains ("compensateMaster");
  6891. }
  6892. // LYNX's pre-fader sends (round 190aq): saved only when one is used, in a list of its own ("preSends") that a
  6893. // version from before ignores (its sends then play post-fader, as FL's)
  6894. bool preSendOk = false;
  6895. {
  6896. auto song = lynx::Song::makeDefault();
  6897. song.setRoute (1, 3, true, 0.5f);
  6898. song.setRoute (1, 4, true);
  6899. song.setRoute (2, 3, true);
  6900. const auto plain = lynx::ProjectFile::toJson (song);
  6901. song.setSendPre (1, 3, true);
  6902. const auto json = lynx::ProjectFile::toJson (song);
  6903. const auto back = lynx::ProjectFile::fromJson (json, error);
  6904. preSendOk = back && back->sendPre (1, 3) && ! back->sendPre (1, 4) && ! back->sendPre (2, 3)
  6905. && std::abs (back->routeLevel (1, 3) - 0.5f) < 1.0e-4f && back->mixer[1].sends == song.mixer[1].sends
  6906. && ! plain.contains ("preSends") && json.contains ("preSends")
  6907. && json.replace ("\"preSends\"", "\"preSendsOld\"") != json;
  6908. // the same file without the list (what an older version reads): the sends are there, post-fader
  6909. if (const auto old = lynx::ProjectFile::fromJson (json.replace ("\"preSends\"", "\"unknownToOldVersions\""), error))
  6910. preSendOk = preSendOk && old->routes (1, 3) && ! old->sendPre (1, 3) && old->mixer[1].sends.size() == 2;
  6911. else
  6912. preSendOk = false;
  6913. }
  6914. // LYNX's "Low latency while recording" (round 190aq): a latency-adding effect on a monitored insert's path is
  6915. // bypassed in the engine only — PDC drops, the slot is marked, the song and the saved project stay as they are —
  6916. // and it is back when the option goes off
  6917. bool lowLatencyOk = false;
  6918. {
  6919. lynx::AudioEngine live (false);
  6920. live.editSong ([] (lynx::Song& s) {
  6921. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter)); // 1.5 ms look-ahead
  6922. s.mixer[1].inputChannel = 0;
  6923. s.mixer[1].monitor = lynx::InputMonitor::on;
  6924. });
  6925. const auto before = live.getLatencySamples();
  6926. const auto saved = lynx::ProjectFile::toJson (live.getSong());
  6927. const auto idle = live.lowLatencyBypassedCount() == 0; // the option is off: nothing is bypassed
  6928. auto o = live.getRecordOptions();
  6929. o.lowLatencyRecording = true;
  6930. live.setRecordOptions (o);
  6931. const auto during = live.getLatencySamples();
  6932. const auto marked = live.isSlotLowLatencyBypassed (1, 0) && live.lowLatencyBypassedLatency (1, 0) > 0 && live.lowLatencyBypassedCount() >= 1;
  6933. const auto untouched = live.getSong().mixer[1].effects[0].enabled && lynx::ProjectFile::toJson (live.getSong()) == saved;
  6934. // monitoring leaves "On" (nothing armed): the effect returns
  6935. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::whenArmed; });
  6936. const auto released = live.getLatencySamples() == before && ! live.isSlotLowLatencyBypassed (1, 0);
  6937. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::on; });
  6938. const auto again = live.getLatencySamples() == during && live.isSlotLowLatencyBypassed (1, 0);
  6939. o.lowLatencyRecording = false;
  6940. live.setRecordOptions (o);
  6941. lowLatencyOk = before > 0 && idle && during < before && marked && untouched && released && again
  6942. && live.getLatencySamples() == before && live.lowLatencyBypassedCount() == 0;
  6943. }
  6944. // The Browser's "Preview in time" (round 190aq): a loop whose name gives its tempo is stretched to the project's
  6945. // and starts on the beat; a one-shot plays as it always did; off, nothing changes
  6946. bool previewInTimeOk = false;
  6947. double previewPrepareMs = 0.0;
  6948. {
  6949. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-preview");
  6950. dir.deleteRecursively();
  6951. dir.createDirectory();
  6952. auto writeWav = [&dir] (const juce::String& name, int frames, bool loop) {
  6953. const auto wav = dir.getChildFile (name);
  6954. juce::WavAudioFormat format;
  6955. juce::AudioBuffer<float> audio (1, frames);
  6956. for (int i = 0; i < frames; ++i) // a click on every beat of 120 BPM over a tone, or a decaying hit
  6957. audio.setSample (0, i, loop ? (i % 24000 < 400 ? 0.8f : 0.0f) + 0.1f * std::sin (0.02f * (float) i)
  6958. : 0.6f * std::exp (-(float) i / 2000.0f) * std::sin (0.05f * (float) i));
  6959. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  6960. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  6961. {
  6962. out.release();
  6963. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  6964. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  6965. }
  6966. return wav;
  6967. };
  6968. const auto loop = writeWav ("selftest loop 120 bpm.wav", 96000, true); // 4 beats at 120 BPM
  6969. const auto hit = writeWav ("selftest hit.wav", 14400, false); // 0.3 s
  6970. lynx::AudioEngine player (false);
  6971. const auto projectBpm = player.getTransport().bpm.load();
  6972. // off (FL's preview): nothing is prepared, the file plays as it is
  6973. player.previewFile (loop);
  6974. const auto offOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  6975. player.setPreviewInTime (true);
  6976. player.previewFile (hit); // a one-shot: as it always played, at once
  6977. const auto hitOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  6978. player.previewFile (loop);
  6979. const auto queued = player.getPreviewTiming().pending || std::abs (projectBpm - 120.0) < 0.2;
  6980. player.finishPreviewJobs();
  6981. const auto timing = player.getPreviewTiming();
  6982. previewPrepareMs = player.getLastPreviewPrepareMs();
  6983. const auto wanted = lynx::previewtempo::stretchRatio (120.0, projectBpm);
  6984. const auto stretchedOk = timing.inTime && ! timing.pending && timing.source == lynx::previewtempo::Source::name
  6985. && std::abs (timing.fileBpm - 120.0) < 1.0e-9 && std::abs (timing.ratio - wanted) < 1.0e-12
  6986. && std::abs ((double) timing.frames - 96000.0 * wanted) < 96000.0 * 0.01;
  6987. // the second click on the same file has its stretch ready
  6988. player.previewFile (loop);
  6989. const auto cachedOk = ! player.getPreviewTiming().pending && player.getPreviewTiming().inTime && player.getPreviewTiming().frames == timing.frames;
  6990. player.previewFile ({});
  6991. const auto stoppedOk = ! player.getPreviewTiming().inTime && player.getPreviewInTimeProgress() < 0.0;
  6992. // the start: on the next heard beat while the transport plays (sample exact), at once when it is stopped
  6993. auto firstSample = [] (bool playing, double startTick, int latency) {
  6994. lynx::Transport transport;
  6995. transport.sampleRate.store (48000.0);
  6996. transport.bpm.store (120.0); // 0.04 ticks per sample
  6997. transport.playing.store (playing);
  6998. transport.positionTicks.store (startTick);
  6999. lynx::PreviewPlayer p;
  7000. p.prepareToPlay (48000.0, 512);
  7001. p.setTransport (&transport);
  7002. p.setSyncLatency (latency);
  7003. auto dc = std::make_shared<lynx::SampleData>();
  7004. dc->sampleRate = 48000.0;
  7005. dc->left.assign (48000, 0.5f);
  7006. p.playBrowser (dc, 1.0f, true);
  7007. juce::AudioBuffer<float> block (2, 512);
  7008. juce::MidiBuffer midi;
  7009. for (int done = 0; done < 48000; done += 512)
  7010. {
  7011. p.processBlock (block, midi);
  7012. for (int i = 0; i < 512; ++i)
  7013. if (block.getSample (0, i) != 0.0f)
  7014. return done + i;
  7015. if (playing)
  7016. transport.positionTicks.store (transport.positionTicks.load() + 512 * transport.ticksPerSample());
  7017. }
  7018. return -1;
  7019. };
  7020. const auto beatOk = firstSample (true, 480.0, 0) == 12000 // half a beat to go: 480 ticks / 0.04
  7021. && firstSample (true, 480.0, 100) == 12100 // the song is heard 100 samples late (PDC)
  7022. && firstSample (true, 960.0, 0) == 0 // on a beat: now
  7023. && firstSample (false, 480.0, 0) == 0; // stopped: a free start
  7024. previewInTimeOk = loop.existsAsFile() && hit.existsAsFile() && offOk && hitOk && queued && stretchedOk && cachedOk && stoppedOk && beatOk;
  7025. dir.deleteRecursively();
  7026. }
  7027. // LYNX substitutes (round 98): a missing plugin's slot plays a built-in equivalent and the project keeps the
  7028. // original reference byte for byte (.flp record and LYNX plugin state)
  7029. bool substituteOk = false;
  7030. {
  7031. auto song = lynx::Song::makeDefault();
  7032. lynx::ForeignPlugin vv; // an .flp VST3 record (ValhallaVintageVerb's class ID), opaque state
  7033. vv.format = lynx::ForeignPlugin::Format::vst3;
  7034. const std::uint8_t cid[] = { 0x76, 0x54, 0x53, 0x56, 0x65, 0x65, 0x76, 0x33, 0x61, 0x6c, 0x68, 0x61, 0x6c, 0x6c, 0x61, 0x76 };
  7035. std::copy (std::begin (cid), std::end (cid), vv.classId.begin());
  7036. vv.hasClassId = true;
  7037. vv.name = "ValhallaVintageVerb";
  7038. vv.path = "C:\\x\\ValhallaVintageVerb.vst3";
  7039. for (int i = 0; i < 777; ++i)
  7040. vv.state.push_back ((std::uint8_t) (i * 13 + 1));
  7041. lynx::EffectSlot fromFlp;
  7042. fromFlp.kind = lynx::EffectKind::plugin;
  7043. fromFlp.plugin.foreign = vv;
  7044. lynx::EffectSlot fromLynx; // a LYNX reference whose plugin isn't installed here
  7045. fromLynx.kind = lynx::EffectKind::plugin;
  7046. fromLynx.plugin.id = "VST3-FabFilter Pro-Q 3-1a2b3c4d-5e6f7a8b";
  7047. fromLynx.plugin.name = "FabFilter Pro-Q 3";
  7048. fromLynx.plugin.state = "AAECAwQFBgcICQ==";
  7049. const auto flpRef = fromFlp.plugin, lynxRef = fromLynx.plugin;
  7050. song.mixer[1].effects = { fromFlp, fromLynx };
  7051. const auto substitutesOn = lynx::pluginSubstitutesEnabled();
  7052. const auto changed = offline.getPluginHost().applySubstitutes (song);
  7053. auto& fx = song.mixer[1].effects;
  7054. // only the LYNX reference is substituted here (an .flp record is the import's job); do the .flp one directly
  7055. const auto flpSubstituted = lynx::substituteEffectSlot (fx[0], lynx::pluginIdentity (vv));
  7056. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  7057. substituteOk = flpSubstituted && fx[0].kind == lynx::EffectKind::epochVerb
  7058. && (! substitutesOn || (changed == 1 && fx[1].kind == lynx::EffectKind::facetEq && fx[1].substituteFor == lynxRef))
  7059. && back && back->mixer[1].effects.size() == 2 && back->mixer[1].effects[0].kind == lynx::EffectKind::epochVerb
  7060. && back->mixer[1].effects[0].substituteFor == flpRef && back->mixer[1].effects[0].substituteFor.foreign.state == vv.state
  7061. && back->mixer[1].effects[1].kind == fx[1].kind && back->mixer[1].effects[1].substituteFor == fx[1].substituteFor;
  7062. }
  7063. // undo/redo
  7064. offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
  7065. offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  7066. offline.undo();
  7067. const auto afterUndo = offline.getSong().bpm;
  7068. offline.redo();
  7069. const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
  7070. && offline.isModified();
  7071. // Remote-owned steps still behave as ordinary native history when no RemoteControl instance is enabled.
  7072. // Only API undo/redo refuse device drift; remote reads, staging and publication never hold the audio-device callback lock.
  7073. const auto remoteHistoryResult = []() -> juce::String {
  7074. int checks = 0;
  7075. const auto require = [&] (bool condition, const char* message) {
  7076. ++checks;
  7077. if (! condition) throw std::runtime_error (message);
  7078. };
  7079. try
  7080. {
  7081. for (const auto session : { false, true })
  7082. {
  7083. lynx::AudioEngine history (false);
  7084. lynx::Song initial;
  7085. initial.channels.resize (1);
  7086. initial.channels[0].instrument = lynx::InstrumentKind::synth;
  7087. initial.mixer = lynx::Song::defaultMixer (1);
  7088. initial.bpm = 120.0;
  7089. history.setSong (std::move (initial));
  7090. history.setSessionHistory (session);
  7091. const auto editTempo = [&] (double bpm) {
  7092. require (history.editSongRemoteTransaction ([&] (lynx::Song& s) { s.bpm = bpm; }), "remote tempo edit was not committed");
  7093. };
  7094. const auto refused = [&] (const std::function<void()>& operation) {
  7095. const auto position = history.getHistoryPosition();
  7096. const auto before = lynx::ProjectFile::toJsonExact (history.getSong());
  7097. bool changed = false;
  7098. try { operation(); }
  7099. catch (const lynx::RemoteError& e) { changed = e.code == "changed" && ! e.uncertain; }
  7100. require (changed, "API history did not refuse untracked device changes");
  7101. require (history.getHistoryPosition() == position && lynx::ProjectFile::toJsonExact (history.getSong()) == before,
  7102. "refused API history changed the project or history position");
  7103. };
  7104. const auto withoutDeviceLock = [&] (const std::function<void()>& operation) {
  7105. juce::WaitableEvent locked, release;
  7106. bool timedOut = false;
  7107. std::thread callback ([&] {
  7108. const juce::ScopedLock lock (history.getDeviceManager().getAudioCallbackLock());
  7109. locked.signal();
  7110. timedOut = ! release.wait (3000);
  7111. });
  7112. const auto acquired = locked.wait (3000);
  7113. std::exception_ptr failure;
  7114. try { if (acquired) operation(); }
  7115. catch (...) { failure = std::current_exception(); }
  7116. release.signal();
  7117. callback.join();
  7118. // Check before rethrowing: an expected rejection must not conceal waiting for this lock.
  7119. require (acquired && ! timedOut, "remote read, edit or history publication waited for the audio-device callback lock");
  7120. if (failure) std::rethrow_exception (failure);
  7121. };
  7122. const auto baseline = lynx::ProjectFile::toJsonExact (history.getSong());
  7123. const auto baselineStamp = history.getSongStamp();
  7124. const auto baselinePosition = history.getHistoryPosition();
  7125. const auto unchanged = [&] {
  7126. return history.getSongStamp() == baselineStamp && history.getHistoryPosition() == baselinePosition
  7127. && lynx::ProjectFile::toJsonExact (history.getSong()) == baseline;
  7128. };
  7129. withoutDeviceLock ([&] {
  7130. require (lynx::ProjectFile::toJsonExact (history.snapshotForRemoteControl()) == baseline,
  7131. "remote snapshot changed the project");
  7132. require (history.remoteDeviceStateHash().isNotEmpty(), "remote snapshot did not hash device state");
  7133. });
  7134. require (unchanged(), "remote reads changed the project, revision or history");
  7135. bool staged = false;
  7136. withoutDeviceLock ([&] {
  7137. require (! history.editSongRemoteTransaction ([&] (lynx::Song&) { staged = true; }),
  7138. "remote no-op committed a history step");
  7139. });
  7140. require (staged && unchanged(), "remote no-op did not stage cleanly without changing history");
  7141. bool rejected = false;
  7142. try {
  7143. withoutDeviceLock ([&] {
  7144. history.editSongRemoteTransaction ([] (lynx::Song& next) {
  7145. next.bpm = 999.0;
  7146. throw lynx::RemoteError ("invalid", "selftest stage rejection");
  7147. });
  7148. });
  7149. }
  7150. catch (const lynx::RemoteError& e) { rejected = e.code == "invalid" && ! e.uncertain; }
  7151. require (rejected && unchanged(), "rejected staging changed the project, revision or history");
  7152. for (const auto cancelAfterStage : { false, true })
  7153. {
  7154. int calls = 0;
  7155. staged = false;
  7156. bool cancelledEdit = false;
  7157. try {
  7158. withoutDeviceLock ([&] {
  7159. history.editSongRemoteTransaction ([&] (lynx::Song& next) { staged = true; next.bpm = 999.0; },
  7160. [&] { return ++calls >= (cancelAfterStage ? 2 : 1); });
  7161. });
  7162. }
  7163. catch (const lynx::RemoteError& e) { cancelledEdit = e.code == "failed" && ! e.uncertain; }
  7164. require (cancelledEdit && staged == cancelAfterStage && unchanged(),
  7165. "cancelled edit changed the project, revision or history");
  7166. }
  7167. withoutDeviceLock ([&] { editTempo (130.0); });
  7168. require (history.getSong().bpm == 130.0 && history.getHistoryPosition() == baselinePosition + 1
  7169. && history.getSongStamp() > baselineStamp, "remote commit did not publish one history step");
  7170. history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.23f; }, false);
  7171. refused ([&] { history.undoRemoteControl(); });
  7172. withoutDeviceLock ([&] { history.undo(); });
  7173. require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0 && history.getRemoteHistoryError().isEmpty(),
  7174. "native undo refused device drift while remote control was disabled");
  7175. history.editSong ([] (lynx::Song& s) { s.channels[0].name = "Untracked change"; }, false);
  7176. refused ([&] { history.redoRemoteControl(); });
  7177. withoutDeviceLock ([&] { history.redo(); });
  7178. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
  7179. "native redo refused device drift while remote control was disabled");
  7180. withoutDeviceLock ([&] { editTempo (140.0); });
  7181. history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.42f; }, false);
  7182. withoutDeviceLock ([&] { history.jumpToHistory (0); });
  7183. require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0, "native history jump stopped at a remote step");
  7184. withoutDeviceLock ([&] { history.jumpToHistory (2); });
  7185. require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "native redo jump stopped at a remote step");
  7186. withoutDeviceLock ([&] { history.undoRemoteControl(); });
  7187. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0, "API undo failed with an unchanged device fence");
  7188. withoutDeviceLock ([&] { history.redoRemoteControl(); });
  7189. require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "API redo failed with an unchanged device fence");
  7190. int cancelledChecks = 0;
  7191. bool cancelled = false;
  7192. try { history.undoRemoteControl ([&] { return ++cancelledChecks >= 2; }); }
  7193. catch (const lynx::RemoteError& e) { cancelled = e.code == "failed" && ! e.uncertain; }
  7194. require (cancelled && history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0,
  7195. "cancelled API history moved a step");
  7196. withoutDeviceLock ([&] { history.undo(); });
  7197. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
  7198. "API cancellation leaked into native history");
  7199. }
  7200. return "OK (" + juce::String (checks) + " checks)";
  7201. }
  7202. catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
  7203. }();
  7204. // Hosted state access and processing share a per-instance lock, including fixed blocks and deferred resets.
  7205. const auto hostedStateLockResult = []() -> juce::String {
  7206. struct Probe final : juce::AudioPluginInstance
  7207. {
  7208. struct Parameter final : juce::HostedAudioProcessorParameter
  7209. {
  7210. explicit Parameter (Probe& p) : owner (p) {}
  7211. float getValue() const override { owner.access (owner.parameterReads); return value.load(); }
  7212. void setValue (float v) override { owner.access (owner.parameterWrites); value.store (v); }
  7213. float getDefaultValue() const override { return 0.0f; }
  7214. juce::String getName (int) const override { return "Value"; }
  7215. juce::String getLabel() const override { return {}; }
  7216. juce::String getParameterID() const override { return "value"; }
  7217. float getValueForText (const juce::String& text) const override { return text.getFloatValue(); }
  7218. Probe& owner;
  7219. std::atomic<float> value { 0.0f };
  7220. };
  7221. Probe() : AudioPluginInstance (BusesProperties().withInput ("Input", juce::AudioChannelSet::stereo(), true)
  7222. .withOutput ("Output", juce::AudioChannelSet::stereo(), true))
  7223. {
  7224. addHostedParameter (std::make_unique<Parameter> (*this));
  7225. }
  7226. const juce::String getName() const override { return "State lock probe"; }
  7227. void fillInPluginDescription (juce::PluginDescription& d) const override { d.name = getName(); }
  7228. void prepareToPlay (double, int) override {}
  7229. void releaseResources() override {}
  7230. void processBlock (juce::AudioBuffer<float>& audio, juce::MidiBuffer&) override { access (blocks); audio.clear(); }
  7231. void reset() override { access (resets, std::this_thread::get_id() == ui); } // (on the UI thread: the export reset)
  7232. double getTailLengthSeconds() const override { return 0.0; }
  7233. bool acceptsMidi() const override { return true; }
  7234. bool producesMidi() const override { return false; }
  7235. bool hasEditor() const override { return false; }
  7236. juce::AudioProcessorEditor* createEditor() override { return nullptr; }
  7237. int getNumPrograms() override { return 1; }
  7238. int getCurrentProgram() override { return 0; }
  7239. void setCurrentProgram (int) override {}
  7240. const juce::String getProgramName (int) override { return {}; }
  7241. void changeProgramName (int, const juce::String&) override {}
  7242. void getStateInformation (juce::MemoryBlock& state) override { access (captures); state.replaceAll ("state", 5); }
  7243. void setStateInformation (const void*, int) override { access (restores, true); }
  7244. // Round 190ha: only a restore and the export reset are exclusive with the audio side. A capture and the
  7245. // UI's parameter changes run beside processing, as on JUCE's own hosts (UI-thread calls never overlap
  7246. // each other here: they run in turn).
  7247. void access (std::atomic<int>& calls, bool exclusive = false)
  7248. {
  7249. ++calls;
  7250. if (exclusive)
  7251. {
  7252. ++exclusiveActive;
  7253. if (active.fetch_add (1) != 0) overlap = true;
  7254. }
  7255. else
  7256. {
  7257. ++active;
  7258. if (exclusiveActive.load() != 0) overlap = true;
  7259. }
  7260. juce::Thread::sleep (1); // widen the concurrent vendor-call window without using real plugins
  7261. --active;
  7262. if (exclusive) --exclusiveActive;
  7263. }
  7264. const std::thread::id ui = std::this_thread::get_id();
  7265. std::atomic<int> active { 0 }, exclusiveActive { 0 }, blocks { 0 }, resets { 0 }, captures { 0 }, restores { 0 };
  7266. std::atomic<int> parameterReads { 0 }, parameterWrites { 0 };
  7267. std::atomic<bool> overlap { false };
  7268. };
  7269. int checks = 0;
  7270. const auto require = [&] (bool condition, const char* message) {
  7271. ++checks;
  7272. if (! condition) throw std::runtime_error (message);
  7273. };
  7274. const auto exercise = [&] (auto& adapter, Probe& probe, const auto& render, const auto& reset) {
  7275. const auto saved = adapter.captureState();
  7276. require (saved.has_value(), "mock hosted state could not be captured");
  7277. juce::WaitableEvent start (true);
  7278. std::thread audio ([&] {
  7279. start.wait();
  7280. for (int i = 0; i < 32; ++i)
  7281. {
  7282. adapter.setParameter (0, i % 2 == 0 ? 0.25f : 0.75f);
  7283. (void) adapter.parameterValue (0);
  7284. reset();
  7285. render();
  7286. }
  7287. });
  7288. const juce::ScopeGuard joinAudio { [&] { if (audio.joinable()) audio.join(); } };
  7289. start.signal();
  7290. bool stateOk = true;
  7291. for (int i = 0; i < 32; ++i)
  7292. {
  7293. stateOk = adapter.captureState().has_value() && stateOk;
  7294. stateOk = adapter.restoreState (*saved) && stateOk;
  7295. adapter.setParameterFromUi (0, i % 2 == 0 ? 0.1f : 0.9f);
  7296. if (i % 8 == 0) adapter.resetForExport();
  7297. }
  7298. audio.join();
  7299. // Contended audio callbacks may all have bypassed while state was held.
  7300. // Exercise a successful callback after release before checking coverage.
  7301. adapter.setParameter (0, 0.5f);
  7302. (void) adapter.parameterValue (0);
  7303. reset();
  7304. render();
  7305. require (stateOk && probe.blocks > 0 && probe.resets > 0 && probe.captures > 0 && probe.restores > 0,
  7306. "mock did not exercise processing, resets and hosted state access");
  7307. require (probe.parameterReads > 0 && probe.parameterWrites > 0,
  7308. "mock did not exercise concurrent hosted parameter access");
  7309. require (! probe.overlap, "hosted processing/reset/parameters overlapped a state restore or the export reset");
  7310. require (! adapter.hasCrashed(), "mock hosted adapter crashed");
  7311. };
  7312. try
  7313. {
  7314. for (const auto fixed : { 0, 64 })
  7315. {
  7316. std::array<float, 128> left {}, right {};
  7317. auto instrument = std::make_unique<Probe>();
  7318. auto* instrumentProbe = instrument.get();
  7319. lynx::PluginInstrument voice (std::move (instrument), 128, fixed);
  7320. exercise (voice, *instrumentProbe, [&] { voice.render (left.data(), right.data(), 128, 1.0f, 1.0f); }, [&] { voice.panic(); });
  7321. auto effect = std::make_unique<Probe>();
  7322. auto* effectProbe = effect.get();
  7323. lynx::PluginEffect fx (std::move (effect), 128, fixed);
  7324. exercise (fx, *effectProbe, [&] { fx.process (left.data(), right.data(), 128, {}, 120.0); }, [&] { fx.transportReset(); });
  7325. }
  7326. return "OK (" + juce::String (checks) + " checks)";
  7327. }
  7328. catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
  7329. }();
  7330. const auto hostedStateContentionResult = lynx::pluginStateContentionSelfTest();
  7331. const auto modulators190oxResult = lynx::modulators190oxSelfTest(); // round 190ox: modulators stage 2
  7332. const auto generatorSmartResult = lynx::generatorSmartDisableSelfTest(); // (round 190ok, D2)
  7333. // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
  7334. // (Blend on: this checks that the take joins the pattern's notes; a new install starts with Blend off)
  7335. const auto notesBefore = offline.getSong().patterns[0].notes.size();
  7336. {
  7337. auto o = offline.getRecordOptions();
  7338. o.mode = lynx::RecordMode::overdub;
  7339. offline.setRecordOptions (o);
  7340. }
  7341. offline.setRecording (true);
  7342. offline.play();
  7343. offline.getTransport().positionTicks.store (960.0);
  7344. offline.sendLiveNote (2, 72, 0.9f, true, true);
  7345. offline.getTransport().positionTicks.store (1920.0);
  7346. offline.sendLiveNote (2, 72, 0.0f, false, true);
  7347. offline.setRecording (false);
  7348. offline.stop();
  7349. const auto& recorded = offline.getSong().patterns[0].notes;
  7350. const auto recordOk = recorded.size() == notesBefore + 1
  7351. && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
  7352. return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
  7353. });
  7354. offline.undo();
  7355. const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
  7356. // FL's Tools › Cancel recording (round 187a): the pass's notes go, an edit made before it stays, recording turns
  7357. // off and playback goes on; nothing to redo
  7358. bool cancelRecordOk = false;
  7359. {
  7360. offline.editSong ([] (lynx::Song& s) { s.bpm = 123.0; });
  7361. const auto notesThen = offline.getSong().patterns[0].notes.size();
  7362. offline.setRecording (true);
  7363. offline.play();
  7364. offline.getTransport().positionTicks.store (960.0);
  7365. offline.sendLiveNote (2, 74, 0.9f, true, true);
  7366. offline.getTransport().positionTicks.store (1920.0);
  7367. offline.sendLiveNote (2, 74, 0.0f, false, true);
  7368. offline.sendLiveNote (2, 76, 0.9f, true, true); // (still held when the pass is cancelled)
  7369. const auto cancelled = offline.cancelRecording();
  7370. cancelRecordOk = cancelled && ! offline.isRecording() && offline.getTransport().playing.load()
  7371. && offline.getSong().patterns[0].notes.size() == notesThen && offline.getSong().bpm == 123.0 && ! offline.canRedo()
  7372. && ! offline.cancelRecording(); // (not recording: nothing to cancel)
  7373. offline.sendLiveNote (2, 76, 0.0f, false, false);
  7374. offline.stop();
  7375. }
  7376. // MIDI: exporting the pattern and importing it back gives the same notes
  7377. bool midiOk = false;
  7378. {
  7379. auto source = lynx::Song::makeDefault();
  7380. source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
  7381. source.patterns[0].sortNotes();
  7382. const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
  7383. juce::String midiError;
  7384. const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
  7385. const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
  7386. midiFile.deleteFile();
  7387. if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
  7388. && std::abs (song->bpm - source.bpm) < 0.01)
  7389. {
  7390. midiOk = true;
  7391. const auto& a = source.patterns[0].notes;
  7392. const auto& b = song->patterns[0].notes;
  7393. for (std::size_t i = 0; i < a.size(); ++i)
  7394. midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
  7395. }
  7396. }
  7397. // project package (REA round 118): a project with a sample exported as .zip, extracted and opened again,
  7398. // finds its sample inside the extracted folder
  7399. bool packageOk = false;
  7400. {
  7401. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-package");
  7402. dir.deleteRecursively();
  7403. dir.getChildFile ("src").createDirectory();
  7404. const auto wav = dir.getChildFile ("src/hit.wav");
  7405. {
  7406. juce::WavAudioFormat format;
  7407. juce::AudioBuffer<float> hit (1, 480);
  7408. for (int i = 0; i < 480; ++i)
  7409. hit.setSample (0, i, 0.5f * std::sin (0.1f * (float) i));
  7410. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  7411. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  7412. {
  7413. out.release();
  7414. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  7415. writer->writeFromAudioSampleBuffer (hit, 0, 480);
  7416. }
  7417. }
  7418. auto source = lynx::Song::makeDefault();
  7419. lynx::ChannelDef c;
  7420. c.name = "Hit";
  7421. c.instrument = lynx::InstrumentKind::sampler;
  7422. c.samplePath = wav.getFullPathName().toStdString();
  7423. source.channels.push_back (c);
  7424. lynx::ProjectPackage::Result packed;
  7425. juce::String packageError;
  7426. const auto zip = dir.getChildFile ("Beat.zip");
  7427. if (wav.existsAsFile() && lynx::ProjectPackage::exportZip (source, "Beat", zip, packed, packageError) && packed.files == 1)
  7428. {
  7429. const auto project = lynx::ProjectPackage::extractZip (zip, dir.getChildFile ("out"), packageError);
  7430. const auto song = project.existsAsFile() ? lynx::ProjectFile::load (project, packageError) : std::nullopt;
  7431. if (song && ! song->channels.empty())
  7432. {
  7433. const juce::File back (juce::String::fromUTF8 (song->channels.back().samplePath.c_str()));
  7434. packageOk = back.existsAsFile() && back.isAChildOf (project.getParentDirectory()) && back.getSize() == wav.getSize();
  7435. }
  7436. }
  7437. dir.deleteRecursively();
  7438. }
  7439. // D#92, round 180a: a non-ASCII folder and a dotted name save and load back; an unwritable place says so, and a
  7440. // relative path resolves as the start-up argument does
  7441. bool projectSaveOk = false;
  7442. {
  7443. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-save180a");
  7444. dir.deleteRecursively();
  7445. const auto folder = dir.getChildFile (juce::String::fromUTF8 ("M\xc3\xbasica nova"));
  7446. folder.createDirectory();
  7447. const auto named = lynx::ProjectFile::withProjectExtension (folder.getChildFile (juce::String::fromUTF8 ("Can\xc3\xa7\xc3\xa3o.v2")));
  7448. auto song = lynx::Song::makeDefault();
  7449. lynx::Note note;
  7450. note.length = 240;
  7451. note.key = 64;
  7452. song.patterns[0].notes.push_back (note);
  7453. juce::String error, blockedError;
  7454. const auto again = lynx::ProjectFile::save (song, named, error) ? lynx::ProjectFile::load (named, error) : std::nullopt;
  7455. const auto blocker = dir.getChildFile ("a file");
  7456. blocker.replaceWithText ("x");
  7457. const auto cwd = juce::File::getCurrentWorkingDirectory();
  7458. folder.setAsCurrentWorkingDirectory();
  7459. const auto relative = juce::File::getCurrentWorkingDirectory().getChildFile (named.getFileName());
  7460. cwd.setAsCurrentWorkingDirectory();
  7461. projectSaveOk = named.getFileName().endsWith (".v2.lynx") && again && again->patterns[0].notes.size() == song.patterns[0].notes.size()
  7462. && relative == named && ! lynx::ProjectFile::save (song, blocker.getChildFile ("x.lynx"), blockedError)
  7463. && blockedError.isNotEmpty() && lynx::ProjectFile::withProjectExtension (named) == named;
  7464. dir.deleteRecursively();
  7465. }
  7466. // Online Sessions (round 168a): a project sent as a .lynxpack (one sample used twice is stored once, the uids
  7467. // survive), a stand-in rendered through an ExportJob, the guest's part sent back and merged by the host
  7468. juce::String sessionResult = "ERROR";
  7469. {
  7470. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-session");
  7471. dir.deleteRecursively();
  7472. dir.getChildFile ("src").createDirectory();
  7473. const auto wav = dir.getChildFile ("src/hit.wav");
  7474. {
  7475. juce::WavAudioFormat format;
  7476. juce::AudioBuffer<float> hit (1, 4800);
  7477. for (int i = 0; i < 4800; ++i)
  7478. hit.setSample (0, i, 0.5f * std::sin (0.05f * (float) i) * (1.0f - (float) i / 4800.0f));
  7479. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  7480. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  7481. {
  7482. out.release();
  7483. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  7484. writer->writeFromAudioSampleBuffer (hit, 0, 4800);
  7485. }
  7486. }
  7487. auto host = lynx::Song::makeDefault();
  7488. host.mode = lynx::PlayMode::song;
  7489. const auto copyOfWav = dir.getChildFile ("src/hit copy.wav"); // the same bytes under another name: stored once
  7490. wav.copyFileTo (copyOfWav);
  7491. for (const auto& [name, file] : { std::pair<const char*, juce::File> { "Hit", wav }, { "Hit 2", copyOfWav } })
  7492. {
  7493. lynx::ChannelDef c;
  7494. c.name = name;
  7495. c.instrument = lynx::InstrumentKind::sampler;
  7496. c.samplePath = file.getFullPathName().toStdString();
  7497. host.channels.push_back (c);
  7498. }
  7499. const auto hitChannel = (int) host.channels.size() - 2;
  7500. lynx::Note hitNote;
  7501. hitNote.channel = hitChannel;
  7502. hitNote.length = 480;
  7503. host.patterns[0].notes.push_back (hitNote);
  7504. host.playlist.push_back ({ 0, 0, 0, host.patterns[0].effectiveLength (host.meter()), 0 });
  7505. lynx::uids::normalize (host);
  7506. const auto* guest = lynx::parts::invite (host, "Host", "Ana", 0xFF3D9BE9, false);
  7507. juce::String e;
  7508. std::vector<lynx::sessionpack::Rendered> rendered;
  7509. // (a sampler stands in for a plugin channel here: render() renders whatever it is given)
  7510. const std::vector<lynx::sessionpack::RenderItem> items { { false, hitChannel, false, "Hit", "Test" } };
  7511. const auto renderedOk = guest != nullptr && lynx::sessionpack::render (host, items, 44100.0, dir.getChildFile ("stems"), "Host", rendered, {}, e)
  7512. && rendered.size() == 1 && rendered[0].standIns.size() == 2
  7513. && juce::File (juce::String::fromUTF8 (rendered[0].standIns[0].path.c_str())).getSize() > 1000;
  7514. if (renderedOk)
  7515. lynx::sessionpack::apply (host, rendered);
  7516. lynx::sessionpack::Manifest m;
  7517. m.projectName = "Selftest";
  7518. m.from = *host.session.find (lynx::session::hostTag);
  7519. m.to = *host.session.find (2);
  7520. lynx::sessionpack::WriteResult written;
  7521. const auto pack = dir.getChildFile (juce::String ("Selftest") + lynx::sessionpack::extension);
  7522. const auto packOk = renderedOk && lynx::sessionpack::write (lynx::parts::guestCopy (host, 2), m, offline.getPluginHost(), pack, written, e)
  7523. && written.media == 3 && written.duplicates == 1; // the sample once (used twice), the stand-in pair
  7524. auto opened = packOk ? lynx::sessionpack::open (pack, dir.getChildFile ("received"), e) : std::nullopt;
  7525. bool openOk = false, mergeOk = false;
  7526. if (opened && opened->corrupt.isEmpty())
  7527. {
  7528. const auto& g = opened->song;
  7529. const juce::File sample (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].samplePath.c_str()));
  7530. openOk = g.session.me == 2 && g.projectId == host.projectId && g.channels[(std::size_t) hitChannel].uid == host.channels[(std::size_t) hitChannel].uid
  7531. && sample.existsAsFile() && sample.isAChildOf (opened->folder) && g.channels[(std::size_t) hitChannel].standIns.size() == 2
  7532. && juce::File (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].standIns[1].path.c_str())).existsAsFile();
  7533. // the guest adds a channel and a pattern of his own, sends his part back
  7534. auto copy = g;
  7535. lynx::ChannelDef mine;
  7536. mine.name = "Ana's hit";
  7537. mine.instrument = lynx::InstrumentKind::sampler;
  7538. mine.samplePath = sample.getFullPathName().toStdString();
  7539. copy.channels.push_back (mine);
  7540. lynx::Pattern p;
  7541. p.name = "Ana";
  7542. lynx::Note note;
  7543. note.channel = (int) copy.channels.size() - 1;
  7544. note.length = 240;
  7545. note.key = 64;
  7546. p.notes.push_back (note);
  7547. copy.patterns.push_back (p);
  7548. lynx::uids::normalize (copy);
  7549. // its uids survive a save and a load
  7550. const auto saved = dir.getChildFile ("guest.lynx");
  7551. auto reloaded = lynx::ProjectFile::save (copy, saved, e) ? lynx::ProjectFile::load (saved, e) : std::nullopt;
  7552. lynx::sessionpack::Manifest back;
  7553. back.part = true;
  7554. back.from = *copy.session.self();
  7555. const auto partFile = dir.getChildFile (juce::String ("Ana part") + lynx::sessionpack::extension);
  7556. lynx::sessionpack::WriteResult partWritten;
  7557. auto part = reloaded && reloaded->channels.back().uid == copy.channels.back().uid && lynx::uids::tagOf (reloaded->channels.back().uid) == 2
  7558. ? lynx::sessionpack::write (lynx::parts::extract (*reloaded, 2), back, offline.getPluginHost(), partFile, partWritten, e)
  7559. : false;
  7560. auto partOpened = part ? lynx::sessionpack::open (partFile, dir.getChildFile ("parts"), e) : std::nullopt;
  7561. if (partOpened && partOpened->manifest.part && lynx::sessionpack::adoptMedia (partOpened->song, dir.getChildFile ("Session media/Ana"), e))
  7562. {
  7563. const auto report = lynx::parts::merge (host, partOpened->song, 2);
  7564. const auto& added = host.channels.back();
  7565. mergeOk = report.ok && report.channels >= 1 && added.name == "Ana's hit" && lynx::uids::tagOf (added.uid) == 2
  7566. && juce::File (juce::String::fromUTF8 (added.samplePath.c_str())).isAChildOf (dir.getChildFile ("Session media/Ana"))
  7567. && host.channels[(std::size_t) hitChannel].name == "Hit";
  7568. }
  7569. }
  7570. // a crafted package whose project points at a file elsewhere on this computer: opening it must not
  7571. // reach that file, or merging would copy it into the project and the next package would send it on
  7572. if (mergeOk)
  7573. {
  7574. const auto secret = dir.getChildFile ("secret.wav");
  7575. wav.copyFileTo (secret);
  7576. auto evil = lynx::Song::makeDefault();
  7577. lynx::ChannelDef c;
  7578. c.instrument = lynx::InstrumentKind::sampler;
  7579. c.samplePath = secret.getFullPathName().toStdString();
  7580. evil.channels.push_back (c);
  7581. lynx::ChannelDef keys; // (FL Keys' zones are read by the engine but are not in the media list)
  7582. keys.instrument = lynx::InstrumentKind::flkeys;
  7583. keys.zones.push_back ({});
  7584. keys.zones.back().path = c.samplePath;
  7585. evil.channels.push_back (keys);
  7586. lynx::ChannelDef patch; // (a Patcher's nodes are not in the media list either)
  7587. patch.instrument = lynx::InstrumentKind::patcher;
  7588. patch.patcher.nodes.resize (2);
  7589. patch.patcher.nodes[0].generator = true;
  7590. patch.patcher.nodes[0].channel = c;
  7591. patch.patcher.nodes[1].effect.samplePath = c.samplePath;
  7592. evil.channels.push_back (patch);
  7593. evil.mixer[1].recordTo = dir.getChildFile ("overwritten.wav").getFullPathName().toStdString();
  7594. const auto evilProject = dir.getChildFile ("evil.lynx");
  7595. lynx::sessionpack::Manifest em;
  7596. em.part = true;
  7597. juce::ZipFile::Builder b;
  7598. const auto json = lynx::sessionpack::manifestToJson (em);
  7599. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  7600. const auto evilPack = dir.getChildFile (juce::String ("Evil") + lynx::sessionpack::extension);
  7601. bool zipped = false;
  7602. if (lynx::ProjectFile::save (evil, evilProject, e))
  7603. {
  7604. b.addFile (evilProject, 0, "project.lynx");
  7605. juce::FileOutputStream out (evilPack);
  7606. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  7607. }
  7608. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil"), e) : std::nullopt;
  7609. const auto media = dir.getChildFile ("Session media/Evil");
  7610. mergeOk = evilOpened && lynx::sessionpack::adoptMedia (evilOpened->song, media, e)
  7611. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  7612. return juce::File (juce::String::fromUTF8 (ch.samplePath.c_str())) == secret
  7613. || std::any_of (ch.zones.begin(), ch.zones.end(), [&] (const lynx::SampleZone& z) { return juce::File (juce::String::fromUTF8 (z.path.c_str())) == secret; });
  7614. })
  7615. && evilOpened->song.channels.back().patcher.nodes.size() == 2
  7616. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[0].channel.samplePath.c_str())) != secret
  7617. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[1].effect.samplePath.c_str())) != secret
  7618. && evilOpened->song.mixer[1].recordTo.empty()
  7619. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  7620. if (! mergeOk && e.isEmpty())
  7621. e = "a received package reached a file outside it";
  7622. }
  7623. // ... nor through its own folder: "..", Windows' dotted names (". ." climbs like ".." there), and a manifest
  7624. // media entry outside the package (it must not even be read: "/dev/zero" would never end)
  7625. if (mergeOk)
  7626. {
  7627. const auto secret = dir.getChildFile ("secret.wav");
  7628. const auto folder = dir.getChildFile ("evil2").getChildFile ("Evil2"); // (where open() will unpack it)
  7629. const auto climb = folder.getFullPathName() + "/media/../../../secret.wav";
  7630. const auto dotted = folder.getFullPathName() + "/. ./.. ./secret.wav";
  7631. auto evil = lynx::Song::makeDefault();
  7632. for (const auto& path : { climb, dotted })
  7633. {
  7634. lynx::ChannelDef c;
  7635. c.instrument = lynx::InstrumentKind::sampler;
  7636. c.samplePath = path.toStdString();
  7637. evil.channels.push_back (c);
  7638. }
  7639. juce::MemoryBlock secretBytes;
  7640. secret.loadFileAsData (secretBytes);
  7641. lynx::sessionpack::Manifest em;
  7642. em.part = true;
  7643. em.media.push_back ({ "sha256-" + juce::String (lynx::sha256Hex ((const std::uint8_t*) secretBytes.getData(), secretBytes.getSize())),
  7644. "secret.wav", (juce::int64) secretBytes.getSize(), "../../secret.wav" });
  7645. const auto evilProject = dir.getChildFile ("evil2.lynx");
  7646. juce::ZipFile::Builder b;
  7647. const auto json = lynx::sessionpack::manifestToJson (em);
  7648. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  7649. const auto evilPack = dir.getChildFile (juce::String ("Evil2") + lynx::sessionpack::extension);
  7650. bool zipped = false;
  7651. if (lynx::ProjectFile::save (evil, evilProject, e))
  7652. {
  7653. b.addFile (evilProject, 0, "project.lynx");
  7654. juce::FileOutputStream out (evilPack);
  7655. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  7656. }
  7657. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil2"), e) : std::nullopt;
  7658. const auto media = dir.getChildFile ("Session media/Evil2");
  7659. mergeOk = evilOpened && evilOpened->folder == folder && evilOpened->corrupt.contains ("secret.wav")
  7660. && lynx::sessionpack::adoptMedia (evilOpened->song, media, e) && evilOpened->song.channels.size() >= 2
  7661. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  7662. const auto p = juce::String::fromUTF8 (ch.samplePath.c_str());
  7663. return p == climb || p == dotted || (juce::File::isAbsolutePath (p) && juce::File (p) == secret);
  7664. })
  7665. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  7666. if (! mergeOk && e.isEmpty())
  7667. e = "a received package climbed out of its folder";
  7668. }
  7669. if (! packOk && e.isEmpty())
  7670. e = "media " + juce::String (written.media) + ", duplicates " + juce::String (written.duplicates) + ", missing "
  7671. + written.missing.joinIntoString (";");
  7672. sessionResult = mergeOk ? juce::String ("OK")
  7673. : "ERROR (" + juce::String (renderedOk ? packOk ? openOk ? "merge" : "open" : "pack" : "render") + (e.isEmpty() ? "" : ": " + e) + ")";
  7674. dir.deleteRecursively();
  7675. }
  7676. // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
  7677. juce::String wavpack = "NO_FL";
  7678. {
  7679. const auto roots = lynx::findFlStudioRoots();
  7680. const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
  7681. const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
  7682. if (! found.isEmpty())
  7683. {
  7684. lynx::SampleLibrary library;
  7685. const auto sample = library.load (found.getFirst().getFullPathName());
  7686. float peakWv = 0.0f;
  7687. if (sample != nullptr)
  7688. for (std::size_t i = 0; i < sample->frames(); ++i)
  7689. peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
  7690. wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
  7691. }
  7692. }
  7693. // every built-in effect's editor and engine with extreme settings (round 111): a crash or NaN output fails here
  7694. const auto effectsOk = runEffectFuzz (4, {}); // (no mouse drags: nothing may open on screen)
  7695. // FL's Patcher (round 141): a mixer slot and a generator channel with their graphs survive save / load, and the
  7696. // generator one plays through the rack
  7697. bool patcherOk = false;
  7698. {
  7699. auto song = lynx::Song::makeDefault();
  7700. song.mixer.resize (4);
  7701. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  7702. lynx::PatchNode reverb, gain;
  7703. reverb.effect = lynx::makeEffectSlot (lynx::EffectKind::utility); // (exact defaults: params are saved to 4 decimals)
  7704. reverb.label = "Room";
  7705. reverb.x = 120.5f;
  7706. reverb.y = 40.0f;
  7707. gain.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  7708. gain.effect.enabled = false;
  7709. slot.patcher.nodes = { reverb, gain };
  7710. lynx::PatchWire a, b, c, control;
  7711. a.to = 0;
  7712. b.from = 0, b.to = 1, b.gain = 0.5f;
  7713. c.from = 1;
  7714. control.kind = lynx::PatchWire::Kind::control, control.from = 0, control.to = 1, control.toPort = 0, control.curve = { 0.0f, 0.25f, 1.0f };
  7715. slot.patcher.wires = { a, b, c, control };
  7716. slot.patcher.outputTracks = { 3 };
  7717. song.mixer[1].effects = { slot };
  7718. lynx::ChannelDef ch;
  7719. ch.name = "Patched";
  7720. ch.instrument = lynx::InstrumentKind::patcher;
  7721. lynx::PatchNode synth;
  7722. synth.generator = true;
  7723. synth.channel.instrument = lynx::InstrumentKind::synth;
  7724. synth.channel.name = "Synth";
  7725. ch.patcher.nodes = { synth };
  7726. lynx::PatchWire notes, out;
  7727. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  7728. out.from = 0;
  7729. ch.patcher.wires = { notes, out };
  7730. // round 162: the I/O nodes' MIDI pins and a MIDI Out node between them
  7731. lynx::PatchNode midiOutNode;
  7732. midiOutNode.generator = true;
  7733. midiOutNode.channel.instrument = lynx::InstrumentKind::midiOut;
  7734. lynx::midictl::writeMidiOut (midiOutNode.channel.pluginState.edit(), { 4, 0, 0, -1, -1 });
  7735. ch.patcher.nodes.push_back (midiOutNode);
  7736. lynx::PatchWire portIn, portOut;
  7737. portIn.kind = portOut.kind = lynx::PatchWire::Kind::midi;
  7738. portIn.fromPort = lynx::patchMidiPortPin (7), portIn.to = 1;
  7739. portOut.from = 1, portOut.to = lynx::patchToHost, portOut.toPort = 9;
  7740. ch.patcher.wires.push_back (portIn);
  7741. ch.patcher.wires.push_back (portOut);
  7742. ch.patcher.fromMidiPorts = { 2, 7 };
  7743. ch.patcher.toMidiPorts = { 9, 11 };
  7744. ch.patcher.fromNotesHidden = true;
  7745. song.channels.push_back (ch);
  7746. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  7747. patcherOk = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1
  7748. && back->mixer[1].effects[0].kind == lynx::EffectKind::patcher && back->mixer[1].effects[0].patcher == slot.patcher
  7749. && back->channels.back().instrument == lynx::InstrumentKind::patcher && back->channels.back().patcher.nodes.size() == 2
  7750. && back->channels.back().patcher.fromMidiPorts == ch.patcher.fromMidiPorts
  7751. && back->channels.back().patcher.toMidiPorts == ch.patcher.toMidiPorts && back->channels.back().patcher.fromNotesHidden
  7752. && back->channels.back().patcher.nodes[1].channel.pluginState == midiOutNode.channel.pluginState
  7753. && back->channels.back().patcher.nodes[0].generator
  7754. && back->channels.back().patcher.nodes[0].channel.instrument == lynx::InstrumentKind::synth
  7755. && back->channels.back().patcher.wires == ch.patcher.wires;
  7756. }
  7757. // Round 183c, Racks: (1) a plain Patcher's stored JSON loads and saves back byte for byte and never holds a
  7758. // "rack" key (FL's Patcher is untouched); (2) an Audio Effect Rack slot and an Instrument Rack channel survive save /
  7759. // load with their chains, zones, macros, mappings, variations and compiled cables
  7760. juce::String rackResult = "OK";
  7761. {
  7762. lynx::MixerTrack plain;
  7763. plain.name = "Plain Patcher";
  7764. auto fx = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  7765. lynx::PatchNode a, b;
  7766. a.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  7767. a.label = "A";
  7768. a.x = 120.5f;
  7769. b.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  7770. b.effect.enabled = false;
  7771. fx.patcher.nodes = { a, b };
  7772. lynx::PatchWire w1, w2, w3, wc;
  7773. w1.to = 0;
  7774. w2.from = 0, w2.to = 1, w2.gain = 0.5f;
  7775. w3.from = 1;
  7776. wc.kind = lynx::PatchWire::Kind::control, wc.from = 0, wc.to = 1, wc.toPort = 0, wc.curve = { 0.0f, 0.25f, 1.0f };
  7777. fx.patcher.wires = { w1, w2, w3, wc };
  7778. lynx::SurfaceControl knob;
  7779. knob.name = "Drive";
  7780. knob.value = 0.25f;
  7781. fx.patcher.surface = { knob };
  7782. lynx::PatchParam pp;
  7783. pp.node = 0, pp.param = 1, pp.name = "Balance";
  7784. fx.patcher.published = { pp };
  7785. plain.effects = { fx };
  7786. const auto first = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (plain), true);
  7787. const auto again = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (first))), true);
  7788. if (first != again || first.contains ("\"rack\"") || first.contains ("rackMixer"))
  7789. rackResult = "ERROR plain Patcher changed";
  7790. auto song = lynx::Song::makeDefault();
  7791. song.mixer.resize (3);
  7792. auto rackSlot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  7793. auto& doc = rackSlot.patcher;
  7794. lynx::PatchNode u;
  7795. u.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  7796. const auto n0 = lynx::rack::addDevice (doc, 0, u);
  7797. lynx::rack::addChain (doc, "Wet");
  7798. lynx::rack::addDevice (doc, 1, u);
  7799. doc.rack[0].chains[1].select = { 10, 90, 30, 70 };
  7800. lynx::rack::setChainPan (doc, 1, -0.5f);
  7801. lynx::RackMapping m;
  7802. m.node = n0, m.param = 0, m.min = 0.2f, m.max = 0.9f;
  7803. lynx::rack::map (doc, 0, m);
  7804. lynx::RackMapping v;
  7805. v.target = lynx::RackMapping::Target::chainVolume, v.chain = 1, v.min = 0.0f, v.max = lynx::rack::unityVolume;
  7806. lynx::rack::map (doc, 1, v);
  7807. lynx::rack::setMacro (doc, 0, 64.0f);
  7808. lynx::rack::storeVariation (doc);
  7809. lynx::rack::setMacro (doc, 0, 100.0f);
  7810. lynx::rack::storeVariation (doc);
  7811. doc.rack[0].morphOn = true, doc.rack[0].morphA = 0, doc.rack[0].morphB = 1;
  7812. lynx::rack::setMorph (doc, 0.5f);
  7813. lynx::rack::compile (doc);
  7814. song.mixer[1].effects = { rackSlot };
  7815. lynx::ChannelDef inst;
  7816. inst.name = "Instrument Rack";
  7817. inst.instrument = lynx::InstrumentKind::patcher;
  7818. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  7819. lynx::PatchNode synth;
  7820. synth.generator = true;
  7821. synth.channel.instrument = lynx::InstrumentKind::synth;
  7822. synth.channel.name = "Synth";
  7823. lynx::rack::addDevice (inst.patcher, 0, synth);
  7824. inst.patcher.rack[0].chains[0].velocity = { 1, 127, 64, 127 };
  7825. lynx::rack::compile (inst.patcher);
  7826. song.channels.push_back (inst);
  7827. const auto json = lynx::ProjectFile::toJson (song);
  7828. const auto back = lynx::ProjectFile::fromJson (json, error);
  7829. // (the devices' parameters are stored to 4 decimals: the documents are compared as stored, the rack exactly)
  7830. const auto loaded = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1;
  7831. const auto& got = loaded ? back->mixer[1].effects[0].patcher : doc;
  7832. if (! loaded)
  7833. rackResult = "ERROR rack slot not loaded";
  7834. else if (got.rack != doc.rack)
  7835. rackResult = "ERROR rack model";
  7836. else if (got.wires != doc.wires)
  7837. rackResult = "ERROR rack cables";
  7838. else if (got.nodes.size() != doc.nodes.size())
  7839. rackResult = "ERROR rack devices";
  7840. else if (back->channels.back().patcher.rack != inst.patcher.rack || back->channels.back().patcher.wires != inst.patcher.wires
  7841. || back->channels.back().patcher.zones != inst.patcher.zones || back->channels.back().patcher.nodes.size() != inst.patcher.nodes.size())
  7842. rackResult = "ERROR instrument rack";
  7843. // the slot's insert as stored, once more: the same text (the stored form is stable)
  7844. else if (const auto once = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (back->mixer[1]), true);
  7845. once != juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (once))), true))
  7846. rackResult = "ERROR rack stored form not stable";
  7847. }
  7848. // Round 190ec, Drum Rack: pads (Receive / Play / Choke / Audio To / sends), return chains and the views survive save /
  7849. // load with their compiled zones and cables
  7850. if (rackResult == "OK")
  7851. {
  7852. lynx::Song song;
  7853. song.mixer.resize (2);
  7854. lynx::ChannelDef ch;
  7855. ch.name = "Drums";
  7856. ch.instrument = lynx::InstrumentKind::patcher;
  7857. ch.patcher = lynx::rack::makeDrumRack();
  7858. lynx::PatchNode synth;
  7859. synth.generator = true;
  7860. synth.channel.instrument = lynx::InstrumentKind::synth;
  7861. const auto kick = lynx::rack::addPad (ch.patcher, 36, "Kick", synth);
  7862. const auto hat = lynx::rack::addPad (ch.patcher, 42, "Hat", synth);
  7863. lynx::rack::addPad (ch.patcher, -1, "Every note");
  7864. lynx::rack::addReturn (ch.patcher, "A Verb");
  7865. lynx::rack::setPlay (ch.patcher, kick, 64);
  7866. lynx::rack::setChoke (ch.patcher, hat, 2);
  7867. lynx::rack::setSend (ch.patcher, hat, 0, 0.25f, false);
  7868. lynx::rack::setAudioTo (ch.patcher, kick, 0);
  7869. lynx::rack::rackOf (ch.patcher)->showIO = true;
  7870. lynx::rack::rackOf (ch.patcher)->padScroll = 17;
  7871. song.channels.push_back (ch);
  7872. juce::String error;
  7873. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  7874. const auto& got = back && ! back->channels.empty() ? back->channels.back().patcher : lynx::PatcherDoc {};
  7875. if (! back || ! lynx::rack::isDrumRack (got))
  7876. rackResult = "ERROR drum rack not loaded";
  7877. else if (got.rack != ch.patcher.rack)
  7878. rackResult = "ERROR drum rack model";
  7879. else if (got.zones != ch.patcher.zones || got.wires != ch.patcher.wires)
  7880. rackResult = "ERROR drum rack cables";
  7881. }
  7882. // FL engines in a native project (round 142, issue #5): every engine this PC can make survives save / load and
  7883. // the instruments play through the rack
  7884. juce::String nativesResult = "OK";
  7885. int nativesMade = 0, nativesSilent = 0;
  7886. {
  7887. auto song = lynx::Song::makeDefault();
  7888. song.channels.clear();
  7889. song.patterns[0].notes.clear();
  7890. song.mixer.resize (3);
  7891. const auto& fl = lynx::flStudioAccess();
  7892. for (const auto& e : lynx::natives::instrumentEngines())
  7893. if (lynx::natives::available (e, fl))
  7894. if (auto c = lynx::natives::makeChannel (e.kind, fl))
  7895. {
  7896. c->mixerTrack = 1;
  7897. song.channels.push_back (*c);
  7898. }
  7899. for (const auto& e : lynx::natives::effectEngines())
  7900. if (auto fx = lynx::natives::makeSlot (e.kind, fl))
  7901. song.mixer[2].effects.push_back (*fx);
  7902. nativesMade = (int) (song.channels.size() + song.mixer[2].effects.size());
  7903. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  7904. auto same = back && back->channels.size() == song.channels.size() && back->mixer.size() >= 3
  7905. && back->mixer[2].effects.size() == song.mixer[2].effects.size();
  7906. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  7907. {
  7908. const auto& a = song.channels[i];
  7909. const auto& b = back->channels[i];
  7910. same = a.instrument == b.instrument && a.pluginState == b.pluginState && a.samplePath == b.samplePath && a.zones.size() == b.zones.size()
  7911. && a.modelParams.size() == b.modelParams.size();
  7912. if (! same)
  7913. nativesResult = "ERROR channel " + juce::String::fromUTF8 (a.name.c_str());
  7914. }
  7915. for (std::size_t i = 0; same && i < song.mixer[2].effects.size(); ++i)
  7916. {
  7917. const auto& a = song.mixer[2].effects[i];
  7918. const auto& b = back->mixer[2].effects[i];
  7919. same = a.kind == b.kind && a.state == b.state;
  7920. for (std::size_t p = 0; same && p < a.params.size(); ++p)
  7921. same = std::abs (a.params[p] - b.params[p]) < 1.0e-3f;
  7922. if (! same)
  7923. nativesResult = juce::String ("ERROR effect ") + lynx::effectInfo (a.kind).name;
  7924. }
  7925. if (! back)
  7926. nativesResult = "ERROR " + error;
  7927. // each instrument plays a note alone. The Granulizer and Wave Traveller play the channel's sample, and a new
  7928. // one has none (a PC without FL Studio, macOS / Linux: FL's presets are not there either), so they get a
  7929. // generated one: a second of a 220 Hz tone (round 167m, PR #19: Wave Traveller was "SILENT 1" on macOS)
  7930. const auto toneWav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-natives.wav");
  7931. {
  7932. juce::WavAudioFormat format;
  7933. juce::AudioBuffer<float> tone (1, 48000);
  7934. for (int i = 0; i < 48000; ++i)
  7935. tone.setSample (0, i, 0.5f * std::sin (juce::MathConstants<float>::twoPi * 220.0f * (float) i / 48000.0f));
  7936. toneWav.deleteFile();
  7937. std::unique_ptr<juce::OutputStream> out (toneWav.createOutputStream().release());
  7938. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  7939. {
  7940. out.release();
  7941. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  7942. writer->writeFromAudioSampleBuffer (tone, 0, 48000);
  7943. }
  7944. }
  7945. juce::StringArray silentNames;
  7946. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  7947. {
  7948. auto one = song;
  7949. one.channels = { song.channels[i] };
  7950. one.channels[0].mixerTrack = 1;
  7951. const auto kind = song.channels[i].instrument;
  7952. // A new Fruity Slicer has no sample and no slices, and FL's is silent then too (round 180c), so it is
  7953. // not one of the engines that must sound here (Linux / macOS CI: "SILENT 1 [Fruity Slicer]", 0.1.25)
  7954. if (kind == lynx::InstrumentKind::fruityslicer && one.channels[0].samplePath.empty())
  7955. continue;
  7956. if (kind == lynx::InstrumentKind::slicex && one.channels[0].samplePath.empty()) // (the same: no sample on its decks yet)
  7957. continue;
  7958. if (kind == lynx::InstrumentKind::directwave && one.channels[0].zones.empty()) // (FL's new DirectWave: no zones yet, round 190hz)
  7959. continue;
  7960. if ((kind == lynx::InstrumentKind::granulizer || kind == lynx::InstrumentKind::wavetraveller) && one.channels[0].samplePath.empty())
  7961. one.channels[0].samplePath = toneWav.getFullPathName().toStdString();
  7962. one.mixer[2].effects.clear();
  7963. // Drumaxx plays pad 1's key: FL's default kit has a pad at 48, LYNX's own bank kits (a PC without FL,
  7964. // macOS / Linux; round 168p) start at 36 (round 169d: "SILENT 1 [Drumaxx]" on the Linux / macOS CI)
  7965. auto key = 60;
  7966. if (kind == lynx::InstrumentKind::drumaxx)
  7967. {
  7968. const auto padKey = lynx::drumaxxParam (one.channels[0].pluginState, 4);
  7969. key = std::isfinite (padKey) && padKey >= 0.0f && padKey <= 127.0f ? (int) padKey : 48;
  7970. }
  7971. // FPC plays its pads' keys; a kit without a sample (FL's "Empty" kit: no FL Studio on this PC) is silent
  7972. // in FL too (round 190q)
  7973. if (kind == lynx::InstrumentKind::fpc)
  7974. {
  7975. const auto pads = lynx::fpcChannelPads (one.channels[0]);
  7976. if (pads.empty())
  7977. continue;
  7978. key = pads.front().key;
  7979. }
  7980. one.patterns[0].notes = { { 0, 1920, 0, key, 0.8f } };
  7981. lynx::AudioEngine player (false);
  7982. player.setSong (std::move (one));
  7983. player.dispatchPendingMessages();
  7984. if (! (player.renderOffline (1.0, 48000.0) > 1.0e-4f))
  7985. {
  7986. ++nativesSilent;
  7987. silentNames.add (juce::String::fromUTF8 (song.channels[i].name.c_str()));
  7988. }
  7989. }
  7990. toneWav.deleteFile();
  7991. if (nativesSilent > 0 && nativesResult == "OK")
  7992. nativesResult = "SILENT " + juce::String (nativesSilent) + " [" + silentNames.joinIntoString (", ") + "]";
  7993. }
  7994. const auto nativesOk = nativesResult == "OK";
  7995. // The metronome as FL 2026 plays it (round 165z-a2): FL's five sounds from its install, the downbeat at
  7996. // 0.9404 × the Tick two semitones up, into the Master ("---") by default; insert 2 as its track plays it through
  7997. // insert 2 (muted: silent); never in an export
  7998. juce::String metronomeResult = "OK";
  7999. int metronomeFlSounds = 0;
  8000. float metronomeMaster = 0.0f;
  8001. {
  8002. const auto& flData = lynx::flStudioAccess().roots.data;
  8003. const auto sounds = lynx::Metronome::loadSounds (flData.empty() ? juce::File() : lynx::platform::localFile (flData));
  8004. for (const auto& s : sounds)
  8005. metronomeFlSounds += s.fromFl ? 1 : 0;
  8006. auto renderClick = [] (int track, bool muteInsert, bool include) {
  8007. auto song = lynx::Song::makeDefault();
  8008. song.channels.clear();
  8009. song.playlist.clear();
  8010. for (auto& p : song.patterns)
  8011. p.notes.clear();
  8012. song.mixer[0].effects.clear(); // (the default Master limiter)
  8013. song.mixer[2].muted = muteInsert;
  8014. lynx::AudioEngine player (false);
  8015. player.setSong (std::move (song));
  8016. player.dispatchPendingMessages();
  8017. auto& t = player.getTransport();
  8018. t.metronome = true;
  8019. t.metronomeSound = 1; // Tick
  8020. t.metronomeTrack = track;
  8021. lynx::AudioEngine::RenderOptions o;
  8022. o.seconds = 0.25;
  8023. o.sampleRate = 44100.0;
  8024. o.pluginWarmUp = false;
  8025. o.includeMetronome = include;
  8026. return player.renderOffline (o);
  8027. };
  8028. metronomeMaster = renderClick (0, false, true);
  8029. const auto insert = renderClick (2, false, true);
  8030. const auto muted = renderClick (2, true, true);
  8031. const auto exported = renderClick (0, false, false);
  8032. // FL's Tick peaks at 1.0: its downbeat at most 0.9404 (the interpolation may land between peaks)
  8033. const auto expectHigh = metronomeFlSounds == lynx::metronome::soundCount ? lynx::metronome::downbeatGain + 1.0e-3f : 1.0f;
  8034. if (! (metronomeMaster > 0.5f && metronomeMaster < expectHigh))
  8035. metronomeResult = "ERROR master " + juce::String (metronomeMaster, 4);
  8036. else if (std::abs (insert - metronomeMaster) > 2.0e-3f)
  8037. metronomeResult = "ERROR insert " + juce::String (insert, 4);
  8038. else if (muted > 1.0e-4f)
  8039. metronomeResult = "ERROR muted insert " + juce::String (muted, 4);
  8040. else if (exported > 1.0e-4f)
  8041. metronomeResult = "ERROR in export " + juce::String (exported, 4);
  8042. }
  8043. const auto metronomeOk = metronomeResult == "OK";
  8044. // Settings › Audio "Driver settings…" with a fake driver panel (issue #13's crash, the panel's buffer kept)
  8045. const auto driverPanel = lynx::AudioEngine::driverPanelSelfTest();
  8046. // issue #134 (round 190c): the output device, its rate and its buffer changed under a playing project, on
  8047. // stand-in devices (a short run; --devicechangetest plays every instrument and effect)
  8048. const auto deviceChange = lynx::AudioEngine::deviceChangeSelfTest (10, false);
  8049. // round 190gh: export parity (B7) and MIDI device hot-plug (B8)
  8050. const auto exportParity = lynx::AudioEngine::exportParitySelfTest();
  8051. // round 190jb: exports with the live plugin instances (Surge XT when it is installed here; otherwise only noted)
  8052. juce::StringArray livePlugins;
  8053. #if JUCE_WINDOWS
  8054. livePlugins.add ("C:\\Program Files\\Common Files\\VST3\\Surge Synth Team\\Surge XT.vst3");
  8055. #elif JUCE_MAC
  8056. livePlugins.add ("/Library/Audio/Plug-Ins/VST3/Surge XT.vst3");
  8057. #else
  8058. livePlugins.add (juce::File::getSpecialLocation (juce::File::userHomeDirectory).getChildFile (".vst3/Surge XT.vst3").getFullPathName());
  8059. #endif
  8060. const auto exportLive = lynx::AudioEngine::exportLiveSelfTest ({}, livePlugins);
  8061. const auto midiHotplug = lynx::AudioEngine::midiHotplugSelfTest();
  8062. const auto midiOutPorts = lynx::AudioEngine::midiOutPortSelfTest(); // round 190jl
  8063. // Online Sessions P2 (round 169b): live sessions without a network (the JSON round trip of every entity, replicas
  8064. // through it, the invite code's keys)
  8065. const auto liveResult = lynx::livetest::selfTest (&rich);
  8066. // issue #67: every built-in effect's parameters, named and hidden (the Parametric EQ's FL law, processing, band
  8067. // mask...), at odd values, through a project save and reload: the same floats back
  8068. juce::String effectParamsResult = "OK";
  8069. {
  8070. auto song = lynx::Song::makeDefault();
  8071. song.mixer.resize (1);
  8072. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  8073. {
  8074. const auto kind = (lynx::EffectKind) k;
  8075. if (kind == lynx::EffectKind::plugin || kind == lynx::EffectKind::parallel)
  8076. continue;
  8077. auto fx = lynx::makeEffectSlot (kind);
  8078. for (std::size_t i = 0; i < fx.params.size(); ++i)
  8079. {
  8080. auto v = (float) ((double) ((i * 7919 + (std::size_t) k * 104729) % 65521) / 65521.0);
  8081. fx.params[i] = v == fx.params[i] ? 1.0f - v : v;
  8082. }
  8083. if (kind == lynx::EffectKind::fruitySend) // ("Send to" is written over the insert span)
  8084. fx.params[3] = 0.0f;
  8085. song.mixer.emplace_back();
  8086. song.mixer.back().name = "Insert " + std::to_string (song.mixer.size() - 1);
  8087. song.mixer.back().effects.push_back (fx);
  8088. }
  8089. // round 171b's Patcher round trip (coordinator): the Frequency Splitter, Fruity Delay 3 and Peak Controller
  8090. // nodes came back different (their FL defaults, e.g. the LFO speed 32750 / 65336, lost to 4 decimals)
  8091. {
  8092. auto patch = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  8093. for (const auto kind : { lynx::EffectKind::frequencySplitter, lynx::EffectKind::fruityDelay3, lynx::EffectKind::peakController,
  8094. lynx::EffectKind::reverb, lynx::EffectKind::hardwareInsert })
  8095. {
  8096. lynx::PatchNode node;
  8097. node.effect = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  8098. if (kind == lynx::EffectKind::peakController)
  8099. node.effect.params[7] = 32750.0f / 65336.0f;
  8100. node.x = 200.0f, node.y = 60.0f * (float) patch.patcher.nodes.size();
  8101. patch.patcher.nodes.push_back (node);
  8102. }
  8103. song.mixer.emplace_back();
  8104. song.mixer.back().name = "Patcher";
  8105. song.mixer.back().effects.push_back (patch);
  8106. }
  8107. juce::String why;
  8108. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  8109. if (back && back->mixer.size() == song.mixer.size())
  8110. {
  8111. const auto& a = song.mixer.back().effects[0].patcher.nodes;
  8112. const auto& b = back->mixer.back().effects[0].patcher.nodes;
  8113. for (std::size_t n = 0; n < a.size(); ++n)
  8114. if (n >= b.size() || ! (a[n].effect == b[n].effect))
  8115. effectParamsResult = juce::String ("ERROR Patcher node ") + lynx::effectInfo (a[n].effect.kind).name;
  8116. }
  8117. if (! back || back->mixer.size() != song.mixer.size())
  8118. effectParamsResult = "ERROR load " + why;
  8119. else
  8120. for (std::size_t t = 1; t + 1 < song.mixer.size() && effectParamsResult == "OK"; ++t)
  8121. if (back->mixer[t].effects.size() != 1 || back->mixer[t].effects[0].params != song.mixer[t].effects[0].params)
  8122. {
  8123. effectParamsResult = juce::String ("ERROR ") + lynx::effectInfo (song.mixer[t].effects[0].kind).name;
  8124. break;
  8125. }
  8126. }
  8127. // round 170j: the Themed plugin style (its resolution with and without art; every art draws)
  8128. const auto artResult = lynx::skin::artSelfTest();
  8129. // round 177b: a plugin's sidechain bus gets the slot's sidechain (one-click sidechain)
  8130. const auto sidechainResult = lynx::pluginSidechainSelfTest();
  8131. // round 190pj (issue #241): JSFX scripts in slots, their state, PDC, MIDI, file policy, the copy for older releases
  8132. // (rollup 0.1.31 step 7: the message thread's floating-point environment before and after it, reported and put back:
  8133. // the Linux arm64 self-test's float round trips, renders and paint tiles after this item differed from x86's: EEL2's
  8134. // code left FPCR at round-toward-minus-infinity; ysfx_lynx_fp_guard in third_party/ysfx/sources/ysfx.cpp now puts the
  8135. // caller's environment back, and this check counts in result=)
  8136. std::fenv_t fpBeforeJsfx {};
  8137. std::fegetenv (&fpBeforeJsfx);
  8138. const auto fpModeNow = [] {
  8139. #if defined (__aarch64__) && ! defined (_MSC_VER)
  8140. juce::uint64 fpcr = 0; // (an instruction, not GCC's __builtin_aarch64_get_fpcr: Apple clang has no such builtin)
  8141. asm volatile ("mrs %0, fpcr" : "=r" (fpcr));
  8142. return fpcr;
  8143. #else
  8144. return (juce::uint64) std::fegetround();
  8145. #endif
  8146. };
  8147. const auto fpModeBeforeJsfx = fpModeNow();
  8148. const auto jsfxResult = lynx::jsfx::selfTest ({});
  8149. const auto fpModeAfterJsfx = fpModeNow();
  8150. std::fesetenv (&fpBeforeJsfx);
  8151. const auto jsfxFpResult = fpModeAfterJsfx == fpModeBeforeJsfx ? juce::String ("OK")
  8152. : "CHANGED 0x" + juce::String::toHexString ((juce::int64) fpModeBeforeJsfx) + " -> 0x"
  8153. + juce::String::toHexString ((juce::int64) fpModeAfterJsfx) + " (put back)";
  8154. // round 190qi: the slot menu's Recent section, a plugin hidden from the lists, one row per plugin's formats, a MIDI
  8155. // file's preview schedule (src/Picker190qiShot.inc)
  8156. const auto picker190qiResult = picker190qiSelfTest (juce::File::getSpecialLocation (juce::File::tempDirectory));
  8157. // round 190ap: the Versions panel's list of files, and its labels on disk beside them
  8158. const auto versionsResult = lynx::versionsSelfTest();
  8159. // round 190ap: a project opened with its plugins off creates none of them and saves their settings unchanged
  8160. const auto pluginsOffResult = lynx::pluginsOffSelfTest();
  8161. const auto missingFilesResult = lynx::missingFilesSelfTest(); // issue #165
  8162. // round 190cj: a dancer's own native window stays where the stage put it (it drifted off the screen: JUCE
  8163. // moved a transparent child window by the main window's client offset on every repaint)
  8164. juce::String danceWindowDetail;
  8165. const auto danceWindowResult = lynx::danceWindowSelfTest (&danceWindowDetail);
  8166. // issue #161: a click in a panel (a native child window that takes no focus on a click) of an inactive main
  8167. // window activates it (back from another app, Space played nothing until the Browser was clicked)
  8168. const auto clickActivationResult = lynx::nativechild::clickActivationSelfTest();
  8169. // round 190jy (queue item 44): the holes the native panels get under a docked editor drawn by the main window
  8170. const auto editorHolesResult = lynx::nativechild::editorHolesSelfTest();
  8171. // round 177b: automation lanes come back from a project (track, automation, height, folded)
  8172. juce::String lanesResult = "OK";
  8173. {
  8174. auto song = lynx::Song::makeDefault();
  8175. const auto lane = lynx::autolanes::addLane (song, 3, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Vol", 0.4f);
  8176. song.playlistTracks[3].lanes[0].height = 72;
  8177. song.playlistTracks[3].lanesFolded = true;
  8178. // (the same round's clip LFO and modulators ride along)
  8179. auto& lfo = song.automations[(std::size_t) lane].lfo;
  8180. lfo.on = true;
  8181. lfo.level = -40;
  8182. lfo.speed = 30000;
  8183. lfo.flags = 1 | 4;
  8184. lfo.phase = 123456789u;
  8185. lfo.amp = { { 0, 0.5f, 0.0f }, { 960, 1.0f, 0.0f } };
  8186. lynx::Modulator mod;
  8187. mod.name = "LFO 1";
  8188. mod.shape = lynx::ModShape::square;
  8189. mod.sync = false;
  8190. mod.hz = 2.5;
  8191. mod.routes = { { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  8192. song.modulators.push_back (mod);
  8193. juce::String why;
  8194. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  8195. if (! back || back->playlistTracks.size() < 4 || ! (back->playlistTracks[3].lanes == song.playlistTracks[3].lanes)
  8196. || ! back->playlistTracks[3].lanesFolded || back->automations.size() != song.automations.size()
  8197. || ! (back->automations[(std::size_t) lane].points == song.automations[(std::size_t) lane].points)
  8198. || ! (back->automations[(std::size_t) lane].lfo == lfo) || ! (back->modulators == song.modulators))
  8199. lanesResult = "ERROR " + why;
  8200. }
  8201. // round 190cg: the loop switch, folded tracks and the tempo lane's range come back from a project; a project
  8202. // without them loads as before (loop on, nothing folded, the whole range)
  8203. juce::String arrange190cgResult = "OK";
  8204. {
  8205. auto song = lynx::Song::makeDefault();
  8206. juce::String why;
  8207. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  8208. song.loopStart = 960;
  8209. song.loopEnd = 4800;
  8210. song.loopOff = true;
  8211. song.tempoViewLow = 80.0;
  8212. song.tempoViewHigh = 160.0;
  8213. song.playlistTracks.resize (std::max<std::size_t> (song.playlistTracks.size(), 6));
  8214. song.playlistTracks[2].folded = song.playlistTracks[5].folded = true;
  8215. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  8216. if (! plain || plain->loopOff || plain->tempoViewLow != 0.0 || plain->tempoViewHigh != 0.0
  8217. || std::any_of (plain->playlistTracks.begin(), plain->playlistTracks.end(), [] (const lynx::PlaylistTrack& t) { return t.folded; }))
  8218. arrange190cgResult = "ERROR defaults " + why;
  8219. else if (! back || ! back->loopOff || back->loopStart != 960 || back->loopEnd != 4800 || back->loopPlays() || back->tempoViewLow != 80.0
  8220. || back->tempoViewHigh != 160.0 || back->playlistTracks.size() < 6 || ! back->playlistTracks[2].folded
  8221. || ! back->playlistTracks[5].folded || back->playlistTracks[3].folded)
  8222. arrange190cgResult = "ERROR round trip " + why;
  8223. }
  8224. // round 190gz (issue #170): "Link Playlist tracks to mixer tracks" comes back from a project with its links; a
  8225. // project without it loads with it off (FL's tracks)
  8226. juce::String trackauto190gzResult = "OK";
  8227. {
  8228. auto song = lynx::Song::makeDefault();
  8229. juce::String why;
  8230. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  8231. lynx::Clip clip;
  8232. clip.kind = lynx::ClipKind::pattern;
  8233. clip.pattern = 0; // (the default pattern: Kick, Clap and Hat; a second one plays Kick alone)
  8234. song.playlist.push_back (clip);
  8235. auto& kick = song.patterns.emplace_back();
  8236. kick.name = "Kick";
  8237. kick.toggleStep (0, 0);
  8238. clip.pattern = (int) song.patterns.size() - 1;
  8239. clip.track = 1;
  8240. song.playlist.push_back (clip);
  8241. lynx::autolink::setOn (song, true);
  8242. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  8243. if (! plain || plain->linkTracksToMixer)
  8244. trackauto190gzResult = "ERROR defaults " + why;
  8245. // (round 190ib: Track 1 holds Kick, Clap and Hat, so they all go through insert 1 and Track 1 is its audio
  8246. // track; Track 2 only repeats Kick and stays unassigned)
  8247. // (a .lynx keeps the tracks up to the last one that differs from a plain track: Track 2 may not be written)
  8248. else if (! back || ! back->linkTracksToMixer || back->playlistTracks.empty() || back->playlistTracks[0].mode != lynx::PlaylistTrackMode::audio
  8249. || back->playlistTracks[0].mixerTrack != 1
  8250. || (back->playlistTracks.size() > 1 && back->playlistTracks[1].mode != lynx::PlaylistTrackMode::unassigned)
  8251. || back->channels[1].mixerTrack != 1 || back->channels[2].mixerTrack != 1)
  8252. {
  8253. trackauto190gzResult = "ERROR round trip " + why;
  8254. if (back && ! back->playlistTracks.empty() && back->channels.size() >= 3)
  8255. trackauto190gzResult << " tracks " << (int) back->playlistTracks.size() << " mode " << (int) back->playlistTracks[0].mode << " insert "
  8256. << back->playlistTracks[0].mixerTrack << " routes " << back->channels[0].mixerTrack << " "
  8257. << back->channels[1].mixerTrack << " " << back->channels[2].mixerTrack;
  8258. }
  8259. }
  8260. // round 190fm: the MIDI Tools generators' settings come back from a project; a project without them loads with
  8261. // Live's defaults (and saves none)
  8262. juce::String midigen190fmResult = "OK";
  8263. {
  8264. auto song = lynx::Song::makeDefault();
  8265. juce::String why;
  8266. const auto plainJson = lynx::ProjectFile::toJson (song);
  8267. const auto plain = lynx::ProjectFile::fromJson (plainJson, why);
  8268. song.midiGenerate.tool = lynx::midigen::Settings::stacks;
  8269. song.midiGenerate.rhythmOptions.pattern = 3;
  8270. song.midiGenerate.seedOptions.voices = 2;
  8271. song.midiGenerate.shapeOptions.levels[4] = 0.25f;
  8272. song.midiGenerate.shapeOptions.preset = lynx::midigen::ShapeOptions::custom;
  8273. song.midiGenerate.stacksOptions.sequence.push_back ({ 4, 3, 67, 1, 1, 0.5f, 2.0f });
  8274. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  8275. if (! plain || ! plain->midiGenerate.isDefault() || plainJson.contains ("midiGenerate"))
  8276. midigen190fmResult = "ERROR defaults " + why;
  8277. else if (! back || ! (back->midiGenerate == song.midiGenerate))
  8278. midigen190fmResult = "ERROR round trip " + why;
  8279. }
  8280. // round 190gi: audio clip envelopes come back from a project (an entry two clips share stays shared, an unused one
  8281. // is not written, the lane shown, FL's curve modes); a project without them writes neither "clipEnvelopes" nor a
  8282. // clip field 25 (older projects save byte-identical)
  8283. juce::String clipenv190giResult = "OK";
  8284. {
  8285. auto song = lynx::Song::makeDefault();
  8286. lynx::ChannelDef channel;
  8287. channel.instrument = lynx::InstrumentKind::audioClip;
  8288. channel.samplePath = "clipenv190gi.wav";
  8289. song.channels.push_back (channel);
  8290. lynx::Clip clip;
  8291. clip.kind = lynx::ClipKind::audio;
  8292. clip.channel = (int) song.channels.size() - 1;
  8293. clip.length = lynx::ppq * 4;
  8294. song.playlist.push_back (clip);
  8295. juce::String why;
  8296. const auto plainJson = lynx::ProjectFile::toJson (song);
  8297. lynx::ClipEnvelope e;
  8298. e.volume = { { 0, 1.0f, 0.0f, 0 }, { lynx::ppq * 4, 0.25f, 0.3f, 1 } };
  8299. e.pan = { { 0, 0.5f, 0.0f, 0 }, { lynx::ppq * 2, 0.0f, 0.0f, 0 } };
  8300. e.shown = lynx::clipenv::panLane;
  8301. song.clipEnvelopes.emplace_back(); // (no clip uses it: not written)
  8302. song.clipEnvelopes.push_back (e);
  8303. song.playlist.back().envelope = 1;
  8304. auto twin = song.playlist.back();
  8305. twin.start = lynx::ppq * 8;
  8306. song.playlist.push_back (twin);
  8307. const auto json = lynx::ProjectFile::toJson (song);
  8308. const auto back = lynx::ProjectFile::fromJson (json, why);
  8309. if (plainJson.contains ("clipEnvelopes") || ! json.contains ("clipEnvelopes"))
  8310. clipenv190giResult = "ERROR written " + why;
  8311. else if (! back || back->clipEnvelopes.size() != 1 || ! (back->clipEnvelopes[0] == e))
  8312. clipenv190giResult = "ERROR table " + why;
  8313. else
  8314. {
  8315. int withEnvelope = 0;
  8316. for (const auto& c : back->playlist)
  8317. withEnvelope += c.kind == lynx::ClipKind::audio && c.envelope == 0 ? 1 : 0;
  8318. if (withEnvelope != 2)
  8319. clipenv190giResult = "ERROR clips " + why;
  8320. }
  8321. }
  8322. // round 190gx: Beats' law in the .lynx — a new project's channels are Measured; a project saved before the law
  8323. // (no "beatsLaw190gx" mark, or a nine-number warpModes list) loads Classic; a Classic channel stays Classic
  8324. juce::String beatslaw190gxResult = "OK";
  8325. {
  8326. auto song = lynx::Song::makeDefault();
  8327. lynx::ChannelDef channel;
  8328. channel.instrument = lynx::InstrumentKind::audioClip;
  8329. channel.samplePath = "beatslaw190gx.wav";
  8330. channel.sampler.keepPitch = true;
  8331. channel.sampler.stretchMethod = lynx::StretchMethod::beats;
  8332. song.channels.push_back (channel);
  8333. const auto index = song.channels.size() - 1;
  8334. juce::String why;
  8335. const auto json = lynx::ProjectFile::toJson (song);
  8336. const auto lawOf = [&] (const juce::String& text) {
  8337. const auto back = lynx::ProjectFile::fromJson (text, why);
  8338. return back && back->channels.size() > index ? (int) back->channels[index].sampler.warpModes.beatsLaw : -1;
  8339. };
  8340. auto oldVar = juce::JSON::parse (json); // (the mark removed: a project saved before 190gx)
  8341. if (auto* o = oldVar.getDynamicObject())
  8342. o->removeProperty ("beatsLaw190gx");
  8343. const auto old = juce::JSON::toString (oldVar);
  8344. auto classic = song;
  8345. classic.channels[index].sampler.warpModes.beatsLaw = lynx::WarpModeSettings::beatsLawClassic;
  8346. auto nine = song;
  8347. nine.channels[index].sampler.warpModes.beatsLoop = 0; // (a 190fm project with a changed setting: nine numbers)
  8348. // (the list with its tenth number, the law, removed: what a 190fm build wrote)
  8349. auto nineVar = juce::JSON::parse (lynx::ProjectFile::toJson (nine));
  8350. bool trimmed = false;
  8351. if (auto* channels = nineVar.getProperty ("channels", {}).getArray(); channels != nullptr && (int) index < channels->size())
  8352. if (auto* modes = (*channels)[(int) index].getProperty ("samplerSettings", {}).getProperty ("warpModes", {}).getArray(); modes != nullptr && modes->size() == 11)
  8353. {
  8354. modes->removeLast (2); // (round 190ik's eleventh number too)
  8355. trimmed = true;
  8356. }
  8357. const auto nineJson = juce::JSON::toString (nineVar);
  8358. if (! json.contains ("beatsLaw190gx") || old.contains ("beatsLaw190gx"))
  8359. beatslaw190gxResult = "ERROR mark";
  8360. else if (lawOf (json) != lynx::WarpModeSettings::beatsLawPitchAware) // (round 190ik: the new default)
  8361. beatslaw190gxResult = "ERROR new " + why;
  8362. else if (lawOf (old) != lynx::WarpModeSettings::beatsLawClassic)
  8363. beatslaw190gxResult = "ERROR old " + why;
  8364. else if (lawOf (lynx::ProjectFile::toJson (classic)) != lynx::WarpModeSettings::beatsLawClassic)
  8365. beatslaw190gxResult = "ERROR classic kept " + why;
  8366. else if (! trimmed || lawOf (nineJson) != lynx::WarpModeSettings::beatsLawClassic)
  8367. beatslaw190gxResult = "ERROR nine-number list";
  8368. }
  8369. // round 190ik: the pitch-aware Beats law and the Texture / Complex Pro engines in the .lynx — a new project's channels
  8370. // use them; a project saved before 190ik (no "warpLaw190ik" mark, or a ten-number warpModes list) keeps Beats Measured
  8371. // and the Classic engines; a channel kept on an older law stays on it when saved again
  8372. juce::String warplaw190ikResult = "OK";
  8373. {
  8374. auto song = lynx::Song::makeDefault();
  8375. lynx::ChannelDef channel;
  8376. channel.instrument = lynx::InstrumentKind::audioClip;
  8377. channel.samplePath = "warplaw190ik.wav";
  8378. channel.sampler.keepPitch = true;
  8379. channel.sampler.stretchMethod = lynx::StretchMethod::texture;
  8380. song.channels.push_back (channel);
  8381. const auto index = song.channels.size() - 1;
  8382. juce::String why;
  8383. const auto lawsOf = [&] (const juce::String& text) {
  8384. const auto back = lynx::ProjectFile::fromJson (text, why);
  8385. if (! back || back->channels.size() <= index)
  8386. return std::pair<int, int> { -1, -1 };
  8387. const auto& w = back->channels[index].sampler.warpModes;
  8388. return std::pair<int, int> { (int) w.beatsLaw, (int) w.warpLaw };
  8389. };
  8390. const auto json = lynx::ProjectFile::toJson (song);
  8391. auto oldVar = juce::JSON::parse (json); // (the mark removed: a project saved by 0.1.28 / 0.1.29)
  8392. if (auto* o = oldVar.getDynamicObject())
  8393. o->removeProperty ("warpLaw190ik");
  8394. const auto old = juce::JSON::toString (oldVar);
  8395. auto kept = song; // a channel left on the older laws
  8396. kept.channels[index].sampler.warpModes.beatsLaw = lynx::WarpModeSettings::beatsLawMeasured;
  8397. kept.channels[index].sampler.warpModes.warpLaw = lynx::WarpModeSettings::warpLawClassic;
  8398. auto ten = song; // a changed setting saved by 0.1.28: a ten-number list
  8399. ten.channels[index].sampler.warpModes.textureFlux = 60.0f;
  8400. auto tenVar = juce::JSON::parse (lynx::ProjectFile::toJson (ten));
  8401. bool trimmed = false;
  8402. if (auto* channels = tenVar.getProperty ("channels", {}).getArray(); channels != nullptr && (int) index < channels->size())
  8403. if (auto* modes = (*channels)[(int) index].getProperty ("samplerSettings", {}).getProperty ("warpModes", {}).getArray(); modes != nullptr && modes->size() == 11)
  8404. {
  8405. modes->removeLast();
  8406. modes->set (9, 1); // (0.1.28 wrote Measured)
  8407. trimmed = true;
  8408. }
  8409. const auto tenJson = juce::JSON::toString (tenVar);
  8410. const std::pair<int, int> newest { lynx::WarpModeSettings::beatsLawPitchAware, lynx::WarpModeSettings::warpLawMeasured };
  8411. const std::pair<int, int> older { lynx::WarpModeSettings::beatsLawMeasured, lynx::WarpModeSettings::warpLawClassic };
  8412. if (! json.contains ("warpLaw190ik") || old.contains ("warpLaw190ik"))
  8413. warplaw190ikResult = "ERROR mark";
  8414. else if (lawsOf (json) != newest)
  8415. warplaw190ikResult = "ERROR new " + why;
  8416. else if (lawsOf (old) != older)
  8417. warplaw190ikResult = "ERROR old " + why;
  8418. else if (lawsOf (lynx::ProjectFile::toJson (kept)) != older)
  8419. warplaw190ikResult = "ERROR older laws kept " + why;
  8420. else if (! trimmed || lawsOf (tenJson) != std::pair<int, int> { lynx::WarpModeSettings::beatsLawMeasured, lynx::WarpModeSettings::warpLawClassic })
  8421. warplaw190ikResult = "ERROR ten-number list";
  8422. }
  8423. // round 190he (issue #152): a channel window's Scaling is saved with the channel; the default (125 %) writes
  8424. // nothing, so older projects and untouched channels read as before
  8425. juce::String editorScale190heResult = "OK";
  8426. {
  8427. auto song = lynx::Song::makeDefault();
  8428. song.channels[0].editorScale = 100;
  8429. song.channels[1].editorScale = 0;
  8430. juce::String why;
  8431. const auto json = lynx::ProjectFile::toJson (song);
  8432. const auto back = lynx::ProjectFile::fromJson (json, why);
  8433. auto outOfRange = juce::JSON::parse (json);
  8434. if (auto* chans = outOfRange.getProperty ("channels", {}).getArray(); chans != nullptr && ! chans->isEmpty())
  8435. if (auto* o = (*chans)[0].getDynamicObject())
  8436. o->setProperty ("editorScale", 9000);
  8437. const auto clamped = lynx::ProjectFile::fromJson (juce::JSON::toString (outOfRange), why);
  8438. if (! back || back->channels[0].editorScale != 100 || back->channels[1].editorScale != 0)
  8439. editorScale190heResult = "ERROR round trip " + why;
  8440. else if (json.indexOf ("editorScale") != json.lastIndexOf ("editorScale"))
  8441. editorScale190heResult = "ERROR written for a default channel";
  8442. else if (! clamped || clamped->channels[0].editorScale != lynx::editorscale::maxPercent)
  8443. editorScale190heResult = "ERROR not clamped";
  8444. }
  8445. // round 190he (coordinator's gate): a project saved before 190he (no "sfModBase190he") keeps the old 0.5 centre of
  8446. // a Modulation route on a Soundfont knob; a new song, saved and opened again, centres on the knob
  8447. juce::String sfModBase190heResult = "OK";
  8448. {
  8449. auto song = lynx::Song::makeDefault();
  8450. juce::String why;
  8451. const auto json = lynx::ProjectFile::toJson (song);
  8452. auto oldVar = juce::JSON::parse (json);
  8453. if (auto* o = oldVar.getDynamicObject())
  8454. o->removeProperty ("sfModBase190he");
  8455. const auto back = lynx::ProjectFile::fromJson (json, why);
  8456. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (oldVar), why);
  8457. auto resaved = old ? lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*old), why) : std::optional<lynx::Song> {};
  8458. if (! json.contains ("sfModBase190he") || ! back || ! back->soundfontModBaseReal)
  8459. sfModBase190heResult = "ERROR new song " + why;
  8460. else if (! old || old->soundfontModBaseReal)
  8461. sfModBase190heResult = "ERROR old project " + why;
  8462. else if (! resaved || resaved->soundfontModBaseReal)
  8463. sfModBase190heResult = "ERROR old project saved again";
  8464. }
  8465. // round 190hq: tempo markers (B11) and the fader / route PDC switch (B13) in the .lynx, and the copy for an older
  8466. // LYNX (B20): an effect 0.1.27 does not know keeps its slot (as a switched-off Utility) and loses its automation,
  8467. // the later slots and their automation stay; the copy for 0.1.28 turns the markers into a plain tempo clip
  8468. juce::String community190hqResult = "OK";
  8469. {
  8470. auto song = lynx::Song::makeDefault();
  8471. song.mode = lynx::PlayMode::song;
  8472. lynx::tempomarkers::add (song, 4 * lynx::ppq, 90.0);
  8473. lynx::tempomarkers::add (song, 8 * lynx::ppq, 140.0, true);
  8474. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::anvilBus));
  8475. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  8476. for (const auto slot : { 0, 1 })
  8477. {
  8478. lynx::Automation a;
  8479. a.name = slot == 0 ? "Anvil" : "Delay";
  8480. a.target = { lynx::AutomationTargetKind::effectParam, 1, slot, 1 };
  8481. a.points = { { 0, 0.2f }, { 1920, 0.8f } };
  8482. song.automations.push_back (a);
  8483. }
  8484. juce::String why;
  8485. const auto json = lynx::ProjectFile::toJson (song);
  8486. const auto back = lynx::ProjectFile::fromJson (json, why);
  8487. auto unmarked = juce::JSON::parse (json);
  8488. if (auto* o = unmarked.getDynamicObject())
  8489. o->removeProperty ("mixerLevelPdc190hq");
  8490. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (unmarked), why);
  8491. const auto marks = back ? lynx::tempomarkers::list (*back) : std::vector<lynx::tempomarkers::Mark> {};
  8492. const auto for127 = lynx::olderlynx::forRelease (song, "0.1.27");
  8493. const auto for128 = lynx::olderlynx::forRelease (song, "0.1.28");
  8494. const auto copy127 = for127.ok ? lynx::ProjectFile::fromJson (for127.json, why) : std::optional<lynx::Song> {};
  8495. const auto copy128 = for128.ok ? lynx::ProjectFile::fromJson (for128.json, why) : std::optional<lynx::Song> {};
  8496. const auto anvilLost = std::any_of (for127.lost.begin(), for127.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  8497. return juce::String (l.text).startsWith ("Anvil Bus");
  8498. });
  8499. auto targetOf = [] (const std::optional<lynx::Song>& s, const char* name) {
  8500. if (s)
  8501. for (const auto& a : s->automations)
  8502. if (a.name == name)
  8503. return a.target;
  8504. return lynx::AutomationTarget {};
  8505. };
  8506. if (! back || ! back->compensateMixerLevels || ! old || old->compensateMixerLevels)
  8507. community190hqResult = "ERROR mixer level PDC mark " + why;
  8508. 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
  8509. || std::abs (back->tempoAt (5.0 * lynx::ppq) - 102.5) > 0.5) // (90 at bar 2, ramping into the gliding 140 at bar 3)
  8510. community190hqResult = "ERROR tempo markers round trip";
  8511. else if (! copy127 || for127.json.contains ("anvilBus") || copy127->mixer[1].effects.size() != 2
  8512. || copy127->mixer[1].effects[0].kind != lynx::EffectKind::utility || copy127->mixer[1].effects[0].enabled
  8513. || copy127->mixer[1].effects[1].kind != lynx::EffectKind::delay || ! anvilLost)
  8514. community190hqResult = "ERROR copy for 0.1.27: slots " + why;
  8515. else if (targetOf (copy127, "Anvil").kind != lynx::AutomationTargetKind::none
  8516. || ! (targetOf (copy127, "Delay") == lynx::AutomationTarget { lynx::AutomationTargetKind::effectParam, 1, 1, 1 }))
  8517. community190hqResult = "ERROR copy for 0.1.27: automation";
  8518. else if (! juce::JSON::parse (for127.json)["savedBy"].toString().equalsIgnoreCase ("0.1.27") || for127.json.contains ("tempoMarkers")
  8519. || for127.json.contains ("mixerLevelPdc190hq") || for127.json.contains ("beatsLaw190gx"))
  8520. community190hqResult = "ERROR copy for 0.1.27: fields";
  8521. else if (! copy128 || for128.json.contains ("tempoMarkers") || ! for128.json.contains ("anvilBus") || lynx::tempomarkers::automationIndex (*copy128) >= 0
  8522. || std::abs (copy128->tempoAt (5.0 * lynx::ppq) - 102.5) > 0.5 || std::abs (copy128->tempoAt (12.0 * lynx::ppq) - 140.0) > 0.01)
  8523. community190hqResult = "ERROR copy for 0.1.28";
  8524. else if (lynx::olderlynx::forRelease (song, "0.1.9").ok)
  8525. community190hqResult = "ERROR unknown release accepted";
  8526. }
  8527. // 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
  8528. // an empty Sampler, MPE note curves, muted Pattern Blocks, clips transposed past ±12, clip slots' Start markers and
  8529. // 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
  8530. // out; a DirectWave state's 36-byte sample format record is completed (0.1.28 skipped it, and the loop with it)
  8531. juce::String rollup030Result = "OK";
  8532. {
  8533. auto song = lynx::Song::makeDefault();
  8534. lynx::ChannelDef tetra;
  8535. tetra.name = "FM";
  8536. tetra.instrument = lynx::InstrumentKind::tetra;
  8537. tetra.modelParams = { 0.5f, 0.25f };
  8538. song.channels.push_back (tetra);
  8539. lynx::ChannelDef wave;
  8540. wave.name = "Piano";
  8541. wave.instrument = lynx::InstrumentKind::directwave;
  8542. {
  8543. auto doc = lynx::dw::freshDoc();
  8544. lynx::dw::Node zone;
  8545. zone.id = 3;
  8546. zone.container = true;
  8547. lynx::dw::Node format;
  8548. format.id = 0x1F7;
  8549. format.body.assign (36, 0);
  8550. format.body[20] = 2; // loop mode
  8551. format.body[24] = 44; // loop A
  8552. format.body[28] = 200; // loop B
  8553. zone.kids.push_back (format);
  8554. for (auto& n : doc.top)
  8555. if (n.id == 1 && n.container)
  8556. {
  8557. n.kids.push_back (zone);
  8558. break;
  8559. }
  8560. wave.pluginState = lynx::dw::writeDoc (doc);
  8561. }
  8562. song.channels.push_back (wave);
  8563. lynx::Note curved;
  8564. curved.key = 60;
  8565. curved.length = lynx::ppq;
  8566. lynx::NoteCurves curves;
  8567. curves.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { 96.0f, 200.0f } };
  8568. curved.curves = curves;
  8569. song.patterns[0].notes.push_back (curved);
  8570. song.patternBlocksOn = true;
  8571. lynx::patternblocks::place (song, 0, 0);
  8572. lynx::patternblocks::place (song, 0, 4 * lynx::ppq);
  8573. lynx::patternblocks::setMuted (song, 1, true);
  8574. lynx::Clip up;
  8575. up.track = 1;
  8576. up.length = 4 * lynx::ppq;
  8577. up.pitch = 24.0f;
  8578. song.playlist.push_back (up);
  8579. lynx::Clip slotClip;
  8580. slotClip.length = 4 * lynx::ppq;
  8581. if (const auto id = lynx::launcher::setClip (song, 0, 0, slotClip); id >= 0)
  8582. {
  8583. song.clipGrid->slots[(std::size_t) id].startMarker = lynx::ppq;
  8584. song.clipGrid->slots[(std::size_t) id].ownScale = true;
  8585. }
  8586. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::voiceShift)); // (a new one: revision 1)
  8587. auto ridgeSlot = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  8588. ridgeSlot.params[(std::size_t) lynx::mixsuite::ridge::k4Pink] = 1.0f;
  8589. song.mixer[2].effects.push_back (ridgeSlot);
  8590. auto hushSlot = lynx::makeEffectSlot (lynx::EffectKind::hushDeEsser); // (a new one: the measured timing, round 190iq)
  8591. hushSlot.params[(std::size_t) lynx::mixsuite::hush::allround] = 1.0f;
  8592. song.mixer[3].effects.push_back (hushSlot);
  8593. lynx::Automation coloured;
  8594. coloured.name = "Cutoff";
  8595. coloured.colour = 0xFFC03030u;
  8596. coloured.points = { { 0, 0.2f }, { 1920, 0.8f } };
  8597. song.automations.push_back (coloured);
  8598. lynx::mixsnap::take (song);
  8599. // rollup step 3 (round 190jk): Helix (190ja), the effects' hidden revisions (190is / 190it), a warped Texture
  8600. // channel with its offline transposition and tempo automation (190ik), a deactivated clip slot (190im)
  8601. lynx::ChannelDef helix;
  8602. helix.name = "WT";
  8603. helix.instrument = lynx::InstrumentKind::helix;
  8604. helix.modelParams = { 0.5f };
  8605. song.channels.push_back (helix);
  8606. lynx::ChannelDef loop;
  8607. loop.name = "Loop";
  8608. loop.instrument = lynx::InstrumentKind::sampler;
  8609. loop.sampler.stretchBeats = 8.0f;
  8610. loop.sampler.keepPitch = true;
  8611. loop.sampler.stretchMethod = lynx::StretchMethod::texture;
  8612. loop.sampler.stretchPitch = 5.0f;
  8613. song.channels.push_back (loop);
  8614. lynx::Automation tempoClip;
  8615. tempoClip.name = "Tempo";
  8616. tempoClip.target.kind = lynx::AutomationTargetKind::tempo;
  8617. tempoClip.points = { { 0, 0.4f }, { 1920, 0.6f } };
  8618. song.automations.push_back (tempoClip);
  8619. if (song.clipGrid)
  8620. for (auto& slot : song.clipGrid->slots)
  8621. slot.active = false;
  8622. auto echoSlot = lynx::makeEffectSlot (lynx::EffectKind::echoform); // (new: voicings revision 1)
  8623. echoSlot.params[(std::size_t) lynx::echosuite::echoform::voicing] = 1.0f;
  8624. song.mixer[4].effects.push_back (echoSlot);
  8625. auto haloSlot = lynx::makeEffectSlot (lynx::EffectKind::halo); // (new: revision 1 of the Measured law)
  8626. haloSlot.params[(std::size_t) lynx::verbs::halo::engineLaw] = 1.0f;
  8627. song.mixer[5].effects.push_back (haloSlot);
  8628. song.mixer[6].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::latticeMod));
  8629. auto luxeSlot = lynx::makeEffectSlot (lynx::EffectKind::luxeVerb);
  8630. luxeSlot.params[(std::size_t) lynx::luxeVerbSpaceDucking] = 0.5f;
  8631. song.mixer[7].effects.push_back (luxeSlot);
  8632. // rollup step 4 (round 190jt): Facet's automatic threshold (190jh), a MIDI Out channel (190jl), a hosted VST3's
  8633. // automated parameter (190jg), a nested Playlist folder (190jf), the Limiter's CURVE view (190jd)
  8634. auto facetSlot = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  8635. facetSlot.params[(std::size_t) lynx::facet::autoThresholdParam0 + 2] = 1.0f;
  8636. song.mixer[8].effects.push_back (facetSlot);
  8637. auto limiterSlot = lynx::makeEffectSlot (lynx::EffectKind::fruityLimiter);
  8638. limiterSlot.displayView = 1;
  8639. song.mixer[9].effects.push_back (limiterSlot);
  8640. lynx::ChannelDef midiOut;
  8641. midiOut.name = "Hardware";
  8642. midiOut.instrument = lynx::InstrumentKind::midiOut;
  8643. song.channels.push_back (midiOut);
  8644. lynx::ChannelDef hosted;
  8645. hosted.name = "Hosted";
  8646. hosted.instrument = lynx::InstrumentKind::plugin;
  8647. hosted.plugin.id = "VST3-Test Synth-1a2b3c4d-5e6f7a8b";
  8648. hosted.plugin.name = "Test Synth";
  8649. song.channels.push_back (hosted);
  8650. lynx::Automation pluginKnob;
  8651. pluginKnob.name = "Test Synth - Cutoff";
  8652. pluginKnob.target.kind = lynx::AutomationTargetKind::channelParam;
  8653. pluginKnob.target.index = (int) song.channels.size() - 1;
  8654. pluginKnob.target.param = 3;
  8655. pluginKnob.points = { { 0, 0.1f }, { 1920, 0.9f } };
  8656. song.automations.push_back (pluginKnob);
  8657. if (song.playlistTracks.size() < 4)
  8658. song.playlistTracks.resize (4);
  8659. song.playlistTracks[1].grouped = true;
  8660. song.playlistTracks[2].grouped = true;
  8661. song.playlistTracks[2].nest = 1;
  8662. // rollup step 5 (round 190kh): Hush's Single Vocal revision (190js), a slide note on an FL native generator (190jv)
  8663. song.mixer[10].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::hushDeEsser)); // (new: Single Vocal, revision 1)
  8664. lynx::ChannelDef slider;
  8665. slider.name = "Slides";
  8666. slider.instrument = lynx::InstrumentKind::sampler;
  8667. song.channels.push_back (slider);
  8668. if (song.patterns.empty())
  8669. song.patterns.emplace_back();
  8670. {
  8671. lynx::Note slide;
  8672. slide.start = 0;
  8673. slide.length = lynx::ppq;
  8674. slide.channel = (int) song.channels.size() - 1;
  8675. slide.key = 64;
  8676. slide.slide = true;
  8677. song.patterns[0].notes.push_back (slide);
  8678. }
  8679. // rollup step 6 (round 190km): Live's Crossfade Assign and a return track (190kc), the Simple Controls tab's own
  8680. // mapping (190ke), a Newtone slot whose state is version 3 (natives190kj: + the key and the notes' velocity)
  8681. song.mixer[11].crossfade = lynx::CrossfadeAssign::a;
  8682. song.crossfader = -0.5f;
  8683. song.mixer[12].liveReturn = true;
  8684. song.mixer[12].returnPre = true;
  8685. song.mixer[13].smartControls = "custom";
  8686. {
  8687. auto newtoneSlot = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  8688. lynx::newtonefx::Track nt;
  8689. nt.frames = 48000;
  8690. nt.key = 9;
  8691. lynx::newtonefx::Note n;
  8692. n.origEnd = n.curEnd = 24000;
  8693. n.origPitch = 69.0;
  8694. n.velocity = 0.8;
  8695. n.validEnd = 20000;
  8696. nt.pitches = { n };
  8697. nt.notes = 1;
  8698. newtoneSlot.state = lynx::newtonefx::writeNative (nt);
  8699. song.mixer[14].effects.push_back (newtoneSlot);
  8700. }
  8701. // rollup step 7 (round 190lc): a Peak Controller on a LYNX shape (190kl), Crest's console law (190kt), a locked
  8702. // insert beside a solo (190kn), an imported take lane (qafix190kq), a plugin that records no notes from its
  8703. // window (190ks)
  8704. {
  8705. auto peakSlot = lynx::makeEffectSlot (lynx::EffectKind::peakController);
  8706. peakSlot.params[(std::size_t) lynx::peakshapes::extraShapeParam] = (float) lynx::peakshapes::expFall / lynx::peakshapes::idScale;
  8707. song.mixer[15].effects.push_back (peakSlot);
  8708. auto crestSlot = lynx::makeEffectSlot (lynx::EffectKind::crestCompressor);
  8709. crestSlot.params[(std::size_t) lynx::dyn::crest::busLaw] = 1.0f;
  8710. song.mixer[16].effects.push_back (crestSlot);
  8711. // rollup step 8: a new Crest (round 190kw's revision 1), a Crest on round 190ky's FET law, a Ridge Strip with
  8712. // round 190lb's 4K G filters, an Echoform on round 190kw's Timeless 3 line law in a locked slot (round
  8713. // 190ld), and a Playlist track's solo lock (round 190ld)
  8714. song.mixer[16].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::crestCompressor));
  8715. auto fetSlot = lynx::makeEffectSlot (lynx::EffectKind::crestCompressor);
  8716. fetSlot.params[(std::size_t) lynx::dyn::crest::revision] = 0.0f;
  8717. fetSlot.params[(std::size_t) lynx::dyn::crest::fetLaw] = lynx::dyn::crest::fetLawValue (0);
  8718. song.mixer[16].effects.push_back (fetSlot);
  8719. auto k4gSlot = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  8720. k4gSlot.params[(std::size_t) lynx::mixsuite::ridge::k4gLaw] = 1.0f;
  8721. song.mixer[16].effects.push_back (k4gSlot);
  8722. auto lineSlot = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  8723. lineSlot.params[(std::size_t) lynx::echosuite::echoform::lineLaw] = 1.0f;
  8724. lineSlot.lockState = true;
  8725. song.mixer[16].effects.push_back (lineSlot);
  8726. // (round 190mo: track 4 is the fifth; the song had four tracks here, so this wrote one byte past the
  8727. // vector's end: the heap corruption of the Linux self-test, "corrupted size vs. prev_size" later on)
  8728. if (song.playlistTracks.size() < 5)
  8729. song.playlistTracks.resize (5);
  8730. song.playlistTracks[4].soloLock = true;
  8731. song.mixer[1].lockState = true; // (the default mixer has inserts 1…16)
  8732. song.mixer[2].solo = true;
  8733. song.playlistTracks[3].takeLane = true;
  8734. for (auto& c : song.channels)
  8735. if (c.name == "Hosted")
  8736. c.plugin.recordOwnNotes = false;
  8737. }
  8738. // rollup step 9 (round 190lu): a new Ember (round 190kw / 190lg's Saturn laws), a Prism on round 190lg's Pro-MB
  8739. // law, round 190lf's L2 law on the Limiter, cell law on Glow Leveler, direct sound on Reeverb 2, zero law on Quell
  8740. // and H-Delay loop law on Echoform, round 190ln's all-pass dispersion on Facet, and a note on an audio clip
  8741. // channel (round 190lq: FL's law in a marked project)
  8742. {
  8743. auto& m16 = song.mixer[16].effects;
  8744. m16.push_back (lynx::makeEffectSlot (lynx::EffectKind::ember)); // [5]
  8745. auto prism = lynx::makeEffectSlot (lynx::EffectKind::prismMultiband);
  8746. prism.params[(std::size_t) lynx::dyn::prism::revision] = 1.0f;
  8747. m16.push_back (prism); // [6]
  8748. auto l2 = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  8749. l2.params[(std::size_t) lynx::limiterlaw::lawParam] = lynx::limiterlaw::l2LawValue;
  8750. m16.push_back (l2); // [7]
  8751. auto glow = lynx::makeEffectSlot (lynx::EffectKind::glowLeveler);
  8752. glow.params[(std::size_t) lynx::mixsuite::glow::cellLaw] = 1.0f;
  8753. m16.push_back (glow); // [8]
  8754. auto verb = lynx::makeEffectSlot (lynx::EffectKind::reeverb2);
  8755. verb.params[(std::size_t) lynx::reeverb2DirectLaw] = 1.0f;
  8756. m16.push_back (verb); // [9]
  8757. auto quell = lynx::makeEffectSlot (lynx::EffectKind::quellDenoiser);
  8758. quell.params[(std::size_t) lynx::voicetools::quell::zeroLaw] = 1.0f;
  8759. m16.push_back (quell); // [10]
  8760. auto disperser = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  8761. disperser.params[(std::size_t) lynx::facet::dispersionCountParam] = 0.25f;
  8762. m16.push_back (disperser); // [11]
  8763. auto hybrid = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  8764. hybrid.params[(std::size_t) lynx::echosuite::echoform::hybridLaw] = 1.0f;
  8765. m16.push_back (hybrid); // [12]
  8766. lynx::ChannelDef clipChannel;
  8767. clipChannel.name = "Clip";
  8768. clipChannel.instrument = lynx::InstrumentKind::audioClip;
  8769. song.channels.push_back (clipChannel);
  8770. lynx::Note hit;
  8771. hit.length = lynx::ppq / 4;
  8772. hit.channel = (int) song.channels.size() - 1;
  8773. hit.key = 67;
  8774. song.patterns[0].notes.push_back (hit);
  8775. }
  8776. // rollup step 10 (round 190me): a new Apex Limiter and Sentry Gate (round 190lp's revision 1), a LuxeVerb on its
  8777. // Space engine (revision 1, round 190kw / 190lz), an Echoform on round 190ly's ValhallaDelay law, a new Spiral Echo
  8778. // on the Measured law (round 190ly's rate law) and a scene follow action (round 190lr)
  8779. {
  8780. auto& m16 = song.mixer[16].effects; // (after step 9's [5] … [12]: the song has inserts 0 … 16)
  8781. m16.push_back (lynx::makeEffectSlot (lynx::EffectKind::apexLimiter)); // [13]
  8782. m16.push_back (lynx::makeEffectSlot (lynx::EffectKind::sentryGate)); // [14]
  8783. auto luxe = lynx::makeEffectSlot (lynx::EffectKind::luxeVerb);
  8784. luxe.params[(std::size_t) lynx::luxeVerbSpaceFirst] = 1.0f;
  8785. m16.push_back (luxe); // [15]
  8786. auto valhalla = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  8787. valhalla.params[(std::size_t) lynx::echosuite::echoform::valhallaLaw] = 1.0f;
  8788. m16.push_back (valhalla); // [16]
  8789. auto spiral = lynx::makeEffectSlot (lynx::EffectKind::spiralEcho);
  8790. spiral.params[(std::size_t) lynx::echosuite::spiral::law] = 1.0f;
  8791. m16.push_back (spiral); // [17]
  8792. if (! song.clipGrid)
  8793. song.clipGrid.emplace();
  8794. if (song.clipGrid->scenes.empty())
  8795. song.clipGrid->scenes.emplace_back();
  8796. song.clipGrid->scenes[0].follow.enabled = true;
  8797. }
  8798. // rollup step 11 (round 190mn): a new Horizon (round 190mb / 190mj's revision and FutureVerb law), a Nebula on the
  8799. // Supermassive tone, an Orbit on the SpaceModulator laws (190mb / 190mj), round 190mg's Waves laws (Prism C4,
  8800. // Compressor Renaissance, Quell NS1, Gemini splice, LYNX Tune Waves Tune, Facet PuigTec) and a note repeat (190ma)
  8801. {
  8802. auto& m16 = song.mixer[16].effects; // (after step 10's [13] … [17])
  8803. m16.push_back (lynx::makeEffectSlot (lynx::EffectKind::horizon)); // [18]
  8804. auto nebula = lynx::makeEffectSlot (lynx::EffectKind::nebula);
  8805. nebula.params[(std::size_t) lynx::verbs::nebula::toneLaw] = 1.0f;
  8806. m16.push_back (nebula); // [19]
  8807. auto orbit = lynx::makeEffectSlot (lynx::EffectKind::orbit);
  8808. orbit.params[(std::size_t) lynx::echosuite::orbit::smLaw] = 1.0f;
  8809. orbit.params[(std::size_t) lynx::echosuite::orbit::voiceLaw] = 1.0f;
  8810. m16.push_back (orbit); // [20]
  8811. auto c4 = lynx::makeEffectSlot (lynx::EffectKind::prismMultiband);
  8812. c4.params[(std::size_t) lynx::dyn::prism::c4Law] = lynx::dyn::prism::c4LawValue (false);
  8813. m16.push_back (c4); // [21]
  8814. auto ren = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  8815. ren.params[(std::size_t) lynx::compressorRenLaw] = 1.0f;
  8816. m16.push_back (ren); // [22]
  8817. auto ns1 = lynx::makeEffectSlot (lynx::EffectKind::quellDenoiser);
  8818. ns1.params[(std::size_t) lynx::voicetools::quell::ns1Law] = 1.0f;
  8819. m16.push_back (ns1); // [23]
  8820. auto splice = lynx::makeEffectSlot (lynx::EffectKind::geminiDoubler);
  8821. splice.params[(std::size_t) lynx::voicetools::gemini::spliceLaw] = 1.0f;
  8822. m16.push_back (splice); // [24]
  8823. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  8824. tune.params[(std::size_t) lynx::lynxtune::wavesLaw] = 1.0f;
  8825. m16.push_back (tune); // [25]
  8826. auto puig = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  8827. puig.params[(std::size_t) lynx::facet::puigLawParam] = lynx::facet::puigLawValue (2);
  8828. m16.push_back (puig); // [26]
  8829. lynx::Note repeated;
  8830. repeated.length = lynx::ppq;
  8831. repeated.channel = 0;
  8832. repeated.key = 60;
  8833. repeated.repeat = 9;
  8834. song.patterns[0].notes.push_back (repeated);
  8835. }
  8836. // rollup step 12 (round 190mu): round 190mm's Waves laws (Facet's Waves design law, Compressor's Vox / API-2500 /
  8837. // RChannel EQ, Prism's C6 floating bands, Hush's Renaissance law, Low Lifter's bass law, Aether's Vitamin law,
  8838. // Ridge's omni law), round 190mk's Multiband display SPEED and a zipped channel
  8839. {
  8840. auto& m16 = song.mixer[16].effects; // (after step 11's [18] … [26])
  8841. auto req = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  8842. req.params[(std::size_t) lynx::facet::wavesLawParam] = 1.0f;
  8843. req.params[(std::size_t) lynx::facet::wavesBandParam0] = lynx::facet::waveCodeValue (lynx::facet::WaveCode::reqBell);
  8844. m16.push_back (req); // [27]
  8845. auto vox = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  8846. vox.params[8] = 1.0f;
  8847. vox.params[(std::size_t) lynx::compressorVoxLaw] = 1.0f;
  8848. m16.push_back (vox); // [28]
  8849. auto api = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  8850. api.params[(std::size_t) lynx::compressorApiLaw] = 1.0f;
  8851. m16.push_back (api); // [29]
  8852. auto rchannel = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  8853. rchannel.params[(std::size_t) lynx::compressorRenLaw] = 1.0f;
  8854. rchannel.params[(std::size_t) lynx::compressorChannelLaw] = 1.0f;
  8855. m16.push_back (rchannel); // [30]
  8856. auto c6 = lynx::makeEffectSlot (lynx::EffectKind::prismMultiband);
  8857. c6.params[(std::size_t) lynx::dyn::prism::c4Law] = lynx::dyn::prism::c4LawValue (false);
  8858. c6.params[(std::size_t) lynx::dyn::prism::c6Param (1, lynx::dyn::prism::c6On)] = 1.0f;
  8859. m16.push_back (c6); // [31]
  8860. auto rdeesser = lynx::makeEffectSlot (lynx::EffectKind::hushDeEsser);
  8861. rdeesser.params[(std::size_t) lynx::mixsuite::hush::essLaw] = 1.0f;
  8862. m16.push_back (rdeesser); // [32]
  8863. auto maxx = lynx::makeEffectSlot (lynx::EffectKind::flLowLifter);
  8864. maxx.params[(std::size_t) lynx::lowlifter::bassLaw] = 1.0f;
  8865. m16.push_back (maxx); // [33]
  8866. auto vitamin = lynx::makeEffectSlot (lynx::EffectKind::aether);
  8867. vitamin.params[(std::size_t) lynx::mixsuite::aether::vitLaw] = 1.0f;
  8868. m16.push_back (vitamin); // [34]
  8869. auto scheps = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  8870. scheps.params[(std::size_t) lynx::mixsuite::ridge::omniLaw] = 1.0f;
  8871. m16.push_back (scheps); // [35]
  8872. auto multiband = lynx::makeEffectSlot (lynx::EffectKind::fruityMultiband);
  8873. multiband.displayView = 100;
  8874. m16.push_back (multiband); // [36]
  8875. song.channels[0].zipped = true;
  8876. }
  8877. // rollup step 13 (round 190na): round 190mt's Waves laws (Facet's API-560 law, Compressor's RVox type and gate,
  8878. // Ridge's G-Channel EQ law) and round 190mv's FL Current mixer track (round 190mr's window layout: below)
  8879. int currentAt = -1;
  8880. {
  8881. auto& m16 = song.mixer[16].effects; // (after step 12's [27] … [36])
  8882. auto api560 = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  8883. api560.params[(std::size_t) lynx::facet::api560LawParam] = 1.0f;
  8884. api560.params[(std::size_t) lynx::facet::api560GainParam0 + 3] = lynx::facet::api560GainValue (6.0);
  8885. m16.push_back (api560); // [37]
  8886. auto rch = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  8887. rch.params[(std::size_t) lynx::compressorRenLaw] = 1.0f;
  8888. rch.params[(std::size_t) lynx::compressorRVoxType] = 1.0f;
  8889. rch.params[(std::size_t) lynx::compressorRchGate] = 1.0f;
  8890. m16.push_back (rch); // [38]
  8891. auto sslG = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  8892. sslG.params[(std::size_t) lynx::mixsuite::ridge::gEqLaw] = 1.0f;
  8893. sslG.params[(std::size_t) lynx::mixsuite::ridge::gHfKHz] = 0.5f;
  8894. m16.push_back (sslG); // [39]
  8895. currentAt = lynx::mixerops::addCurrentTrack (song);
  8896. if (currentAt >= 0)
  8897. song.mixer[(std::size_t) currentAt].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::facetEq));
  8898. }
  8899. // rollup step 14 (round 190nf): round 190nb's Kilohearts law on Effector, round 190mx's launched pattern clip that
  8900. // plays its pattern's events (the grid's slot clip above plays pattern 1)
  8901. {
  8902. auto khs = lynx::makeEffectSlot (lynx::EffectKind::effector);
  8903. khs.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::resonator);
  8904. khs.params[(std::size_t) lynx::khsdsp::valueParam] = 0.5f;
  8905. song.mixer[16].effects.push_back (khs); // [40]
  8906. lynx::PatternEvents knob;
  8907. knob.target.kind = lynx::AutomationTargetKind::channelVolume;
  8908. knob.target.index = 0;
  8909. knob.events = { { 0, 0.2f }, { lynx::ppq, 0.8f } };
  8910. song.patterns[0].events.push_back (knob);
  8911. }
  8912. // round 190qf (PR #260): a copy for 0.1.30 / 0.1.28 keeps 10 effect slots per insert (those releases hold 10) and
  8913. // leaves the rest out. The effects [10] … [40] this test lays on insert 16 move to inserts of their own, 10 each
  8914. // (added at the end), so every law above still reaches the copy; m16[k] below finds effect k where it went.
  8915. std::vector<int> spread16;
  8916. for (std::size_t from = 10; from < song.mixer[16].effects.size(); from += 10)
  8917. {
  8918. auto& added = song.mixer.emplace_back();
  8919. added.name = "Insert " + std::to_string (song.mixer.size() - 1);
  8920. const auto end = std::min (from + 10, song.mixer[16].effects.size());
  8921. added.effects.assign (song.mixer[16].effects.begin() + (std::ptrdiff_t) from, song.mixer[16].effects.begin() + (std::ptrdiff_t) end);
  8922. for (auto& fx : added.effects)
  8923. fx.row = -1;
  8924. spread16.push_back ((int) song.mixer.size() - 1);
  8925. }
  8926. if (song.mixer[16].effects.size() > 10)
  8927. song.mixer[16].effects.resize (10);
  8928. struct Spread16
  8929. {
  8930. const juce::var& root;
  8931. const std::vector<int>& inserts;
  8932. juce::var operator[] (int k) const
  8933. {
  8934. if (k < 10)
  8935. return root["mixer"][16]["effects"][k];
  8936. const auto chunk = (std::size_t) (k / 10 - 1);
  8937. return chunk < inserts.size() ? root["mixer"][inserts[chunk]]["effects"][k % 10] : juce::var();
  8938. }
  8939. };
  8940. const auto copy = lynx::olderlynx::forRelease (song, "0.1.28");
  8941. juce::String why;
  8942. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  8943. const auto said = [&copy] (const char* start) {
  8944. return std::any_of (copy.lost.begin(), copy.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  8945. };
  8946. const auto parsed = juce::JSON::parse (copy.json);
  8947. const auto* channels = parsed["channels"].getArray();
  8948. bool fmEmpty = false, notesCut = true, waveDone = false, wtEmpty = false, loopKnob = false;
  8949. if (channels != nullptr)
  8950. for (const auto& c : *channels)
  8951. {
  8952. if (c["name"].toString() == "FM")
  8953. fmEmpty = c["instrument"].toString() == "sampler" && ! c.hasProperty ("modelParams");
  8954. if (c["name"].toString() == "WT")
  8955. wtEmpty = c["instrument"].toString() == "sampler" && ! c.hasProperty ("modelParams");
  8956. if (c["name"].toString() == "Loop")
  8957. loopKnob = std::abs ((double) c["samplerSettings"]["pitch"] - 5.0) < 1.0e-6 && ! c["samplerSettings"].hasProperty ("stretchPitch")
  8958. && (! c["samplerSettings"]["warpModes"].isArray() || c["samplerSettings"]["warpModes"].size() <= 10);
  8959. if (c["name"].toString() == "Piano")
  8960. {
  8961. juce::MemoryOutputStream bytes;
  8962. if (juce::Base64::convertFromBase64 (bytes, c["pluginState"].toString()))
  8963. {
  8964. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  8965. if (const auto st = lynx::dw::parseState (std::vector<std::uint8_t> (b, b + bytes.getDataSize())))
  8966. for (const auto& prog : st->programs)
  8967. for (const auto& z : prog.zones)
  8968. waveDone = waveDone || (z.loopMode == 2 && z.loopA == 44 && z.loopB == 200 && z.bits == 32);
  8969. if (const auto doc = lynx::dw::readDoc (std::vector<std::uint8_t> (b, b + bytes.getDataSize())))
  8970. for (const auto& n : doc->top)
  8971. for (const auto& z : n.kids)
  8972. for (const auto& r : z.kids)
  8973. if (r.id == 0x1F7)
  8974. waveDone = waveDone && r.body.size() == 40;
  8975. }
  8976. }
  8977. }
  8978. if (const auto* patterns = parsed["patterns"].getArray())
  8979. for (const auto& pt : *patterns)
  8980. if (const auto* notes = pt["notes"].getArray())
  8981. for (const auto& n : *notes)
  8982. notesCut = notesCut && n.size() <= 19;
  8983. if (! copy.ok || ! back)
  8984. rollup030Result = "ERROR copy " + why;
  8985. else if (! fmEmpty || ! said ("Tetra is not in this release"))
  8986. rollup030Result = "ERROR Tetra channel";
  8987. else if (! waveDone)
  8988. rollup030Result = "ERROR DirectWave short record";
  8989. else if (! notesCut || ! said ("{0} note(s) lose their MPE curves"))
  8990. rollup030Result = "ERROR note curves";
  8991. else if (back->blocks.size() != 1 || back->blocks[0].start != 0 || ! said ("{0} muted Pattern Block(s)"))
  8992. rollup030Result = "ERROR muted blocks";
  8993. else if (std::none_of (back->playlist.begin(), back->playlist.end(), [] (const lynx::Clip& c) { return c.pitch == 12.0f; })
  8994. || ! said ("{0} clip(s) transposed"))
  8995. rollup030Result = "ERROR clip pitch";
  8996. else if (copy.json.contains ("startMarker") || copy.json.contains ("clipScale") || ! said ("{0} clip slot(s) launch") || ! said ("Clip scales"))
  8997. rollup030Result = "ERROR clip slots";
  8998. else if (! said ("Voice Shift's Measured law") || ! said ("Ridge Strip's 4K Pink EQ") || ! said ("Hush De-esser's Allround mode")
  8999. || parsed["mixer"][1]["effects"][0]["params"].size() > lynx::voiceshift::revision
  9000. || parsed["mixer"][3]["effects"][0]["params"].size() > lynx::mixsuite::hush::timing)
  9001. rollup030Result = "ERROR effects";
  9002. else if (copy.json.contains ("mixSnapshots") || ! said ("Mix snapshots") || ! said ("Automation clip colours")
  9003. || std::any_of (back->automations.begin(), back->automations.end(), [] (const lynx::Automation& a) { return a.colour != 0; }))
  9004. rollup030Result = "ERROR view items";
  9005. else if (! wtEmpty || ! said ("Helix is not in this release"))
  9006. rollup030Result = "ERROR Helix channel";
  9007. else if (! said ("Echoform's echo voicings") || ! said ("Epoch Verb, Atrium, Foil Plate and Halo") || ! said ("Lattice Mod plays")
  9008. || ! said ("LuxeVerb's Space ducking")
  9009. || parsed["mixer"][4]["effects"][0]["params"].size() > lynx::echosuite::echoform::revision
  9010. || parsed["mixer"][5]["effects"][0]["params"].size() > lynx::verbs::halo::revision
  9011. || parsed["mixer"][6]["effects"][0]["params"].size() > lynx::echosuite::lattice::revision
  9012. || parsed["mixer"][7]["effects"][0]["params"].size() > lynx::luxeVerbSpaceDucking)
  9013. rollup030Result = "ERROR step-3 effects";
  9014. else if (! loopKnob || ! said ("Texture and Complex Pro play") || ! said ("Complex Pro and Texture transpositions") || ! said ("Warped samples do not follow"))
  9015. rollup030Result = juce::String ("ERROR warp engines ") + (loopKnob ? "" : "knob ") + (said ("Texture and Complex Pro play") ? "" : "engines ")
  9016. + (said ("Complex Pro and Texture transpositions") ? "" : "transpose ") + (said ("Warped samples do not follow") ? "" : "tempo");
  9017. else if (copy.json.contains ("\"inactive\"") || ! said ("{0} deactivated clip slot(s)"))
  9018. rollup030Result = "ERROR deactivated slots";
  9019. else if (! said ("Facet EQ's automatic dynamic thresholds") || parsed["mixer"][8]["effects"][0]["params"].size() > lynx::facet::autoThresholdParam0)
  9020. rollup030Result = "ERROR Facet automatic threshold";
  9021. else if (! said ("MIDI Out channels and plugins' MIDI output") || ! said ("Automation of hosted CLAP and VST3 plugins"))
  9022. rollup030Result = juce::String ("ERROR engine notes ") + (said ("MIDI Out channels") ? "" : "midi-out ") + (said ("Automation of hosted") ? "" : "timed");
  9023. else if (copy.json.contains ("playlistTrackNest") || copy.json.contains ("displayView") || ! said ("{0} track(s) in nested Playlist folders")
  9024. || ! said ("Fruity Limiter's CURVE view"))
  9025. rollup030Result = "ERROR step-4 view items";
  9026. else if (! said ("Hush De-esser's Single Vocal mode") || ! said ("Slide notes on FL's native generators"))
  9027. rollup030Result = juce::String ("ERROR step-5 engine notes ") + (said ("Hush De-esser's Single Vocal") ? "" : "hush ") + (said ("Slide notes") ? "" : "slides");
  9028. else if (! said ("The crossfader (Live's Crossfade Assign)") || ! said ("Live return tracks show") || ! said ("The Simple Controls tab's")
  9029. || copy.json.contains ("\"crossfade") || copy.json.contains ("liveReturn") || copy.json.contains ("returnPre")
  9030. || copy.json.contains ("smartControls") || copy.json.contains ("engineRev"))
  9031. rollup030Result = "ERROR step-6 mixer items";
  9032. else if (const auto nts = [&parsed] {
  9033. juce::MemoryOutputStream bytes;
  9034. std::vector<std::uint8_t> st;
  9035. if (juce::Base64::convertFromBase64 (bytes, parsed["mixer"][14]["effects"][0]["state"].toString()))
  9036. st.assign (static_cast<const std::uint8_t*> (bytes.getData()), static_cast<const std::uint8_t*> (bytes.getData()) + bytes.getDataSize());
  9037. return st;
  9038. }();
  9039. ! said ("Newtone's detected key") || lynx::newtonefx::nativeVersionOf (nts) != 2 || ! lynx::newtonefx::parseNative (nts)
  9040. || lynx::newtonefx::parseNative (nts)->pitches.size() != 1 || lynx::newtonefx::parseNative (nts)->pitches[0].curEnd != 24000)
  9041. rollup030Result = "ERROR step-6 Newtone state";
  9042. else if (! said ("The Peak Controller's LYNX LFO shapes") || ! said ("Crest Compressor's console law") || ! said ("Mixer lock states")
  9043. || ! said ("{0} imported take lane(s)")
  9044. || parsed["mixer"][15]["effects"][0]["params"].size() > lynx::peakshapes::extraShapeParam
  9045. || parsed["mixer"][16]["effects"][0]["params"].size() > lynx::dyn::crest::busLaw
  9046. || copy.json.contains ("lockState") || copy.json.contains ("playlistTakeLanes") || copy.json.contains ("recordOwnNotes"))
  9047. rollup030Result = "ERROR step-7 items";
  9048. else if (const Spread16 m16 { parsed, spread16 };
  9049. ! said ("Crest Compressor's styles play their earlier laws") || ! said ("Crest Compressor's FET law")
  9050. || ! said ("Ridge Strip's measured SSL 4K G / 4K E filters") || ! said ("Echoform's Timeless 3 line law")
  9051. || ! said ("Lock states of effect slots and Playlist tracks") || copy.json.contains ("playlistTrackSoloLocks")
  9052. || m16[1]["params"].size() > lynx::dyn::crest::busLaw || m16[2]["params"].size() > lynx::dyn::crest::busLaw
  9053. || m16[3]["params"].size() > lynx::mixsuite::ridge::k4Pink || m16[4]["params"].size() > lynx::echosuite::echoform::revision)
  9054. rollup030Result = "ERROR step-8 items";
  9055. else if (const Spread16 m16 { parsed, spread16 };
  9056. ! said ("Ember's Saturn styles") || ! said ("Prism Multiband's Pro-MB band law") || ! said ("The Limiter's L2 law")
  9057. || ! said ("Glow Leveler's cell law") || ! said ("Reeverb 2's measured direct sound") || ! said ("Quell's zero law")
  9058. || ! said ("Facet EQ's all-pass dispersion") || ! said ("Echoform's H-Delay loop law")
  9059. || ! said ("Notes on audio clip channels play cut") || copy.json.contains ("clipNotes190lq") || copy.json.contains ("clipNoteLegacy")
  9060. || m16[5]["params"].size() > lynx::mixsuite::ember::revision || m16[6]["params"].size() > lynx::dyn::prism::revision
  9061. || m16[7]["params"].size() > lynx::limiterlaw::lawParam || m16[8]["params"].size() > lynx::mixsuite::glow::cellLaw
  9062. || m16[9]["params"].size() > lynx::reeverb2DirectLaw || m16[10]["params"].size() > lynx::voicetools::quell::zeroLaw
  9063. || m16[11]["params"].size() > lynx::facet::autoThresholdParam0 || m16[12]["params"].size() > lynx::echosuite::echoform::revision)
  9064. rollup030Result = "ERROR step-9 items";
  9065. else if (const Spread16 m16 { parsed, spread16 };
  9066. ! said ("Apex Limiter's styles") || ! said ("Sentry Gate plays its earlier") || ! said ("LuxeVerb's Space engine plays")
  9067. || ! said ("Echoform's ValhallaDelay loop law") || ! said ("Spiral Echo's Measured loop") || ! said ("{0} scene follow action")
  9068. || m16[13]["params"].size() > lynx::apex::pRevision || m16[14]["params"].size() > (int) lynx::dyn::sentry::revision
  9069. || m16[15]["params"].size() > lynx::luxeVerbSpaceDucking || m16[16]["params"].size() > lynx::echosuite::echoform::revision
  9070. || m16[17]["params"].size() > (int) lynx::echosuite::spiral::rateLaw || parsed["clipGrid"]["scenes"][0].hasProperty ("follow"))
  9071. rollup030Result = "ERROR step-10 items";
  9072. else if (const Spread16 m16 { parsed, spread16 };
  9073. ! said ("Horizon plays its earlier") || ! said ("Nebula's classic modes") || ! said ("Orbit plays its own voices")
  9074. || ! said ("Prism Multiband's C4 law") || ! said ("Compressor's Renaissance law") || ! said ("Quell's NS1 law")
  9075. || ! said ("Gemini Doubler's splice law") || ! said ("LYNX Tune's Waves Tune") || ! said ("Facet EQ's PuigTec law")
  9076. || ! said ("{0} note(s) play once instead of repeating")
  9077. || m16[18]["params"].size() > lynx::verbs::horizon::revision || m16[19]["params"].size() > lynx::verbs::nebula::toneLaw
  9078. || m16[20]["params"].size() > (int) lynx::echosuite::orbit::smLaw || m16[21]["params"].size() > (int) lynx::dyn::prism::revision
  9079. || m16[22]["params"].size() > lynx::compressorRenLaw || m16[23]["params"].size() > (int) lynx::voicetools::quell::zeroLaw
  9080. || m16[24]["params"].size() > (int) lynx::voicetools::gemini::spliceLaw || m16[25]["params"].size() > (int) lynx::lynxtune::wavesLaw
  9081. || m16[26]["params"].size() > lynx::facet::autoThresholdParam0)
  9082. rollup030Result = "ERROR step-11 items";
  9083. else if (const Spread16 m16 { parsed, spread16 };
  9084. ! said ("Facet EQ's Waves design law") || ! said ("Compressor's Vox law") || ! said ("Compressor's bus law")
  9085. || ! said ("Compressor's channel EQ") || ! said ("Prism Multiband's floating bands") || ! said ("Hush De-esser's Renaissance law")
  9086. || ! said ("Low Lifter's bass law") || ! said ("Aether's Vitamin law") || ! said ("Ridge Strip's omni law")
  9087. || ! said ("Fruity Multiband Compressor's display SPEED") || ! said ("{0} zipped channel(s)")
  9088. || m16[27]["params"].size() > lynx::facet::autoThresholdParam0 || m16[28]["params"].size() > lynx::compressorRenLaw
  9089. || m16[29]["params"].size() > lynx::compressorRenLaw || m16[30]["params"].size() > lynx::compressorRenLaw
  9090. || m16[31]["params"].size() > (int) lynx::dyn::prism::revision || m16[32]["params"].size() > (int) lynx::mixsuite::hush::timing
  9091. || m16[33]["params"].size() > (int) lynx::lowlifter::bassLaw || m16[34]["params"].size() > (int) lynx::mixsuite::aether::vitLaw
  9092. || m16[35]["params"].size() > (int) lynx::mixsuite::ridge::k4Pink || m16[36].hasProperty ("displayView")
  9093. || copy.json.contains ("\"zipped\""))
  9094. rollup030Result = "ERROR step-12 items";
  9095. else if (const Spread16 m16 { parsed, spread16 };
  9096. ! said ("Facet EQ's API-560 law") || ! said ("Compressor's RVox type") || ! said ("Compressor's gate")
  9097. || ! said ("Ridge Strip's G-Channel EQ law") || ! said ("The Current mixer track shows as an ordinary insert")
  9098. || m16[37]["params"].size() > lynx::facet::autoThresholdParam0 || m16[38]["params"].size() > lynx::compressorRenLaw
  9099. || m16[39]["params"].size() > (int) lynx::mixsuite::ridge::k4Pink || currentAt < 0
  9100. || parsed["mixer"][currentAt].hasProperty ("current") || parsed["mixer"][currentAt]["effects"].size() != 1)
  9101. rollup030Result = "ERROR step-13 items";
  9102. else if (const auto laid = lynx::olderlynx::forRelease (lynx::ProjectFile::withWindowLayout (lynx::ProjectFile::toJson (lynx::Song::makeDefault()),
  9103. { 0, "rollup step 13" }), "0.1.28");
  9104. ! laid.ok || laid.json.contains ("windowLayout")
  9105. || std::none_of (laid.lost.begin(), laid.lost.end(), [] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith ("The window layout saved"); }))
  9106. rollup030Result = "ERROR step-13 window layout";
  9107. else if (const Spread16 m16 { parsed, spread16 };
  9108. ! said ("Effector's Kilohearts laws") || ! said ("Launched pattern clips play without their pattern's events")
  9109. || m16[40]["params"].size() > lynx::khsdsp::lawParam || parsed["patterns"][0]["events"].size() != 1)
  9110. rollup030Result = juce::String ("ERROR step-14 items (") + (said ("Effector's Kilohearts laws") ? "" : "no Kilohearts line, ")
  9111. + (said ("Launched pattern clips play without their pattern's events") ? "" : "no launched-clip line, ")
  9112. + "Effector params " + juce::String (m16[40]["params"].size()) + ", events " + juce::String (parsed["patterns"][0]["events"].size()) + ")";
  9113. else if (const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.28");
  9114. ! plain.ok || std::any_of (plain.lost.begin(), plain.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  9115. const auto t = juce::String (l.text);
  9116. return t.startsWith ("Tetra") || t.contains ("MPE") || t.contains ("Pattern Block") || t.contains ("Voice Shift")
  9117. || t.contains ("Ridge") || t.contains ("Hush") || t.startsWith ("Automation clip colours") || t.startsWith ("Mix snapshots")
  9118. || t.startsWith ("Helix") || t.contains ("Echoform") || t.contains ("Halo") || t.contains ("Lattice") || t.contains ("LuxeVerb")
  9119. || t.contains ("Texture") || t.contains ("Beats'") || t.startsWith ("Warped") || t.contains ("deactivated")
  9120. || t.contains ("Facet") || t.contains ("MIDI Out") || t.contains ("hosted CLAP") || t.contains ("nested Playlist")
  9121. || t.contains ("CURVE") || t.startsWith ("Slide notes") || t.contains ("crossfader") || t.contains ("return tracks")
  9122. || t.contains ("Controls tab") || t.startsWith ("Harmor") || t.startsWith ("Newtone")
  9123. || t.contains ("Peak Controller") || t.contains ("console law") || t.startsWith ("Mixer lock") || t.contains ("take lane")
  9124. || t.contains ("Crest") || t.startsWith ("Lock states") || t.startsWith ("Ember") || t.startsWith ("Prism")
  9125. || t.contains ("L2 law") || t.startsWith ("Glow") || t.startsWith ("Reeverb 2") || t.startsWith ("Quell")
  9126. || t.contains ("audio clip channels") || t.startsWith ("Apex") || t.startsWith ("Sentry") || t.startsWith ("Spiral")
  9127. || t.contains ("scene follow") || t.startsWith ("Horizon") || t.startsWith ("Nebula") || t.startsWith ("Orbit")
  9128. || t.startsWith ("Compressor's") || t.startsWith ("Gemini") || t.startsWith ("LYNX Tune") || t.contains ("Repeat")
  9129. || t.startsWith ("Low Lifter") || t.startsWith ("Aether") || t.startsWith ("Ridge Strip's omni") || t.startsWith ("Hush De-esser's Renaissance")
  9130. || t.startsWith ("Fruity Multiband") || t.contains ("zipped") || t.contains ("Current mixer track") || t.contains ("window layout")
  9131. || t.startsWith ("Effector's Kilohearts") || t.startsWith ("Launched pattern clips");
  9132. }))
  9133. rollup030Result = "ERROR a plain project reports a loss it does not have";
  9134. }
  9135. // 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
  9136. // 0.1.31 rounds save (190ni LYNX Model, 190nh Kilohearts part-2 laws, 190ne track clips, 190nc Solo / Cue); round
  9137. // 190nb's laws (0.1.30 has them) stay; the copy for 0.1.28 runs this step first; a plain project loses nothing
  9138. juce::String rollup031Result = "OK";
  9139. {
  9140. auto song = lynx::Song::makeDefault();
  9141. lynx::ChannelDef model;
  9142. model.name = "Bars";
  9143. model.instrument = lynx::InstrumentKind::lynxModel;
  9144. model.modelParams = { 0.0f, 0.5f, 0.3f };
  9145. song.channels.push_back (model);
  9146. auto comb = lynx::makeEffectSlot (lynx::EffectKind::effector);
  9147. comb.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::comb);
  9148. comb.params[(std::size_t) lynx::khsdsp::valueParam] = 0.4f;
  9149. auto resonator = lynx::makeEffectSlot (lynx::EffectKind::effector);
  9150. resonator.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::resonator);
  9151. resonator.params[(std::size_t) lynx::khsdsp::valueParam] = 0.5f;
  9152. song.mixer[3].effects.push_back (comb); // [0]
  9153. song.mixer[3].effects.push_back (resonator); // [1]
  9154. song.patterns[0].trackClip = true;
  9155. if (song.playlistTracks.empty())
  9156. song.playlistTracks.resize (1);
  9157. song.playlistTracks[0].ownClips = true;
  9158. lynx::launcher::ensureGrid (song);
  9159. song.clipGrid->cue.cueMode = true;
  9160. song.clipGrid->cue.out = 2;
  9161. song.mixer[2].cue = true;
  9162. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  9163. const auto older = lynx::olderlynx::forRelease (song, "0.1.28");
  9164. juce::String why;
  9165. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  9166. const auto count = [] (const lynx::olderlynx::Copy& c, const char* start) {
  9167. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  9168. };
  9169. const auto parsed = juce::JSON::parse (copy.json);
  9170. const auto& fx = parsed["mixer"][3]["effects"];
  9171. juce::String bars;
  9172. if (const auto* channels = parsed["channels"].getArray())
  9173. for (const auto& c : *channels)
  9174. if (c["name"].toString() == "Bars")
  9175. bars = c["instrument"].toString() + (c.hasProperty ("modelParams") ? "+params" : "");
  9176. const char* lines[] = { "LYNX Model is not in this release", "Effector's newer Kilohearts laws", "{0} track clip(s) show as ordinary patterns",
  9177. "Live's Solo/Cue settings" };
  9178. if (! copy.ok || ! back)
  9179. rollup031Result = "ERROR copy " + copy.error + why;
  9180. else if (! parsed["savedBy"].toString().equalsIgnoreCase ("0.1.30") || lynx::olderlynx::releases()[2] != "0.1.30") // (rollup 0.1.32: 0.1.31 is [0]; rollup 0.1.33, round 190tf: 0.1.32 is [0])
  9181. rollup031Result = "ERROR release list / stamp";
  9182. else if (bars != "sampler")
  9183. rollup031Result = "ERROR LYNX Model channel: " + bars;
  9184. else if (fx[0]["params"].size() > lynx::khsdsp::lawParam || fx[1]["params"].size() <= lynx::khsdsp::lawParam
  9185. || lynx::khsdsp::lawOf ((float) (double) fx[1]["params"][lynx::khsdsp::lawParam]) != lynx::khsdsp::Law::resonator)
  9186. rollup031Result = "ERROR Kilohearts laws (comb params " + juce::String (fx[0]["params"].size()) + ")";
  9187. else if (copy.json.contains ("\"trackClip\"") || copy.json.contains ("playlistOwnClips") || parsed["clipGrid"].hasProperty ("cue")
  9188. || parsed["mixer"][2].hasProperty ("cue"))
  9189. rollup031Result = "ERROR 0.1.31 keys left in the copy";
  9190. else if (std::any_of (std::begin (lines), std::end (lines), [&] (const char* l) { return count (copy, l) != 1 || count (older, l) != 1; }))
  9191. rollup031Result = "ERROR loss lines (each once, in both copies)";
  9192. else if (! older.ok || older.json.contains ("lynxmodel") || juce::JSON::parse (older.json)["mixer"][3]["effects"][1]["params"].size() > lynx::khsdsp::lawParam
  9193. || count (older, "Effector's Kilohearts laws") != 1)
  9194. rollup031Result = "ERROR copy for 0.1.28 after the 0.1.30 step";
  9195. else if (const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30"); ! plain.ok || ! plain.lost.empty())
  9196. rollup031Result = "ERROR a plain project loses something in the copy for 0.1.30";
  9197. }
  9198. // 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 —
  9199. // 190ns's Created date (#231, ProjectInfo.created: 0.1.30 reads it), its linked audio track ⇄ insert names and
  9200. // colours (#235: the same mixerTrack / name / colour fields; only the syncing is new), 190nq's "(target deleted)"
  9201. // automation names (#226: text) — and 190np's onboarding, 190nq's ruler / fade switches and 190nr's installed-files
  9202. // list live in the profile, never in a project. Checked: the copy keeps them, reports no loss and has every key of
  9203. // the project (the copy keeps every key the project has, none dropped or renamed)
  9204. juce::String rollup031s2Result = "OK";
  9205. {
  9206. auto song = lynx::Song::makeDefault();
  9207. song.info.created = 1763600000.0;
  9208. if (song.mixer.size() < 3)
  9209. song.mixer.resize (3);
  9210. song.playlistTracks.resize (std::max<std::size_t> (2, song.playlistTracks.size()));
  9211. auto& vox = song.playlistTracks[1];
  9212. vox.mode = lynx::PlaylistTrackMode::audio;
  9213. vox.mixerTrack = 2;
  9214. vox.name = song.mixer[2].name = "Vox";
  9215. vox.colour = song.mixer[2].colour = 0xff8040c0;
  9216. song.patterns[0].name = lynx::mixerops::targetDeletedName ("BEAT BUS - Send level");
  9217. const auto keysOf = [] (const juce::var& v) {
  9218. std::set<juce::String> keys;
  9219. std::function<void (const juce::var&, const juce::String&)> walk = [&] (const juce::var& x, const juce::String& path) {
  9220. if (auto* o = x.getDynamicObject())
  9221. for (const auto& p : o->getProperties())
  9222. {
  9223. if (path.isEmpty() && (p.name.toString() == "savedBy" || p.name.toString() == "copiedFrom")) // (the copy's stamp)
  9224. continue;
  9225. keys.insert (path + "/" + p.name.toString());
  9226. walk (p.value, path + "/" + p.name.toString());
  9227. }
  9228. else if (auto* a = x.getArray())
  9229. for (const auto& e : *a)
  9230. walk (e, path + "[]");
  9231. };
  9232. walk (v, {});
  9233. return keys;
  9234. };
  9235. const auto original = juce::JSON::parse (lynx::ProjectFile::toJson (song));
  9236. for (const auto* release : { "0.1.30", "0.1.28" })
  9237. {
  9238. const auto copy = lynx::olderlynx::forRelease (song, release);
  9239. juce::String why;
  9240. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  9241. if (! copy.ok || ! back)
  9242. rollup031s2Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  9243. else if (back->info.created != song.info.created)
  9244. rollup031s2Result = juce::String ("ERROR Created date in the copy for ") + release;
  9245. else if (back->playlistTracks.size() < 2 || back->playlistTracks[1].mixerTrack != 2 || back->playlistTracks[1].colour != vox.colour
  9246. || back->playlistTracks[1].name != "Vox" || back->mixer[2].colour != vox.colour || back->mixer[2].name != "Vox")
  9247. rollup031s2Result = juce::String ("ERROR linked track / insert in the copy for ") + release;
  9248. else if (back->patterns[0].name != song.patterns[0].name)
  9249. rollup031s2Result = juce::String ("ERROR automation name in the copy for ") + release;
  9250. else if (! copy.lost.empty())
  9251. rollup031s2Result = juce::String ("ERROR loss lines in the copy for ") + release + ": " + juce::String (copy.lost.front().text);
  9252. else if (const auto kept = keysOf (juce::JSON::parse (copy.json)), all = keysOf (original); juce::String (release) == "0.1.30" && kept != all)
  9253. {
  9254. juce::StringArray diff;
  9255. for (const auto& k : all)
  9256. if (kept.count (k) == 0)
  9257. diff.add ("-" + k);
  9258. for (const auto& k : kept)
  9259. if (all.count (k) == 0)
  9260. diff.add ("+" + k);
  9261. rollup031s2Result = "ERROR keys differ in the copy for 0.1.30: " + diff.joinIntoString (" ").substring (0, 300);
  9262. }
  9263. if (rollup031s2Result != "OK")
  9264. break;
  9265. }
  9266. }
  9267. // 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
  9268. // else — 190nu's key markers' keys ("markerKeys" beside each pattern's marker list; the markers and their names
  9269. // stay) and 190nw's tracker view settings (root "tracker"; the notes are the patterns' own) — each with its one
  9270. // line, in both copies; 190nx (offline switch, --demo) and 190nt (site) save nothing in a project
  9271. juce::String rollup031s3Result = "OK";
  9272. {
  9273. using namespace lynx::keyregions;
  9274. auto song = lynx::Song::makeDefault();
  9275. auto& p = song.patterns[(std::size_t) song.currentPattern];
  9276. p.markers.push_back ({ 2 * lynx::ppq, "Verse", 0, 4 });
  9277. addKeyMarker (p, 0, { State::key, { 9, flScaleNamed ("Minor Harmonic") } });
  9278. addKeyMarker (p, 4 * lynx::ppq, { State::key, { 2, flScaleNamed ("Other Dorian") } });
  9279. for (int c = 0; c < 2; ++c)
  9280. song.channels.emplace_back().name = "S3-" + std::to_string (c);
  9281. lynx::uids::normalize (song);
  9282. song.tracker.rowsPerBeat = 6;
  9283. song.tracker.showPan = true;
  9284. song.tracker.groups.push_back ({ "Pair", { song.channels[song.channels.size() - 2].uid, song.channels.back().uid } });
  9285. const auto keysOf = [] (const juce::var& v) {
  9286. std::set<juce::String> keys;
  9287. std::function<void (const juce::var&, const juce::String&)> walk = [&] (const juce::var& x, const juce::String& path) {
  9288. if (auto* o = x.getDynamicObject())
  9289. for (const auto& prop : o->getProperties())
  9290. {
  9291. if (path.isEmpty() && (prop.name.toString() == "savedBy" || prop.name.toString() == "copiedFrom")) // (the copy's stamp)
  9292. continue;
  9293. keys.insert (path + "/" + prop.name.toString());
  9294. walk (prop.value, path + "/" + prop.name.toString());
  9295. }
  9296. else if (auto* a = x.getArray())
  9297. for (const auto& e : *a)
  9298. walk (e, path + "[]");
  9299. };
  9300. walk (v, {});
  9301. return keys;
  9302. };
  9303. const auto json = lynx::ProjectFile::toJson (song);
  9304. auto expected = keysOf (juce::JSON::parse (json));
  9305. for (auto it = expected.begin(); it != expected.end();)
  9306. it = it->startsWith ("/tracker") || it->contains ("/markerKeys") ? expected.erase (it) : std::next (it);
  9307. const char* lines[] = { "key marker(s) in the Piano roll", "The tracker's view settings" };
  9308. for (const auto* release : { "0.1.30", "0.1.28" })
  9309. {
  9310. const auto copy = lynx::olderlynx::forRelease (song, release);
  9311. juce::String why;
  9312. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  9313. const auto count = [&copy] (const char* l) {
  9314. return (int) std::count_if (copy.lost.begin(), copy.lost.end(), [l] (const lynx::olderlynx::Loss& x) { return juce::String (x.text).contains (l); });
  9315. };
  9316. if (! copy.ok || ! back)
  9317. rollup031s3Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  9318. else if (copy.json.contains ("markerKeys") || copy.json.contains ("\"tracker\""))
  9319. rollup031s3Result = juce::String ("ERROR 0.1.31 keys left in the copy for ") + release;
  9320. else if (std::any_of (std::begin (lines), std::end (lines), [&] (const char* l) { return count (l) != 1; }))
  9321. rollup031s3Result = juce::String ("ERROR loss lines in the copy for ") + release + " (" + juce::String ((int) copy.lost.size()) + ")";
  9322. else if (const auto& bp = back->patterns[(std::size_t) back->currentPattern];
  9323. bp.markers.size() != p.markers.size() || bp.notes != p.notes
  9324. || std::any_of (bp.markers.begin(), bp.markers.end(), [] (const lynx::Marker& m) { return keyOf (m).has_value(); }))
  9325. rollup031s3Result = juce::String ("ERROR markers / notes in the copy for ") + release;
  9326. else if (juce::String (release) == "0.1.30" && (copy.lost.size() != 2 || keysOf (juce::JSON::parse (copy.json)) != expected))
  9327. rollup031s3Result = "ERROR the copy for 0.1.30 drops more than the two (" + juce::String ((int) copy.lost.size()) + " lines)";
  9328. if (rollup031s3Result != "OK")
  9329. break;
  9330. }
  9331. }
  9332. // round chord2_190nu (discussion #105): the Piano roll's key markers come back from a project (their keys beside the
  9333. // marker list, so older releases keep the markers), the copy for 0.1.30 / 0.1.28 drops the keys with a line, and
  9334. // a MIDI file carries them as key signatures (with the exact scale in a "Key: ..." marker meta event)
  9335. juce::String keys190nuResult = "OK";
  9336. {
  9337. using namespace lynx::keyregions;
  9338. auto song = lynx::Song::makeDefault();
  9339. auto& p = song.patterns[(std::size_t) song.currentPattern];
  9340. const auto bar = 4 * lynx::ppq;
  9341. const lynx::projectkey::Key dorian { 2, flScaleNamed ("Other Dorian") }, harmonic { 0, flScaleNamed ("Minor Harmonic") };
  9342. p.markers.push_back ({ bar / 2, "Verse", 0, 4 });
  9343. addKeyMarker (p, 0, { State::key, dorian });
  9344. addKeyMarker (p, bar, { State::key, harmonic });
  9345. addKeyMarker (p, 2 * bar, { State::none, {} });
  9346. lynx::Note n;
  9347. n.key = 62;
  9348. n.length = lynx::ppq;
  9349. p.notes.push_back (n);
  9350. p.lengthTicks = 3 * bar; // (a MIDI file gets the key changes within the pattern's length)
  9351. juce::String why;
  9352. const auto json = lynx::ProjectFile::toJson (song);
  9353. const auto back = lynx::ProjectFile::fromJson (json, why);
  9354. bool oldShape = true; // (every marker array as 0.1.30 reads it: 4 or 5 items)
  9355. const auto parsedJson = juce::JSON::parse (json); // (kept: operator[] refers into it)
  9356. if (auto* patterns = parsedJson["patterns"].getArray())
  9357. for (const auto& pv : *patterns)
  9358. if (auto* ms = pv["markers"].getArray())
  9359. for (const auto& m : *ms)
  9360. oldShape = oldShape && m.isArray() && (m.size() == 4 || m.size() == 5);
  9361. const auto for130 = lynx::olderlynx::forRelease (song, "0.1.30");
  9362. const auto for128 = lynx::olderlynx::forRelease (song, "0.1.28");
  9363. const auto copy130 = for130.ok ? lynx::ProjectFile::fromJson (for130.json, why) : std::optional<lynx::Song> {};
  9364. 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)"); });
  9365. const auto file = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-keys190nu.mid");
  9366. juce::String midiError;
  9367. const auto saved = lynx::MidiFileIo::savePattern (song, song.currentPattern, file, midiError);
  9368. const auto parsed = saved ? lynx::MidiFileIo::parseFile (file, midiError) : std::nullopt;
  9369. const auto loaded = saved ? lynx::MidiFileIo::loadSong (file, midiError) : std::nullopt;
  9370. file.deleteFile();
  9371. const auto& bp = back ? back->patterns[(std::size_t) back->currentPattern] : p;
  9372. if (! back || bp.markers != p.markers)
  9373. keys190nuResult = "ERROR project round trip " + why;
  9374. else if (! oldShape)
  9375. keys190nuResult = "ERROR marker arrays an older release skips";
  9376. else if (! copy130 || for130.json.contains ("markerKeys") || ! said || ! for128.ok || for128.json.contains ("markerKeys"))
  9377. keys190nuResult = "ERROR copy for 0.1.30 / 0.1.28";
  9378. else if (const auto& cp = copy130->patterns[(std::size_t) copy130->currentPattern];
  9379. cp.markers.size() != 4 || cp.markers[0].name != "D Other Dorian" || cp.markers[0].action != lynx::Marker::keyScale || keyOf (cp.markers[0]))
  9380. keys190nuResult = "ERROR the copy's markers";
  9381. else if (! parsed || parsed->keys.size() != 2 || parsed->keys[0].tick != 0 || parsed->keys[0].flScale != dorian.flScale || parsed->keys[0].root != 2
  9382. || parsed->keys[1].tick != bar || parsed->keys[1].flScale != harmonic.flScale)
  9383. keys190nuResult = "ERROR MIDI key signatures " + midiError;
  9384. else if (! loaded || ! (lynx::projectkey::get (*loaded) == dorian) || ! (stateAt (loaded->patterns[0], bar).value == harmonic))
  9385. keys190nuResult = "ERROR MIDI file opened as a project " + midiError;
  9386. }
  9387. // 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
  9388. // or reverse grains play) and the Kilohearts Nonlinear Filter law (code 49, its own loss line); the copy for 0.1.28
  9389. // still turns Helix into an empty Sampler after it; a Helix channel of revision 4 at the block's defaults loses nothing
  9390. juce::String helix4khs190ocResult = "OK";
  9391. {
  9392. auto song = lynx::Song::makeDefault();
  9393. if (song.mixer.size() < 3)
  9394. song.mixer.resize (3);
  9395. lynx::ChannelDef plain, swarm;
  9396. plain.name = "Plain", swarm.name = "Swarm";
  9397. plain.instrument = swarm.instrument = lynx::InstrumentKind::helix;
  9398. const auto d = lynx::helixDefaults();
  9399. plain.modelParams = swarm.modelParams = d;
  9400. swarm.modelParams[(std::size_t) (lynx::wt::ext4Base + lynx::wt::ext4::grainUnison)] = 5.0f;
  9401. swarm.modelParams[(std::size_t) (lynx::wt::ext4Base + lynx::wt::ext4::grainReverse)] = 0.4f;
  9402. song.channels.push_back (plain);
  9403. song.channels.push_back (swarm);
  9404. auto nlf = lynx::makeEffectSlot (lynx::EffectKind::effector);
  9405. nlf.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::nonlinearFilter);
  9406. nlf.params[(std::size_t) lynx::khsdsp::valueParam + 2] = 0.5f;
  9407. song.mixer[2].effects.push_back (nlf);
  9408. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  9409. const auto older = lynx::olderlynx::forRelease (song, "0.1.28");
  9410. const auto count = [] (const lynx::olderlynx::Copy& c, const char* start) {
  9411. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  9412. };
  9413. const auto parsed = juce::JSON::parse (copy.json);
  9414. int helixCut = 0, revisions3 = 0;
  9415. juce::String lossDetail;
  9416. for (const auto& l : copy.lost)
  9417. if (juce::String (l.text).startsWith ("Helix's unison"))
  9418. lossDetail = l.detail;
  9419. if (const auto* channels = parsed["channels"].getArray())
  9420. for (const auto& c : *channels)
  9421. if (c["instrument"].toString() == "helix")
  9422. {
  9423. auto values = juce::StringArray::fromTokens (c["modelParams"].toString(), " ", "");
  9424. values.removeEmptyStrings();
  9425. helixCut += values.size() == lynx::wt::ext4Base ? 1 : 0;
  9426. revisions3 += values.size() > lynx::wt::extBase && values[lynx::wt::extBase].getFloatValue() == 3.0f ? 1 : 0;
  9427. }
  9428. if (! copy.ok || ! older.ok)
  9429. helix4khs190ocResult = "ERROR copy " + copy.error + older.error;
  9430. else if (helixCut != 2 || revisions3 != 2)
  9431. helix4khs190ocResult = "ERROR Helix block in the copy (cut " + juce::String (helixCut) + ", revision 3 " + juce::String (revisions3) + ")";
  9432. else if (count (copy, "Helix's unison") != 1 || ! lossDetail.contains ("Swarm") || lossDetail.contains ("Plain"))
  9433. helix4khs190ocResult = "ERROR Helix loss line: " + lossDetail;
  9434. else if (parsed["mixer"][2]["effects"][0]["params"].size() > lynx::khsdsp::lawParam || count (copy, "Effector's Kilohearts Nonlinear Filter") != 1
  9435. || count (copy, "Effector's newer Kilohearts laws") != 0)
  9436. helix4khs190ocResult = "ERROR Nonlinear Filter law in the copy";
  9437. else if (older.json.contains ("\"helix\"") || count (older, "Helix is not in this release") != 1)
  9438. helix4khs190ocResult = "ERROR copy for 0.1.28 after the 0.1.30 step";
  9439. }
  9440. // 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:
  9441. // 190oc's Helix round-4 block and Effector law 49 (each one line), 190od's slide of the note properties (#236: the
  9442. // key goes; one line counting only slide notes that move something), 190od's #239 colours and icons by name and a
  9443. // #238 "no colour" channel (ordinary project data: kept as they are), 190nz's clipboard (no project data), 190oa's
  9444. // main (monitor) volume and Gross Beat's scratch offset (merge 4; its window places are not in a copy: the copy is
  9445. // the song's JSON without the window layout). The 0.1.30 copy keeps every key but "slideNoteProps" and "mainVolume";
  9446. // a project whose slide notes move nothing, or saved before #236, gets no slide line
  9447. juce::String rollup031s4Result = "OK";
  9448. {
  9449. auto song = lynx::Song::makeDefault();
  9450. if (song.mixer.size() < 3)
  9451. song.mixer.resize (3);
  9452. song.slideNoteProps = true;
  9453. lynx::ChannelDef bass, lead, swarm, plain;
  9454. bass.name = "Bass 808", lead.name = "Lead", swarm.name = "Swarm", plain.name = "No colour";
  9455. swarm.instrument = lynx::InstrumentKind::helix;
  9456. swarm.modelParams = lynx::helixDefaults();
  9457. swarm.modelParams[(std::size_t) (lynx::wt::ext4Base + lynx::wt::ext4::specUnison)] = 4.0f;
  9458. for (auto* c : { &bass, &lead, &swarm, &plain })
  9459. song.channels.push_back (*c);
  9460. const int bassIndex = (int) song.channels.size() - 4, leadIndex = bassIndex + 1;
  9461. auto nlf = lynx::makeEffectSlot (lynx::EffectKind::effector);
  9462. nlf.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::nonlinearFilter);
  9463. song.mixer[2].effects.push_back (nlf);
  9464. // merge 4 (190oa): the toolbar's main (monitor) volume off 0 dB and Gross Beat's scratch offset set (DF-21, DP-8)
  9465. song.mainVolume = 0.5f;
  9466. auto gross = lynx::makeEffectSlot (lynx::EffectKind::grossBeat);
  9467. gross.params[8] = 0.25f;
  9468. song.mixer[2].effects.push_back (gross);
  9469. lynx::autolook::Rules rules;
  9470. rules.on = true;
  9471. rules.list.push_back ({ "bass", lynx::autolook::Match::contains, 0xFF2266AAu, 7, lynx::autolook::everything });
  9472. const auto coloured = lynx::autolook::applyAll (song, rules);
  9473. auto& p = song.patterns[(std::size_t) song.currentPattern];
  9474. const auto note = [] (int channel, juce::int64 start, int key, float velocity, float pan, bool slide) {
  9475. lynx::Note n;
  9476. n.channel = channel, n.start = start, n.length = lynx::ppq, n.key = key, n.velocity = velocity, n.pan = pan, n.slide = slide;
  9477. return n;
  9478. };
  9479. p.notes.push_back (note (bassIndex, 0, 36, 0.78f, 0.0f, false));
  9480. p.notes.push_back (note (bassIndex, lynx::ppq / 2, 43, 0.3f, 0.0f, true)); // moves the velocity
  9481. p.notes.push_back (note (bassIndex, lynx::ppq, 41, 0.78f, -0.5f, true)); // moves the pan
  9482. p.notes.push_back (note (leadIndex, 0, 60, 0.78f, 0.0f, false));
  9483. p.notes.push_back (note (leadIndex, lynx::ppq / 2, 64, 0.78f, 0.0f, true)); // pitch only: sounds the same in 0.1.30
  9484. p.sortNotes(); // (the order a project reads back in)
  9485. lynx::uids::normalize (song);
  9486. const auto keysOf = [] (const juce::var& v) {
  9487. std::set<juce::String> keys;
  9488. std::function<void (const juce::var&, const juce::String&)> walk = [&] (const juce::var& x, const juce::String& path) {
  9489. if (auto* o = x.getDynamicObject())
  9490. for (const auto& prop : o->getProperties())
  9491. {
  9492. if (path.isEmpty() && (prop.name.toString() == "savedBy" || prop.name.toString() == "copiedFrom"))
  9493. continue;
  9494. keys.insert (path + "/" + prop.name.toString());
  9495. walk (prop.value, path + "/" + prop.name.toString());
  9496. }
  9497. else if (auto* a = x.getArray())
  9498. for (const auto& e : *a)
  9499. walk (e, path + "[]");
  9500. };
  9501. walk (v, {});
  9502. return keys;
  9503. };
  9504. auto expected = keysOf (juce::JSON::parse (lynx::ProjectFile::toJson (song)));
  9505. const auto hadKey = expected.erase ("/slideNoteProps") == 1 && expected.erase ("/mainVolume") == 1;
  9506. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* start) {
  9507. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  9508. };
  9509. const char* slideLine = "{0} slide note(s) move only the pitch";
  9510. if (coloured != 1 || ! hadKey)
  9511. rollup031s4Result = "ERROR set-up (coloured " + juce::String (coloured) + ")";
  9512. for (const auto* release : { "0.1.30", "0.1.28" })
  9513. {
  9514. if (rollup031s4Result != "OK")
  9515. break;
  9516. const auto copy = lynx::olderlynx::forRelease (song, release);
  9517. juce::String why;
  9518. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  9519. juce::String slideDetail;
  9520. for (const auto& l : copy.lost)
  9521. if (juce::String (l.text).startsWith (slideLine))
  9522. slideDetail = l.detail;
  9523. const auto is130 = juce::String (release) == "0.1.30";
  9524. if (! copy.ok || ! back)
  9525. rollup031s4Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  9526. else if (copy.json.contains ("slideNoteProps") || back->slideNoteProps)
  9527. rollup031s4Result = juce::String ("ERROR slideNoteProps left in the copy for ") + release;
  9528. else if (countOf (copy, slideLine) != 1 || slideDetail != "2")
  9529. rollup031s4Result = juce::String ("ERROR the slide line in the copy for ") + release + " (" + slideDetail + ")";
  9530. else if (countOf (copy, "Effector's Kilohearts Nonlinear Filter") != 1 || (is130 && countOf (copy, "Helix's unison") != 1)
  9531. || (! is130 && countOf (copy, "Helix is not in this release") != 1))
  9532. rollup031s4Result = juce::String ("ERROR 190oc's lines in the copy for ") + release;
  9533. else if (countOf (copy, "The main (monitor) volume") != 1 || countOf (copy, "Gross Beat's scratch offset") != 1
  9534. || copy.json.contains ("mainVolume") || juce::JSON::parse (copy.json)["mixer"][2]["effects"][1]["params"].size() != 8)
  9535. rollup031s4Result = juce::String ("ERROR 190oa's main volume / Gross Beat offset in the copy for ") + release;
  9536. else if (back->patterns[(std::size_t) back->currentPattern].notes != p.notes)
  9537. rollup031s4Result = juce::String ("ERROR the notes in the copy for ") + release;
  9538. else if (back->channels[(std::size_t) bassIndex].colour != 0xFF2266AAu || back->channels[(std::size_t) bassIndex].icon != 7
  9539. || back->channels[(std::size_t) bassIndex + 3].colour != 0 || back->channels[(std::size_t) leadIndex].colour != song.channels[(std::size_t) leadIndex].colour)
  9540. rollup031s4Result = juce::String ("ERROR #239 / #238 colours in the copy for ") + release;
  9541. else if (is130 && (copy.lost.size() != 5 || keysOf (juce::JSON::parse (copy.json)) != expected))
  9542. rollup031s4Result = "ERROR the copy for 0.1.30 drops more than step 4's five (" + juce::String ((int) copy.lost.size()) + " lines)";
  9543. }
  9544. // slide notes that move nothing, and a project saved before #236 (key off): no slide line
  9545. if (rollup031s4Result == "OK")
  9546. {
  9547. auto still = song;
  9548. auto& sp = still.patterns[(std::size_t) still.currentPattern];
  9549. 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());
  9550. auto before = song;
  9551. before.slideNoteProps = false;
  9552. const auto a = lynx::olderlynx::forRelease (still, "0.1.30"), b = lynx::olderlynx::forRelease (before, "0.1.30");
  9553. if (! a.ok || ! b.ok || countOf (a, slideLine) != 0 || countOf (b, slideLine) != 0)
  9554. rollup031s4Result = "ERROR a slide line where nothing moves";
  9555. }
  9556. }
  9557. // 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
  9558. // (plain markers at their starts, one view line); 190ol's Simple time signature changes (ordinary signature markers
  9559. // 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
  9560. // dropped, one view line naming both); gap190og's transport mappings (the Overdub key mapping dropped with a line,
  9561. // the Play one kept); 190ob's tracker volume automation (a channel Volume multiplier clip: kept point for point);
  9562. // 190on's stacked lanes and palette are profile settings and 190og's .flm export keeps no settings (the song is the
  9563. // same after an export). The 0.1.30 copy keeps every key but the three dropped ones and has exactly three lines
  9564. const auto autolinks190ovResult = runAutoLinks190ovCheck(); // round 190ov (src/AutoLinks190ovCheck.inc)
  9565. juce::String rollup031s5Result = "OK";
  9566. {
  9567. auto song = lynx::Song::makeDefault();
  9568. if (song.mixer.size() < 3)
  9569. song.mixer.resize (3);
  9570. // 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:
  9571. // a signature marker)
  9572. lynx::sections::add (song, "Intro");
  9573. lynx::sections::add (song, "Verse");
  9574. lynx::signatureedit::set (song, 0, 5, 1);
  9575. lynx::signatureedit::set (song, song.barAt (0).tick + 8 * 5 * lynx::ppq * 4, 7, 8);
  9576. std::vector<lynx::Marker> signatures;
  9577. for (const auto& m : song.markers())
  9578. if (m.isSignature())
  9579. signatures.push_back (m);
  9580. // 190oh: a plugin channel with DPI aware off, an insert plugin with Scale editor dimensions on
  9581. lynx::ChannelDef synth;
  9582. synth.name = "Old Synth";
  9583. synth.instrument = lynx::InstrumentKind::plugin;
  9584. synth.plugin.id = "VST3:old-synth";
  9585. synth.plugin.name = "Old Synth";
  9586. synth.plugin.dpiAware = false;
  9587. synth.smartDisable = true; // (merge 6, 190ok D2: dropped without a line)
  9588. song.channels.push_back (synth);
  9589. const auto synthIndex = (int) song.channels.size() - 1;
  9590. lynx::EffectSlot fx;
  9591. fx.kind = lynx::EffectKind::plugin;
  9592. fx.plugin.id = "VST3:tiny-eq";
  9593. fx.plugin.name = "Tiny EQ";
  9594. fx.plugin.scaleEditorDimensions = true;
  9595. song.mixer[2].effects.push_back (fx);
  9596. auto ember = lynx::makeEffectSlot (lynx::EffectKind::ember); // (merge 6, 190ok D3: engine revision 2 -> 1 in the copies)
  9597. song.mixer[2].effects.push_back (ember);
  9598. // gap190og: a key mapped to Arrangement Overdub (newer) and one to Play (0.1.30 has it)
  9599. lynx::RemoteMapping overdub, play;
  9600. overdub.source = play.source = lynx::RemoteMapping::Source::key;
  9601. overdub.key = 'O', overdub.action = lynx::RemoteAction::overdub;
  9602. play.key = 'P', play.action = lynx::RemoteAction::play;
  9603. song.remoteMappings = { overdub, play };
  9604. // 190ob: the tracker import's volume automation (the channel's Levels "Volume multiplier", 5000 = 100 %)
  9605. lynx::Automation volume;
  9606. volume.name = "Old Synth volume (ch 1)";
  9607. volume.target.kind = lynx::AutomationTargetKind::channelAdjust;
  9608. volume.target.index = synthIndex;
  9609. volume.target.param = lynx::leveladjust::volume;
  9610. volume.points = { { 0, 0.5f }, { lynx::ppq, 0.25f }, { 2 * lynx::ppq, 0.4f } };
  9611. song.automations.push_back (volume);
  9612. lynx::uids::normalize (song);
  9613. const auto json = lynx::ProjectFile::toJson (song);
  9614. const auto keysOf = [] (const juce::var& v) {
  9615. std::set<juce::String> keys;
  9616. std::function<void (const juce::var&, const juce::String&)> walk = [&] (const juce::var& x, const juce::String& path) {
  9617. if (auto* o = x.getDynamicObject())
  9618. for (const auto& prop : o->getProperties())
  9619. {
  9620. if (path.isEmpty() && (prop.name.toString() == "savedBy" || prop.name.toString() == "copiedFrom"))
  9621. continue;
  9622. keys.insert (path + "/" + prop.name.toString());
  9623. walk (prop.value, path + "/" + prop.name.toString());
  9624. }
  9625. else if (auto* a = x.getArray())
  9626. for (const auto& e : *a)
  9627. walk (e, path + "[]");
  9628. };
  9629. walk (v, {});
  9630. return keys;
  9631. };
  9632. auto expected = keysOf (juce::JSON::parse (json));
  9633. const auto hadKeys = expected.erase ("/arrangements[]/sections") == 1 && expected.erase ("/channels[]/plugin/dpiAware") == 1
  9634. && expected.erase ("/mixer[]/effects[]/plugin/scaleEditorDimensions") == 1 && expected.erase ("/channels[]/smartDisable") == 1;
  9635. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* start) {
  9636. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  9637. };
  9638. const auto detailOf = [] (const lynx::olderlynx::Copy& c, const char* start) {
  9639. for (const auto& l : c.lost)
  9640. if (juce::String (l.text).startsWith (start))
  9641. return juce::String (l.detail);
  9642. return juce::String();
  9643. };
  9644. if (! hadKeys || song.sections().size() != 2 || song.beatsPerBar != 5 || song.beatUnit != 1 || signatures.size() != 1 || signatures[0].numerator != 7)
  9645. rollup031s5Result = "ERROR set-up (" + juce::String ((int) signatures.size()) + " signature changes)";
  9646. // (190og: the .flm export reads the song and keeps nothing in it)
  9647. if (rollup031s5Result == "OK")
  9648. {
  9649. const auto flm = lynx::exportFlm (song);
  9650. if (flm.bytes.empty() || lynx::ProjectFile::toJson (song) != json)
  9651. rollup031s5Result = "ERROR the .flm export (" + juce::String ((int) flm.bytes.size()) + " bytes)";
  9652. }
  9653. for (const auto* release : { "0.1.30", "0.1.28" })
  9654. {
  9655. if (rollup031s5Result != "OK")
  9656. break;
  9657. const auto copy = lynx::olderlynx::forRelease (song, release);
  9658. juce::String why;
  9659. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  9660. const auto is130 = juce::String (release) == "0.1.30";
  9661. std::vector<lynx::Marker> backSignatures;
  9662. int sectionMarkers = 0;
  9663. if (back)
  9664. {
  9665. for (const auto& m : back->markers())
  9666. {
  9667. if (m.isSignature())
  9668. backSignatures.push_back (m);
  9669. else if (m.name == "Intro" || m.name == "Verse")
  9670. ++sectionMarkers;
  9671. }
  9672. }
  9673. const auto bars = song.barsBetween (0, 400 * lynx::ppq);
  9674. const auto backBars = back ? back->barsBetween (0, 400 * lynx::ppq) : std::vector<lynx::Bar> {};
  9675. 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 {};
  9676. const auto backEmberRev = back && back->mixer.size() > 2 && ! back->mixer[2].effects.empty() ? back->mixer[2].effects.back().engineRev : -1;
  9677. if (! copy.ok || ! back)
  9678. rollup031s5Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  9679. else if (copy.json.contains ("\"sections\"") || ! back->sections().empty() || sectionMarkers != 2
  9680. || countOf (copy, "{0} song section(s) of the Sections lane") != 1)
  9681. rollup031s5Result = juce::String ("ERROR 190ol's sections in the copy for ") + release;
  9682. else if (backSignatures.size() != signatures.size()
  9683. || ! std::equal (signatures.begin(), signatures.end(), backSignatures.begin(), [] (const lynx::Marker& a, const lynx::Marker& b) {
  9684. return a.tick == b.tick && a.numerator == b.numerator && a.denominator == b.denominator;
  9685. })
  9686. || back->beatsPerBar != song.beatsPerBar || back->beatUnit != song.beatUnit
  9687. || ! std::equal (bars.begin(), bars.end(), backBars.begin(), backBars.end(), [] (const lynx::Bar& a, const lynx::Bar& b) {
  9688. return a.tick == b.tick && a.length == b.length && a.number == b.number;
  9689. }))
  9690. rollup031s5Result = juce::String ("ERROR 190ol's time signature changes in the copy for ") + release;
  9691. else if (copy.json.contains ("dpiAware") || copy.json.contains ("scaleEditorDimensions") || ! back->channels[(std::size_t) synthIndex].plugin.dpiAware
  9692. || backFx.scaleEditorDimensions || backFx.name != "Tiny EQ"
  9693. || countOf (copy, "FL's wrapper GUI settings") != 1 || ! detailOf (copy, "FL's wrapper GUI settings").contains ("Old Synth")
  9694. || ! detailOf (copy, "FL's wrapper GUI settings").contains ("Tiny EQ"))
  9695. rollup031s5Result = juce::String ("ERROR 190oh's wrapper GUI settings in the copy for ") + release + " (" + detailOf (copy, "FL's wrapper GUI settings") + ")";
  9696. else if (back->remoteMappings.size() != 1 || back->remoteMappings[0].action != lynx::RemoteAction::play
  9697. || countOf (copy, "{0} key / MIDI mapping(s) of Overdub") != 1 || detailOf (copy, "{0} key / MIDI mapping(s) of Overdub") != "1")
  9698. rollup031s5Result = juce::String ("ERROR gap190og's transport mappings in the copy for ") + release;
  9699. 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)
  9700. || backEmberRev != (is130 ? 1 : 0))
  9701. rollup031s5Result = juce::String ("ERROR 190ok's smart disable / engine revision in the copy for ") + release + " (rev " + juce::String (backEmberRev) + ")";
  9702. else if (back->automations != song.automations)
  9703. rollup031s5Result = juce::String ("ERROR 190ob's volume automation in the copy for ") + release;
  9704. else if (is130 && (copy.lost.size() != 3 || keysOf (juce::JSON::parse (copy.json)) != expected))
  9705. rollup031s5Result = "ERROR the copy for 0.1.30 drops more than step 5's three (" + juce::String ((int) copy.lost.size()) + " lines)";
  9706. }
  9707. // a project without any of them: no step-5 line (the default song)
  9708. if (rollup031s5Result == "OK")
  9709. {
  9710. const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30");
  9711. if (! plain.ok || ! plain.lost.empty())
  9712. rollup031s5Result = "ERROR lines for a project with none of step 5's data (" + juce::String ((int) plain.lost.size()) + ")";
  9713. }
  9714. }
  9715. // round 190pi: "Save a copy for 0.1.30" of FL's slide law (Song::slideNoteProps): a slide note over a chord (FL moves
  9716. // every held note by one interval) and a Slide arpeggio (its voice at the first held note's velocity) each get one
  9717. // sound line; a project with neither gets none of them; the copy reads back
  9718. juce::String slides190piResult = "OK";
  9719. {
  9720. auto song = lynx::Song::makeDefault();
  9721. song.slideNoteProps = true;
  9722. if (song.patterns.empty())
  9723. song.patterns.emplace_back();
  9724. if (song.channels.empty())
  9725. song.channels.emplace_back();
  9726. song.patterns[0].notes.clear();
  9727. const auto count = [] (const lynx::olderlynx::Copy& copy, const char* start) {
  9728. return (int) std::count_if (copy.lost.begin(), copy.lost.end(), [start] (const lynx::olderlynx::Loss& l) {
  9729. return juce::String (l.text).startsWith (start) && l.sound;
  9730. });
  9731. };
  9732. const auto plain = lynx::olderlynx::forRelease (song, "0.1.30");
  9733. lynx::Note a, b, slide;
  9734. a.start = 0, a.length = 4 * lynx::ppq, a.key = 60, a.channel = 0;
  9735. b = a, b.key = 67;
  9736. slide = a, slide.start = lynx::ppq, slide.length = lynx::ppq / 2, slide.slide = true;
  9737. song.patterns[0].notes = { a, b, slide };
  9738. song.channels[0].arp.direction = 1;
  9739. song.channels[0].arp.slide = true;
  9740. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  9741. juce::String why;
  9742. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  9743. if (! plain.ok || count (plain, "{0} slide note(s) over chords") != 0 || count (plain, "{0} channel(s) with a Slide arpeggio") != 0)
  9744. slides190piResult = "ERROR lines for a project without chord slides or Slide arpeggios";
  9745. else if (! copy.ok || count (copy, "{0} slide note(s) over chords") != 1 || count (copy, "{0} channel(s) with a Slide arpeggio") != 1)
  9746. slides190piResult = "ERROR the copy's lines " + copy.error;
  9747. else if (! back || back->slideNoteProps || copy.json.contains ("slideNoteProps"))
  9748. slides190piResult = "ERROR the copy read back " + why;
  9749. }
  9750. // round 190qo (issues #270, #271): LYNX's typing chord layouts follow FL's own four chord files; "Save a copy for 0.1.31"
  9751. // of a SoundFont channel with slide notes (engine revision 5: slide velocity and pan) gets one sound line and
  9752. // revision 3, a project without slide notes none
  9753. juce::String issues190qoResult = "OK";
  9754. {
  9755. const auto rule = lynx::keys::typingpiano::chordRuleCheck();
  9756. auto song = lynx::Song::makeDefault();
  9757. if (song.patterns.empty())
  9758. song.patterns.emplace_back();
  9759. lynx::ChannelDef sf;
  9760. sf.instrument = lynx::InstrumentKind::soundfont;
  9761. sf.name = "SF 190qo";
  9762. song.channels.push_back (sf);
  9763. const auto ch = (int) song.channels.size() - 1;
  9764. lynx::Note a, slide;
  9765. a.start = 0, a.length = 4 * lynx::ppq, a.key = 60, a.channel = ch;
  9766. slide = a, slide.start = lynx::ppq, slide.length = lynx::ppq, slide.slide = true, slide.velocity = 0.1f;
  9767. song.patterns[0].notes = { a };
  9768. const auto lines = [] (const lynx::olderlynx::Copy& copy) {
  9769. return (int) std::count_if (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  9770. return juce::String (l.text).startsWith ("Slide notes move only the pitch on these channels") && l.sound;
  9771. });
  9772. };
  9773. const auto plain = lynx::olderlynx::forRelease (song, "0.1.31");
  9774. song.patterns[0].notes.push_back (slide);
  9775. const auto copy = lynx::olderlynx::forRelease (song, "0.1.31");
  9776. juce::String why;
  9777. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  9778. if (rule != "OK")
  9779. issues190qoResult = "ERROR typing chord rule " + juce::String (rule);
  9780. else if (! plain.ok || lines (plain) != 0)
  9781. issues190qoResult = "ERROR a line for a project without SoundFont slides";
  9782. else if (! copy.ok || lines (copy) != 1)
  9783. issues190qoResult = "ERROR the copy's line " + copy.error;
  9784. else if (! back || back->channels.back().engineRev > 3)
  9785. issues190qoResult = "ERROR the copy read back " + why;
  9786. }
  9787. // round 190pr: "Save a copy for 0.1.30" of the export's marker actions (Song::exportMarkers: one sound line when an
  9788. // arrangement has a skip or Start marker, none otherwise; the key goes), of Harmor's automation and of Sytrus'
  9789. // note Mod X / Y (engine revision 3: written at 2, one line each naming the clip / channel); the .lynx keys read back
  9790. juce::String flparity190prResult = "OK";
  9791. {
  9792. auto song = lynx::Song::makeDefault();
  9793. song.exportMarkers = true;
  9794. const auto has = [] (const lynx::olderlynx::Copy& copy, const char* start) {
  9795. return std::any_of (copy.lost.begin(), copy.lost.end(), [start] (const lynx::olderlynx::Loss& l) {
  9796. return juce::String (l.text).startsWith (start) && l.sound;
  9797. });
  9798. };
  9799. const char* markerLine = "The export plays the song straight through in this release";
  9800. const char* harmorLine = "Automation of Harmor's filter frequencies";
  9801. const auto plain = lynx::olderlynx::forRelease (song, "0.1.30");
  9802. lynx::Marker skip;
  9803. skip.tick = 4 * lynx::ppq, skip.action = lynx::Marker::markerSkip, skip.name = "Skip";
  9804. song.addMarker (skip);
  9805. lynx::ChannelDef harmorChannel;
  9806. harmorChannel.name = "Harmor 190pr";
  9807. harmorChannel.instrument = lynx::InstrumentKind::harmor;
  9808. song.channels.push_back (harmorChannel);
  9809. lynx::ChannelDef sytrusChannel;
  9810. sytrusChannel.name = "Sytrus 190pr";
  9811. sytrusChannel.instrument = lynx::InstrumentKind::sytrus;
  9812. song.channels.push_back (sytrusChannel);
  9813. if (song.patterns.empty())
  9814. song.patterns.emplace_back();
  9815. lynx::Note click;
  9816. click.channel = (int) song.channels.size() - 1, click.key = 60, click.length = lynx::ppq, click.modY = 190.0f / 256.0f;
  9817. song.patterns[0].notes.push_back (click);
  9818. const char* sytrusLine = "Sytrus plays every note at the default Mod X / Y";
  9819. lynx::Automation clip;
  9820. clip.name = "Cutoff 190pr";
  9821. clip.target = { lynx::AutomationTargetKind::channelParam, (int) song.channels.size() - 2, 0, 52 };
  9822. song.automations.push_back (clip);
  9823. const auto json = lynx::ProjectFile::toJson (song);
  9824. juce::String why;
  9825. const auto back = lynx::ProjectFile::fromJson (json, why);
  9826. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  9827. juce::String why2;
  9828. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why2) : std::optional<lynx::Song> {};
  9829. const auto n = song.channels.size();
  9830. if (! plain.ok || has (plain, markerLine) || has (plain, harmorLine) || has (plain, sytrusLine))
  9831. flparity190prResult = "ERROR lines for a project without markers, Harmor automation or Sytrus Mod X / Y";
  9832. else if (! json.contains ("exportMarkers") || ! back || ! back->exportMarkers || back->channels.size() != n
  9833. || back->channels[n - 2].engineRev < 3 || back->channels[n - 1].engineRev < 3) // (round 190py: 4 is current)
  9834. flparity190prResult = "ERROR the .lynx keys " + why;
  9835. else if (! copy.ok || ! has (copy, markerLine) || ! has (copy, harmorLine) || ! has (copy, sytrusLine))
  9836. flparity190prResult = "ERROR the copy's lines " + copy.error;
  9837. else if (! old || old->exportMarkers || copy.json.contains ("exportMarkers") || old->channels.size() != n
  9838. || old->channels[n - 2].engineRev != 2 || old->channels[n - 1].engineRev != 2)
  9839. flparity190prResult = "ERROR the copy read back " + why2;
  9840. }
  9841. // round 190oz: FL's held step notes (Note::held) in .lynx ("heldNotes", only when a pattern has one), back from it,
  9842. // and the copy for 0.1.30 (the marks dropped with one sound line, the notes kept one step long)
  9843. juce::String heldSteps190ozResult = "OK";
  9844. {
  9845. auto song = lynx::Song::makeDefault();
  9846. const auto plainJson = lynx::ProjectFile::toJson (song);
  9847. if (song.patterns.empty())
  9848. song.patterns.emplace_back();
  9849. auto& notes = song.patterns[0].notes;
  9850. notes.clear();
  9851. lynx::Note held, plain;
  9852. held.start = 0, held.channel = 0, held.held = true;
  9853. plain.start = lynx::ticksPerStep * 4, plain.channel = 0;
  9854. notes = { held, plain };
  9855. const auto json = lynx::ProjectFile::toJson (song);
  9856. juce::String why;
  9857. const auto back = lynx::ProjectFile::fromJson (json, why);
  9858. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  9859. const auto lines = (int) std::count_if (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  9860. return juce::String (l.text).startsWith ("{0} FL step note(s) on generators") && l.detail == "1" && l.sound;
  9861. });
  9862. juce::String why2;
  9863. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why2) : std::optional<lynx::Song> {};
  9864. if (plainJson.contains ("heldNotes") || ! json.contains ("heldNotes"))
  9865. heldSteps190ozResult = "ERROR the .lynx key";
  9866. else if (! back || back->patterns.empty() || back->patterns[0].notes.size() != 2 || ! back->patterns[0].notes[0].held
  9867. || back->patterns[0].notes[1].held || back->patterns[0].notes[0].start != 0)
  9868. heldSteps190ozResult = "ERROR the .lynx round trip " + why;
  9869. else if (! copy.ok || copy.json.contains ("heldNotes") || lines != 1 || ! old || old->patterns.empty()
  9870. || old->patterns[0].notes.size() != 2 || old->patterns[0].notes[0].held)
  9871. heldSteps190ozResult = "ERROR the copy for 0.1.30 (" + juce::String (lines) + " lines) " + copy.error + why2;
  9872. }
  9873. // 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
  9874. // (engine revision 2, the velocity law), two patterns' event lanes on one control and a note with a pitch curve in a
  9875. // Playlist clip (decisions 4 / 5: lines only); 190op's hidden track and deactivated insert; 190oq's ARA plugin on an
  9876. // insert (#243); 190ot's "Duck under..."; 190ov's clip linked to two controls with a scale; 190ow's step on an
  9877. // automation row, a re-ranged clip and a muted clip; 190ox's Steps modulator. Each line once in each copy, none of the
  9878. // new keys left in the 0.1.30 copy, both copies read back; the default song gets none of these lines
  9879. juce::String rollup031s6Result = "OK";
  9880. {
  9881. namespace st = lynx::simpletracks;
  9882. auto song = lynx::Song::makeDefault();
  9883. st::Request q;
  9884. q.kind = st::Kind::audio;
  9885. q.name = "Kick";
  9886. const auto kick = st::addTrack (song, q).insert;
  9887. q.name = "Pad";
  9888. const auto pad = st::addTrack (song, q).insert;
  9889. const auto duckSet = st::setDuck (song, pad, kick, 0.6f) == st::DuckResult::set;
  9890. lynx::ChannelDef sim;
  9891. sim.name = "Sim Lead";
  9892. sim.instrument = lynx::InstrumentKind::simsynth; // (engineRev 2: a new channel)
  9893. song.channels.push_back (sim);
  9894. const auto simIndex = (int) song.channels.size() - 1;
  9895. while (song.patterns.size() < 2)
  9896. song.patterns.push_back (song.patterns.front());
  9897. song.patterns[0].name = "Lanes A";
  9898. song.patterns[1].name = "Lanes B";
  9899. lynx::AutomationTarget simVolume;
  9900. simVolume.kind = lynx::AutomationTargetKind::channelVolume;
  9901. simVolume.index = simIndex;
  9902. for (int p = 0; p < 2; ++p)
  9903. {
  9904. lynx::PatternEvents lane;
  9905. lane.target = simVolume;
  9906. lane.events = { { 0, 0.3f + 0.2f * (float) p } };
  9907. song.patterns[(std::size_t) p].events.push_back (lane);
  9908. lynx::Clip clip;
  9909. clip.pattern = p;
  9910. clip.track = 0;
  9911. clip.start = (std::int64_t) p * 4 * lynx::ppq;
  9912. clip.length = 4 * lynx::ppq;
  9913. song.playlist.push_back (clip);
  9914. }
  9915. {
  9916. lynx::Note bent;
  9917. bent.channel = simIndex;
  9918. bent.length = lynx::ppq;
  9919. lynx::NoteCurves curves;
  9920. curves.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { (float) lynx::ppq, 200.0f } };
  9921. bent.curves = curves;
  9922. song.patterns[0].notes.push_back (bent);
  9923. }
  9924. if (song.playlistTracks.size() < 4)
  9925. song.playlistTracks.resize (4);
  9926. song.playlistTracks[3].hidden = true;
  9927. song.mixer[(std::size_t) kick].deactivated = true;
  9928. lynx::EffectSlot ara;
  9929. ara.kind = lynx::EffectKind::plugin;
  9930. ara.plugin.id = "VST3:ara-editor";
  9931. ara.plugin.name = "ARA Editor";
  9932. ara.ara = true;
  9933. song.mixer[(std::size_t) pad].effects.push_back (ara);
  9934. // 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
  9935. lynx::Automation linked;
  9936. linked.name = "Linked";
  9937. linked.target = simVolume;
  9938. lynx::Automation::Link first, second;
  9939. first.target = simVolume;
  9940. first.scale = { 0.0f, 0.4f, 1.0f };
  9941. second.target.kind = lynx::AutomationTargetKind::channelPan;
  9942. second.target.index = simIndex;
  9943. linked.links = { first, second };
  9944. linked.points = { { 0, 0.2f }, { lynx::ppq, 0.8f } };
  9945. song.automations.push_back (linked);
  9946. const auto linkedIndex = (int) song.automations.size() - 1;
  9947. lynx::Clip autoClip;
  9948. autoClip.kind = lynx::ClipKind::automation;
  9949. autoClip.automation = linkedIndex;
  9950. autoClip.track = 2;
  9951. autoClip.length = 4 * lynx::ppq;
  9952. song.playlist.push_back (autoClip);
  9953. lynx::Automation ranged = linked;
  9954. ranged.name = "Ranged";
  9955. ranged.links.clear();
  9956. ranged.target.kind = lynx::AutomationTargetKind::mixerVolume;
  9957. ranged.target.index = pad;
  9958. ranged.rangeMin = 0.25f;
  9959. ranged.rangeMax = 0.75f;
  9960. song.automations.push_back (ranged);
  9961. lynx::Automation muted = ranged;
  9962. muted.name = "Muted";
  9963. muted.rangeMin = 0.0f;
  9964. muted.rangeMax = 1.0f;
  9965. muted.target.kind = lynx::AutomationTargetKind::mixerPan;
  9966. muted.muted = true;
  9967. song.automations.push_back (muted);
  9968. lynx::Note step;
  9969. step.channel = (int) song.automations.size() - 2; // ("Ranged": a step on its rack row)
  9970. step.length = 0;
  9971. song.patterns[1].autoNotes.push_back (step);
  9972. auto steps = lynx::Modulator::make (lynx::ModKind::steps);
  9973. steps.name = "Steps 1";
  9974. lynx::ModRoute route;
  9975. route.target.kind = lynx::AutomationTargetKind::mixerPan;
  9976. route.target.index = pad;
  9977. steps.routes.push_back (route);
  9978. song.modulators.push_back (steps);
  9979. lynx::uids::normalize (song);
  9980. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* start) {
  9981. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  9982. };
  9983. const char* const lines[] = { "SimSynth plays every note at full level", "Controls that several patterns' event lanes drive",
  9984. "In Song mode these patterns' notes play without", "{0} hidden Playlist track(s) show again",
  9985. "Deactivated channels and inserts load their plugins again", "ARA plugins on mixer inserts play as ordinary",
  9986. "{0} \"Duck under...\" effect(s)", "Automation clips linked to several controls move them 1:1",
  9987. "{0} step(s) or note(s) on automation clip rows start no clip", "An automation clip's LFO keeps",
  9988. "Muted automation clips lose their target", "These modulators are not in this release" };
  9989. const auto hasLane = [&simVolume] (const lynx::Pattern& p) {
  9990. return std::any_of (p.events.begin(), p.events.end(), [&simVolume] (const lynx::PatternEvents& l) { return l.target == simVolume && ! l.events.empty(); });
  9991. };
  9992. if (! duckSet || kick <= 0 || pad <= 0 || song.channels[(std::size_t) simIndex].engineRev < 2) // (≥ 2: round 190pr's 3 too)
  9993. rollup031s6Result = "ERROR set-up";
  9994. for (const auto* release : { "0.1.30", "0.1.28" })
  9995. {
  9996. if (rollup031s6Result != "OK")
  9997. break;
  9998. const auto is130 = juce::String (release) == "0.1.30";
  9999. const auto copy = lynx::olderlynx::forRelease (song, release);
  10000. juce::String why;
  10001. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  10002. if (! copy.ok || ! back)
  10003. {
  10004. rollup031s6Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  10005. break;
  10006. }
  10007. for (const auto* line : lines)
  10008. {
  10009. // (no LFO on the re-ranged clip: that line must not show)
  10010. const auto want = juce::String (line).startsWith ("An automation clip's LFO") ? 0 : 1;
  10011. if (countOf (copy, line) != want)
  10012. {
  10013. rollup031s6Result = juce::String ("ERROR the copy for ") + release + ": \"" + line + "\" " + juce::String (countOf (copy, line)) + " times";
  10014. break;
  10015. }
  10016. }
  10017. if (rollup031s6Result != "OK")
  10018. break;
  10019. const auto json = copy.json;
  10020. if (json.contains ("playlistTracksHidden") || json.contains ("\"deactivated\"") || json.contains ("\"ara\": true") || json.contains ("autoNotes")
  10021. || json.contains ("modulators190ox"))
  10022. rollup031s6Result = juce::String ("ERROR a new key is left in the copy for ") + release;
  10023. else if (is130 && back->channels[(std::size_t) simIndex].engineRev != 1)
  10024. rollup031s6Result = "ERROR SimSynth's revision in the copy for 0.1.30 (" + juce::String (back->channels[(std::size_t) simIndex].engineRev) + ")";
  10025. else if (! back->mixer[(std::size_t) kick].muted || back->mixer[(std::size_t) kick].deactivated || (back->playlistTracks.size() > 3 && back->playlistTracks[3].hidden))
  10026. rollup031s6Result = juce::String ("ERROR 190op's units in the copy for ") + release;
  10027. else if (is130 && (back->patterns.size() < 2 || ! hasLane (back->patterns[0]) || ! hasLane (back->patterns[1])
  10028. || std::none_of (back->patterns[0].notes.begin(), back->patterns[0].notes.end(), [] (const lynx::Note& n) { return n.curves.has(); })))
  10029. rollup031s6Result = "ERROR the copy for 0.1.30 lost 190om's lanes or curves (lines only)";
  10030. else if (back->automations.size() < 3 || (is130 && back->automations[(std::size_t) linkedIndex].links.size() != 2)
  10031. || (! 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
  10032. || back->automations[back->automations.size() - 2].reranged())
  10033. rollup031s6Result = juce::String ("ERROR 190ov / 190ow's clips in the copy for ") + release;
  10034. else if (is130 && (back->modulators.size() != song.modulators.size() - 1))
  10035. rollup031s6Result = "ERROR 190ox's Steps modulator in the copy for 0.1.30 (" + juce::String ((int) back->modulators.size()) + ")";
  10036. }
  10037. // the default song: none of these lines
  10038. if (rollup031s6Result == "OK")
  10039. {
  10040. const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30");
  10041. if (! plain.ok || ! plain.lost.empty())
  10042. rollup031s6Result = "ERROR lines for a project with none of step 6's data (" + juce::String ((int) plain.lost.size()) + ")";
  10043. }
  10044. }
  10045. // 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
  10046. // lane (2 chords, a following channel), 190pe's track versions (2 on a track), 190pa's write mode (Latch) and range,
  10047. // 190pj's JSFX insert, 190pi's Ogun (engine revision 2) and an automation clip of Sytrus' Mod X; each copy: every line
  10048. // once (the Ogun line only for a patch with link velocity: none here without FL's files), the chords as markers,
  10049. // none of the new keys left, Ogun at revision 1 (0.1.30), both copies read back; the default song gets none of them.
  10050. // (Note repeats / conditions, research190oe P19: not built, nothing to convert; the header gear's choice is window
  10051. // state, never in a copy.)
  10052. juce::String rollup031s7Result = "OK";
  10053. {
  10054. auto song = lynx::Song::makeDefault();
  10055. if (song.playlistTracks.size() < 3)
  10056. song.playlistTracks.resize (3);
  10057. lynx::SongChord am, g7;
  10058. am.start = 0, am.length = 4 * lynx::ppq, am.root = 9, am.quality = 1;
  10059. g7.start = 4 * lynx::ppq, g7.length = 4 * lynx::ppq, g7.root = 7, g7.quality = 0, g7.extensions = { 10 }, g7.bass = 11;
  10060. song.chords() = { am, g7 };
  10061. lynx::ChannelDef follower;
  10062. follower.name = "Follower";
  10063. follower.followChords = 1;
  10064. song.channels.push_back (follower);
  10065. lynx::ChannelDef ogun;
  10066. ogun.name = "Ogun Pad";
  10067. ogun.instrument = lynx::InstrumentKind::ogun; // (engineRev 2: a new channel)
  10068. song.channels.push_back (ogun);
  10069. const auto ogunIndex = (int) song.channels.size() - 1;
  10070. lynx::ChannelDef sytrus;
  10071. sytrus.name = "Sytrus Lead";
  10072. sytrus.instrument = lynx::InstrumentKind::sytrus;
  10073. song.channels.push_back (sytrus);
  10074. lynx::Automation modX;
  10075. modX.name = "Sytrus Mod X";
  10076. modX.target.kind = lynx::AutomationTargetKind::channelParam;
  10077. modX.target.index = (int) song.channels.size() - 1;
  10078. modX.target.param = 18;
  10079. modX.points = { { 0, 0.2f }, { lynx::ppq, 0.8f } };
  10080. song.automations.push_back (modX);
  10081. song.automationWriteMode = 2; // (Latch)
  10082. song.trackRange.from = 0, song.trackRange.to = 2 * lynx::ppq, song.trackRange.tracks = { 0, 1 };
  10083. lynx::EffectSlot jsfx;
  10084. jsfx.kind = lynx::EffectKind::plugin;
  10085. jsfx.plugin.id = "JSFX-chokehold/soft_clipper";
  10086. jsfx.plugin.name = "soft_clipper";
  10087. if (song.mixer.size() < 3)
  10088. song.mixer.resize (3);
  10089. song.mixer[2].effects.push_back (jsfx);
  10090. lynx::Clip clip;
  10091. clip.pattern = 0;
  10092. clip.track = 1;
  10093. clip.length = 4 * lynx::ppq;
  10094. song.playlist.push_back (clip);
  10095. const auto versioned = lynx::trackversions::add (song, 1, lynx::trackversions::Start::empty, "Take B", "Take A") >= 0;
  10096. lynx::uids::normalize (song);
  10097. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* start) {
  10098. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  10099. };
  10100. const char* const lines[] = { "{0} chord(s) of the Chord lane become plain Playlist markers", "{0} channel(s) followed the Chord lane",
  10101. "{0} track version(s) that are not active are left out", "The automation write mode ({0}) goes back",
  10102. "The range selected on some Playlist tracks is left out", "JSFX scripts are not in this release",
  10103. "Automation of Sytrus' main knobs" };
  10104. if (! versioned || song.channels[(std::size_t) ogunIndex].engineRev < 2) // (≥ 2: round 190pr's 3 too)
  10105. rollup031s7Result = "ERROR set-up";
  10106. for (const auto* release : { "0.1.30", "0.1.28" })
  10107. {
  10108. if (rollup031s7Result != "OK")
  10109. break;
  10110. const auto is130 = juce::String (release) == "0.1.30";
  10111. const auto copy = lynx::olderlynx::forRelease (song, release);
  10112. juce::String why;
  10113. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  10114. if (! copy.ok || ! back)
  10115. {
  10116. rollup031s7Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  10117. break;
  10118. }
  10119. for (const auto* line : lines)
  10120. if (countOf (copy, line) != 1)
  10121. {
  10122. rollup031s7Result = juce::String ("ERROR the copy for ") + release + ": \"" + line + "\" " + juce::String (countOf (copy, line)) + " times";
  10123. break;
  10124. }
  10125. if (rollup031s7Result != "OK")
  10126. break;
  10127. const auto& json = copy.json;
  10128. const auto markerNamed = [&back] (const char* name) {
  10129. return std::any_of (back->markers().begin(), back->markers().end(), [name] (const lynx::Marker& m) { return m.name == name; });
  10130. };
  10131. if (countOf (copy, "Ogun and Autogun play every note") != 0)
  10132. rollup031s7Result = juce::String ("ERROR an Ogun line without a link-velocity patch in the copy for ") + release;
  10133. else if (json.contains ("\"chords\"") || json.contains ("followChords") || json.contains ("playlistTrackVersions")
  10134. || json.contains ("automationWriteMode") || json.contains ("trackRange") || json.contains ("JSFX-"))
  10135. rollup031s7Result = juce::String ("ERROR a new key is left in the copy for ") + release;
  10136. else if (! markerNamed ("Am") || ! markerNamed ("G7/B"))
  10137. rollup031s7Result = juce::String ("ERROR the chords are not markers in the copy for ") + release;
  10138. else if (is130 && back->channels[(std::size_t) ogunIndex].engineRev != 1)
  10139. rollup031s7Result = "ERROR Ogun's revision in the copy for 0.1.30 (" + juce::String (back->channels[(std::size_t) ogunIndex].engineRev) + ")";
  10140. else if ((back->playlistTracks.size() > 1 && ! back->playlistTracks[1].versions.empty()) // (an empty default row may not be written)
  10141. || std::any_of (back->playlist.begin(), back->playlist.end(), [] (const lynx::Clip& c) { return c.track == 1; }))
  10142. rollup031s7Result = juce::String ("ERROR track 2 is not its active (empty) version in the copy for ") + release + " (rows "
  10143. + juce::String ((int) back->playlistTracks.size()) + ", clips on it "
  10144. + juce::String ((int) std::count_if (back->playlist.begin(), back->playlist.end(), [] (const lynx::Clip& c) { return c.track == 1; })) + ")";
  10145. else if (back->automations.empty() || back->automations[0].points.size() != 2)
  10146. rollup031s7Result = juce::String ("ERROR the Sytrus clip's data in the copy for ") + release;
  10147. }
  10148. if (rollup031s7Result == "OK")
  10149. {
  10150. const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30");
  10151. if (! plain.ok || ! plain.lost.empty())
  10152. rollup031s7Result = "ERROR lines for a project with none of step 7's data (" + juce::String ((int) plain.lost.size()) + ")";
  10153. }
  10154. }
  10155. // 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
  10156. // imports and new channels) and of the export's marker switch (Song::exportMarkers). One project with a channel of
  10157. // every kind a revision gates (SimSynth, Ogun, Autogun: 2; Harmor, Sytrus: 3) and a plain Synth, all new (3), a
  10158. // Harmor filter clip, a Sytrus note off the default Mod Y, a Start marker after bar 1 and a skip marker. Each copy:
  10159. // 190pr's three lines once, no exportMarkers key, the markers kept as markers; 0.1.30: SimSynth / Ogun / Autogun at 1,
  10160. // Harmor / Sytrus / the Synth at 2; 0.1.28: no revision at all (0). Revisions stay ordered: a project saved before
  10161. // (every channel at 2, the switch off) reads back as it was saved and gets none of 190pr's lines.
  10162. juce::String rollup031s8Result = "OK";
  10163. {
  10164. auto song = lynx::Song::makeDefault();
  10165. song.exportMarkers = true;
  10166. lynx::Marker start, skip;
  10167. start.tick = 4 * lynx::ppq, start.action = lynx::Marker::start, start.name = "Start 190s8";
  10168. skip.tick = 8 * lynx::ppq, skip.action = lynx::Marker::markerSkip, skip.name = "Skip 190s8";
  10169. song.addMarker (start);
  10170. song.addMarker (skip);
  10171. const lynx::InstrumentKind kinds[] = { lynx::InstrumentKind::simsynth, lynx::InstrumentKind::ogun, lynx::InstrumentKind::autogun,
  10172. lynx::InstrumentKind::harmor, lynx::InstrumentKind::sytrus, lynx::InstrumentKind::synth };
  10173. const int want130[] = { 1, 1, 1, 2, 2, 2 };
  10174. const auto first = (int) song.channels.size();
  10175. for (const auto kind : kinds)
  10176. {
  10177. lynx::ChannelDef c;
  10178. c.name = "Rev3 " + std::to_string ((int) song.channels.size() - first + 1);
  10179. c.instrument = kind;
  10180. song.channels.push_back (c);
  10181. }
  10182. const auto harmorIndex = first + 3, sytrusIndex = first + 4;
  10183. if (song.patterns.empty())
  10184. song.patterns.emplace_back();
  10185. lynx::Note click;
  10186. click.channel = sytrusIndex, click.key = 60, click.length = lynx::ppq, click.modY = 0.8f;
  10187. song.patterns[0].notes.push_back (click);
  10188. lynx::Automation cutoff;
  10189. cutoff.name = "Harmor cutoff s8";
  10190. cutoff.target = { lynx::AutomationTargetKind::channelParam, harmorIndex, 0, 52 };
  10191. cutoff.points = { { 0, 0.2f }, { lynx::ppq, 0.8f } };
  10192. song.automations.push_back (cutoff);
  10193. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* begin) {
  10194. return (int) std::count_if (c.lost.begin(), c.lost.end(), [begin] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (begin); });
  10195. };
  10196. const char* const lines[] = { "The export plays the song straight through in this release", "Automation of Harmor's filter frequencies",
  10197. "Sytrus plays every note at the default Mod X / Y" };
  10198. const auto markersKept = [] (const lynx::Song& s) {
  10199. const auto& m = s.markers();
  10200. return std::any_of (m.begin(), m.end(), [] (const lynx::Marker& x) { return x.name == "Start 190s8"; })
  10201. && std::any_of (m.begin(), m.end(), [] (const lynx::Marker& x) { return x.name == "Skip 190s8"; });
  10202. };
  10203. juce::String why;
  10204. const auto json = lynx::ProjectFile::toJson (song);
  10205. const auto back = lynx::ProjectFile::fromJson (json, why);
  10206. const auto n = (int) song.channels.size();
  10207. if (std::any_of (song.channels.begin() + first, song.channels.end(), [] (const lynx::ChannelDef& c) { return c.engineRev < 3; }))
  10208. rollup031s8Result = "ERROR set-up: a new channel is not at revision 3 or later"; // (round 190py: 4 is current)
  10209. else if (! back || ! back->exportMarkers || (int) back->channels.size() != n
  10210. || std::any_of (back->channels.begin() + first, back->channels.end(), [] (const lynx::ChannelDef& c) { return c.engineRev < 3; }))
  10211. rollup031s8Result = "ERROR the .lynx did not keep revision 3 / the export's markers " + why;
  10212. for (const auto* release : { "0.1.30", "0.1.28" })
  10213. {
  10214. if (rollup031s8Result != "OK")
  10215. break;
  10216. const auto is130 = juce::String (release) == "0.1.30";
  10217. const auto copy = lynx::olderlynx::forRelease (song, release);
  10218. juce::String why2;
  10219. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why2) : std::optional<lynx::Song> {};
  10220. if (! copy.ok || ! old || (int) old->channels.size() != n)
  10221. {
  10222. rollup031s8Result = juce::String ("ERROR copy ") + release + " " + copy.error + why2;
  10223. break;
  10224. }
  10225. for (const auto* line : lines)
  10226. if (countOf (copy, line) != 1)
  10227. {
  10228. rollup031s8Result = juce::String ("ERROR the copy for ") + release + ": \"" + line + "\" " + juce::String (countOf (copy, line)) + " times";
  10229. break;
  10230. }
  10231. if (rollup031s8Result != "OK")
  10232. break;
  10233. if (copy.json.contains ("exportMarkers") || old->exportMarkers)
  10234. rollup031s8Result = juce::String ("ERROR the export's marker switch is left in the copy for ") + release;
  10235. else if (! markersKept (*old))
  10236. rollup031s8Result = juce::String ("ERROR the Start / skip markers are gone from the copy for ") + release;
  10237. else if (! is130 && copy.json.contains ("engineRev"))
  10238. rollup031s8Result = "ERROR a revision is left in the copy for 0.1.28";
  10239. else
  10240. for (int k = 0; k < (int) std::size (kinds); ++k)
  10241. if (const auto rev = old->channels[(std::size_t) (first + k)].engineRev; rev != (is130 ? want130[k] : 0))
  10242. {
  10243. rollup031s8Result = juce::String ("ERROR the copy for ") + release + ": channel " + juce::String (first + k + 1)
  10244. + " at revision " + juce::String (rev) + " (want " + juce::String (is130 ? want130[k] : 0) + ")";
  10245. break;
  10246. }
  10247. }
  10248. if (rollup031s8Result == "OK")
  10249. {
  10250. auto before = song; // (a project saved before round 190pr: revision 2 at most, the switch off)
  10251. before.exportMarkers = false;
  10252. for (auto& c : before.channels)
  10253. c.engineRev = std::min (c.engineRev, 2);
  10254. juce::String why3;
  10255. const auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (before), why3);
  10256. const auto copy = lynx::olderlynx::forRelease (before, "0.1.30");
  10257. if (! again || again->exportMarkers
  10258. || std::any_of (again->channels.begin() + first, again->channels.end(), [] (const lynx::ChannelDef& c) { return c.engineRev != 2; }))
  10259. rollup031s8Result = "ERROR a project saved before 190pr does not read back as saved " + why3;
  10260. else if (! copy.ok || std::any_of (std::begin (lines), std::end (lines), [&] (const char* l) { return countOf (copy, l) != 0; }))
  10261. rollup031s8Result = "ERROR 190pr's lines for a project saved before it";
  10262. else if (const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30"); ! plain.ok || ! plain.lost.empty())
  10263. rollup031s8Result = "ERROR lines for the default song (" + juce::String ((int) plain.lost.size()) + ")";
  10264. }
  10265. }
  10266. // 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.
  10267. // One project with every 0.1.32 format addition: 12 effects on an insert with 14 rows and an automation of slot 12 (PR
  10268. // #260), a note with 4 ratchets and one with a Condition (190pm), a 3x Osc at revision 4 with an automation of one of
  10269. // its FL parameters and a channel PITCH clip (190py), Effector at the Kilohearts Flanger (50) and Ensemble (52) laws
  10270. // (190py-khs). The copy for 0.1.31: 10 effects and no slotRows, the ratchets as 4 notes and no note past [20], every
  10271. // channel at revision 3 or lower, Effector's [12 …] cut, each line once, stamped 0.1.31; the copies for 0.1.30 and
  10272. // 0.1.28 run it first: each line once there too, revisions 2 / none. The default song: no line. Round 190px's caches are
  10273. // not in projects: a stretched copy of a stereo file with identical channels is written with header channels -2 (one
  10274. // channel; 0.1.31 accepts only 1 / 2 and stretches again) and reads back as both channels; a streamed one (over 30 s)
  10275. // keeps .L.pcm + .R.same and no .R.pcm (0.1.31 wants both .pcm files, so it decodes again).
  10276. juce::String rollup032Result = "OK";
  10277. {
  10278. auto song = lynx::Song::makeDefault();
  10279. if (song.mixer.size() < 3)
  10280. song.mixer = lynx::Song::defaultMixer (4);
  10281. auto& bus = song.mixer[1];
  10282. bus.name = "Bus 190qn";
  10283. bus.effects.clear();
  10284. for (int i = 0; i < 12; ++i)
  10285. {
  10286. auto fx = lynx::makeEffectSlot (i == 0 ? lynx::EffectKind::effector : i == 1 ? lynx::EffectKind::effector : lynx::EffectKind::utility);
  10287. fx.row = i;
  10288. if (i < 2)
  10289. fx.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (i == 0 ? lynx::khsdsp::Law::flanger : lynx::khsdsp::Law::ensemble2);
  10290. bus.effects.push_back (fx);
  10291. }
  10292. bus.slotRows = 14;
  10293. lynx::Automation slotGain;
  10294. slotGain.name = "Slot 12 gain 190qn";
  10295. slotGain.target = { lynx::AutomationTargetKind::effectParam, 1, 11, 0 };
  10296. slotGain.points = { { 0, 0.25f }, { lynx::ppq, 0.75f } };
  10297. song.automations.push_back (slotGain);
  10298. const auto first = (int) song.channels.size();
  10299. lynx::ChannelDef osc;
  10300. osc.name = "3x Osc 190qn";
  10301. osc.instrument = lynx::InstrumentKind::threeosc;
  10302. song.channels.push_back (osc);
  10303. int oscParam = -1;
  10304. for (int k = 0; k < 120 && oscParam < 0; ++k)
  10305. if (lynx::threeosc::isFlTarget (k))
  10306. oscParam = k;
  10307. lynx::Automation oscClip, pitchClip;
  10308. oscClip.name = "3x Osc param 190qn";
  10309. oscClip.target = { lynx::AutomationTargetKind::channelParam, first, 0, oscParam };
  10310. oscClip.points = { { 0, 0.2f }, { lynx::ppq, 0.8f } };
  10311. pitchClip.name = "Pitch 190qn";
  10312. pitchClip.target = { lynx::AutomationTargetKind::channelParam, 0, 0, lynx::channelPitchParam };
  10313. pitchClip.points = { { 0, 0.5f }, { lynx::ppq, 0.75f } };
  10314. song.automations.push_back (oscClip);
  10315. song.automations.push_back (pitchClip);
  10316. // rollup 0.1.32 step 2: round 190qo's engine revision 5 (issue #271): a SoundFont channel with a slide note and a
  10317. // quiet note, a BooBass channel with a quiet note
  10318. const auto fontChannel = (int) song.channels.size();
  10319. lynx::ChannelDef font, boo;
  10320. font.name = "SoundFont 190qv";
  10321. font.instrument = lynx::InstrumentKind::soundfont;
  10322. boo.name = "BooBass 190qv";
  10323. boo.instrument = lynx::InstrumentKind::boobass;
  10324. song.channels.push_back (font);
  10325. song.channels.push_back (boo);
  10326. // round 190qz: an Envelope Controller (channel revision 6) and a Peak Controller (slot revision 3) with links; an
  10327. // Effector at round 190qz-khs's law 55 (kHs Delay) on insert 2
  10328. lynx::ChannelDef envelope;
  10329. envelope.name = "Envelope 190qz";
  10330. envelope.instrument = lynx::InstrumentKind::controller;
  10331. envelope.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  10332. song.channels.push_back (envelope);
  10333. {
  10334. auto& bus2 = song.mixer[2];
  10335. bus2.effects.clear();
  10336. auto peakCtl = lynx::makeEffectSlot (lynx::EffectKind::peakController);
  10337. auto delay55 = lynx::makeEffectSlot (lynx::EffectKind::effector);
  10338. delay55.row = 1;
  10339. delay55.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::delay);
  10340. bus2.effects = { peakCtl, delay55 };
  10341. lynx::Automation envLink, peakLink;
  10342. envLink.name = "Envelope link 190qz";
  10343. envLink.target = { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
  10344. envLink.source.channel = fontChannel + 2;
  10345. peakLink.name = "Peak link 190qz";
  10346. peakLink.target = { lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 };
  10347. peakLink.source.track = 2;
  10348. peakLink.source.slot = 0;
  10349. song.automations.push_back (envLink);
  10350. song.automations.push_back (peakLink);
  10351. }
  10352. if (song.patterns.empty())
  10353. song.patterns.emplace_back();
  10354. auto& notes = song.patterns[0].notes;
  10355. notes.clear();
  10356. lynx::Note ratchet, conditioned;
  10357. ratchet.channel = 0, ratchet.key = 60, ratchet.start = 0, ratchet.length = lynx::ppq, ratchet.ratchets = 4;
  10358. conditioned.channel = 0, conditioned.key = 64, conditioned.start = 2 * lynx::ppq, conditioned.length = lynx::ppq;
  10359. conditioned.cycle = 4, conditioned.cycleMask = 2; // 2:4
  10360. notes.push_back (ratchet);
  10361. notes.push_back (conditioned);
  10362. lynx::Note fontNote, fontSlide, booNote;
  10363. fontNote.channel = fontChannel, fontNote.key = 48, fontNote.start = 0, fontNote.length = 2 * lynx::ppq, fontNote.velocity = 0.3f;
  10364. fontSlide.channel = fontChannel, fontSlide.key = 55, fontSlide.start = lynx::ppq, fontSlide.length = lynx::ppq / 2, fontSlide.slide = true;
  10365. booNote.channel = fontChannel + 1, booNote.key = 36, booNote.start = 0, booNote.length = lynx::ppq, booNote.velocity = 0.4f;
  10366. notes.push_back (fontNote);
  10367. notes.push_back (fontSlide);
  10368. notes.push_back (booNote);
  10369. const char* const lines[] = { "This release holds 10 effect slots", "{0} note(s) with ratchets become their strikes",
  10370. "{0} note(s) with a Condition", "Automation of a channel's Pitch knob does nothing",
  10371. "Automation of 3x Osc's parameters does nothing", "Effector's newer Kilohearts laws (the Comb Filter",
  10372. "Effector's Kilohearts Flanger and Dual Delay laws",
  10373. "Slide notes move only the pitch on these channels", // (round 190qo, revision 5)
  10374. "SoundFont channels play low velocities much quieter", "BooBass plays every note at full level",
  10375. "Peak and Envelope Controller links set their targets from the start", // (round 190qz)
  10376. "Effector's newer Kilohearts laws (the kHs Ring Mod's oversampled path" }; // (round 190qz-khs)
  10377. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* begin) {
  10378. return (int) std::count_if (c.lost.begin(), c.lost.end(), [begin] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (begin); });
  10379. };
  10380. const auto rels = lynx::olderlynx::releases();
  10381. if (oscParam < 0)
  10382. rollup032Result = "ERROR set-up: no 3x Osc FL target";
  10383. 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)
  10384. rollup032Result = "ERROR set-up: a new channel is not at revision 6";
  10385. else if (rels.size() != 5 || rels[0] != "0.1.32" || rels[1] != "0.1.31" || rels[2] != "0.1.30" || rels[3] != "0.1.28" || rels[4] != "0.1.27") // (rollup 0.1.33, round 190tf: 0.1.32 first)
  10386. rollup032Result = "ERROR the release list: " + rels.joinIntoString (" ");
  10387. for (const auto* release : { "0.1.31", "0.1.30", "0.1.28" })
  10388. {
  10389. if (rollup032Result != "OK")
  10390. break;
  10391. const auto rel = juce::String (release);
  10392. const auto copy = lynx::olderlynx::forRelease (song, rel);
  10393. const auto root = juce::JSON::parse (copy.json);
  10394. juce::String why;
  10395. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  10396. if (! copy.ok || ! old)
  10397. {
  10398. rollup032Result = "ERROR copy " + rel + " " + copy.error + why;
  10399. break;
  10400. }
  10401. for (const auto* l : lines)
  10402. if (countOf (copy, l) != 1)
  10403. {
  10404. rollup032Result = "ERROR the copy for " + rel + ": \"" + l + "\" " + juce::String (countOf (copy, l)) + " times";
  10405. break;
  10406. }
  10407. if (rollup032Result != "OK")
  10408. break;
  10409. const auto& fx = root["mixer"][1]["effects"];
  10410. int longest = 0, struck = 0;
  10411. if (const auto* ns = root["patterns"][0]["notes"].getArray())
  10412. for (const auto& n : *ns)
  10413. {
  10414. longest = std::max (longest, n.size());
  10415. struck += (int) n[3] == 60 ? 1 : 0;
  10416. }
  10417. bool detached = false;
  10418. if (const auto* autos = root["automations"].getArray())
  10419. for (const auto& a : *autos)
  10420. if (a["name"].toString() == "Slot 12 gain 190qn")
  10421. detached = a["target"][0].toString() == "none";
  10422. const auto maxRev = rel == "0.1.31" ? 3 : rel == "0.1.30" ? 2 : 0;
  10423. const auto revOk = std::all_of (old->channels.begin(), old->channels.end(), [maxRev] (const lynx::ChannelDef& c) { return c.engineRev <= maxRev; })
  10424. && (rel != "0.1.28" || ! copy.json.contains ("engineRev"))
  10425. && (rel != "0.1.31" || (old->channels[(std::size_t) first].engineRev == 3 && old->channels[(std::size_t) fontChannel].engineRev == 3));
  10426. if (! root["savedBy"].toString().equalsIgnoreCase (rel))
  10427. rollup032Result = "ERROR the copy for " + rel + " is stamped " + root["savedBy"].toString();
  10428. else if (fx.size() != 10 || copy.json.contains ("slotRows") || ! detached)
  10429. rollup032Result = "ERROR the copy for " + rel + ": slots (" + juce::String (fx.size()) + " effects)";
  10430. else if (longest > 21 || struck != 4)
  10431. rollup032Result = "ERROR the copy for " + rel + ": notes (longest " + juce::String (longest) + ", strikes " + juce::String (struck) + ")";
  10432. else if (fx[0]["params"].size() > lynx::khsdsp::lawParam || fx[1]["params"].size() > lynx::khsdsp::lawParam)
  10433. rollup032Result = "ERROR the copy for " + rel + ": Effector's [12] is left";
  10434. else if (! revOk)
  10435. rollup032Result = "ERROR the copy for " + rel + ": engine revisions";
  10436. else if ((int) root["mixer"][2]["effects"][0]["engineRev"] > 2 || root["mixer"][2]["effects"][1]["params"].size() > lynx::khsdsp::lawParam)
  10437. rollup032Result = "ERROR the copy for " + rel + ": round 190qz's Peak Controller revision / Effector law 55";
  10438. }
  10439. if (rollup032Result == "OK")
  10440. if (const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.31"); ! plain.ok || ! plain.lost.empty())
  10441. rollup032Result = "ERROR lines for the default song (" + juce::String ((int) plain.lost.size()) + ")";
  10442. // rollup 0.1.32 step 3 (round 190qt): a project from an FL trial save keeps "flTrialSaved" in every copy and gets no
  10443. // line: 0.1.31 and older ignore the key (only the trial mark of a later Export to FL Studio from that release is
  10444. // lost, as 0.1.31.1's FlOrigin trial key); the copy reads back as the same project
  10445. if (rollup032Result == "OK")
  10446. {
  10447. auto trial = lynx::Song::makeDefault();
  10448. trial.flTrialSaved = true;
  10449. for (const auto* release : { "0.1.31", "0.1.30", "0.1.28" })
  10450. {
  10451. const auto copy = lynx::olderlynx::forRelease (trial, release);
  10452. juce::String why;
  10453. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  10454. if (! copy.ok || ! copy.lost.empty() || ! back || ! back->flTrialSaved)
  10455. rollup032Result = "ERROR the trial mark (round 190qt) in the copy for " + juce::String (release) + " " + copy.error + why;
  10456. }
  10457. }
  10458. // round 190px's caches (not in projects; what 0.1.31 does with them)
  10459. if (rollup032Result == "OK")
  10460. {
  10461. const auto dir = lynx::SampleLibrary::cacheFolder().getParentDirectory().getChildFile ("selftest-190qn");
  10462. dir.deleteRecursively();
  10463. dir.createDirectory();
  10464. const auto writeSame = [&dir] (const juce::String& name, int frames) {
  10465. const auto wav = dir.getChildFile (name);
  10466. juce::WavAudioFormat format;
  10467. juce::AudioBuffer<float> audio (2, frames);
  10468. for (int i = 0; i < frames; ++i)
  10469. {
  10470. const auto v = 0.4f * std::sin (0.031f * (float) i) + 0.2f * std::sin (0.0071f * (float) i);
  10471. audio.setSample (0, i, v);
  10472. audio.setSample (1, i, v);
  10473. }
  10474. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  10475. if (auto* w = format.createWriterFor (out.get(), 44100.0, 2, 16, {}, 0))
  10476. {
  10477. out.release();
  10478. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  10479. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  10480. }
  10481. return wav;
  10482. };
  10483. const auto cache = lynx::SampleLibrary::cacheFolder();
  10484. const auto newest = [&cache] (const juce::String& pattern, juce::Time since) {
  10485. juce::File found;
  10486. for (const auto& f : cache.findChildFiles (juce::File::findFiles, false, pattern))
  10487. if (f.getLastModificationTime() >= since && (found == juce::File() || f.getLastModificationTime() > found.getLastModificationTime()))
  10488. found = f;
  10489. return found;
  10490. };
  10491. const auto since = juce::Time::getCurrentTime() - juce::RelativeTime::seconds (2.0);
  10492. lynx::SampleLibrary library;
  10493. const auto shortWav = writeSame ("same 190qn.wav", 44100);
  10494. // (a ratio within resampleTolerance: the copy is resampled channel by channel, so identical channels stay identical,
  10495. // as Thief's near-tempo stems; the spectral stretchers' stereo output need not be bit-identical across channels)
  10496. const auto stretched = library.loadStretched (shortWav.getFullPathName(), 1.0005);
  10497. // (the copy is written by the cache's writer thread: the new .str file whose frames are this copy's)
  10498. juce::File str;
  10499. juce::MemoryBlock bytes;
  10500. std::int32_t channels = 0;
  10501. std::int64_t frames = 0;
  10502. 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)
  10503. {
  10504. juce::Thread::sleep (50);
  10505. for (const auto& f : cache.findChildFiles (juce::File::findFiles, false, "*.str"))
  10506. {
  10507. juce::MemoryBlock b;
  10508. std::int64_t n = 0;
  10509. // (round 190tg: the header is 64 bytes, version 2 with its hash; frames and channels where they were)
  10510. constexpr int head = (int) lynx::cachecheck::str::headerBytes;
  10511. if (f.getLastModificationTime() < since || ! f.loadFileAsData (b) || b.getSize() < (std::size_t) head)
  10512. continue;
  10513. std::memcpy (&n, static_cast<const char*> (b.getData()) + 16, 8);
  10514. if (n != (std::int64_t) stretched->frames() || (juce::int64) b.getSize() < head + n * (juce::int64) sizeof (float))
  10515. continue;
  10516. str = f, bytes = b, frames = n;
  10517. std::memcpy (&channels, static_cast<const char*> (b.getData()) + 24, 4);
  10518. break;
  10519. }
  10520. }
  10521. // 0.1.31's acceptance (SampleLibrary.cpp readStretched at v0.1.31-alpha): channels 1 or 2 and the size they make
  10522. const auto acceptedBy0131 = frames > 0 && (channels == 1 || channels == 2)
  10523. && (juce::int64) bytes.getSize() == 32 + frames * channels * (juce::int64) sizeof (float);
  10524. if (stretched == nullptr || ! stretched->isStereo() || str == juce::File())
  10525. rollup032Result = juce::String ("ERROR stretch cache: nothing written (")
  10526. + (stretched == nullptr ? "no copy" : ! stretched->isStereo() ? "the copy is mono" : "no new .str in 30 s") + ")";
  10527. else if (channels != -2 || frames != (std::int64_t) stretched->frames()
  10528. || (juce::int64) bytes.getSize() != (juce::int64) lynx::cachecheck::str::headerBytes + frames * (juce::int64) sizeof (float)
  10529. || std::memcmp (static_cast<const char*> (bytes.getData()) + lynx::cachecheck::str::headerBytes, stretched->leftData(), (std::size_t) frames * sizeof (float)) != 0
  10530. || std::memcmp (stretched->leftData(), stretched->rightData(), (std::size_t) frames * sizeof (float)) != 0)
  10531. rollup032Result = "ERROR stretch cache: header channels " + juce::String (channels) + ", frames " + juce::String ((juce::int64) frames);
  10532. else if (acceptedBy0131)
  10533. rollup032Result = "ERROR stretch cache: 0.1.31 would read the one-channel file";
  10534. if (rollup032Result == "OK")
  10535. {
  10536. const auto longWav = writeSame ("same long 190qn.wav", 44100 * 31);
  10537. const auto streamed = library.load (longWav.getFullPathName());
  10538. const auto same = newest ("*.R.same", since);
  10539. const auto key = same.getFileName().upToFirstOccurrenceOf (".R.same", false, false);
  10540. if (streamed == nullptr || ! streamed->isMapped() || ! streamed->isStereo() || streamed->rightData() != streamed->leftData())
  10541. rollup032Result = "ERROR stream cache: not mapped as one channel";
  10542. else if (same == juce::File() || ! cache.getChildFile (key + ".L.pcm").existsAsFile() || cache.getChildFile (key + ".R.pcm").existsAsFile())
  10543. rollup032Result = "ERROR stream cache files (" + same.getFileName() + ")";
  10544. }
  10545. dir.deleteRecursively();
  10546. }
  10547. }
  10548. // rollup 0.1.31 step 7 (PRs #248 / #256 by FKHR26): the docked channel window's header shows by default; its gear hides
  10549. // it, a window of the same channel opened again hides it too (the choice kept per window), the project's window
  10550. // places carry it ([key, "headerHidden"]) and give it back, an older project's places (0.1.30's shape) none; the gear
  10551. // shows it again
  10552. juce::String headerGearResult = "OK";
  10553. {
  10554. lynx::AudioEngine e (false);
  10555. lynx::windowplaces::fromVar ({});
  10556. const auto shownIn = [] (juce::Component* w) { return w == nullptr ? std::optional<bool> {} : lynx::channelWindowHeaderShown (*w); };
  10557. auto first = lynx::makeChannelWindowForShot (e, 0, 0);
  10558. if (shownIn (first.get()) != std::optional<bool> (true))
  10559. headerGearResult = "ERROR not shown by default";
  10560. else if (! lynx::pressChannelHeaderGear (*first) || shownIn (first.get()) != std::optional<bool> (false))
  10561. headerGearResult = "ERROR the gear did not hide it";
  10562. first.reset();
  10563. if (headerGearResult == "OK")
  10564. {
  10565. auto again = lynx::makeChannelWindowForShot (e, 0, 0);
  10566. const auto saved = lynx::windowplaces::toVar();
  10567. const auto savedText = juce::JSON::toString (saved, true);
  10568. if (shownIn (again.get()) != std::optional<bool> (false))
  10569. headerGearResult = "ERROR the choice was not kept for the window";
  10570. else if (! savedText.contains ("headerHidden"))
  10571. headerGearResult = "ERROR the places do not carry it: " + savedText;
  10572. else
  10573. {
  10574. again.reset();
  10575. lynx::windowplaces::fromVar (juce::JSON::parse (juce::String ("[[\"ch:1\", 10, 10, 300, 200, false]]")));
  10576. auto older = lynx::makeChannelWindowForShot (e, 0, 0);
  10577. if (shownIn (older.get()) != std::optional<bool> (true))
  10578. headerGearResult = "ERROR hidden after an older project's places";
  10579. older.reset();
  10580. lynx::windowplaces::fromVar (saved);
  10581. auto restored = lynx::makeChannelWindowForShot (e, 0, 0);
  10582. if (headerGearResult == "OK" && shownIn (restored.get()) != std::optional<bool> (false))
  10583. headerGearResult = "ERROR the saved places did not give it back";
  10584. else if (headerGearResult == "OK" && (! lynx::pressChannelHeaderGear (*restored) || shownIn (restored.get()) != std::optional<bool> (true)
  10585. || ! lynx::windowplaces::hiddenHeaders().empty()))
  10586. headerGearResult = "ERROR the gear did not show it again";
  10587. }
  10588. }
  10589. lynx::windowplaces::fromVar ({});
  10590. }
  10591. // round 190pw (PR #259 by FKHR26): the channel window is the size of the tab it shows, as FL's (FL 2026: Sytrus
  10592. // 860 px wide on its plugin tab, 568 on Misc): a Synth channel's window (docked look) on its plugin tab, then Misc
  10593. // (another size), back (the first size again), and with the header hidden by the gear, each less the header
  10594. // round 190qf (PR #260 by codewithamoako): FL 2026.2's effect slots, up to 25 per insert (src/Slots260Shot190qf.inc)
  10595. const auto slots260Result = slots260Checks ({});
  10596. juce::String perTab259Result = "OK";
  10597. {
  10598. lynx::AudioEngine e (false);
  10599. lynx::windowplaces::fromVar ({});
  10600. e.editSong ([] (lynx::Song& s) {
  10601. lynx::ChannelDef d;
  10602. d.instrument = lynx::InstrumentKind::synth;
  10603. d.name = "Synth";
  10604. d.mixerTrack = s.claimFreeInsert();
  10605. s.channels.push_back (d);
  10606. });
  10607. e.dispatchPendingMessages();
  10608. const auto header = lynx::channelFrameHeaderHeight();
  10609. if (auto w = lynx::makeChannelWindowForShot (e, (int) e.getSong().channels.size() - 1, 0))
  10610. {
  10611. const auto first = w->getBounds();
  10612. lynx::showChannelWindowTab (*w, -1);
  10613. const auto misc = w->getBounds();
  10614. lynx::showChannelWindowTab (*w, 0);
  10615. const auto back = w->getBounds();
  10616. lynx::pressChannelHeaderGear (*w);
  10617. const auto hiddenFirst = w->getBounds();
  10618. lynx::showChannelWindowTab (*w, -1);
  10619. const auto hiddenMisc = w->getBounds();
  10620. if (misc.getWidth() == first.getWidth() && misc.getHeight() == first.getHeight())
  10621. perTab259Result = "ERROR Misc has the plugin tab's size " + first.toString();
  10622. else if (back != first)
  10623. perTab259Result = "ERROR back on the plugin tab " + back.toString() + ", first " + first.toString();
  10624. else if (hiddenFirst.getHeight() != first.getHeight() - header || hiddenMisc.getHeight() != misc.getHeight() - header)
  10625. perTab259Result = "ERROR header hidden " + hiddenFirst.toString() + " / " + hiddenMisc.toString();
  10626. }
  10627. else
  10628. perTab259Result = "ERROR no window";
  10629. // round 190qd: FL's Sampler window keeps one size on all its tabs (Sample, Envelope / instrument, Misc)
  10630. e.editSong ([] (lynx::Song& s) {
  10631. lynx::ChannelDef d;
  10632. d.instrument = lynx::InstrumentKind::sampler;
  10633. d.name = "Sampler";
  10634. d.mixerTrack = s.claimFreeInsert();
  10635. s.channels.push_back (d);
  10636. });
  10637. e.dispatchPendingMessages();
  10638. if (auto w = perTab259Result == "OK" ? lynx::makeChannelWindowForShot (e, (int) e.getSong().channels.size() - 1, 0) : nullptr)
  10639. {
  10640. const auto first = w->getBounds();
  10641. lynx::showChannelWindowTab (*w, 1);
  10642. const auto envelope = w->getBounds();
  10643. lynx::showChannelWindowTab (*w, -1);
  10644. const auto misc = w->getBounds();
  10645. if (envelope != first || misc != first)
  10646. perTab259Result = "ERROR Sampler tabs differ " + first.toString() + " / " + envelope.toString() + " / " + misc.toString();
  10647. }
  10648. else if (perTab259Result == "OK")
  10649. perTab259Result = "ERROR no Sampler window";
  10650. lynx::windowplaces::fromVar ({});
  10651. }
  10652. // hotfix 0.1.31.1 (round 190qp): a docked window's place in the dock's coordinates (src/HotfixUi190qp.inc)
  10653. const auto hotfixPlacesResult = hotfixPlaces190qpCheck();
  10654. // hotfix 0.1.31.2 (round 190ra): every list of the start page scrolled and painted (src/Hotfix190ra.inc)
  10655. const auto startPageScrollResult = startPageScroll190raCheck();
  10656. // round 190pv (issue #258): a cloned channel's own automation clip drives its sound (src/Issue258Test.inc: the app's
  10657. // engine, render-ahead off and on; Transistor Bass when FL Studio is here, LYNX Synth always)
  10658. juce::String issue258Log;
  10659. const auto issue258Result = issue258Check (issue258Log);
  10660. // round 190qp (0.1.31.1, issue #253 / Discord): an imported FL project's mixer volume, send level and Fruity Filter
  10661. // cutoff automation heard and shown through the app's engine, as imported, with a flat lane added and with the
  10662. // clips moved into lanes, render-ahead off / on, Clip-launch's override (src/Hotfix190qpTest.inc)
  10663. juce::String autolive190qpLog;
  10664. const auto autolive190qpResult = autoLiveCheck (autoLiveFlSong(), autolive190qpLog, 2, true);
  10665. // round 190qs (issue #282): FL's trial mark travels with its plugin in Export to FL Studio (src/Issue282Check.inc)
  10666. juce::String issue282Log;
  10667. const auto issue282Result = issue282Check (issue282Log);
  10668. // round 190qt (owner's option A): a project from an FL trial save goes back to FL as one (src/TrialMark190qtCheck.inc)
  10669. // round 190rh: the FL natives without FL Studio (src/NoFl190rhCheck.inc)
  10670. juce::String nofl190rhLog;
  10671. auto nofl190rhResult = noFl190rhCheck (nofl190rhLog);
  10672. // round 190tf (rollup 0.1.33): Save a copy for LYNX SHARE 0.1.32 (src/Downgrade0132_190tfCheck.inc)
  10673. juce::String downgrade0132Log;
  10674. juce::String downgrade0132Result;
  10675. {
  10676. const auto folder = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-190tf-" + juce::String (juce::Time::currentTimeMillis()));
  10677. downgrade0132Result = copyFor0132Check (folder, downgrade0132Log);
  10678. folder.deleteRecursively();
  10679. }
  10680. if (nofl190rhResult == "OK")
  10681. nofl190rhResult = flFolder190rhCheck (nofl190rhLog);
  10682. juce::String trialmark190qtLog;
  10683. const auto trialmark190qtResult = trialMark190qtCheck (trialmark190qtLog);
  10684. // round 190qr (issues #274-#281): markers' Delete, the rack's time signature, FL's deepest zoom and the samples drawn
  10685. // there, the zoom-around-the-song-position and gain-handle extras (src/Issues190qrCheck.inc)
  10686. juce::String issues190qrLog;
  10687. const auto issues190qrResult = issues190qrCheck (issues190qrLog);
  10688. // round 190rc (0.1.32 backlog): #288 native generator presets, ... (src/Backlog190rcCheck.inc)
  10689. // round 190ri (0.1.32 community batch): track renders, transpose, scale box, Alt+C, clone names, unique samples
  10690. juce::String community190riLog;
  10691. const auto community190riResult = community190riCheck (community190riLog);
  10692. juce::String flParity190tcLog; // round 190tc: FL parity block D part 1 (src/FlParity190tcCheck.inc)
  10693. const auto flParity190tcResult = flParity190tcCheck (flParity190tcLog);
  10694. // round 190rw (0.1.32 Q1 part A): the song replaced under a held drag in every editor (src/Q1a190rwCheck.inc)
  10695. juce::String q1a190rwResult;
  10696. {
  10697. const auto q1aReport = juce::File::createTempFile ("q1a190rw.txt");
  10698. q1a190rwResult = runQ1a190rwTest (q1aReport) ? "OK" : "FAILED | " + q1aReport.loadFileAsString().replace ("\n", "; ");
  10699. q1aReport.deleteFile();
  10700. }
  10701. juce::String backlog190rcLog;
  10702. const auto backlog190rcResult = backlog190rcCheck (backlog190rcLog);
  10703. // round 190rm (0.1.32 import / export sweep): MIDI tempo map / chunks / meter, FLM losses, DAWproject samples (src/Iox190rmCheck.inc)
  10704. juce::String iox190rmLog;
  10705. const auto iox190rmResult = iox190rmCheck (iox190rmLog);
  10706. // round 190rt (issues #310 / #311): an existing clip linked from Link to controller; the voice block's tab of
  10707. // 3x Osc, DX10, Granulizer and BeepMap (src/Issues190rtShot.inc)
  10708. juce::String issues190rtLog;
  10709. const auto issues190rtResult = issues190rtCheck (issues190rtLog);
  10710. // round 190rn (perf round 10): the undo history's memory cap (src/Perf190rnCheck.inc)
  10711. juce::String perf190rnLog;
  10712. const auto perf190rnResult = perf190rnCheck (perf190rnLog);
  10713. // round 190sb (stage Q2): FL's plugin database kept between starts (src/Perf190sbCheck.inc)
  10714. juce::String perf190sbLog;
  10715. const auto perf190sbResult = perf190sbCheck (perf190sbLog);
  10716. // round 190tg (QUEUE item 85): the disk caches' integrity check (src/CacheCheck190tgCheck.inc)
  10717. juce::String cachecheck190tgLog;
  10718. const auto cachecheck190tgResult = cachecheck190tgCheck (cachecheck190tgLog);
  10719. // round 190sp (0.1.33 perf): the undo history's shared copies, byte for byte (src/Undo190spCheck.inc)
  10720. juce::String undo190spLog;
  10721. const auto undo190spResult = undo190spCheck (undo190spLog);
  10722. // round 190sk (Discord norenkae: "export to DAWproject does nothing"): the File menu's "..." items open their windows
  10723. // through the real menu; DAWproject and FLM written through it (src/MenuWindows190skCheck.inc)
  10724. juce::String menuwindows190skLog;
  10725. const auto menuwindows190skResult = menuWindows190skCheck (menuwindows190skLog);
  10726. // round 190sk: audio2000's Linux issues #330-#342 (src/Issues330skCheck.inc)
  10727. juce::String issues330skLog;
  10728. const auto issues330skResult = issues330skCheck (issues330skLog);
  10729. // round 190sq: yannik's #346 (desktop-entry field codes, "Could not open" names the path), #251 follow-up (the
  10730. // project folder of "Always collect and save") and #347 (the drop outline follows an XWayland drag)
  10731. juce::String yannik190sqLog;
  10732. const auto yannik190sqResult = yannik190sqCheck (yannik190sqLog);
  10733. // round 190sv: #334 (the XDND relay into a plugin's editor), #290 (touchpad pinch on Linux), #304 (command markers)
  10734. juce::String batch334svLog;
  10735. const auto batch334svResult = batch334svCheck (batch334svLog);
  10736. // round 190ta: the 0.1.33 REA gap-hunt's small FL-exact fixes (src/Rea190taCheck.inc)
  10737. juce::String rea190taLog;
  10738. const auto rea190taResult = rea190taCheck (rea190taLog);
  10739. // round 190td: the 0.1.33 details follow-ups (undo names per layout, the Esc switch, ...; src/Details190tdCheck.inc)
  10740. juce::String details190tdLog;
  10741. const auto details190tdResult = details190tdCheck (details190tdLog);
  10742. // round 190ti: Slicex's pitch automation paths (FL 2026's), the Playlist's Add key marker (src/Round190tiCheck.inc)
  10743. juce::String round190tiLog;
  10744. const auto round190tiResult = round190tiCheck (round190tiLog);
  10745. // round 190tk: FL's automation timing for imported FL projects (src/Round190tkCheck.inc)
  10746. juce::String round190tkLog;
  10747. const auto round190tkResult = round190tkCheck (round190tkLog);
  10748. // round 190tm: Reload re-reads the file, the Playlist ▾ Time markers, Song mode key markers, muted clips (src/Round190tmCheck.inc)
  10749. juce::String round190tmLog;
  10750. const auto round190tmResult = round190tmCheck (round190tmLog);
  10751. // round 190to: FL's per-insert effects switch, the Master's / Current column's icons, Extra large (src/Round190toCheck.inc)
  10752. juce::String round190toLog;
  10753. const auto round190toResult = round190toCheck (round190toLog);
  10754. // round 190sr: #350, #349, QUEUE 0.1.33 items 42 / 43 (src/SmallBugs190srCheck.inc)
  10755. juce::String smallbugs190srLog;
  10756. const auto smallbugs190srResult = smallBugs190srCheck (smallbugs190srLog);
  10757. // round 190sr: the quick wins (src/QuickWins190srCheck.inc)
  10758. juce::String quickwins190srLog;
  10759. const auto quickwins190srResult = quickWins190srCheck (quickwins190srLog);
  10760. // round 190st: the Slice tool's line and Escape, issues #339 / #340 (src/AudioEdit190stShot.inc)
  10761. juce::String audioedit190stLog;
  10762. const auto audioedit190stResult = audioedit190stCheck (audioedit190stLog);
  10763. // round 190sy: the Kick / Snare / Clap / Hat editors and docked rack windows (src/DrumSynth190syCheck.inc)
  10764. juce::String drumsynth190syLog;
  10765. const auto drumsynth190syResult = drumSynth190syCheck (drumsynth190syLog);
  10766. // round 190sw: #292 the routing cables, #322 macOS's menu bar, #289 the hardware outputs export (src/Batch292Check190sw.inc)
  10767. juce::String batch292_190swLog;
  10768. const auto batch292_190swResult = batch292Check190sw (batch292_190swLog);
  10769. // round 190te: #356 the latency-compensated transport (LYNX extra), item 58 XDND drops finished as accepted, item 82
  10770. // the Playlist's Time markers › Delete (src/Round190teCheck.inc)
  10771. juce::String round190teLog;
  10772. const auto round190teResult = round190teCheck (round190teLog);
  10773. // round 190rb (0.1.32 quality release): the crash / memory fixes of the crash reports, the sanitizer build and the
  10774. // UI monkey test (src/Qa190rbCheck.inc)
  10775. juce::String qa190rbLog;
  10776. const auto qa190rbResult = qa190rbCheck (qa190rbLog);
  10777. // round 190rv (0.1.32 open bug issues): #317 the native editors' header LED, #319 the pin keeps the window (src/Bugs190rvCheck.inc)
  10778. juce::String bugs190rvLog;
  10779. const auto bugs190rvResult = bugs190rvCheck (bugs190rvLog);
  10780. // round 190sa (0.1.32 Q6): a sound dropped on the Simple timeline is a new track, the hint names the timeline (src/Q6Check190sa.inc)
  10781. juce::String q6190saLog;
  10782. const auto q6190saResult = q6190saCheck (q6190saLog);
  10783. // round 190sg (issue #325): a sample dropped on an audio clip replaces its channel's sample, as FL (src/Issue325Check190sg.inc)
  10784. juce::String issue325Log;
  10785. const auto issue325Result = issue325Check (issue325Log);
  10786. // round 190sj (issue #327): every key of the F1 shortcut sheet runs its key-map action in its panel (src/KeySheetCheck190sj.inc)
  10787. juce::String keysheet190sjLog;
  10788. const auto keysheet190sjResult = keySheet190sjCheck (keysheet190sjLog);
  10789. // round 190tb (0.1.33 details pass): FL's hint readouts, pointers and arrows (src/Details190tbCheck.inc)
  10790. juce::String details190tbLog;
  10791. const auto details190tbResult = details190tbCheck (details190tbLog);
  10792. // round 190th (issue #359): what a plugin's child processes get from LYNX (src/Children190thCheck.inc)
  10793. juce::String children190thLog;
  10794. const auto children190thResult = children190thCheck (children190thLog);
  10795. // round 190tj (issue #358): the Notes window (src/Notes190tjCheck.inc)
  10796. juce::String notes190tjLog;
  10797. const auto notes190tjResult = notes190tjCheck (notes190tjLog);
  10798. // round 190rp (0.1.32 Q4, stability): src/Stab190rpCheck.inc
  10799. juce::String stab190rpLog;
  10800. const auto stab190rpResult = stab190rpCheck (stab190rpLog);
  10801. // round 190qh (research190qa R5, Mixer QoL): FL's rule for a switched-off slot through the app's own publish
  10802. // (D2-MX9, REA 190qc: its latency leaves the plan at once, a muted insert keeps it), the theme's own meter
  10803. // thresholds in a .lynxtheme (D2-MX7; none written for the default look), the three unbound actions (D2-MX1, MX8)
  10804. // and the strips' extras (D2-VF5, MX3: off by default, under the read-out when on, the meters shorter by them)
  10805. juce::String mixerqol190qhResult = "OK";
  10806. {
  10807. lynx::AudioEngine e (false);
  10808. const auto before = e.getLatencySamples(); // (the default song's own: its Master limiter)
  10809. e.editSong ([] (lynx::Song& s) {
  10810. auto limiter = lynx::makeEffectSlot (lynx::EffectKind::fruityLimiter);
  10811. limiter.params[3] = 0.401f; // (FL's look-ahead, about 11 ms: round 188e)
  10812. s.mixer[1].effects.push_back (limiter);
  10813. });
  10814. const auto on = e.getLatencySamples();
  10815. e.editSong ([] (lynx::Song& s) { s.mixer[1].effects[0].enabled = false; });
  10816. const auto off = e.getLatencySamples();
  10817. e.editSong ([] (lynx::Song& s) {
  10818. s.mixer[1].effects[0].enabled = true;
  10819. s.mixer[1].muted = true;
  10820. });
  10821. const auto muted = e.getLatencySamples();
  10822. if (on <= before || off != before || muted != on)
  10823. mixerqol190qhResult = "ERROR PDC before / on / off / muted " + juce::String (before) + " / " + juce::String (on) + " / " + juce::String (off) + " / "
  10824. + juce::String (muted);
  10825. lynx::themes::Spec spec;
  10826. const auto plain = lynx::themeui::toJson (spec);
  10827. spec.meterZones = true;
  10828. spec.meterYellowDb = -12.0f;
  10829. spec.meterRedDb = -3.0f;
  10830. const auto back = lynx::themeui::fromJson (lynx::themeui::toJson (spec));
  10831. if (plain.contains ("meterYellowDb") || ! back || ! back->meterZones || back->meterYellowDb != -12.0f || back->meterRedDb != -3.0f
  10832. || lynx::themeui::fromJson (plain)->meterZones)
  10833. mixerqol190qhResult = "ERROR theme meter thresholds";
  10834. for (const auto* id : { "mixer.unsoloAll", "mixer.unmuteAll", "mixer.inputMonitoring" })
  10835. if (const auto* a = lynx::keys::findAction (id); a == nullptr || ! lynx::keys::KeyMap().chordsFor (id).empty())
  10836. mixerqol190qhResult = "ERROR action " + juce::String (id);
  10837. const auto keptPeaks = lynx::MixerStrips::showPeakValues, keptCorrelation = lynx::MixerStrips::showCorrelation;
  10838. {
  10839. lynx::MixerComponent mixer (e);
  10840. mixer.setSize (1400, 800);
  10841. auto& strips = mixer.getStripsForSnapshot();
  10842. strips.setShowPeakValues (false);
  10843. strips.setShowCorrelation (false);
  10844. const auto fader = strips.faderAreaForSnapshot (1);
  10845. const auto none = strips.peakValueAreaForSnapshot (1).isEmpty() && strips.correlationAreaForSnapshot (1).isEmpty();
  10846. strips.setShowPeakValues (true);
  10847. strips.setShowCorrelation (true);
  10848. const auto peak = strips.peakValueAreaForSnapshot (1), corr = strips.correlationAreaForSnapshot (1);
  10849. const auto shorter = strips.faderAreaForSnapshot (1);
  10850. if (! none || peak.isEmpty() || corr.isEmpty() || corr.getY() <= shorter.getBottom() || peak.getY() < corr.getBottom()
  10851. || fader.getHeight() - shorter.getHeight() != lynx::MixerStrips::correlationRowHeight + lynx::MixerStrips::peakRowHeight
  10852. || ! e.getMeters().correlationWanted.load())
  10853. mixerqol190qhResult = "ERROR strip extras " + peak.toString() + " / " + corr.toString() + " / " + fader.toString() + " / " + shorter.toString();
  10854. strips.setShowPeakValues (false);
  10855. strips.setShowCorrelation (false);
  10856. }
  10857. lynx::MixerStrips::showPeakValues = keptPeaks;
  10858. lynx::MixerStrips::showCorrelation = keptCorrelation;
  10859. }
  10860. // round 190qe (TOP-NEXT R1): the edge scroll at FL's speed, the view stack, the zoom glide and anchor, Restore
  10861. // selection, Keep labels on screen, through the real Playlist / Piano roll off screen (src/Feel190qeTest.inc)
  10862. juce::String feel190qeResult;
  10863. runFeel190qeTest ({}, {}, {}, &feel190qeResult);
  10864. // round 190qg: every toolbar item on the toolbar or in its overflow at every preset, Interface size and width
  10865. juce::String toolbar190qgLog;
  10866. const auto toolbar190qgResult = toolbar190qgCheck (toolbar190qgLog);
  10867. // round 190qu (Discord 11-24): automation clips into lanes play what they played (held value between clips, the
  10868. // control's own value before, FL's MIN / MAX), in the engine's first 1024 slots, and back into clips; FL's Split by
  10869. // channel; Convert to Track-only keeps every note; a Track-only instrument track's pencil draws new clips
  10870. juce::String discord190quResult = "OK";
  10871. {
  10872. using namespace lynx;
  10873. auto s = Song::makeDefault();
  10874. s.playlist.clear();
  10875. s.channels.clear();
  10876. s.automations.clear();
  10877. s.channels.push_back (mididrop::newChannel ("Lead"));
  10878. trackmodes::makeInstrumentTrack (s, 2, 0);
  10879. s.channels[0].volume = 0.62f;
  10880. Automation a;
  10881. a.target = { AutomationTargetKind::channelVolume, 0, 0, 0 };
  10882. a.points = { { 0, 0.0f, 0.0f }, { 4 * ppq, 1.0f, 0.0f } };
  10883. a.rangeMin = 0.2f;
  10884. a.rangeMax = 0.6f;
  10885. s.automations.push_back (a);
  10886. for (int k = 0; k < 1030; ++k) // (more automations than the engine's slots after it, on the tempo: no owner track)
  10887. {
  10888. Automation t;
  10889. t.target = { AutomationTargetKind::tempo, 0, 0, 0 };
  10890. t.points = { { 0, 0.5f, 0.0f } };
  10891. s.automations.push_back (t);
  10892. }
  10893. Clip c;
  10894. c.kind = ClipKind::automation;
  10895. c.automation = 0;
  10896. c.track = 5;
  10897. c.start = 4 * ppq;
  10898. c.length = 4 * ppq;
  10899. s.playlist.push_back (c);
  10900. const auto moved = laneview::clipsToLanes (s);
  10901. const auto lane = s.playlistTracks.size() > 2 && ! s.playlistTracks[2].lanes.empty() ? s.playlistTracks[2].lanes[0].automation : -1;
  10902. if (moved != 1 || lane < 0 || lane >= RackState::maxAutomations)
  10903. discord190quResult = "ERROR lane slot " + juce::String (lane);
  10904. else
  10905. {
  10906. const auto& points = s.automations[(std::size_t) lane];
  10907. const auto atStart = points.valueAt ((double) ppq), mid = points.valueAt (6.0 * ppq), held = points.valueAt (20.0 * ppq);
  10908. 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)
  10909. discord190quResult = "ERROR lane values " + juce::String (atStart) + " / " + juce::String (mid) + " / " + juce::String (held);
  10910. else if (autolanes::lanesToClips (s) != 1 || laneview::laneCount (s) != 0)
  10911. discord190quResult = "ERROR lanes back to clips";
  10912. }
  10913. auto p = Song::makeDefault();
  10914. p.patterns.assign (1, Pattern {});
  10915. p.patterns[0].notes = { { 0, ticksPerStep, 0, 60 }, { ticksPerStep, ticksPerStep, 2, 60 } };
  10916. Clip pc;
  10917. pc.kind = ClipKind::pattern;
  10918. pc.track = 0;
  10919. pc.length = p.barTicks();
  10920. p.playlist = { pc };
  10921. auto split = p;
  10922. if (discord190quResult == "OK"
  10923. && (splitPatternByChannel (split, 0) != 1 || split.patterns[0].name != split.channels[0].name || split.playlist.size() != 1))
  10924. discord190quResult = "ERROR split by channel";
  10925. const auto report = trackonly::convertProject (p);
  10926. if (discord190quResult == "OK" && (report.patternsSplit != 1 || report.clipsMoved != 2 || trackmodes::instrumentTracksOf (p, 2).empty()))
  10927. discord190quResult = "ERROR convert " + juce::String (report.patternsSplit) + " / " + juce::String (report.clipsMoved);
  10928. const auto layout = layoutstyle::current();
  10929. const auto trackOnly = trackonly::enabled();
  10930. layoutstyle::setCurrent (layoutstyle::Style::pattern);
  10931. trackonly::setEnabled (true);
  10932. const auto home = trackmodes::instrumentTracksOf (p, 0);
  10933. if (discord190quResult == "OK" && (home.empty() || ! trackclips::pencilMakesNewClip (p, home.front())))
  10934. discord190quResult = "ERROR pencil";
  10935. trackonly::setEnabled (trackOnly);
  10936. layoutstyle::setCurrent (layout);
  10937. }
  10938. // round 190ot (research190oe P5): the Simple layout's "Duck under..." and shared Echo send in .lynx (the duck's goal,
  10939. // 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,
  10940. // route and sends (an ordinary Fruity Limiter there), one view line, none for a project without a duck
  10941. // round 190pe (research190oe P20 / P11): a track's versions in .lynx (every version, the active one), a switch as one
  10942. // undo step that restores the song bit for bit, the copies for 0.1.30 / 0.1.28 (only the active version, one line;
  10943. // none without versions), and tracks of another project imported as one undo step
  10944. juce::String tracks190peResult = "OK";
  10945. {
  10946. namespace tv = lynx::trackversions;
  10947. auto song = lynx::Song::makeDefault();
  10948. song.playlist.clear();
  10949. lynx::ChannelDef vox;
  10950. vox.name = "Vox";
  10951. vox.instrument = lynx::InstrumentKind::audioClip;
  10952. vox.samplePath = "vox.wav";
  10953. const auto ins = song.nextFreeInsert(); // (an insert of its own: the version's chain)
  10954. vox.mixerTrack = ins;
  10955. song.channels.push_back (vox);
  10956. song.mixer[(std::size_t) ins].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::eq));
  10957. lynx::Clip c;
  10958. c.kind = lynx::ClipKind::audio;
  10959. c.channel = (int) song.channels.size() - 1;
  10960. c.track = 1;
  10961. c.length = 4 * lynx::ppq;
  10962. song.playlist.push_back (c);
  10963. song.playlistTracks.resize (2);
  10964. song.playlistTracks[1].name = "Vox";
  10965. const auto plain = lynx::ProjectFile::toJson (song);
  10966. tv::add (song, 1, tv::Start::duplicate, "B", "A");
  10967. for (auto& k : song.playlist)
  10968. if (k.track == 1)
  10969. k.length = lynx::ppq;
  10970. song.mixer[(std::size_t) ins].effects[0].enabled = false;
  10971. juce::String why;
  10972. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  10973. if (plain.contains ("playlistTrackVersions"))
  10974. tracks190peResult = "ERROR a project without versions writes the key";
  10975. else if (! back || back->playlistTracks.size() < 2 || back->playlistTracks[1].versions != song.playlistTracks[1].versions
  10976. || back->playlistTracks[1].activeVersion != 1 || back->playlist != song.playlist)
  10977. tracks190peResult = "ERROR .lynx round trip " + why;
  10978. if (tracks190peResult == "OK")
  10979. {
  10980. lynx::AudioEngine e (false);
  10981. e.setSong (song);
  10982. // (editSongStructural first adds the working time so far to the song: the undo step holds that)
  10983. const auto json = [] (lynx::Song s) {
  10984. s.info.workSeconds = 0.0;
  10985. return lynx::ProjectFile::toJson (s);
  10986. };
  10987. const auto before = json (e.getSong());
  10988. e.editSongStructural ([] (lynx::Song& s) { tv::switchTo (s, 1, 0); });
  10989. const auto switched = tv::active (e.getSong(), 1) == 0 && e.getSong().mixer[(std::size_t) ins].effects[0].enabled;
  10990. e.undo();
  10991. if (! switched || json (e.getSong()) != before)
  10992. tracks190peResult = juce::String ("ERROR undo of a version switch (switched ") + (switched ? "yes" : "no") + ")";
  10993. // tracks of another project: one undo step
  10994. if (tracks190peResult == "OK")
  10995. {
  10996. auto other = song;
  10997. lynx::trackimport::Result r;
  10998. e.editSongStructural ([&r, &other] (lynx::Song& s) { r = lynx::trackimport::importTracks (s, other, { 1 }, {}); });
  10999. const auto came = r.ok && r.tracks.size() == 1 && r.inserts.size() == 1 && tv::count (e.getSong(), r.tracks[0]) == 2;
  11000. e.undo();
  11001. if (! came || json (e.getSong()) != before)
  11002. tracks190peResult = juce::String ("ERROR import of a track and its undo (came ") + (came ? "yes" : "no") + ")";
  11003. }
  11004. }
  11005. for (const auto* release : { "0.1.30", "0.1.28" })
  11006. {
  11007. if (tracks190peResult != "OK")
  11008. break;
  11009. const auto copy = lynx::olderlynx::forRelease (song, release);
  11010. 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"); });
  11011. const auto opened = lynx::ProjectFile::fromJson (copy.json, why);
  11012. if (! copy.ok || lines != 1 || copy.json.contains ("playlistTrackVersions") || ! opened || opened->playlist != song.playlist
  11013. || opened->mixer[(std::size_t) ins].effects[0].enabled)
  11014. tracks190peResult = juce::String ("ERROR the copy for ") + release + " (" + juce::String ((int) lines) + " lines) " + why;
  11015. }
  11016. if (tracks190peResult == "OK")
  11017. {
  11018. const auto copy = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30");
  11019. if (std::any_of (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains ("track version"); }))
  11020. tracks190peResult = "ERROR a version line without versions";
  11021. }
  11022. }
  11023. juce::String simpleDuck190otResult = "OK";
  11024. {
  11025. namespace st = lynx::simpletracks;
  11026. auto song = lynx::Song::makeDefault();
  11027. st::Request q;
  11028. q.kind = st::Kind::audio;
  11029. q.name = "Kick";
  11030. const auto kick = st::addTrack (song, q).insert;
  11031. q.name = "Pad";
  11032. const auto pad = st::addTrack (song, q).insert;
  11033. const auto set = st::setDuck (song, pad, kick, 0.7f) == st::DuckResult::set && st::setEchoSend (song, pad, 0.3f);
  11034. const auto keeps = [&] (const std::optional<lynx::Song>& back) {
  11035. if (! back || (int) back->mixer.size() <= pad)
  11036. return false;
  11037. const auto slot = st::duckSlot (*back, pad);
  11038. return slot >= 0 && st::duckTrigger (*back, pad) == kick && back->routes (kick, pad) && back->routeLevel (kick, pad) == 0.0f
  11039. && std::abs (back->mixer[(std::size_t) pad].effects[(std::size_t) slot].goalAmount - 0.7f) < 1.0e-4f
  11040. && st::sharedEcho (*back) == st::sharedEcho (song) && std::abs (st::echoSend (*back, pad) - 0.3f) < 1.0e-4f;
  11041. };
  11042. juce::String why;
  11043. if (! set || kick <= 0 || pad <= 0)
  11044. simpleDuck190otResult = "ERROR set-up";
  11045. else if (! keeps (lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why)))
  11046. simpleDuck190otResult = "ERROR .lynx round trip " + why;
  11047. for (const auto* release : { "0.1.30", "0.1.28" })
  11048. {
  11049. if (simpleDuck190otResult != "OK")
  11050. break;
  11051. const auto copy = lynx::olderlynx::forRelease (song, release);
  11052. 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"); });
  11053. if (! copy.ok || ! keeps (lynx::ProjectFile::fromJson (copy.json, why)) || lines != 1)
  11054. simpleDuck190otResult = juce::String ("ERROR the copy for ") + release + " (" + juce::String ((int) lines) + " duck lines) " + why;
  11055. }
  11056. if (simpleDuck190otResult == "OK")
  11057. {
  11058. st::setDuck (song, pad, -1);
  11059. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  11060. if (std::any_of (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains ("Duck under"); }))
  11061. simpleDuck190otResult = "ERROR a duck line without a duck";
  11062. }
  11063. }
  11064. // round 190pm (research190oe P19): Note Repeats and Conditions in .lynx (every field), through the online sessions' note
  11065. // codec (optional fields), and in the copies for 0.1.30 / 0.1.28 (ratchets as notes of their own, one view line;
  11066. // conditions dropped, one sound line), none of it for a project without them
  11067. juce::String repeats190pmResult = "OK";
  11068. {
  11069. auto song = lynx::Song::makeDefault();
  11070. if (song.patterns.empty())
  11071. song.patterns.resize (1);
  11072. if (song.channels.empty())
  11073. song.channels.resize (1);
  11074. lynx::Note a;
  11075. a.start = 0;
  11076. a.length = lynx::ppq;
  11077. a.ratchets = 4;
  11078. a.ratchetVelocity = -0.5f;
  11079. lynx::Note b = a;
  11080. b.start = lynx::ppq;
  11081. b.ratchets = 0;
  11082. b.ratchetVelocity = 0.0f;
  11083. b.condition = lynx::notecondition::notFirst;
  11084. b.cycle = 4;
  11085. b.cycleMask = 0b1010;
  11086. song.patterns[0].notes = { a, b };
  11087. juce::String why;
  11088. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  11089. if (! back || back->patterns[0].notes != song.patterns[0].notes)
  11090. repeats190pmResult = "ERROR .lynx round trip " + why;
  11091. for (const auto& n : song.patterns[0].notes)
  11092. if (repeats190pmResult == "OK" && lynx::remote_notes::fromValue (lynx::remote_notes::toValue (n), song.channels.size()) != n)
  11093. repeats190pmResult = "ERROR the online sessions' note codec";
  11094. for (const auto* release : { "0.1.30", "0.1.28" })
  11095. {
  11096. if (repeats190pmResult != "OK")
  11097. break;
  11098. const auto copy = lynx::olderlynx::forRelease (song, release);
  11099. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  11100. const auto lines = std::count_if (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  11101. return juce::String (l.text).contains ("ratchets") || juce::String (l.text).contains ("Condition");
  11102. });
  11103. if (! old || old->patterns[0].notes.size() != 5 || lines != 2)
  11104. repeats190pmResult = juce::String ("ERROR the copy for ") + release + " (" + juce::String ((int) lines) + " lines) " + why;
  11105. }
  11106. song.patterns[0].notes = { lynx::Note {} };
  11107. if (repeats190pmResult == "OK")
  11108. for (const auto& l : lynx::olderlynx::forRelease (song, "0.1.30").lost)
  11109. if (juce::String (l.text).contains ("ratchets") || juce::String (l.text).contains ("Condition"))
  11110. repeats190pmResult = "ERROR a line without ratchets or conditions";
  11111. }
  11112. // round 190ol (research190oe P1 / P6): the Sections lane in .lynx (both arrangements, and a project without sections
  11113. // keeps its JSON with no "sections" key), a section move as one undo step that restores the song bit for bit, the
  11114. // 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
  11115. // song's metronome table (core/SignatureEdit.h)
  11116. juce::String sections190olResult = "OK";
  11117. {
  11118. const auto bar = 4 * (std::int64_t) lynx::ppq;
  11119. auto song = lynx::Song::makeDefault();
  11120. 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)
  11121. lynx::Clip c;
  11122. c.pattern = 0;
  11123. c.track = 0;
  11124. c.length = 2 * bar;
  11125. song.playlist = { c };
  11126. c.start = 2 * bar;
  11127. c.track = 1;
  11128. song.playlist.push_back (c);
  11129. song.sections() = { { 0, 2 * bar, "Intro", 0, 1 }, { 2 * bar, 2 * bar, "Verse", 0xFF336699u, 2 } };
  11130. song.addArrangement ("Second", true);
  11131. song.sections().push_back ({ 4 * bar, bar, "Outro", 0, 3 });
  11132. song.selectArrangement (0);
  11133. juce::String why;
  11134. const auto json = lynx::ProjectFile::toJson (song);
  11135. const auto back = lynx::ProjectFile::fromJson (json, why);
  11136. if (! back || back->arrangements.size() != 2 || back->arrangements[0].sections != song.arrangements[0].sections
  11137. || back->arrangements[1].sections != song.arrangements[1].sections || back->sections().size() != 2 || back->sections()[1].colour != 0xFF336699u)
  11138. sections190olResult = "ERROR round trip " + why;
  11139. else if (lynx::ProjectFile::toJson (lynx::Song::makeDefault()).contains ("\"sections\""))
  11140. sections190olResult = "ERROR a project without sections writes the key";
  11141. // one undo step, bit for bit
  11142. if (sections190olResult == "OK")
  11143. {
  11144. lynx::AudioEngine e (false);
  11145. e.setSong (song);
  11146. const auto before = lynx::ProjectFile::toJson (e.getSong());
  11147. e.editSong ([] (lynx::Song& s) { lynx::sections::move (s, 1, 0); });
  11148. const auto moved = e.getSong().sections().size() == 2 && e.getSong().sections()[0].name == "Verse";
  11149. e.undo();
  11150. if (! moved || lynx::ProjectFile::toJson (e.getSong()) != before)
  11151. sections190olResult = juce::String ("ERROR undo of a section move (moved ") + (moved ? "yes" : "no") + ")";
  11152. }
  11153. // the copies for older LYNX: plain markers at the sections' starts, "sections" gone, one line
  11154. for (const auto* release : { "0.1.30", "0.1.28" })
  11155. {
  11156. if (sections190olResult != "OK")
  11157. break;
  11158. const auto copy = lynx::olderlynx::forRelease (song, release);
  11159. const auto lines = std::count_if (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  11160. return juce::String (l.text).contains ("Sections lane");
  11161. });
  11162. juce::String why2;
  11163. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why2) : std::nullopt;
  11164. if (! copy.ok || copy.json.contains ("\"sections\"") || lines != 1 || ! old)
  11165. sections190olResult = juce::String ("ERROR the copy for ") + release;
  11166. else if (old->arrangements[0].markers.size() != 2 || old->arrangements[0].markers[1].name != "Verse" || old->arrangements[0].markers[1].tick != 2 * bar
  11167. || old->arrangements[1].markers.size() != 3 || ! old->arrangements[0].sections.empty())
  11168. sections190olResult = juce::String ("ERROR the markers in the copy for ") + release;
  11169. }
  11170. // P6: the metronome follows 4/4 -> 7/8 (bar 3) -> 4/4 (bar 5)
  11171. if (sections190olResult == "OK")
  11172. {
  11173. auto meter = lynx::Song::makeDefault();
  11174. const auto seven = 7 * (std::int64_t) lynx::ppq / 2;
  11175. lynx::signatureedit::set (meter, 2 * bar, 7, 8);
  11176. lynx::signatureedit::set (meter, 2 * bar + 2 * seven, 4, 4);
  11177. lynx::AudioEngine e (false);
  11178. e.setSong (meter);
  11179. e.dispatchPendingMessages();
  11180. const auto& t = e.getTransport();
  11181. if (t.signatureCount.load() != 3 || t.signatureTick[1].load() != 2 * bar || t.signatureLength[1].load() != seven
  11182. || t.signatureBeat[1].load() != (std::int64_t) lynx::ppq / 2 || t.signatureTick[2].load() != 2 * bar + 2 * seven
  11183. || t.signatureLength[2].load() != bar || meter.barAt (2 * bar + 2 * seven).number != 5)
  11184. sections190olResult = "ERROR the metronome's signature table (" + juce::String (t.signatureCount.load()) + " entries)";
  11185. }
  11186. }
  11187. // round 190pf (research190oe P13 / P12): the Chord lane in .lynx (both arrangements; a channel's follow mode; a project
  11188. // without chords keeps its JSON without the keys), a chord edit and Smart Tempo's write as one undo step each that
  11189. // restore the song bit for bit, and the copies for 0.1.30 / 0.1.28 (chords become plain markers named after them,
  11190. // "chords" and "followChords" gone, a line each)
  11191. juce::String chordlane190pfResult = "OK";
  11192. {
  11193. const auto bar = 4 * (std::int64_t) lynx::ppq;
  11194. auto song = lynx::Song::makeDefault();
  11195. 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)
  11196. lynx::Clip c;
  11197. c.pattern = 0;
  11198. c.track = 0;
  11199. c.length = 2 * bar;
  11200. song.playlist = { c };
  11201. const auto chord = [] (int root, int shape, std::int64_t start, std::int64_t length, int bass = -1) {
  11202. auto x = lynx::chordlane::make (root, shape, bass);
  11203. x.start = start;
  11204. x.length = length;
  11205. return x;
  11206. };
  11207. song.chords() = { chord (0, 0, 0, bar), chord (9, 4, bar, bar), chord (7, 2, 2 * bar, bar, 11) };
  11208. lynx::chordlane::normalize (song.chords());
  11209. song.addArrangement ("Second", true);
  11210. song.chords().push_back (chord (5, 3, 4 * bar, bar));
  11211. lynx::chordlane::normalize (song.chords());
  11212. song.selectArrangement (0);
  11213. song.channels.front().followChords = lynx::chordlane::followBass;
  11214. juce::String why;
  11215. const auto json = lynx::ProjectFile::toJson (song);
  11216. const auto back = lynx::ProjectFile::fromJson (json, why);
  11217. if (! back || back->arrangements.size() != 2 || back->arrangements[0].chords != song.arrangements[0].chords
  11218. || back->arrangements[1].chords != song.arrangements[1].chords || back->chords().size() != 3 || back->chords()[2].bass != 11
  11219. || back->channels.front().followChords != lynx::chordlane::followBass)
  11220. chordlane190pfResult = "ERROR round trip " + why;
  11221. else if (const auto plain = lynx::ProjectFile::toJson (lynx::Song::makeDefault()); plain.contains ("\"chords\"") || plain.contains ("followChords"))
  11222. chordlane190pfResult = "ERROR a project without chords writes the keys";
  11223. if (chordlane190pfResult == "OK")
  11224. {
  11225. lynx::AudioEngine e (false);
  11226. e.setSong (song);
  11227. const auto before = lynx::ProjectFile::toJson (e.getSong());
  11228. e.editSong ([bar] (lynx::Song& s) { lynx::chordlane::move (s.chords(), 0, 3 * bar); });
  11229. const auto moved = e.getSong().chords().back().start == 3 * bar;
  11230. e.undo();
  11231. if (! moved || lynx::ProjectFile::toJson (e.getSong()) != before)
  11232. chordlane190pfResult = juce::String ("ERROR undo of a chord move (moved ") + (moved ? "yes" : "no") + ")";
  11233. }
  11234. for (const auto* release : { "0.1.30", "0.1.28" })
  11235. {
  11236. if (chordlane190pfResult != "OK")
  11237. break;
  11238. const auto copy = lynx::olderlynx::forRelease (song, release);
  11239. const auto lines = std::count_if (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  11240. return juce::String (l.text).contains ("Chord lane");
  11241. });
  11242. juce::String why2;
  11243. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why2) : std::nullopt;
  11244. if (! copy.ok || copy.json.contains ("\"chords\"") || copy.json.contains ("followChords") || lines != 2 || ! old)
  11245. chordlane190pfResult = juce::String ("ERROR the copy for ") + release + " (" + juce::String ((int) lines) + " lines)";
  11246. else if (old->arrangements[0].markers.size() != 3 || old->arrangements[0].markers[1].name != "Am7" || old->arrangements[0].markers[2].name != "G7/B"
  11247. || old->arrangements[0].markers[1].tick != bar || old->arrangements[1].markers.size() != 4 || ! old->arrangements[0].chords.empty())
  11248. chordlane190pfResult = juce::String ("ERROR the markers in the copy for ") + release;
  11249. }
  11250. // Smart Tempo: one undo step, bit for bit (the plan of a steady 120 BPM pulse on a clip at bar 2)
  11251. if (chordlane190pfResult == "OK")
  11252. {
  11253. auto take = lynx::Song::makeDefault();
  11254. take.playlist.clear();
  11255. lynx::ChannelDef audio;
  11256. audio.instrument = lynx::InstrumentKind::audioClip;
  11257. take.channels.push_back (audio);
  11258. lynx::Clip a;
  11259. a.kind = lynx::ClipKind::audio;
  11260. a.channel = (int) take.channels.size() - 1;
  11261. a.start = bar;
  11262. a.length = 8 * bar;
  11263. take.playlist.push_back (a);
  11264. std::vector<double> bars;
  11265. for (int k = 0; k <= 8; ++k)
  11266. bars.push_back (0.25 + k * 2.1);
  11267. const auto plan = lynx::smarttempo::plan (take, 0, bars, 20.0);
  11268. lynx::AudioEngine e (false);
  11269. e.setSong (take);
  11270. const auto before = lynx::ProjectFile::toJson (e.getSong());
  11271. auto ok = false;
  11272. e.editSong ([&] (lynx::Song& s) { ok = lynx::smarttempo::apply (s, 0, plan); });
  11273. const auto written = lynx::tempomarkers::list (e.getSong()).size();
  11274. e.undo();
  11275. if (! ok || written != 8 || lynx::ProjectFile::toJson (e.getSong()) != before)
  11276. chordlane190pfResult = "ERROR Smart Tempo's undo (" + juce::String ((int) written) + " markers)";
  11277. }
  11278. }
  11279. // round 190dr: the Session mixer's sections come back from a project (a project without them: Live's defaults);
  11280. // a device dragged to another track and a Warp switch are one undo step each in a real engine
  11281. juce::String livescr190drResult = "OK";
  11282. {
  11283. auto song = lynx::Song::makeDefault();
  11284. lynx::launcher::ensureGrid (song);
  11285. juce::String why;
  11286. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  11287. song.clipGrid->mixerView.io = false;
  11288. song.clipGrid->mixerView.trackOptions = true;
  11289. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  11290. if (! plain || ! plain->clipGrid || ! (plain->clipGrid->mixerView == lynx::SessionMixerView {}))
  11291. livescr190drResult = "ERROR view defaults " + why;
  11292. else if (! back || ! back->clipGrid || back->clipGrid->mixerView.io || ! back->clipGrid->mixerView.trackOptions || ! back->clipGrid->mixerView.shown)
  11293. livescr190drResult = "ERROR view round trip " + why;
  11294. lynx::AudioEngine e (false);
  11295. e.editSong ([] (lynx::Song& s) {
  11296. if (s.mixer.size() < 4)
  11297. s.mixer.resize (4);
  11298. s.mixer[2].effects.clear();
  11299. s.mixer[3].effects.clear();
  11300. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  11301. {
  11302. lynx::EffectSlot fx;
  11303. fx.kind = kind;
  11304. s.mixer[2].effects.push_back (fx);
  11305. }
  11306. lynx::Automation a;
  11307. a.target = { lynx::AutomationTargetKind::effectMix, 2, 1, 0 };
  11308. s.automations.push_back (a);
  11309. }, false);
  11310. const auto id = e.getSong().mixer[2].effects[1].instance.id;
  11311. const auto automations = e.getSong().automations.size();
  11312. e.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  11313. const auto& moved = e.getSong();
  11314. if (livescr190drResult == "OK"
  11315. && (moved.mixer[2].effects.size() != 1 || moved.mixer[3].effects.size() != 1 || moved.mixer[3].effects[0].instance.id != id
  11316. || moved.automations.size() != automations || moved.automations.back().target.index != 3 || moved.automations.back().target.slot != 0))
  11317. livescr190drResult = "ERROR device move";
  11318. e.undo();
  11319. const auto& undone = e.getSong();
  11320. if (livescr190drResult == "OK"
  11321. && (undone.mixer[2].effects.size() != 2 || undone.mixer[3].effects.size() != 0 || undone.mixer[2].effects[1].instance.id != id
  11322. || undone.automations.back().target.index != 2 || undone.automations.back().target.slot != 1))
  11323. livescr190drResult = "ERROR device move undo";
  11324. e.editSong ([] (lynx::Song& s) {
  11325. s.channels.resize (std::max<std::size_t> (s.channels.size(), 1));
  11326. s.channels[0].sampler.stretchBeats = 16.0f;
  11327. lynx::Clip c;
  11328. c.kind = lynx::ClipKind::audio;
  11329. c.channel = 0;
  11330. c.offset = 4 * lynx::ppq;
  11331. c.length = 8 * lynx::ppq;
  11332. lynx::launcher::setClip (s, 0, 0, c);
  11333. }, false);
  11334. e.editSong ([] (lynx::Song& s) { lynx::clipsample::setWarp (s, 0, false, 4.0); });
  11335. const auto* off = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  11336. 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)))
  11337. livescr190drResult = "ERROR warp off";
  11338. e.undo();
  11339. const auto* on = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  11340. if (livescr190drResult == "OK" && (e.getSong().channels[0].sampler.stretchBeats != 16.0f || on == nullptr || on->length != 8 * lynx::ppq))
  11341. livescr190drResult = "ERROR warp undo";
  11342. }
  11343. // round 190ef: the map modes' storage (.lynx round trip of key / MIDI mappings and a link's Min / Max; an older
  11344. // reader keeps the plain link), and in a real engine: a link's range, MIDI Map Mode catching the control instead
  11345. // of moving anything, a slot's MIDI mapping firing on its press and release
  11346. juce::String livewf190efResult = "OK";
  11347. {
  11348. using namespace lynx::remotemap;
  11349. auto song = lynx::Song::makeDefault();
  11350. lynx::launcher::ensureGrid (song);
  11351. const lynx::AutomationTarget vol { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
  11352. assignMidi (song, Target::parameter (vol), { 0, 20, -1 });
  11353. assignMidi (song, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, 2 });
  11354. assignKey (song, Target::sceneLaunch (0), 'S');
  11355. assignKey (song, Target::parameter ({ lynx::AutomationTargetKind::tempo, 0, 0, 0 }), 'T');
  11356. setRange (song, rows (song, Mode::midi)[0], 0.25f, 0.75f);
  11357. setRange (song, rows (song, Mode::key)[1], 0.9f, 0.1f);
  11358. juce::String why;
  11359. const auto json = lynx::ProjectFile::toJson (song);
  11360. const auto back = lynx::ProjectFile::fromJson (json, why);
  11361. if (! back || back->remoteMappings != song.remoteMappings || back->midiLinks != song.midiLinks)
  11362. livewf190efResult = "ERROR round trip " + why;
  11363. auto parsed = juce::JSON::parse (json);
  11364. if (auto* o = parsed.getDynamicObject())
  11365. {
  11366. o->removeProperty ("remoteMappings");
  11367. o->removeProperty ("midiLinkSettings");
  11368. }
  11369. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  11370. if (livewf190efResult == "OK" && (! older || ! older->remoteMappings.empty() || older->midiLinks.size() != 1 || older->midiLinks[0].max != 1.0f))
  11371. livewf190efResult = "ERROR older reader";
  11372. const auto plain = lynx::ProjectFile::toJson (lynx::Song::makeDefault());
  11373. if (livewf190efResult == "OK" && plain.contains ("remoteMappings"))
  11374. livewf190efResult = "ERROR written without mappings";
  11375. lynx::AudioEngine e (false);
  11376. e.editSong ([vol] (lynx::Song& s) {
  11377. if (s.mixer.size() < 3)
  11378. s.mixer.resize (3);
  11379. lynx::MidiLink l { 20, 0, vol };
  11380. l.min = 0.25f;
  11381. l.max = 0.75f;
  11382. s.midiLinks = { l };
  11383. lynx::launcher::ensureGrid (s);
  11384. assignMidi (s, Target::slot (0, 0), { 0, 21, -1 });
  11385. });
  11386. e.injectControllerForTest (20, 0, 127);
  11387. const auto top = e.currentTargetValue (vol);
  11388. e.injectControllerForTest (20, 0, 0);
  11389. const auto bottom = e.currentTargetValue (vol);
  11390. if (livewf190efResult == "OK" && (std::abs (top - 0.75f) > 0.01f || std::abs (bottom - 0.25f) > 0.01f))
  11391. livewf190efResult = "ERROR range " + juce::String (bottom) + " " + juce::String (top);
  11392. std::vector<Fire> fired;
  11393. e.onRemoteFire = [&fired] (const Fire& f) { fired.push_back (f); };
  11394. e.injectControllerForTest (21, 0, 127);
  11395. e.injectControllerForTest (21, 0, 127); // (still down: no new press)
  11396. e.injectControllerForTest (21, 0, 0);
  11397. if (livewf190efResult == "OK"
  11398. && (fired.size() != 2 || fired[0].edge != Edge::press || fired[1].edge != Edge::release || ! (fired[0].target == Target::slot (0, 0))))
  11399. livewf190efResult = "ERROR slot fire " + juce::String ((int) fired.size());
  11400. e.setMapMode (Mode::midi);
  11401. fired.clear();
  11402. e.injectControllerForTest (20, 0, 127);
  11403. e.injectControllerForTest (21, 0, 127);
  11404. const auto caught = e.takeMapCapture();
  11405. if (livewf190efResult == "OK" && (std::abs (e.currentTargetValue (vol) - 0.25f) > 0.01f || ! fired.empty()))
  11406. livewf190efResult = "ERROR mappings acted in MIDI Map Mode";
  11407. else if (livewf190efResult == "OK" && (! caught || caught->number != 21 || caught->channel != 0 || e.takeMapCapture().has_value()))
  11408. livewf190efResult = "ERROR map capture";
  11409. e.setMapMode (Mode::off);
  11410. e.onRemoteFire = nullptr;
  11411. }
  11412. // round 190em: a scene's time signature denominator (.lynx round trip; an older file without it reads n/4; a
  11413. // 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
  11414. // armed track, the selected scene's slot, the tempo from a phrase played while stopped (8 notes at 148 BPM), the
  11415. // new clip launched and the transport started
  11416. juce::String livewf190emResult = "OK";
  11417. {
  11418. auto song = lynx::Song::makeDefault();
  11419. auto& grid = lynx::launcher::ensureGrid (song);
  11420. grid.scenes.resize (3);
  11421. lynx::session::setSceneSignature (song, 1, 6, 8);
  11422. lynx::session::setSceneTempo (song, 1, 100.0);
  11423. juce::String why;
  11424. const auto json = lynx::ProjectFile::toJson (song);
  11425. const auto back = lynx::ProjectFile::fromJson (json, why);
  11426. if (! back || ! back->clipGrid || back->clipGrid->scenes != song.clipGrid->scenes || back->clipGrid->scenes[1].beatUnit != 8)
  11427. livewf190emResult = "ERROR round trip " + why;
  11428. {
  11429. // a captured clip's blank label (ClipGridSlot::blankName) survives the round trip
  11430. auto withClip = song;
  11431. lynx::Clip c;
  11432. c.pattern = 0;
  11433. c.length = 4 * lynx::ppq;
  11434. if (withClip.patterns.empty())
  11435. withClip.patterns.emplace_back();
  11436. const auto slot = lynx::launcher::setClip (withClip, 0, 0, c);
  11437. if (slot >= 0)
  11438. withClip.clipGrid->slots[(std::size_t) slot].blankName = true;
  11439. const auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (withClip), why);
  11440. const auto* keptClip = again && again->clipGrid ? lynx::launcher::clipAt (*again->clipGrid, 0, 0) : nullptr;
  11441. const auto* kept = keptClip != nullptr ? &again->clipGrid->slots[(std::size_t) keptClip->gridSlot] : nullptr;
  11442. if (livewf190emResult == "OK" && (slot < 0 || kept == nullptr || ! kept->blankName))
  11443. livewf190emResult = "ERROR blank clip name round trip";
  11444. }
  11445. auto parsed = juce::JSON::parse (json);
  11446. if (auto* scenes = parsed.getProperty ("clipGrid", {}).getProperty ("scenes", {}).getArray(); scenes != nullptr && scenes->size() > 1)
  11447. if (auto* o = (*scenes)[1].getDynamicObject())
  11448. o->removeProperty ("beatUnit");
  11449. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  11450. if (livewf190emResult == "OK" && (! older || ! older->clipGrid || older->clipGrid->scenes.size() < 2 || older->clipGrid->scenes[1].beatUnit != 4
  11451. || older->clipGrid->scenes[1].beatsPerBar != 6))
  11452. livewf190emResult = "ERROR older reader";
  11453. if (livewf190emResult == "OK" && lynx::ProjectFile::toJson (lynx::Song::makeDefault()).contains ("beatUnit"))
  11454. livewf190emResult = "ERROR beatUnit written by default";
  11455. // round 190fg: the song meter's denominator round-trips through .lynx; a file without it reads n/4
  11456. {
  11457. auto six = lynx::Song::makeDefault();
  11458. six.beatsPerBar = 6;
  11459. six.beatUnit = 8;
  11460. const auto text = lynx::ProjectFile::toJson (six);
  11461. juce::String why2;
  11462. const auto back = lynx::ProjectFile::fromJson (text, why2);
  11463. auto json = juce::JSON::parse (text);
  11464. if (auto* o = json.getDynamicObject())
  11465. o->removeProperty ("beatUnit");
  11466. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (json), why2);
  11467. if (livewf190emResult == "OK" && (! back || back->beatsPerBar != 6 || back->beatUnit != 8 || ! old || old->beatsPerBar != 6 || old->beatUnit != 4))
  11468. livewf190emResult = "ERROR song meter round trip";
  11469. }
  11470. lynx::AudioEngine e (false);
  11471. e.editSong ([] (lynx::Song& s) {
  11472. s.bpm = 120.0;
  11473. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  11474. auto& g = lynx::launcher::ensureGrid (s);
  11475. g.scenes.resize (3);
  11476. lynx::session::setSceneSignature (s, 2, 6, 8);
  11477. lynx::session::setSceneTempo (s, 2, 90.0);
  11478. }, false);
  11479. e.launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, 2 });
  11480. // (round 190fg: the song takes the scene's 6 / 8 as it is: six eighths a bar, 3 quarters long)
  11481. if (livewf190emResult == "OK" && (e.getSong().beatsPerBar != 6 || e.getSong().beatUnit != 8 || e.getSong().barTicks() != 3 * lynx::ppq
  11482. || e.getSong().bpm != 90.0))
  11483. livewf190emResult = "ERROR scene launch " + juce::String (e.getSong().beatsPerBar) + "/" + juce::String (e.getSong().beatUnit) + " "
  11484. + juce::String (e.getSong().bpm);
  11485. e.stop();
  11486. e.editSong ([] (lynx::Song& s) {
  11487. s.bpm = 120.0;
  11488. s.beatsPerBar = 4;
  11489. s.beatUnit = 4;
  11490. }, false);
  11491. e.setGridTrackArmed (2, true, true);
  11492. const auto now = juce::Time::getMillisecondCounterHiRes();
  11493. const auto beat = 60000.0 / 148.0;
  11494. for (int i = 0; i < 8; ++i)
  11495. {
  11496. const auto at = now - 9.0 * beat + i * beat;
  11497. e.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  11498. e.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  11499. }
  11500. int placed = -1;
  11501. bool into = true;
  11502. const auto r = e.captureMidiToSlot (2, 1, placed, into);
  11503. const auto& g = *e.getSong().clipGrid;
  11504. const auto* clip = lynx::launcher::clipAt (g, 2, 1);
  11505. if (livewf190emResult == "OK" && (r.notes != 8 || placed != 1 || into || clip == nullptr || clip->length != 8 * lynx::ppq))
  11506. livewf190emResult = "ERROR capture " + juce::String (r.notes) + " " + juce::String (placed) + (clip == nullptr ? " no clip" : " " + juce::String ((int) clip->length));
  11507. else if (livewf190emResult == "OK" && std::abs (e.getSong().bpm - 148.0) > 0.5)
  11508. livewf190emResult = "ERROR tempo " + juce::String (e.getSong().bpm, 2);
  11509. else if (livewf190emResult == "OK" && ! e.getTransport().playing.load())
  11510. livewf190emResult = "ERROR the capture did not start the transport";
  11511. e.stop();
  11512. }
  11513. const auto mixerBasics = lynx::mixerbasics::run();
  11514. // issue #142: every font has a typeface, and one without does not crash (fonts get theirs through the
  11515. // look and feel, as in the app)
  11516. auto& lookBefore = juce::LookAndFeel::getDefaultLookAndFeel();
  11517. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11518. const auto fontsResult = lynx::theme::fontSelfTest();
  11519. auto paintCachesResult = lynx::theme::paintCacheSelfTest(); // (round 190gr)
  11520. if (paintCachesResult.startsWith ("OK")) // (round 190ki: the Pattern toolbar's cached FL tiles, the pixels of painting them straight)
  11521. {
  11522. const auto tiles = lynx::flTileCacheSelfTest();
  11523. paintCachesResult = tiles == "OK" ? paintCachesResult + ", FL tiles exact at x1 / x2" : tiles;
  11524. }
  11525. // round 190ne (0.1.31, core/TrackClips.h): track clips. A .lynx round trip keeps the flags and an older file opens
  11526. // unchanged; in a real engine a track clip goes with its last clip in the same undo step (Undo brings both back),
  11527. // ordinary patterns stay; the copy for 0.1.28 drops the flags with a loss line; an .flp export merges identical
  11528. // track clips.
  11529. juce::String trackclips190neResult = "OK";
  11530. {
  11531. auto song = lynx::Song::makeDefault();
  11532. if (song.patterns.empty())
  11533. song.patterns.emplace_back().name = "Pattern 1";
  11534. lynx::ChannelDef synth;
  11535. synth.name = "Lead";
  11536. song.channels.push_back (synth);
  11537. const auto channel = (int) song.channels.size() - 1;
  11538. lynx::trackmodes::makeInstrumentTrack (song, 2, channel);
  11539. lynx::trackclips::setOwnClips (song, 2, true);
  11540. const auto a = lynx::trackclips::newClip (song, 2, 4 * lynx::ppq);
  11541. song.patterns[(std::size_t) a].notes.push_back ({});
  11542. song.patterns[(std::size_t) a].notes.back().channel = channel;
  11543. song.patterns[(std::size_t) a].notes.back().key = 60;
  11544. song.patterns[(std::size_t) a].notes.back().length = lynx::ppq;
  11545. const auto b = lynx::trackclips::newClip (song, 2, 4 * lynx::ppq);
  11546. song.patterns[(std::size_t) b].notes = song.patterns[(std::size_t) a].notes;
  11547. for (const auto p : { a, a, b })
  11548. {
  11549. lynx::Clip c;
  11550. c.pattern = p;
  11551. c.track = 2;
  11552. c.start = (std::int64_t) song.playlist.size() * 4 * lynx::ppq;
  11553. c.length = 4 * lynx::ppq;
  11554. song.playlist.push_back (c);
  11555. }
  11556. juce::String why;
  11557. const auto json = lynx::ProjectFile::toJson (song);
  11558. const auto back = lynx::ProjectFile::fromJson (json, why);
  11559. if (! back || back->patterns != song.patterns || back->playlistTracks.size() <= 2 || ! back->playlistTracks[2].ownClips
  11560. || ! back->patterns[(std::size_t) a].trackClip || back->playlist.size() != song.playlist.size())
  11561. trackclips190neResult = "ERROR round trip " + why;
  11562. // an older project (no flags): opens unchanged, nothing becomes a track clip
  11563. const auto plain = lynx::Song::makeDefault();
  11564. const auto plainJson = lynx::ProjectFile::toJson (plain);
  11565. if (trackclips190neResult == "OK" && (plainJson.contains ("trackClip") || plainJson.contains ("playlistOwnClips")))
  11566. trackclips190neResult = "ERROR flags written for a project without track clips";
  11567. if (const auto reread = lynx::ProjectFile::fromJson (plainJson, why); trackclips190neResult == "OK"
  11568. && (! reread || lynx::trackclips::count (*reread) != 0 || lynx::ProjectFile::toJson (*reread) != plainJson))
  11569. trackclips190neResult = "ERROR an older project changed";
  11570. // the copy for 0.1.28: no flags, one loss line
  11571. const auto copy = lynx::olderlynx::forRelease (song, "0.1.28");
  11572. const auto said = [&copy] (const char* text) {
  11573. return std::any_of (copy.lost.begin(), copy.lost.end(), [text] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains (text); });
  11574. };
  11575. if (trackclips190neResult == "OK" && (! copy.ok || copy.json.contains ("\"trackClip\"") || copy.json.contains ("playlistOwnClips") || ! said ("track clip(s) show as ordinary patterns")))
  11576. trackclips190neResult = "ERROR copy for 0.1.28";
  11577. // .flp export: clips a and b hold the same notes: one pattern in FL, every clip kept
  11578. lynx::flpexport::Report flpReport;
  11579. const auto flp = flp::parseProject (lynx::flpexport::exportFlp (song, {}, flpReport));
  11580. auto other = song; // (b with other notes: nothing to merge)
  11581. other.patterns[(std::size_t) b].notes.front().key += 1;
  11582. const auto flpOther = flp::parseProject (lynx::flpexport::exportFlp (other, {}, flpReport));
  11583. if (trackclips190neResult == "OK" && flp.patterns.size() + 1 != flpOther.patterns.size())
  11584. trackclips190neResult = "ERROR flp merge " + juce::String ((int) flp.patterns.size()) + " / " + juce::String ((int) flpOther.patterns.size());
  11585. // a real engine: delete the last clip of b -> b goes in the same undo step; Undo brings it back
  11586. lynx::AudioEngine e (false);
  11587. e.editSong ([&song] (lynx::Song& s) { s = song; });
  11588. const auto before = e.getSong().patterns.size();
  11589. e.editSong ([] (lynx::Song& s) { s.playlist.pop_back(); }); // (the only clip of b)
  11590. if (trackclips190neResult == "OK" && (e.getSong().patterns.size() + 1 != before || e.getSong().playlist.size() != 2))
  11591. trackclips190neResult = "ERROR auto-delete " + juce::String ((int) e.getSong().patterns.size());
  11592. e.undo();
  11593. if (trackclips190neResult == "OK" && (e.getSong().patterns.size() != before || e.getSong().playlist.size() != 3))
  11594. trackclips190neResult = "ERROR undo of the auto-delete";
  11595. // an ordinary pattern without clips stays (FL)
  11596. e.editSong ([] (lynx::Song& s) { s.patterns.emplace_back().name = "Kept"; });
  11597. e.editSong ([] (lynx::Song& s) { s.playlist.erase (s.playlist.begin()); }); // (a's first clip: a still has one)
  11598. if (trackclips190neResult == "OK" && (e.getSong().patterns.size() != before + 1 || e.getSong().patterns.back().name != "Kept"))
  11599. trackclips190neResult = "ERROR an ordinary pattern or a linked clip went";
  11600. }
  11601. // round 190op (P4 / P7, LYNX extras): Hide and Deactivate tracks, Capture automation. Renders in a real engine: a
  11602. // hidden track plays the same (null), a deactivated channel and a deactivated insert are silent, Reactivate gives
  11603. // the same audio back (null), each in one undo step; the .lynx round trip keeps the flags and writes nothing for
  11604. // a project without them; the copy for 0.1.30 drops them with loss lines (deactivated units come back muted);
  11605. // the .flp export reports them; Capture automation writes the last gesture of each moved control in one undo step.
  11606. juce::String trackstates190opResult = "OK";
  11607. {
  11608. lynx::Song song;
  11609. song.mixer = lynx::Song::defaultMixer (4);
  11610. song.bpm = 120.0;
  11611. for (int c = 0; c < 2; ++c)
  11612. {
  11613. lynx::ChannelDef d;
  11614. d.name = c == 0 ? "Lead" : "Bass";
  11615. d.instrument = lynx::InstrumentKind::synth;
  11616. d.mixerTrack = c + 1;
  11617. song.channels.push_back (d);
  11618. }
  11619. song.patterns.clear();
  11620. auto& p = song.patterns.emplace_back();
  11621. p.name = "Both";
  11622. for (int i = 0; i < 4; ++i)
  11623. for (int c = 0; c < 2; ++c)
  11624. {
  11625. lynx::Note n;
  11626. n.channel = c;
  11627. n.key = c == 0 ? 72 + i : 40 + i;
  11628. n.start = i * lynx::ppq;
  11629. n.length = lynx::ppq / 2;
  11630. p.notes.push_back (n);
  11631. }
  11632. song.playlist.clear();
  11633. lynx::Clip clip;
  11634. clip.pattern = 0;
  11635. clip.track = 1;
  11636. clip.start = 0;
  11637. clip.length = 4 * lynx::ppq;
  11638. song.playlist.push_back (clip);
  11639. clip.track = 2;
  11640. clip.start = 24 * lynx::ppq; // (past the renders: the song is seven bars long, Capture's ticks don't fold)
  11641. song.playlist.push_back (clip);
  11642. song.mode = lynx::PlayMode::song;
  11643. const auto render = [] (lynx::AudioEngine& engine) {
  11644. std::vector<float> out;
  11645. lynx::AudioEngine::RenderOptions o;
  11646. o.seconds = 2.5;
  11647. o.sampleRate = 44100.0;
  11648. o.capture = [&out] (const float* l, const float* r, int n) {
  11649. for (int i = 0; i < n; ++i)
  11650. {
  11651. out.push_back (l[i]);
  11652. out.push_back (r[i]);
  11653. }
  11654. };
  11655. engine.renderOffline (o);
  11656. return out;
  11657. };
  11658. const auto peak = [] (const std::vector<float>& v) {
  11659. float m = 0.0f;
  11660. for (const auto x : v)
  11661. m = std::max (m, std::abs (x));
  11662. return m;
  11663. };
  11664. // (every comparison renders the first time on its engine: see the note below)
  11665. const auto renderSong = [&render] (const lynx::Song& s) {
  11666. lynx::AudioEngine fresh (false);
  11667. fresh.setSong (s);
  11668. return render (fresh);
  11669. };
  11670. const auto plain = renderSong (song);
  11671. lynx::AudioEngine e (false);
  11672. e.setSong (song);
  11673. // hide: the same samples, one undo step
  11674. e.editSong ([] (lynx::Song& s) { lynx::trackstates::setHidden (s, { 1 }, true); });
  11675. const auto hidden = renderSong (e.getSong());
  11676. if (peak (plain) < 0.01f || hidden != plain)
  11677. trackstates190opResult = "ERROR hidden track render differs (peak " + juce::String (peak (plain), 4) + ")";
  11678. e.undo();
  11679. if (trackstates190opResult == "OK" && lynx::trackstates::isHidden (e.getSong(), 1))
  11680. trackstates190opResult = "ERROR undo of Hide";
  11681. // (each render below is the first of its engine: a second render of one engine here plays nothing — the
  11682. // notes of a render are not scheduled again — so every state gets its own engine)
  11683. // deactivate the Bass channel (the real menu path: states captured first, one undo step): Lead alone
  11684. auto lead = song;
  11685. lead.channels[1].muted = true;
  11686. const auto leadOnly = renderSong (lead);
  11687. lynx::AudioEngine e1 (false);
  11688. e1.setSong (song);
  11689. e1.setDeactivated ({ 1 }, {}, true);
  11690. const auto noBass = render (e1);
  11691. float diff = 0.0f;
  11692. for (std::size_t i = 0; i < std::min (noBass.size(), leadOnly.size()); ++i)
  11693. diff = std::max (diff, std::abs (noBass[i] - leadOnly[i]));
  11694. if (trackstates190opResult == "OK"
  11695. && (! e1.channelDeactivated (1) || noBass.size() != leadOnly.size() || diff > 1.0e-6f || peak (noBass) < 0.01f))
  11696. trackstates190opResult = "ERROR deactivated channel is not silent (diff " + juce::String (diff, 7) + ")";
  11697. // then insert 1, into which Lead plays (Lead goes with it): silence
  11698. lynx::AudioEngine e2 (false);
  11699. e2.setSong (song);
  11700. e2.setDeactivated ({ 1 }, {}, true);
  11701. e2.setDeactivated ({}, { 1 }, true);
  11702. const auto silent = render (e2);
  11703. if (trackstates190opResult == "OK" && (! e2.channelDeactivated (0) || ! e2.insertDeactivated (1) || peak (silent) > 1.0e-6f))
  11704. trackstates190opResult = "ERROR deactivated insert is not silent (peak " + juce::String (peak (silent), 7) + ")";
  11705. // Reactivate (two undo steps) on an engine that ran the placeholders: its first render nulls with the plain
  11706. // song's (a placeholder kept for a reactivated unit would play nothing)
  11707. lynx::AudioEngine e3 (false);
  11708. e3.setSong (song);
  11709. const auto opened = e3.getSong(); // (as the engine holds it: ids given)
  11710. e3.setDeactivated ({ 1 }, {}, true);
  11711. e3.capturePluginStates(); // (as a save in between does: the shape keeps the placeholders)
  11712. e3.setDeactivated ({}, { 1 }, true);
  11713. e3.undo();
  11714. e3.undo();
  11715. const auto back = render (e3);
  11716. float backDiff = back.size() == plain.size() ? 0.0f : 1.0f;
  11717. for (std::size_t i = 0; i < std::min (back.size(), plain.size()); ++i)
  11718. backDiff = std::max (backDiff, std::abs (back[i] - plain[i]));
  11719. if (trackstates190opResult == "OK"
  11720. && (backDiff > 1.0e-6f || e3.channelDeactivated (1) || e3.insertDeactivated (1) || e3.getSong().channels != opened.channels
  11721. || e3.getSong().mixer != opened.mixer))
  11722. trackstates190opResult = "ERROR reactivated render differs (peak " + juce::String (peak (back), 4) + " / " + juce::String (peak (plain), 4)
  11723. + ", diff " + juce::String (backDiff, 8) + ", channels " + juce::String (e3.getSong().channels == opened.channels ? "same" : "differ")
  11724. + ", mixer " + juce::String (e3.getSong().mixer == opened.mixer ? "same" : "differ") + ")";
  11725. // the .lynx round trip, an older project, the copy for 0.1.30, the .flp report
  11726. auto flagged = song;
  11727. lynx::trackstates::setHidden (flagged, { 3 }, true);
  11728. flagged.channels[1].deactivated = true;
  11729. flagged.mixer[2].deactivated = true;
  11730. juce::String why;
  11731. const auto json = lynx::ProjectFile::toJson (flagged);
  11732. const auto reread = lynx::ProjectFile::fromJson (json, why);
  11733. if (trackstates190opResult == "OK"
  11734. && (! reread || ! lynx::trackstates::isHidden (*reread, 3) || ! reread->channels[1].deactivated || ! reread->mixer[2].deactivated
  11735. || reread->channels[0].deactivated || reread->mixer[1].deactivated))
  11736. trackstates190opResult = "ERROR round trip " + why;
  11737. const auto plainJson = lynx::ProjectFile::toJson (song);
  11738. if (trackstates190opResult == "OK" && (plainJson.contains ("playlistTracksHidden") || plainJson.contains ("\"deactivated\"")))
  11739. trackstates190opResult = "ERROR flags written for a project without them";
  11740. const auto copy = lynx::olderlynx::forRelease (flagged, "0.1.30");
  11741. const auto said = [&copy] (const char* text) {
  11742. return std::any_of (copy.lost.begin(), copy.lost.end(), [text] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains (text); });
  11743. };
  11744. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::nullopt;
  11745. if (trackstates190opResult == "OK"
  11746. && (! copy.ok || copy.json.contains ("playlistTracksHidden") || copy.json.contains ("\"deactivated\"") || ! said ("hidden Playlist track(s) show again")
  11747. || ! said ("Deactivated channels and inserts") || ! old || ! old->channels[1].muted || ! old->mixer[2].muted || old->channels[0].muted))
  11748. trackstates190opResult = "ERROR copy for 0.1.30";
  11749. const auto copy28 = lynx::olderlynx::forRelease (flagged, "0.1.28");
  11750. if (trackstates190opResult == "OK" && (! copy28.ok || copy28.json.contains ("playlistTracksHidden") || copy28.json.contains ("\"deactivated\"")))
  11751. trackstates190opResult = "ERROR copy for 0.1.28";
  11752. lynx::flpexport::Report flpReport;
  11753. (void) lynx::flpexport::exportFlp (flagged, {}, flpReport);
  11754. const auto noted = [&flpReport] (const char* text) {
  11755. return std::any_of (flpReport.notes.begin(), flpReport.notes.end(), [text] (const std::string& n) { return n.find (text) != std::string::npos; });
  11756. };
  11757. if (trackstates190opResult == "OK" && (! noted ("Hidden tracks: 1 track(s) written visible") || ! noted ("Deactivated: Bass")))
  11758. trackstates190opResult = "ERROR flp export report";
  11759. // Capture automation: two controls moved while playing (Song mode, Pattern layout, lanes off): two automation
  11760. // clips with the last gesture's ticks, one undo step; a second capture takes nothing
  11761. lynx::AudioEngine cap (false);
  11762. cap.setSong (song);
  11763. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
  11764. const lynx::AutomationTarget pan { lynx::AutomationTargetKind::mixerPan, 2, 0, 0 };
  11765. const auto bar = (double) song.barTicks();
  11766. auto sample = [&cap] (const lynx::AutomationTarget& t, double ms, double tick, float v) {
  11767. lynx::captureauto::Entry x;
  11768. x.target = t;
  11769. x.ms = ms;
  11770. x.tick = tick;
  11771. x.value = v;
  11772. cap.addAutomationCaptureSample (x);
  11773. };
  11774. sample (volume, 1000.0, 0.0, 0.2f); // gesture 1 (dropped: a gap of three bars follows)
  11775. sample (volume, 1100.0, 0.25 * bar, 0.3f);
  11776. sample (volume, 3000.0, 3.25 * bar, 0.5f); // gesture 2: the one captured
  11777. sample (volume, 3100.0, 3.5 * bar, 0.7f);
  11778. sample (pan, 3200.0, 3.5 * bar, 0.1f);
  11779. sample (pan, 3300.0, 3.75 * bar, 0.9f);
  11780. const auto automations = cap.getSong().automations.size();
  11781. const auto undoBefore = cap.getHistoryPosition();
  11782. const auto r = cap.captureAutomation();
  11783. const auto& as = cap.getSong().automations;
  11784. const auto clipOf = [&cap] (int automation) {
  11785. for (const auto& c : cap.getSong().playlist)
  11786. if (c.kind == lynx::ClipKind::automation && c.automation == automation)
  11787. return c;
  11788. return lynx::Clip {};
  11789. };
  11790. if (trackstates190opResult == "OK" && (r.controls != 2 || as.size() != automations + 2 || cap.getHistoryPosition() != undoBefore + 1))
  11791. trackstates190opResult = "ERROR capture " + juce::String (r.controls) + " controls, " + juce::String ((int) (as.size() - automations)) + " automations";
  11792. else if (trackstates190opResult == "OK")
  11793. {
  11794. const auto a = (int) automations;
  11795. const auto c0 = clipOf (a), c1 = clipOf (a + 1);
  11796. if (! (as[(std::size_t) a].target == volume) || ! (as[(std::size_t) a + 1].target == pan) || c0.kind != lynx::ClipKind::automation
  11797. || 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)
  11798. || 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))
  11799. trackstates190opResult = "ERROR capture ticks: clip " + juce::String (c0.start) + " first point "
  11800. + juce::String (as[(std::size_t) a].points.empty() ? -1 : as[(std::size_t) a].points.front().tick);
  11801. }
  11802. if (trackstates190opResult == "OK" && cap.captureAutomation().controls != 0)
  11803. trackstates190opResult = "ERROR a second capture took the same moves again";
  11804. }
  11805. // round 190pa (research190oe P21 / P14, LYNX extras): automation write modes and range edits on chosen tracks. The
  11806. // .lynx round trip keeps the mode and the range and writes neither for a project without them; the copies for
  11807. // 0.1.30 / 0.1.28 drop them with a line each; Capture automation in a real engine with Latch holds the gesture's
  11808. // last value to where its play pass stopped and Write writes its first value from where the pass started (Read
  11809. // as before); a range Delete / Duplicate on two tracks changes only them and is one undo step, undone bit for bit.
  11810. juce::String automodes190paResult = "OK";
  11811. {
  11812. const auto bar = (std::int64_t) 4 * lynx::ppq;
  11813. lynx::Song song;
  11814. song.mixer = lynx::Song::defaultMixer (4);
  11815. song.bpm = 120.0;
  11816. song.mode = lynx::PlayMode::song;
  11817. song.patterns.resize (4);
  11818. for (int t = 0; t < 4; ++t)
  11819. {
  11820. lynx::Clip c;
  11821. c.pattern = t;
  11822. c.track = t;
  11823. c.start = 0;
  11824. c.length = 16 * bar;
  11825. song.playlist.push_back (c);
  11826. }
  11827. song.playlistTracks.resize (4);
  11828. juce::String why;
  11829. const auto plainJson = lynx::ProjectFile::toJson (song);
  11830. if (plainJson.contains ("trackRange") || plainJson.contains ("automationWriteMode"))
  11831. automodes190paResult = "ERROR written for a project without them";
  11832. auto flagged = song;
  11833. flagged.automationWriteMode = 2;
  11834. flagged.trackRange = lynx::rangeedit::fromCorners (4 * bar, 8 * bar, 1, 2);
  11835. const auto reread = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (flagged), why);
  11836. if (automodes190paResult == "OK" && (! reread || reread->automationWriteMode != 2 || ! (reread->trackRange == flagged.trackRange)))
  11837. automodes190paResult = "ERROR round trip " + why;
  11838. for (const char* release : { "0.1.30", "0.1.28" })
  11839. {
  11840. const auto copy = lynx::olderlynx::forRelease (flagged, release);
  11841. const auto said = [&copy] (const char* text) {
  11842. return std::any_of (copy.lost.begin(), copy.lost.end(), [text] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains (text); });
  11843. };
  11844. if (automodes190paResult == "OK"
  11845. && (! copy.ok || copy.json.contains ("trackRange") || copy.json.contains ("automationWriteMode") || ! said ("automation write mode")
  11846. || ! said ("range selected on some Playlist tracks")))
  11847. automodes190paResult = "ERROR copy for " + juce::String (release);
  11848. }
  11849. // Capture automation per mode: one gesture of insert 1's volume at bars 2..2.5 of a pass that played 1..4
  11850. for (int mode = 0; mode < 4 && automodes190paResult == "OK"; ++mode)
  11851. {
  11852. lynx::AudioEngine cap (false);
  11853. auto s = song;
  11854. s.automationWriteMode = mode;
  11855. cap.setSong (s);
  11856. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
  11857. auto& buffer = cap.automationCaptureForTests();
  11858. buffer.notePlaying ((double) bar);
  11859. for (int i = 0; i <= 4; ++i)
  11860. {
  11861. lynx::captureauto::Entry x;
  11862. x.target = volume;
  11863. x.ms = 1000.0 + 100.0 * i;
  11864. x.tick = (double) (2 * bar) + i * (double) bar / 8.0;
  11865. x.value = 0.2f + 0.15f * (float) i;
  11866. x.pass = buffer.currentPass();
  11867. buffer.notePlaying (x.tick);
  11868. cap.addAutomationCaptureSample (x);
  11869. }
  11870. buffer.notePlaying ((double) (4 * bar));
  11871. buffer.noteStopped();
  11872. if (cap.captureAutomation().controls != 1)
  11873. {
  11874. automodes190paResult = "ERROR capture in mode " + juce::String (mode);
  11875. break;
  11876. }
  11877. const auto& song2 = cap.getSong();
  11878. const auto& a = song2.automations.back();
  11879. const lynx::Clip* clip = nullptr;
  11880. for (const auto& c : song2.playlist)
  11881. if (c.kind == lynx::ClipKind::automation && c.automation == (int) song2.automations.size() - 1)
  11882. clip = &c;
  11883. if (clip == nullptr)
  11884. {
  11885. automodes190paResult = "ERROR no automation clip in mode " + juce::String (mode);
  11886. break;
  11887. }
  11888. const auto valueAt = [&] (double songTick) { return a.valueAt (songTick - (double) clip->start + (double) clip->offset); };
  11889. const auto lastPoint = a.points.empty() ? (std::int64_t) -1 : a.points.back().tick + clip->start - clip->offset;
  11890. const auto firstPoint = a.points.empty() ? (std::int64_t) -1 : a.points.front().tick + clip->start - clip->offset;
  11891. const auto holds = std::abs (valueAt (3.5 * (double) bar) - 0.8f) < 0.01f && lastPoint >= 4 * bar - 1;
  11892. const auto fromStart = firstPoint <= bar && std::abs (valueAt (1.5 * (double) bar) - 0.2f) < 0.01f;
  11893. const bool ok = mode == 0 || mode == 1 ? (! holds && ! fromStart && firstPoint == 2 * bar)
  11894. : mode == 2 ? (holds && ! fromStart && firstPoint == 2 * bar)
  11895. : (holds && fromStart);
  11896. if (! ok)
  11897. automodes190paResult = "ERROR capture curve in mode " + juce::String (mode) + " (first " + juce::String (firstPoint) + ", last "
  11898. + juce::String (lastPoint) + ")";
  11899. }
  11900. // range edits on tracks 2-3 (1, 2): one undo step each, the other tracks untouched, undo bit for bit
  11901. if (automodes190paResult == "OK")
  11902. {
  11903. lynx::AudioEngine e (false);
  11904. e.setSong (song);
  11905. const auto before = e.getSong().playlist;
  11906. e.editSong ([bar] (lynx::Song& s) { s.trackRange = lynx::rangeedit::fromCorners (4 * bar, 8 * bar, 1, 2); }, false);
  11907. const auto steps = e.getHistoryPosition();
  11908. e.editSong ([] (lynx::Song& s) { lynx::rangeedit::clearRange (s, s.trackRange); });
  11909. const auto& after = e.getSong().playlist;
  11910. const auto count = [] (const std::vector<lynx::Clip>& list, int track) {
  11911. return (int) std::count_if (list.begin(), list.end(), [track] (const lynx::Clip& c) { return c.track == track; });
  11912. };
  11913. if (e.getHistoryPosition() != steps + 1 || count (after, 0) != 1 || count (after, 3) != 1 || count (after, 1) != 2 || count (after, 2) != 2)
  11914. automodes190paResult = "ERROR range delete";
  11915. e.undo();
  11916. if (automodes190paResult == "OK" && ! (e.getSong().playlist == before))
  11917. automodes190paResult = "ERROR range delete undo";
  11918. e.editSong ([] (lynx::Song& s) { s.trackRange = lynx::rangeedit::duplicateRange (s, s.trackRange); });
  11919. if (automodes190paResult == "OK" && (e.getSong().trackRange.from != 8 * bar || count (e.getSong().playlist, 1) != 3 || count (e.getSong().playlist, 0) != 1))
  11920. automodes190paResult = "ERROR range duplicate";
  11921. e.undo();
  11922. if (automodes190paResult == "OK" && (! (e.getSong().playlist == before) || e.getSong().trackRange.from != 4 * bar))
  11923. automodes190paResult = "ERROR range duplicate undo";
  11924. }
  11925. }
  11926. // round 190nw (0.1.31): the tracker. Its settings are saved only when changed (an older project's file stays the
  11927. // 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
  11928. // real engine (one note, one Sampler channel, its sample written) and its notes render.
  11929. juce::String tracker190nwResult = "OK", tracker190obResult = "OK", tracker190omResult = "OK";
  11930. {
  11931. auto song = lynx::Song::makeDefault();
  11932. juce::String why;
  11933. const auto plainJson = lynx::ProjectFile::toJson (song);
  11934. if (plainJson.contains ("\"tracker\""))
  11935. tracker190nwResult = "ERROR settings written for a project that never changed them";
  11936. if (const auto reread = lynx::ProjectFile::fromJson (plainJson, why); tracker190nwResult == "OK" && (! reread || lynx::ProjectFile::toJson (*reread) != plainJson))
  11937. tracker190nwResult = "ERROR an older project changed";
  11938. for (int c = 0; c < 2; ++c)
  11939. song.channels.emplace_back().name = "T" + std::to_string (c);
  11940. lynx::uids::normalize (song);
  11941. song.tracker.rowsPerBeat = 8;
  11942. song.tracker.showPan = true;
  11943. song.tracker.groups.push_back ({ "Drums", { song.channels[song.channels.size() - 2].uid, song.channels.back().uid } });
  11944. const auto json = lynx::ProjectFile::toJson (song);
  11945. const auto back = lynx::ProjectFile::fromJson (json, why);
  11946. if (tracker190nwResult == "OK" && (! back || ! (back->tracker == song.tracker)))
  11947. tracker190nwResult = "ERROR round trip " + why;
  11948. for (const auto* release : { "0.1.30", "0.1.28" })
  11949. {
  11950. const auto copy = lynx::olderlynx::forRelease (song, release);
  11951. 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"); });
  11952. if (tracker190nwResult == "OK" && (! copy.ok || copy.json.contains ("\"tracker\"") || ! said))
  11953. tracker190nwResult = "ERROR copy for " + juce::String (release);
  11954. }
  11955. // a ProTracker module of one note, through the engine's import (its sample written beside it)
  11956. const auto folder = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-190nw-" + juce::String (juce::Time::currentTimeMillis()));
  11957. folder.createDirectory();
  11958. std::vector<std::uint8_t> mod (1084 + 1024 + 128, 0);
  11959. std::memcpy (mod.data(), "selftest", 8);
  11960. mod[20 + 22] = 0, mod[20 + 23] = 64, mod[20 + 25] = 64, mod[20 + 29] = 1; // sample 1: 128 bytes, volume 64, no loop
  11961. for (int k = 1; k < 31; ++k)
  11962. mod[(std::size_t) (20 + k * 30 + 29)] = 1;
  11963. mod[950] = 1, mod[951] = 127;
  11964. std::memcpy (mod.data() + 1080, "M.K.", 4);
  11965. mod[1084] = 0x01, mod[1085] = 0xAC, mod[1086] = 0x10; // row 0: C-2 (428), sample 1
  11966. for (int i = 0; i < 128; ++i)
  11967. mod[(std::size_t) (1084 + 1024 + i)] = (std::uint8_t) (std::int8_t) std::lround (90.0 * std::sin (i * 0.39));
  11968. const auto modFile = folder.getChildFile ("one note.mod");
  11969. modFile.replaceWithData (mod.data(), mod.size());
  11970. lynx::AudioEngine e (false);
  11971. juce::String error;
  11972. if (tracker190nwResult == "OK" && ! e.importFlpFile (modFile, error))
  11973. tracker190nwResult = "ERROR module import: " + error;
  11974. const auto& imported = e.getSong();
  11975. if (tracker190nwResult == "OK" && (imported.channels.size() != 1 || imported.patterns.empty() || imported.patterns.front().notes.size() != 1
  11976. || ! folder.getChildFile ("one note samples").getChildFile ("01-01.wav").existsAsFile()))
  11977. tracker190nwResult = "ERROR module import: " + juce::String ((int) imported.channels.size()) + " channel(s), "
  11978. + juce::String (imported.patterns.empty() ? 0 : (int) imported.patterns.front().notes.size()) + " note(s)";
  11979. if (tracker190nwResult == "OK")
  11980. {
  11981. const auto peak = e.renderOffline (1.0, 44100.0, nullptr);
  11982. if (peak < 0.01f)
  11983. tracker190nwResult = "ERROR the imported note is silent (peak " + juce::String (peak) + ")";
  11984. }
  11985. // round 190ob: the same note, its sample looping, with a volume set on row 1 (C10, no note): its channel's
  11986. // Volume multiplier automation comes in, is saved and read back the same, and the note still sounds
  11987. if (tracker190obResult == "OK")
  11988. {
  11989. mod[1084 + 16 + 2] = 0x0C, mod[1084 + 16 + 3] = 0x10;
  11990. mod[20 + 28] = 0, mod[20 + 29] = 64; // (the sample loops whole: the note still sounds on row 1)
  11991. const auto volumeFile = folder.getChildFile ("one note volume.mod");
  11992. volumeFile.replaceWithData (mod.data(), mod.size());
  11993. lynx::AudioEngine ve (false);
  11994. if (! ve.importFlpFile (volumeFile, error))
  11995. tracker190obResult = "ERROR module import: " + error;
  11996. else
  11997. {
  11998. const auto& vs = ve.getSong();
  11999. const auto automation = std::find_if (vs.automations.begin(), vs.automations.end(), [] (const lynx::Automation& a) {
  12000. return a.target.kind == lynx::AutomationTargetKind::channelAdjust && a.target.param == lynx::leveladjust::volume && a.target.index == 0;
  12001. });
  12002. // (round 190om: a pattern played once changes its volume as pattern events of the multiplier)
  12003. const auto events = std::any_of (vs.patterns.begin(), vs.patterns.end(), [] (const lynx::Pattern& p) {
  12004. return std::any_of (p.events.begin(), p.events.end(), [] (const lynx::PatternEvents& l) {
  12005. return l.target.kind == lynx::AutomationTargetKind::channelAdjust && l.target.param == lynx::leveladjust::volume && l.target.index == 0
  12006. && l.events.size() >= 2;
  12007. });
  12008. });
  12009. if ((automation == vs.automations.end() || automation->points.size() < 2) && ! events)
  12010. tracker190obResult = "ERROR no volume automation";
  12011. else if (const auto reread = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (vs), why); ! reread || reread->automations != vs.automations
  12012. || reread->patterns != vs.patterns)
  12013. tracker190obResult = "ERROR the automation changed on the .lynx round trip " + why;
  12014. else if (ve.renderOffline (1.0, 44100.0, nullptr) < 0.001f)
  12015. tracker190obResult = "ERROR the note is silent";
  12016. }
  12017. }
  12018. // round 190om: a pitch slide (102 on row 1) on that note: its pitch curve and the volume set's pattern events
  12019. // come in, are saved and read back the same, and it sounds; SimSynth's velocity law and its copy for 0.1.30
  12020. {
  12021. mod[1084 + 16 + 2] = 0x01, mod[1084 + 16 + 3] = 0x02;
  12022. mod[1084 + 32 + 2] = 0x0C, mod[1084 + 32 + 3] = 0x10;
  12023. const auto slideFile = folder.getChildFile ("one note slide.mod");
  12024. slideFile.replaceWithData (mod.data(), mod.size());
  12025. lynx::AudioEngine se (false);
  12026. if (! se.importFlpFile (slideFile, error))
  12027. tracker190omResult = "ERROR module import: " + error;
  12028. else
  12029. {
  12030. const auto& ss = se.getSong();
  12031. const auto curved = std::any_of (ss.patterns.begin(), ss.patterns.end(), [] (const lynx::Pattern& p) {
  12032. return std::any_of (p.notes.begin(), p.notes.end(), [] (const lynx::Note& n) { return n.curves.has() && n.curves->moves (lynx::NoteCurveLane::pitch); });
  12033. });
  12034. const auto events = std::any_of (ss.patterns.begin(), ss.patterns.end(), [] (const lynx::Pattern& p) { return ! p.events.empty(); });
  12035. if (! curved || ! events)
  12036. tracker190omResult = juce::String ("ERROR import: ") + (curved ? "" : "no pitch curve ") + (events ? "" : "no pattern events");
  12037. else if (const auto reread = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (ss), why); ! reread || reread->patterns != ss.patterns)
  12038. tracker190omResult = "ERROR the curves or events changed on the .lynx round trip " + why;
  12039. else if (se.renderOffline (1.0, 44100.0, nullptr) < 0.001f)
  12040. tracker190omResult = "ERROR the note is silent";
  12041. }
  12042. }
  12043. if (tracker190omResult == "OK")
  12044. {
  12045. auto song = lynx::Song::makeDefault();
  12046. auto& sim = song.channels.emplace_back();
  12047. sim.name = "Sim";
  12048. sim.instrument = lynx::InstrumentKind::simsynth;
  12049. sim.pluginState = lynx::simsynth::defaultState();
  12050. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  12051. 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"); });
  12052. auto older = song;
  12053. older.channels.back().engineRev = 1;
  12054. const auto olderCopy = lynx::olderlynx::forRelease (older, "0.1.30");
  12055. 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"); });
  12056. juce::String why2;
  12057. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why2);
  12058. if (sim.engineRev < 2 || ! copy.ok || ! said || olderSaid || ! back || back->channels.back().engineRev != sim.engineRev) // (≥ 2: round 190pr's 3 too)
  12059. tracker190omResult = "ERROR SimSynth revision: copy " + juce::String (said ? "said" : "silent") + (olderSaid ? ", old one said" : "");
  12060. }
  12061. folder.deleteRecursively();
  12062. }
  12063. // round 190oo (design review 2, PAT-7; core/RackAutomation.h): the automation clips' Channel rack rows. A .lynx
  12064. // round trip keeps each clip's place; a clip without one (every clip of an older file) writes nothing and reads
  12065. // back after the channels; the copy for 0.1.30 drops the key without a loss line.
  12066. juce::String rackauto190ooResult = "OK";
  12067. {
  12068. auto song = lynx::Song::makeDefault();
  12069. for (int c = 0; c < 3; ++c)
  12070. song.channels.emplace_back().name = "R" + std::to_string (c);
  12071. lynx::Automation placed, appended;
  12072. placed.name = "placed";
  12073. placed.points = { { 0, 0.2f, 0.0f }, { lynx::ppq, 0.8f, 0.0f } };
  12074. placed.rackSlot = 1;
  12075. appended = placed;
  12076. appended.name = "appended";
  12077. appended.rackSlot = -1;
  12078. song.automations.push_back (placed);
  12079. song.automations.push_back (appended);
  12080. juce::String why;
  12081. const auto json = lynx::ProjectFile::toJson (song);
  12082. const auto back = lynx::ProjectFile::fromJson (json, why);
  12083. if (! back || back->automations.size() != 2 || back->automations[0].rackSlot != 1 || back->automations[1].rackSlot != -1
  12084. || lynx::rackauto::order (*back) != lynx::rackauto::order (song))
  12085. rackauto190ooResult = "ERROR round trip " + why;
  12086. const auto plain = lynx::Song::makeDefault();
  12087. const auto plainJson = lynx::ProjectFile::toJson (plain);
  12088. if (rackauto190ooResult == "OK" && plainJson.contains ("rackSlot"))
  12089. rackauto190ooResult = "ERROR rackSlot written for a project without placed clips";
  12090. auto older = song;
  12091. older.automations[0].rackSlot = -1; // (as a file saved before round 190oo)
  12092. if (const auto reread = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (older), why); rackauto190ooResult == "OK"
  12093. && (! reread || reread->automations.size() != 2 || reread->automations[0].rackSlot != -1 || lynx::ProjectFile::toJson (older).contains ("rackSlot")))
  12094. rackauto190ooResult = "ERROR an older project's clips";
  12095. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  12096. if (rackauto190ooResult == "OK" && (! copy.ok || copy.json.contains ("rackSlot")))
  12097. rackauto190ooResult = "ERROR copy for 0.1.30";
  12098. }
  12099. // round 190ow (PAT-7 rest, details DE-123; core/RackAutomation.h): what the automation clip rows play. A .lynx round
  12100. // trip keeps the steps / notes on the rows (Pattern::autoNotes), the clips' MIN / MAX and their mute light; a
  12101. // project without them writes none of the keys; the copy for 0.1.30 drops the steps (a loss line: 0.1.30 starts
  12102. // no clip from a pattern), writes the MIN / MAX into the points (the same values play there) and leaves a muted
  12103. // clip without a target (it stays silent), with a loss line each.
  12104. juce::String rackauto190owResult = "OK";
  12105. {
  12106. auto song = lynx::Song::makeDefault();
  12107. lynx::Automation duck;
  12108. duck.name = "duck";
  12109. duck.points = { { 0, 0.0f, 0.0f }, { lynx::ppq, 1.0f, 0.0f } };
  12110. duck.target = { lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 };
  12111. duck.rangeMin = 0.25f;
  12112. duck.rangeMax = 0.75f;
  12113. auto quiet = duck;
  12114. quiet.name = "quiet";
  12115. quiet.rangeMin = 0.0f;
  12116. quiet.rangeMax = 1.0f;
  12117. quiet.muted = true;
  12118. song.automations = { duck, quiet };
  12119. song.patterns[0].toggleAutoStep (0, 0);
  12120. song.patterns[0].toggleAutoStep (0, 4);
  12121. lynx::Note held;
  12122. held.start = 8 * lynx::ticksPerStep;
  12123. held.length = 0; // (FL's step of no length)
  12124. held.channel = 1;
  12125. held.key = 64;
  12126. song.patterns[0].autoNotes.push_back (held);
  12127. song.patterns[0].sortNotes();
  12128. juce::String why;
  12129. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  12130. if (! back || back->patterns.empty() || back->patterns[0].autoNotes != song.patterns[0].autoNotes || back->automations.size() != 2
  12131. || back->automations[0].rangeMin != 0.25f || back->automations[0].rangeMax != 0.75f || back->automations[1].muted != true
  12132. || back->automations[0].muted || ! back->patterns[0].hasAutoStep (0, 4))
  12133. rackauto190owResult = "ERROR round trip " + why;
  12134. const auto plainJson = lynx::ProjectFile::toJson (lynx::Song::makeDefault());
  12135. if (rackauto190owResult == "OK" && (plainJson.contains ("autoNotes") || plainJson.contains ("\"range\"")))
  12136. rackauto190owResult = "ERROR keys written for a project without them";
  12137. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  12138. int lossLines = 0;
  12139. for (const auto& l : copy.lost)
  12140. lossLines += juce::String (l.text).contains ("automation clip") || juce::String (l.text).contains ("Muted automation") ? 1 : 0;
  12141. if (rackauto190owResult == "OK" && (! copy.ok || copy.json.contains ("autoNotes") || copy.json.contains ("\"range\"") || lossLines < 2))
  12142. rackauto190owResult = "ERROR copy for 0.1.30 (" + juce::String (lossLines) + " loss lines)";
  12143. if (rackauto190owResult == "OK")
  12144. if (const auto old = lynx::ProjectFile::fromJson (copy.json, why); ! old || old->automations.size() != 2
  12145. || 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
  12146. || old->automations[1].target.kind != lynx::AutomationTargetKind::none)
  12147. rackauto190owResult = "ERROR the copy's values";
  12148. const auto copy28 = lynx::olderlynx::forRelease (song, "0.1.28");
  12149. if (rackauto190owResult == "OK" && (! copy28.ok || copy28.json.contains ("autoNotes")))
  12150. rackauto190owResult = "ERROR copy for 0.1.28";
  12151. }
  12152. const auto motionOverlayResult = lynx::ui::MotionOverlay::selfTest(); // (round 190ip)
  12153. // round 190bm (0.1.25 showed the Mixer and the Playlist black): their cached pictures shown on native and
  12154. // software targets against straight paints (ui/PictureCheck.h; --picturetest runs more sizes and scales)
  12155. juce::String picturesResult = "OK";
  12156. {
  12157. lynx::AudioEngine pictureEngine (false);
  12158. auto pictureFailures = 0;
  12159. juce::String lines;
  12160. {
  12161. lynx::PlaylistComponent playlist (pictureEngine);
  12162. playlist.setBounds (0, 0, 1200, 700);
  12163. playlist.setVisible (true);
  12164. lines << lynx::ui::picturecheck::run (playlist, "Playlist 1200 x 700", { 1.0f, 1.5f }, pictureFailures, {});
  12165. }
  12166. {
  12167. lynx::MixerComponent mixer (pictureEngine);
  12168. mixer.setBounds (0, 0, 1200, 500);
  12169. mixer.setVisible (true);
  12170. lines << lynx::ui::picturecheck::run (mixer, "Mixer 1200 x 500", { 1.0f, 1.5f }, pictureFailures, {});
  12171. }
  12172. if (pictureFailures > 0 || ! lines.contains (": ok"))
  12173. picturesResult = "ERROR " + lines.trim().replace ("\n", "; ");
  12174. }
  12175. // round 190ci (the 0.1.26 release candidate ended when an FPC channel was added): every built-in generator and
  12176. // effect, its editor built as the Channel Rack / mixer opens it and painted once. The report file names the
  12177. // plugin being opened, so a run that dies there says which one.
  12178. const auto editorsResult = lynx::pluginthumbs::checkEditors ([&reportPath] (const juce::String& key) {
  12179. if (reportPath.isNotEmpty())
  12180. juce::File (reportPath).replaceWithText ("(opening the editor of " + key + ")\n");
  12181. });
  12182. // round 190ci: a fault leaves a crash file, also on a stack Windows cannot walk (that FPC fault left none)
  12183. const auto faultResult = faultReportSelfTest();
  12184. const auto stemsResult = stemsSinglePassSelfTest(); // round 190gj
  12185. const auto exportFormatsResult = lynx::shortexport::formatsCheck(); // AIFF and M4A (owner decision D5)
  12186. const auto hotfix190qpWfResult = hotfix190qpWfCheck(); // round 190qp (0.1.31.1): track clips' notes, Export... with folders
  12187. const auto sweep190reResult = sweep190reSelfTest(); // round 190re: the 0.1.32 regression sweep's fast part (src/Sweep190re.inc)
  12188. const auto renderAgainResult = lynx::renderagain::check(); // round 190ou: offline renders made again
  12189. const auto determinismResult = lynx::determinism190po::check(); // round 190po: one render on any threads (Windows' x87)
  12190. juce::LookAndFeel::setDefaultLookAndFeel (&lookBefore);
  12191. const auto ok = editorsResult.startsWith ("OK") && ! faultResult.startsWith ("ERROR") && stemsResult == "OK" && exportFormatsResult.startsWith ("OK")
  12192. && 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
  12193. && sessionResult == "OK" && liveResult.startsWith ("OK")
  12194. && 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"
  12195. && 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"
  12196. && midigen190fmResult == "OK" && clipenv190giResult == "OK" && beatslaw190gxResult == "OK" && warplaw190ikResult == "OK" && editorScale190heResult == "OK" && sfModBase190heResult == "OK" && trackauto190gzResult == "OK" && community190hqResult == "OK" && rollup030Result == "OK" && rollup031Result == "OK" && rollup031s2Result == "OK"
  12197. && keys190nuResult == "OK" && rollup031s3Result == "OK"
  12198. && helix4khs190ocResult == "OK" && rollup031s4Result == "OK" && sections190olResult == "OK" && rollup031s5Result == "OK" && simpleDuck190otResult == "OK" && tracks190peResult == "OK" && issue258Result == "OK" && issues190qrResult == "OK" && backlog190rcResult == "OK" && community190riResult == "OK" && flParity190tcResult == "OK" && q1a190rwResult == "OK" && iox190rmResult == "OK" && issues190rtResult == "OK" && perf190rnResult == "OK" && perf190sbResult == "OK" && cachecheck190tgResult == "OK" && undo190spResult == "OK" && menuwindows190skResult == "OK" && issues330skResult == "OK" && audioedit190stResult == "OK" && drumsynth190syResult == "OK" && smallbugs190srResult == "OK" && quickwins190srResult == "OK" && batch292_190swResult == "OK" && round190teResult == "OK" && yannik190sqResult == "OK" && rea190taResult == "OK" && round190tiResult == "OK" && round190tkResult == "OK" && round190tmResult == "OK" && round190toResult == "OK" && batch334svResult == "OK" && details190tdResult == "OK" && qa190rbResult == "OK" && bugs190rvResult == "OK" && q6190saResult == "OK" && issue325Result == "OK" && keysheet190sjResult == "OK" && details190tbResult == "OK" && notes190tjResult == "OK" && children190thResult == "OK" && stab190rpResult == "OK" && repeats190pmResult == "OK" && mixerqol190qhResult == "OK" && autolive190qpResult == "OK" && issue282Result == "OK" && feel190qeResult == "OK" && toolbar190qgResult == "OK" && extras190qkResult == "OK" && extras190roResult == "OK" && playlistview190soResult == "OK" && custom190ssResult == "OK" && discord190quResult == "OK" && trialmark190qtResult == "OK" && optionsux190qxResult == "OK" && chordlane190pfResult == "OK" && nofl190rhResult == "OK" && downgrade0132Result == "OK" && autolinks190ovResult == "OK"
  12199. && trackstates190opResult == "OK" && rollup031s6Result == "OK" // (round 190op's item, reported but not counted in its branch: rollup 0.1.31 step 6)
  12200. && rollup031s7Result == "OK" && rollup031s8Result == "OK" && rollup032Result == "OK" && headerGearResult == "OK" && perTab259Result == "OK" && slots260Result == "OK" && hotfixPlacesResult == "OK" && startPageScrollResult.startsWith ("OK") // (round 190qf: slots260) (rollup 0.1.31 step 7, round 190pw; and the three rounds' items its branches reported but did not count:)
  12201. && slides190piResult == "OK" && automodes190paResult == "OK" && heldSteps190ozResult == "OK"
  12202. && issues190qoResult == "OK" // (round 190qo)
  12203. && flparity190prResult == "OK"
  12204. && hotfix190qpWfResult == "OK" // (round 190qp)
  12205. && sweep190reResult == "OK" // (round 190re)
  12206. && renderAgainResult.startsWith ("OK") && determinismResult.startsWith ("OK")
  12207. && remoteHistoryResult.startsWith ("OK") && hostedStateLockResult.startsWith ("OK")
  12208. && hostedStateContentionResult.startsWith ("OK") && modulators190oxResult == "OK"
  12209. && generatorSmartResult.startsWith ("OK") && jsfxResult.startsWith ("OK") && jsfxFpResult == "OK"
  12210. && danceWindowResult == "OK" && clickActivationResult == "OK" && motionOverlayResult.startsWith ("OK")
  12211. && editorHolesResult.startsWith ("OK") && picker190qiResult == "OK";
  12212. juce::String report;
  12213. report << "connections=" << offline.getNumGraphConnections() << "\n"
  12214. << "peak=" << peak << "\n"
  12215. << "stems_single_pass=" << stemsResult << "\n"
  12216. << "export_formats=" << exportFormatsResult << "\n"
  12217. << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
  12218. << "playlist_track_modes_roundtrip=" << (trackModes122Ok ? "OK" : "ERROR") << "\n"
  12219. << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
  12220. << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
  12221. << "plugin_host_keys_option=" << (hostKeysOk ? "OK" : "ERROR") << "\n"
  12222. << "plugin_levels_new_project=" << (pluginLevelsOk ? "OK" : "ERROR") << "\n"
  12223. << "flp168j_fields=" << (flp168jOk ? "OK" : "ERROR") << "\n"
  12224. << "clip_fades_180d=" << (clipFades180dOk ? "OK" : "ERROR") << "\n"
  12225. << "pattern_blocks=" << (blocksOk ? "OK" : "ERROR") << "\n"
  12226. << "pattern_clip_takeover=" << (takeoverOk ? "OK" : "ERROR") << "\n"
  12227. << "comp_crossfades=" << (compOk ? "OK" : "ERROR") << "\n"
  12228. << "channel_polyphony=" << (polyOk ? "OK" : "ERROR") << "\n"
  12229. << "track_latency=" << (latencyOk ? "OK" : "ERROR") << "\n"
  12230. << "pre_fader_sends=" << (preSendOk ? "OK" : "ERROR") << "\n"
  12231. << "low_latency_recording=" << (lowLatencyOk ? "OK" : "ERROR") << "\n"
  12232. << "preview_in_time=" << (previewInTimeOk ? "OK" : "ERROR") << " (2 s loop prepared in " << juce::String (previewPrepareMs, 1) << " ms)\n"
  12233. << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
  12234. << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
  12235. << "racks=" << rackResult << "\n"
  12236. << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
  12237. << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
  12238. << "mixer_basics=" << mixerBasics << "\n"
  12239. << "remote_history=" << remoteHistoryResult << "\n"
  12240. << "hosted_state_lock=" << hostedStateLockResult << "\n"
  12241. << "hosted_state_contention=" << hostedStateContentionResult << "\n"
  12242. << "modulators190ox=" << modulators190oxResult << "\n"
  12243. << "generator_smart_disable=" << generatorSmartResult << "\n"
  12244. << "fonts=" << fontsResult << "\n"
  12245. << "paint_caches=" << paintCachesResult << "\n"
  12246. << "motion_overlay=" << motionOverlayResult << "\n"
  12247. << "cached_pictures=" << picturesResult << "\n"
  12248. << "plugin_editors=" << editorsResult << "\n"
  12249. << "fault_report=" << faultResult << "\n"
  12250. << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
  12251. << "cancel_recording=" << (cancelRecordOk ? "OK" : "ERROR") << "\n"
  12252. << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
  12253. << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
  12254. << "projectSave=" << (projectSaveOk ? "OK" : "ERROR") << "\n"
  12255. << "online_session=" << sessionResult << "\n"
  12256. << "live_session=" << liveResult << "\n"
  12257. << "wavpack=" << wavpack << "\n"
  12258. << "effects=" << (effectsOk ? "OK" : "NONFINITE") << "\n"
  12259. << "effect_params_saved=" << effectParamsResult << "\n"
  12260. << "driver_panel=" << driverPanel << "\n"
  12261. << "device_change=" << deviceChange << "\n"
  12262. << "export_parity=" << exportParity << "\n"
  12263. << "export_live=" << exportLive << "\n"
  12264. << "midi_hotplug=" << midiHotplug << "\n"
  12265. << "midi_out_ports=" << midiOutPorts.replace ("\n", " | ").trimCharactersAtEnd (" |") << "\n"
  12266. << "plugin_art=" << artResult << "\n"
  12267. << "plugin_sidechain=" << sidechainResult << "\n"
  12268. << "jsfx190pj=" << jsfxResult << "\n"
  12269. << "jsfx_fp_environment=" << jsfxFpResult << "\n"
  12270. << "picker190qi=" << picker190qiResult << "\n"
  12271. << "versions_panel=" << versionsResult << "\n"
  12272. << "plugins_off=" << pluginsOffResult << "\n"
  12273. << "missing_files_rows=" << missingFilesResult << "\n"
  12274. << "dance_window=" << danceWindowResult << "\n"
  12275. << "dance_window_detail=" << danceWindowDetail << "\n"
  12276. << "click_activation=" << clickActivationResult << "\n"
  12277. << "editor_holes=" << editorHolesResult << "\n"
  12278. << "lanes_saved=" << lanesResult << "\n"
  12279. << "arrange190cg_saved=" << arrange190cgResult << "\n"
  12280. << "livescr190dr=" << livescr190drResult << "\n"
  12281. << "livewf190ef=" << livewf190efResult << "\n"
  12282. << "livewf190em=" << livewf190emResult << "\n"
  12283. << "trackclips190ne=" << trackclips190neResult << "\n"
  12284. << "trackstates190op=" << trackstates190opResult << "\n"
  12285. << "automodes190pa=" << automodes190paResult << "\n"
  12286. << "tracker190nw=" << tracker190nwResult << "\n"
  12287. << "tracker190ob=" << tracker190obResult << "\n"
  12288. << "rackauto190oo=" << rackauto190ooResult << "\n"
  12289. << "tracker190om=" << tracker190omResult << "\n"
  12290. << "rackauto190ow=" << rackauto190owResult << "\n"
  12291. << "midigen190fm_saved=" << midigen190fmResult << "\n"
  12292. << "trackauto190gz_saved=" << trackauto190gzResult << "\n"
  12293. << "clipenv190gi_saved=" << clipenv190giResult << "\n"
  12294. << "beatslaw190gx_saved=" << beatslaw190gxResult << "\n"
  12295. << "warplaw190ik_saved=" << warplaw190ikResult << "\n"
  12296. << "editor_scale190he_saved=" << editorScale190heResult << "\n"
  12297. << "sf_mod_base190he=" << sfModBase190heResult << "\n"
  12298. << "community190hq_saved=" << community190hqResult << "\n"
  12299. << "rollup030_copy_for_0128=" << rollup030Result << "\n"
  12300. << "rollup031_copy_for_0130=" << rollup031Result << "\n"
  12301. << "rollup031s2_copy_for_0130=" << rollup031s2Result << "\n"
  12302. << "keys190nu_key_markers=" << keys190nuResult << "\n"
  12303. << "rollup031s3_copy_for_0130=" << rollup031s3Result << "\n"
  12304. << "helix4_khs190oc_copy_for_0130=" << helix4khs190ocResult << "\n"
  12305. << "rollup031s4_copy_for_0130=" << rollup031s4Result << "\n"
  12306. << "rollup031s5_copy_for_0130=" << rollup031s5Result << "\n"
  12307. << "rollup031s6_copy_for_0130=" << rollup031s6Result << "\n"
  12308. << "rollup031s7_copy_for_0130=" << rollup031s7Result << "\n"
  12309. << "rollup031s8_copy_for_0130=" << rollup031s8Result << "\n"
  12310. << "rollup032_copy_for_0131=" << rollup032Result << "\n"
  12311. << "headergear248=" << headerGearResult << "\n"
  12312. << "pertab259=" << perTab259Result << "\n"
  12313. << "slots260=" << slots260Result << "\n"
  12314. << "startpagescroll190ra=" << startPageScrollResult << "\n"
  12315. << "simpleduck190ot=" << simpleDuck190otResult << "\n"
  12316. << "tracks190pe=" << tracks190peResult << "\n"
  12317. << "feel190qe=" << feel190qeResult << "\n"
  12318. << "issue258=" << issue258Result << "\n"
  12319. << "autolive190qp=" << autolive190qpResult << "\n"
  12320. << "issue282=" << issue282Result << (issue282Result == "OK" ? juce::String() : " | " + issue282Log.replace ("\n", "; ")) << "\n"
  12321. << "issues190qr=" << issues190qrResult << "\n"
  12322. << "backlog190rc=" << backlog190rcResult << "\n"
  12323. << "community190ri=" << community190riResult << "\n"
  12324. << "flparity190tc=" << flParity190tcResult << "\n"
  12325. << "q1a190rw=" << q1a190rwResult << "\n"
  12326. << "iox190rm=" << iox190rmResult << "\n"
  12327. << "issues190rt=" << issues190rtResult << "\n" << issues190rtLog
  12328. << "perf190rn=" << perf190rnResult << "\n"
  12329. << "perf190sb=" << perf190sbResult << (perf190sbResult == "OK" ? juce::String() : " | " + perf190sbLog.replace ("\n", "; ")) << "\n"
  12330. << "cachecheck190tg=" << cachecheck190tgResult << (cachecheck190tgResult == "OK" ? juce::String() : " | " + cachecheck190tgLog.replace ("\n", "; ")) << "\n"
  12331. << "undo190sp=" << undo190spResult << (undo190spResult == "OK" ? juce::String() : " | " + undo190spLog.replace ("\n", "; ")) << "\n"
  12332. << "menuwindows190sk=" << menuwindows190skResult << (menuwindows190skResult == "OK" ? juce::String() : " | " + menuwindows190skLog.replace ("\n", "; ")) << "\n"
  12333. << "issues330sk=" << issues330skResult << (issues330skResult == "OK" ? juce::String() : " | " + issues330skLog.replace ("\n", "; ")) << "\n"
  12334. << "yannik190sq=" << yannik190sqResult << (yannik190sqResult == "OK" ? juce::String() : " | " + yannik190sqLog.replace ("\n", "; ")) << "\n"
  12335. << "batch334sv=" << batch334svResult << (batch334svResult == "OK" ? juce::String() : " | " + batch334svLog.replace ("\n", "; ")) << "\n"
  12336. << "rea190ta=" << rea190taResult << (rea190taResult == "OK" ? juce::String() : " | " + rea190taLog.replace ("\n", "; ")) << "\n"
  12337. << "details190td=" << details190tdResult << (details190tdResult == "OK" ? juce::String() : " | " + details190tdLog.replace ("\n", "; ")) << "\n"
  12338. << "round190ti=" << round190tiResult << (round190tiResult == "OK" ? juce::String() : " | " + round190tiLog.replace ("\n", "; ")) << "\n"
  12339. << "round190tk=" << round190tkResult << (round190tkResult == "OK" ? juce::String() : " | " + round190tkLog.replace ("\n", "; ")) << "\n"
  12340. << "round190tm=" << round190tmResult << (round190tmResult == "OK" ? juce::String() : " | " + round190tmLog.replace ("\n", "; ")) << "\n"
  12341. << "round190to=" << round190toResult << (round190toResult == "OK" ? juce::String() : " | " + round190toLog.replace ("\n", "; ")) << "\n"
  12342. << "smallbugs190sr=" << smallbugs190srResult << (smallbugs190srResult == "OK" ? juce::String() : " | " + smallbugs190srLog.replace ("\n", "; ")) << "\n"
  12343. << "quickwins190sr=" << quickwins190srResult << (quickwins190srResult == "OK" ? juce::String() : " | " + quickwins190srLog.replace ("\n", "; ")) << "\n"
  12344. << "audioedit190st=" << audioedit190stResult << (audioedit190stResult == "OK" ? juce::String() : " | " + audioedit190stLog.replace ("\n", "; ")) << "\n"
  12345. << "drumsynth190sy=" << drumsynth190syResult << (drumsynth190syResult == "OK" ? juce::String() : " | " + drumsynth190syLog.replace ("\n", "; ")) << "\n"
  12346. << "batch292_190sw=" << batch292_190swResult << (batch292_190swResult == "OK" ? juce::String() : " | " + batch292_190swLog.replace ("\n", "; ")) << "\n"
  12347. << "round190te=" << round190teResult << (round190teResult == "OK" ? juce::String() : " | " + round190teLog.replace ("\n", "; ")) << "\n"
  12348. << "qa190rb=" << qa190rbResult << "\n"
  12349. << "bugs190rv=" << bugs190rvResult << (bugs190rvResult == "OK" ? juce::String() : " | " + bugs190rvLog.replace ("\n", "; ")) << "\n"
  12350. << "q6190sa=" << q6190saResult << (q6190saResult == "OK" ? juce::String() : " | " + q6190saLog.replace ("\n", "; ")) << "\n"
  12351. << "issue325=" << issue325Result << (issue325Result == "OK" ? juce::String() : " | " + issue325Log.replace ("\n", "; ")) << "\n"
  12352. << "keysheet190sj=" << keysheet190sjResult << (keysheet190sjResult == "OK" ? juce::String() : " | " + keysheet190sjLog.replace ("\n", "; ")) << "\n"
  12353. << "details190tb=" << details190tbResult << (details190tbResult == "OK" ? juce::String() : " | " + details190tbLog.replace ("\n", "; ")) << "\n"
  12354. << "children190th=" << children190thResult << (children190thResult == "OK" ? juce::String() : " | " + children190thLog.replace ("\n", "; ")) << "\n"
  12355. << "notes190tj=" << notes190tjResult << (notes190tjResult == "OK" ? juce::String() : " | " + notes190tjLog.replace ("\n", "; ")) << "\n"
  12356. << "stab190rp=" << stab190rpResult << (stab190rpResult == "OK" ? juce::String() : " | " + stab190rpLog.replace ("\n", "; ")) << "\n"
  12357. << "repeats190pm=" << repeats190pmResult << "\n"
  12358. << "mixerqol190qh=" << mixerqol190qhResult << "\n"
  12359. << "hotfixplaces190qp=" << hotfixPlacesResult << "\n"
  12360. << "toolbar_overflow_190qg=" << toolbar190qgResult << "\n"
  12361. << "extras190qk=" << extras190qkResult << "\n"
  12362. << "extras190ro=" << extras190roResult << "\n"
  12363. << "playlistview190so=" << playlistview190soResult << "\n"
  12364. << "custom190ss=" << custom190ssResult << "\n"
  12365. << "discord190qu=" << discord190quResult << "\n"
  12366. << "nofl190rh=" << nofl190rhResult << " | " << nofl190rhLog.replace ("\n", "; ") << "\n"
  12367. << "downgrade0132_190tf=" << downgrade0132Result << (downgrade0132Result == "OK" ? juce::String() : " | " + downgrade0132Log.replace ("\n", "; ")) << "\n"
  12368. << "trialmark190qt=" << trialmark190qtResult << (trialmark190qtResult == "OK" ? juce::String() : " | " + trialmark190qtLog.replace ("\n", "; ")) << "\n"
  12369. << "optionsux190qx=" << optionsux190qxResult << "\n"
  12370. << "autolinks190ov=" << autolinks190ovResult << "\n"
  12371. << "sections190ol=" << sections190olResult << "\n"
  12372. << "heldsteps190oz=" << heldSteps190ozResult << "\n"
  12373. << "slides190pi=" << slides190piResult << "\n"
  12374. << "issues190qo=" << issues190qoResult << "\n"
  12375. << "flparity190pr=" << flparity190prResult << "\n"
  12376. << "chordlane190pf=" << chordlane190pfResult << "\n"
  12377. << "renderagain190ou=" << renderAgainResult << "\n"
  12378. << "determinism190po=" << determinismResult << "\n"
  12379. << "hotfix190qp_wf=" << hotfix190qpWfResult << "\n"
  12380. << "sweep190re=" << sweep190reResult << "\n"
  12381. << "metronome=" << metronomeResult << " (FL sounds " << metronomeFlSounds << "/" << lynx::metronome::soundCount
  12382. << ", downbeat peak " << juce::String (metronomeMaster, 4) << ")\n";
  12383. // issue #138 (round 190c): a short note at the very start of the Playlist against the same note at bar 2, through
  12384. // the Export window's path (its own thread while the message loop runs: the report is finished from there)
  12385. if (reportPath.isNotEmpty())
  12386. juce::File (reportPath).replaceWithText (report + "(short_export running)\n");
  12387. lynx::shortexport::run (false, 1, {}, {}, [this, report, ok, reportPath] (juce::String shortExport) {
  12388. const auto all = ok && shortExport.startsWith ("OK");
  12389. const auto text = report + "short_export=" + shortExport + "\nresult=" + (all ? "OK" : "FAILED") + "\n";
  12390. if (reportPath.isNotEmpty())
  12391. juce::File (reportPath).replaceWithText (text);
  12392. setApplicationReturnValue (all ? 0 : 1);
  12393. if (selfTestTemp != juce::File())
  12394. selfTestTemp.deleteRecursively(); // (round 190mo: this run's own temp folder)
  12395. quit();
  12396. });
  12397. }
  12398. // Every built-in effect in its native editor: random / extreme parameters, mouse drags over the editor, the editor
  12399. // painted, audio rendered at 44.1 / 48 / 96 kHz. Returns false when an effect output NaN / inf (muted by the
  12400. // renderer's guard). The report lists each effect. Used by --fxfuzz and (a short run) by --selftest.
  12401. bool runEffectFuzz (int rounds, const juce::String& reportPath, bool drags = false)
  12402. {
  12403. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12404. lynx::setNativeEditorDemo (true);
  12405. juce::String report;
  12406. auto allFinite = true;
  12407. {
  12408. lynx::AudioEngine offline (false);
  12409. juce::Random random (111);
  12410. const auto value = [&] { const auto r = random.nextInt (6); return r == 0 ? 0.0f : r == 1 ? 1.0f : random.nextFloat(); };
  12411. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  12412. {
  12413. const auto kind = (lynx::EffectKind) k;
  12414. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher) // (the Patcher's editor is a graph window)
  12415. continue;
  12416. const auto before = lynx::RackRenderer::nonFiniteEffectBlocks();
  12417. const auto& info = lynx::effectInfo (kind);
  12418. // (FL engines: a fresh instance as the menus make it, from the user's FL installation; round 142)
  12419. auto fx = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  12420. int dragged = 0; // parameter changes made by the mouse drags
  12421. for (int round = 0; round < rounds; ++round)
  12422. {
  12423. if (round > 0)
  12424. for (std::size_t p = 0; p < info.params.size(); ++p)
  12425. fx.params[p] = round == 1 ? 0.0f : round == 2 ? 1.0f : value();
  12426. auto song = lynx::Song::makeDefault(); // its demo beat feeds the effect
  12427. song.mixer.resize (2);
  12428. song.mixer[0].name = "Master";
  12429. song.mixer[1].name = "Insert 1";
  12430. song.mixer[1].effects.assign (1, fx);
  12431. for (auto& channel : song.channels)
  12432. channel.mixerTrack = 1;
  12433. offline.setSong (std::move (song));
  12434. offline.dispatchPendingMessages();
  12435. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  12436. for (int page = 0; page < pages; ++page)
  12437. {
  12438. auto editor = kind == lynx::EffectKind::facetEq ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  12439. : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  12440. if (editor == nullptr || editor->getWidth() <= 0 || editor->getHeight() <= 0)
  12441. continue;
  12442. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  12443. const auto paint = [&] {
  12444. juce::Graphics g (image);
  12445. editor->paintEntireComponent (g, false);
  12446. };
  12447. paint();
  12448. // drags from a grid of points, as a user moving every control (plain left button)
  12449. if (round >= 3 && drags)
  12450. {
  12451. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  12452. const auto step = juce::jmax (12, juce::jmin (editor->getWidth(), editor->getHeight()) / 8);
  12453. for (int y = step / 2; y < editor->getHeight(); y += step)
  12454. for (int x = step / 2; x < editor->getWidth(); x += step)
  12455. {
  12456. auto* target = editor->getComponentAt (x, y);
  12457. if (target == nullptr)
  12458. continue;
  12459. const auto at = target->getLocalPoint (editor.get(), juce::Point<float> ((float) x, (float) y));
  12460. const auto now = juce::Time::getCurrentTime();
  12461. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods) {
  12462. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, at, now, 1, false);
  12463. };
  12464. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  12465. const juce::Component::SafePointer<juce::Component> alive (target);
  12466. target->mouseDown (event (at, down));
  12467. const auto dy = (float) (random.nextBool() ? 400 : -400), dx = (float) (random.nextInt (401) - 200);
  12468. if (alive != nullptr)
  12469. target->mouseDrag (event (at + juce::Point<float> (dx * 0.5f, dy * 0.5f), down));
  12470. if (alive != nullptr)
  12471. target->mouseDrag (event (at + juce::Point<float> (dx, dy), down));
  12472. if (alive != nullptr)
  12473. target->mouseUp (event (at + juce::Point<float> (dx, dy), juce::ModifierKeys()));
  12474. juce::PopupMenu::dismissAllActiveMenus();
  12475. offline.dispatchPendingMessages();
  12476. }
  12477. paint();
  12478. }
  12479. }
  12480. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  12481. offline.renderOffline (0.05, rate);
  12482. if (round == 0 || round >= 3) // keep what the drags set for the next round
  12483. if (offline.getSong().mixer.size() > 1 && ! offline.getSong().mixer[1].effects.empty())
  12484. {
  12485. const auto& now = offline.getSong().mixer[1].effects[0];
  12486. for (std::size_t p = 0; p < fx.params.size(); ++p)
  12487. dragged += now.params[p] != fx.params[p] ? 1 : 0;
  12488. dragged += now.state != fx.state ? 1 : 0;
  12489. fx = now;
  12490. }
  12491. }
  12492. const auto broken = lynx::RackRenderer::nonFiniteEffectBlocks() - before;
  12493. allFinite = allFinite && broken == 0;
  12494. report << info.name << ": " << (broken == 0 ? juce::String ("OK") : "non-finite output in " + juce::String ((juce::int64) broken) + " blocks")
  12495. << " (" << dragged << " changes by mouse)\n";
  12496. if (reportPath.isNotEmpty())
  12497. juce::File (reportPath).replaceWithText (report + "(running)\n"); // what was reached, if it crashes
  12498. }
  12499. }
  12500. lynx::setNativeEditorDemo (false);
  12501. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  12502. report << "result=" << (allFinite ? "OK" : "NONFINITE") << "\n";
  12503. if (reportPath.isNotEmpty())
  12504. juce::File (reportPath).replaceWithText (report);
  12505. return allFinite;
  12506. }
  12507. // --opentest (round 157a): see the command line. Runs on the message loop (the editors' timers, animations and
  12508. // native windows are real); one step per timer tick.
  12509. // --windowopentime (round 190rd)
  12510. void runWindowOpenTime (const juce::String& reportPath, const juce::StringArray& pluginFiles)
  12511. {
  12512. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12513. lynx::AudioEngine engine (false);
  12514. juce::String text;
  12515. text << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getCpuModel() << "\n";
  12516. const lynx::platform::ThreadInstructions instructions;
  12517. struct Cost
  12518. {
  12519. double wall = 0.0, cpu = 0.0;
  12520. long long instr = -1;
  12521. };
  12522. // every window shown now (none of them existed before the open): painted once into a picture, as its first frame
  12523. const auto paintShown = [] (const std::set<juce::Component*>& before) {
  12524. auto& desktop = juce::Desktop::getInstance();
  12525. for (int k = desktop.getNumComponents(); --k >= 0;)
  12526. if (auto* c = desktop.getComponent (k); c != nullptr && c->isVisible() && before.count (c) == 0 && c->getWidth() > 0 && c->getHeight() > 0
  12527. && c->getWidth() < 8000 && c->getHeight() < 8000)
  12528. {
  12529. juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
  12530. juce::Graphics g (image);
  12531. c->paintEntireComponent (g, false);
  12532. }
  12533. };
  12534. const auto shown = [] {
  12535. std::set<juce::Component*> list;
  12536. auto& desktop = juce::Desktop::getInstance();
  12537. for (int k = 0; k < desktop.getNumComponents(); ++k)
  12538. list.insert (desktop.getComponent (k));
  12539. return list;
  12540. };
  12541. const auto timed = [&] (const std::function<void()>& open) {
  12542. const auto before = shown();
  12543. Cost cost;
  12544. const auto w0 = juce::Time::getMillisecondCounterHiRes();
  12545. const auto c0 = lynx::threadCpuSeconds();
  12546. const auto i0 = instructions.now();
  12547. open();
  12548. paintShown (before);
  12549. const auto i1 = instructions.now();
  12550. cost.wall = juce::Time::getMillisecondCounterHiRes() - w0;
  12551. cost.cpu = 1000.0 * (lynx::threadCpuSeconds() - c0);
  12552. cost.instr = i0 >= 0 && i1 >= i0 ? i1 - i0 : -1;
  12553. return cost;
  12554. };
  12555. std::vector<double> firsts, seconds;
  12556. const auto line = [&] (const juce::String& name, const Cost& a, const Cost& b) {
  12557. text << name << ": first " << juce::String (a.wall, 2) << " ms (cpu " << juce::String (a.cpu, 2) << ", instr " << juce::String ((juce::int64) a.instr)
  12558. << "), second " << juce::String (b.wall, 2) << " ms (cpu " << juce::String (b.cpu, 2) << ", instr " << juce::String ((juce::int64) b.instr) << ")\n";
  12559. firsts.push_back (a.wall);
  12560. seconds.push_back (b.wall);
  12561. juce::File (reportPath).replaceWithText (text);
  12562. };
  12563. const auto songWith = [] (const lynx::EffectSlot& fx) {
  12564. auto song = lynx::Song::makeDefault();
  12565. song.mixer.resize (2);
  12566. song.mixer[0].name = "Master";
  12567. song.mixer[1].name = "Insert 1";
  12568. song.mixer[1].effects.assign (1, fx);
  12569. return song;
  12570. };
  12571. // LYNX_WINDOWOPENTIME_NATIVES=0: the plugin files' windows only (a profiler run of those)
  12572. const auto natives = juce::SystemStats::getEnvironmentVariable ("LYNX_WINDOWOPENTIME_NATIVES", "1") != "0";
  12573. for (int k = 0; natives && k <= (int) lynx::lastEffectKind; ++k)
  12574. {
  12575. const auto kind = (lynx::EffectKind) k;
  12576. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
  12577. continue;
  12578. engine.setSong (songWith (lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind))));
  12579. engine.dispatchPendingMessages();
  12580. Cost a, b;
  12581. for (auto* cost : { &a, &b })
  12582. {
  12583. *cost = timed ([&engine] { lynx::NativeEffectWindows::open (engine, 1, 0); });
  12584. lynx::NativeEffectWindows::closeAll();
  12585. }
  12586. line ("effect " + juce::String::fromUTF8 (lynx::effectInfo (kind).name), a, b);
  12587. }
  12588. for (int k = 0; natives && k <= (int) lynx::InstrumentKind::soundfont; ++k)
  12589. {
  12590. const auto kind = (lynx::InstrumentKind) k;
  12591. if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
  12592. continue;
  12593. auto song = lynx::Song::makeDefault();
  12594. lynx::ChannelDef def;
  12595. def.instrument = kind;
  12596. def.name = "Test";
  12597. const auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
  12598. song.channels.push_back (channel ? *channel : def);
  12599. const auto index = (int) song.channels.size() - 1;
  12600. engine.setSong (std::move (song));
  12601. engine.dispatchPendingMessages();
  12602. Cost a, b;
  12603. for (auto* cost : { &a, &b })
  12604. {
  12605. *cost = timed ([&engine, index] { lynx::openChannelSettings (engine, index); });
  12606. lynx::closeChannelSettings();
  12607. }
  12608. line ("instrument " + juce::String (k), a, b);
  12609. }
  12610. // hosted plugins: each type in each file, in LYNX's plugin window (the wrapper header and the plugin's own editor)
  12611. lynx::PluginHost host (false);
  12612. for (const auto& file : pluginFiles)
  12613. {
  12614. host.addPluginFile (juce::File (file));
  12615. for (const auto& type : host.getKnownPlugins().getTypes())
  12616. {
  12617. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (file).getFileName())
  12618. continue;
  12619. juce::String error;
  12620. const auto load0 = juce::Time::getMillisecondCounterHiRes();
  12621. auto instance = std::shared_ptr<juce::AudioPluginInstance> (lynx::createRightInstance (host.getFormats(), type, 48000.0, 512, error).release());
  12622. if (instance == nullptr || ! instance->hasEditor())
  12623. {
  12624. text << "plugin " << type.name << ": not opened (" << (instance == nullptr ? error : juce::String ("no editor")) << ")\n";
  12625. continue;
  12626. }
  12627. lynx::preparePlugin (*instance, 48000.0, 512);
  12628. text << "plugin " << type.name << ": instance " << juce::String (juce::Time::getMillisecondCounterHiRes() - load0, 1) << " ms\n";
  12629. Cost a, b;
  12630. for (auto* cost : { &a, &b })
  12631. {
  12632. *cost = timed ([&instance] { lynx::PluginWindows::open (instance, *instance, instance->getName()); });
  12633. lynx::PluginWindows::close (*instance);
  12634. }
  12635. line ("plugin " + type.name, a, b);
  12636. }
  12637. }
  12638. const auto sum = [] (const std::vector<double>& v) {
  12639. double total = 0.0;
  12640. for (const auto x : v)
  12641. total += x;
  12642. return total;
  12643. };
  12644. text << "windows " << (int) firsts.size() << ", first opens total " << juce::String (sum (firsts), 1) << " ms, second opens total "
  12645. << juce::String (sum (seconds), 1) << " ms\nresult=OK\n";
  12646. juce::File (reportPath).replaceWithText (text);
  12647. lynx::PluginWindows::closeAll();
  12648. lynx::NativeEffectWindows::closeAll();
  12649. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  12650. }
  12651. void runOpenTest (const juce::String& reportPath, bool visible, std::function<void (bool)> done)
  12652. {
  12653. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  12654. struct OpenTest final : juce::Timer
  12655. {
  12656. juce::String reportPath, report;
  12657. bool visible = false, ok = true;
  12658. std::function<void (bool)> done;
  12659. std::unique_ptr<lynx::AudioEngine> engine;
  12660. std::vector<std::pair<juce::String, std::function<void()>>> steps;
  12661. std::size_t next = 0;
  12662. std::atomic<std::int64_t> lastStep { 0 };
  12663. std::atomic<bool> finished { false };
  12664. std::thread watchdog;
  12665. juce::String current;
  12666. std::mutex currentLock;
  12667. int opened = 0, painted = 0;
  12668. // LYNX_OPENTEST_TIMEOUT (seconds): longer for sanitizer builds
  12669. const std::int64_t timeoutMs = 1000 * juce::jmax (5, juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_TIMEOUT", "20").getIntValue());
  12670. static std::int64_t now() { return (std::int64_t) juce::Time::getMillisecondCounter(); }
  12671. void write (const juce::String& tail = {}) { juce::File (reportPath).replaceWithText (report + tail); }
  12672. ~OpenTest() override
  12673. {
  12674. finished = true;
  12675. if (watchdog.joinable())
  12676. watchdog.join();
  12677. }
  12678. void start()
  12679. {
  12680. lastStep = now();
  12681. // the UI hang watch runs during the whole test (5 s): a slow step leaves its stack next to the report
  12682. const auto folder = juce::File (reportPath).getParentDirectory().getChildFile ("opentest-hang");
  12683. folder.deleteRecursively();
  12684. folder.createDirectory();
  12685. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString(), 5000);
  12686. watchdog = std::thread ([this] {
  12687. while (! finished)
  12688. {
  12689. std::this_thread::sleep_for (std::chrono::milliseconds (200));
  12690. if (now() - lastStep.load() > timeoutMs)
  12691. {
  12692. juce::String at;
  12693. {
  12694. const std::lock_guard<std::mutex> l (currentLock);
  12695. at = current;
  12696. }
  12697. juce::File (reportPath).replaceWithText (report + "HANG at " + at + " (no progress for " + juce::String (timeoutMs / 1000) + " s; stack in opentest-hang)\nresult=HANG\n");
  12698. lynx::crashguard::exitNow (3);
  12699. }
  12700. }
  12701. });
  12702. startTimer (30);
  12703. }
  12704. // every LYNX window but none of the main one (there is none here): moved off-screen, painted once into an image
  12705. void touchWindows (bool resize, bool large)
  12706. {
  12707. auto& desktop = juce::Desktop::getInstance();
  12708. for (int i = desktop.getNumComponents(); --i >= 0;)
  12709. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible())
  12710. {
  12711. if (! visible && c->getScreenX() > -3000)
  12712. c->setTopLeftPosition (-6000, -6000);
  12713. if (resize)
  12714. if (auto* w = dynamic_cast<juce::ResizableWindow*> (c))
  12715. {
  12716. const auto b = w->getBounds();
  12717. w->setSize (large ? b.getWidth() * 2 : juce::jmax (40, b.getWidth() / 3), large ? b.getHeight() * 2 : juce::jmax (40, b.getHeight() / 3));
  12718. }
  12719. if (c->getWidth() > 0 && c->getHeight() > 0 && c->getWidth() < 8000 && c->getHeight() < 8000)
  12720. {
  12721. juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
  12722. juce::Graphics g (image);
  12723. c->paintEntireComponent (g, false);
  12724. ++painted;
  12725. // LYNX_OPENTEST_SHOTS=folder: each window as first painted (before the resizes), for a look
  12726. if (const auto shots = juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_SHOTS", {}); shots.isNotEmpty() && ! resize)
  12727. {
  12728. juce::FileOutputStream out (juce::File (shots).getChildFile (juce::String (painted).paddedLeft ('0', 4) + ".png"));
  12729. if (out.openedOk())
  12730. {
  12731. out.setPosition (0), out.truncate();
  12732. juce::PNGImageFormat().writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  12733. }
  12734. }
  12735. }
  12736. }
  12737. }
  12738. void timerCallback() override
  12739. {
  12740. if (next >= steps.size())
  12741. {
  12742. stopTimer();
  12743. lynx::NativeEffectWindows::closeAll();
  12744. lynx::closeChannelSettings();
  12745. // the UI hang watch itself: the message thread spins past the stall time; the watcher must write the stack
  12746. {
  12747. const auto before = lynx::crashguard::lastHangFile();
  12748. for (const auto until = now() + 7000; now() < until;)
  12749. lastStep = now(); // (busy: no heartbeat; the test's own watchdog stays quiet)
  12750. for (const auto until = now() + 1500; now() < until && lynx::crashguard::lastHangFile() == before;)
  12751. std::this_thread::sleep_for (std::chrono::milliseconds (20));
  12752. lynx::crashguard::stopHangWatch();
  12753. const juce::File hang (juce::String::fromUTF8 (lynx::crashguard::lastHangFile().c_str()));
  12754. const auto text = hang.loadFileAsString();
  12755. const auto frames = juce::StringArray::fromLines (text).size() - 2;
  12756. #if JUCE_WINDOWS
  12757. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && text.contains ("LYNX.exe+0x") && frames >= 3;
  12758. #else
  12759. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && frames >= 3;
  12760. #endif
  12761. report << "hang watch: " << (hangOk ? "OK" : "FAIL") << " (" << hang.getFileName() << ", " << frames << " lines"
  12762. << (before.empty() ? juce::String() : "; a step stalled > 5 s earlier: " + juce::String::fromUTF8 (before.c_str())) << ")\n";
  12763. ok = ok && hangOk;
  12764. }
  12765. report << "windows opened: " << opened << ", paints: " << painted << "\nresult=" << (ok ? "OK" : "FAIL") << "\n";
  12766. write();
  12767. finished = true;
  12768. if (done)
  12769. done (ok);
  12770. return;
  12771. }
  12772. auto& [label, fn] = steps[next++];
  12773. {
  12774. const std::lock_guard<std::mutex> l (currentLock);
  12775. current = label;
  12776. }
  12777. fn();
  12778. lastStep = now();
  12779. lynx::crashguard::heartbeat();
  12780. }
  12781. };
  12782. auto* test = new OpenTest();
  12783. test->reportPath = reportPath;
  12784. test->visible = visible;
  12785. test->engine = std::make_unique<lynx::AudioEngine> (false);
  12786. test->done = [test, done] (bool ok) {
  12787. juce::MessageManager::callAsync ([test, done, ok] {
  12788. delete test;
  12789. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  12790. done (ok);
  12791. });
  12792. };
  12793. auto& engine = *test->engine;
  12794. lynx::setNativeEditorDemo (true); // live displays animate without an audio device
  12795. const auto songWith = [] (const lynx::EffectSlot& fx) {
  12796. auto song = lynx::Song::makeDefault();
  12797. song.mixer.resize (2);
  12798. song.mixer[0].name = "Master";
  12799. song.mixer[1].name = "Insert 1";
  12800. song.mixer[1].effects.assign (1, fx);
  12801. for (auto& channel : song.channels)
  12802. channel.mixerTrack = 1;
  12803. return song;
  12804. };
  12805. // an older project's slot: its parameter list cut to `count` and read back by the project reader (the
  12806. // parameters a newer LYNX added after them take their defaults)
  12807. const auto oldState = [songWith] (const lynx::EffectSlot& fx, std::size_t count) -> std::optional<lynx::Song> {
  12808. auto json = juce::JSON::parse (lynx::ProjectFile::toJson (songWith (fx)));
  12809. if (auto* mixer = json["mixer"].getArray(); mixer != nullptr && mixer->size() > 1)
  12810. if (auto* effects = (*mixer)[1]["effects"].getArray(); effects != nullptr && ! effects->isEmpty())
  12811. if (auto* params = (*effects)[0]["params"].getArray())
  12812. params->removeRange ((int) count, params->size());
  12813. juce::String error;
  12814. return lynx::ProjectFile::fromJson (juce::JSON::toString (json), error);
  12815. };
  12816. auto& steps = test->steps;
  12817. juce::Random random (157);
  12818. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  12819. {
  12820. const auto kind = (lynx::EffectKind) k;
  12821. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
  12822. continue;
  12823. const auto& info = lynx::effectInfo (kind);
  12824. const auto base = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  12825. const auto n = info.params.size();
  12826. std::vector<std::pair<juce::String, std::function<std::optional<lynx::Song>()>>> variants;
  12827. variants.push_back ({ "default", [=] { return std::optional<lynx::Song> (songWith (base)); } });
  12828. for (const auto value : { 0.0f, 1.0f })
  12829. variants.push_back ({ value == 0.0f ? "all 0" : "all 1", [=] {
  12830. auto fx = base;
  12831. for (std::size_t p = 0; p < n; ++p) fx.params[p] = value;
  12832. return std::optional<lynx::Song> (songWith (fx));
  12833. } });
  12834. const auto seed = random.nextInt64();
  12835. variants.push_back ({ "random", [=] {
  12836. juce::Random r (seed);
  12837. auto fx = base;
  12838. for (std::size_t p = 0; p < n; ++p) fx.params[p] = r.nextFloat();
  12839. return std::optional<lynx::Song> (songWith (fx));
  12840. } });
  12841. std::vector<std::size_t> cuts { n / 2 };
  12842. 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)
  12843. if (c < n) cuts.push_back (c);
  12844. for (const auto c : cuts)
  12845. variants.push_back ({ "old project (" + juce::String ((int) c) + " of " + juce::String ((int) n) + " params)", [=] { return oldState (base, c); } });
  12846. for (const auto& [variant, makeSong] : variants)
  12847. {
  12848. const auto label = juce::String::fromUTF8 (info.name) + " / " + variant;
  12849. steps.push_back ({ label + ": open", [test, &engine, label, makeSong = makeSong] {
  12850. auto song = makeSong();
  12851. if (! song)
  12852. {
  12853. test->report << "FAIL " << label << ": project reader refused the state\n";
  12854. test->ok = false;
  12855. return;
  12856. }
  12857. engine.setSong (std::move (*song));
  12858. engine.dispatchPendingMessages();
  12859. lynx::NativeEffectWindows::open (engine, 1, 0);
  12860. ++test->opened;
  12861. test->touchWindows (false, false);
  12862. } });
  12863. steps.push_back ({ label + ": run", [test, &engine] {
  12864. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  12865. engine.renderOffline (0.03, rate);
  12866. test->touchWindows (false, false);
  12867. } });
  12868. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  12869. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  12870. steps.push_back ({ label + ": close", [test, label] {
  12871. lynx::NativeEffectWindows::closeAll();
  12872. test->report << label << ": OK\n";
  12873. test->write ("(running)\n");
  12874. } });
  12875. }
  12876. }
  12877. // instruments: the channel window the Channel rack opens (Patcher: its graph window, not here)
  12878. for (int k = 0; k <= (int) lynx::InstrumentKind::soundfont; ++k)
  12879. {
  12880. const auto kind = (lynx::InstrumentKind) k;
  12881. if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
  12882. continue;
  12883. for (const auto* variant : { "default", "old project (saved and read back)", "odd settings" })
  12884. {
  12885. if (juce::String (variant) == "odd settings" && kind != lynx::InstrumentKind::soundfont)
  12886. continue;
  12887. const auto label = "instrument " + juce::String (k) + " / " + variant;
  12888. steps.push_back ({ label + ": open", [test, &engine, kind, label, variant = juce::String (variant), old = juce::String (variant) != "default"] {
  12889. auto song = lynx::Song::makeDefault();
  12890. auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
  12891. lynx::ChannelDef def;
  12892. def.instrument = kind;
  12893. def.name = "Test";
  12894. song.channels.push_back (channel ? *channel : def);
  12895. if (kind == lynx::InstrumentKind::soundfont && variant != "default")
  12896. {
  12897. // a real font when FL's is there; NaN / huge / truncated settings
  12898. const auto& roots = lynx::flStudioAccess().roots;
  12899. if (! roots.data.empty())
  12900. song.channels.back().samplePath = (juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  12901. .getChildFile ("Patches/Soundfonts/STR_Ensemble.sf2"))
  12902. .getFullPathName().toStdString();
  12903. if (variant == "odd settings")
  12904. song.channels.back().modelParams = { NAN, 1.0e9f, -1.0e9f, 0.5f, 7.0f };
  12905. }
  12906. if (old)
  12907. {
  12908. juce::String error;
  12909. if (auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error))
  12910. song = std::move (*again);
  12911. }
  12912. const auto index = (int) song.channels.size() - 1;
  12913. engine.setSong (std::move (song));
  12914. engine.dispatchPendingMessages();
  12915. lynx::openChannelSettings (engine, index);
  12916. ++test->opened;
  12917. test->touchWindows (false, false);
  12918. } });
  12919. steps.push_back ({ label + ": run", [test, &engine] {
  12920. engine.renderOffline (0.03, 48000.0);
  12921. test->touchWindows (false, false);
  12922. } });
  12923. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  12924. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  12925. steps.push_back ({ label + ": close", [test, label] {
  12926. lynx::closeChannelSettings();
  12927. test->report << label << ": OK\n";
  12928. test->write ("(running)\n");
  12929. } });
  12930. }
  12931. }
  12932. test->start();
  12933. }
  12934. void runPluginOptionsTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath)
  12935. {
  12936. struct Test final : juce::Timer
  12937. {
  12938. juce::String reportPath, report;
  12939. juce::File shots;
  12940. std::unique_ptr<lynx::AudioEngine> engine;
  12941. std::unique_ptr<juce::DocumentWindow> mainWindow, other; // LYNX's main window stand-in; another secondary window
  12942. bool instrument = false, ok = true;
  12943. int channelIndex = -1, phase = 0;
  12944. juce::uint32 phaseStart = 0;
  12945. juce::AudioPluginInstance* instance = nullptr;
  12946. std::function<void (bool)> done;
  12947. void step (const juce::String& line)
  12948. {
  12949. report << line << "\n";
  12950. juce::File (reportPath).replaceWithText (report);
  12951. }
  12952. void expect (const juce::String& name, bool value)
  12953. {
  12954. step (name + "=" + juce::String ((int) value));
  12955. ok = ok && value;
  12956. }
  12957. void next (int to)
  12958. {
  12959. phase = to;
  12960. phaseStart = juce::Time::getMillisecondCounter();
  12961. }
  12962. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  12963. lynx::PluginRef* ref (lynx::Song& song) const
  12964. {
  12965. if (instrument)
  12966. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  12967. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  12968. }
  12969. const lynx::PluginRef& refNow() const { return *ref (const_cast<lynx::Song&> (engine->getSong())); }
  12970. juce::AudioPluginInstance* find()
  12971. {
  12972. if (instrument)
  12973. {
  12974. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  12975. return &p->getInstance();
  12976. }
  12977. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  12978. return &p->getInstance();
  12979. return nullptr;
  12980. }
  12981. void openWindow()
  12982. {
  12983. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  12984. : std::shared_ptr<void> (engine->getEffect (1, 0));
  12985. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  12986. { engine.get(), [this] (lynx::Song& song) { return ref (song); }, instrument, instrument ? -1 : 1,
  12987. instrument ? -1 : 0, {}, {} });
  12988. }
  12989. void shot (const char* name, bool settingsPage = false)
  12990. {
  12991. if (shots != juce::File() && instance != nullptr)
  12992. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  12993. }
  12994. // the plugin window is in front of the other secondary window
  12995. bool pluginInFront()
  12996. {
  12997. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  12998. #if JUCE_WINDOWS
  12999. return plug != nullptr && lynx::nativechild::isAbove (plug, other->getWindowHandle());
  13000. #else
  13001. auto& desktop = juce::Desktop::getInstance();
  13002. for (int i = 0; i < desktop.getNumComponents(); ++i)
  13003. if (auto* c = desktop.getComponent (i); c->getWindowHandle() == plug)
  13004. return c->isAlwaysOnTop() || desktop.getComponent (desktop.getNumComponents() - 1) == c;
  13005. return false;
  13006. #endif
  13007. }
  13008. void timerCallback() override
  13009. {
  13010. if (phase == 0) // waiting for the engine to host the plugin
  13011. {
  13012. instance = find();
  13013. if (instance == nullptr)
  13014. {
  13015. if (elapsed() > 20000)
  13016. finish ("not hosted");
  13017. return;
  13018. }
  13019. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  13020. openWindow();
  13021. next (1);
  13022. return;
  13023. }
  13024. if (phase == 1 && elapsed() >= 800) // Pin on top: off for a new plugin
  13025. {
  13026. expect ("pin_off_by_default", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  13027. shot ("pin-off");
  13028. const auto history = engine->getHistoryPosition();
  13029. lynx::PluginWindows::setPinnedOnTop (*instance, true);
  13030. expect ("pin_set", lynx::PluginWindows::isPinnedOnTop (*instance) && refNow().pinned);
  13031. expect ("pin_no_undo_step_project_modified", engine->getHistoryPosition() == history && engine->isModified());
  13032. // another secondary window brought in front of it
  13033. other = std::make_unique<juce::DocumentWindow> ("Another LYNX window", juce::Colours::darkslategrey, juce::DocumentWindow::closeButton);
  13034. other->setUsingNativeTitleBar (true);
  13035. other->setBounds (mainWindow->getX() + 60, mainWindow->getY() + 60, 420, 300);
  13036. other->setVisible (true);
  13037. lynx::keepAboveMainWindow (*other);
  13038. lynx::forceForegroundForTest (*other);
  13039. other->toFront (true);
  13040. next (2);
  13041. return;
  13042. }
  13043. if (phase == 2 && elapsed() >= 1200)
  13044. {
  13045. expect ("pinned_stays_in_front_of_a_clicked_window", pluginInFront());
  13046. shot ("pin-on");
  13047. // closed and opened again: the pin comes back from the project
  13048. lynx::PluginWindows::close (*instance);
  13049. openWindow();
  13050. next (3);
  13051. return;
  13052. }
  13053. if (phase == 3 && elapsed() >= 600)
  13054. {
  13055. expect ("pin_remembered_when_reopened", lynx::PluginWindows::isPinnedOnTop (*instance));
  13056. lynx::PluginWindows::setPinnedOnTop (*instance, false);
  13057. expect ("pin_cleared", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  13058. other->toFront (true);
  13059. next (4);
  13060. return;
  13061. }
  13062. if (phase == 4 && elapsed() >= 1000)
  13063. {
  13064. #if JUCE_WINDOWS
  13065. expect ("unpinned_goes_behind_a_clicked_window", ! pluginInFront());
  13066. #endif
  13067. other = nullptr;
  13068. // the wrapper settings page: LYNX's Velocity row in the MIDI group (instruments), default = follow
  13069. expect ("velocity_follows_midi_settings_by_default", refNow().velocityMode == lynx::prefs::pluginVelocityFollow
  13070. && refNow().fixedVelocity == lynx::prefs::defaultFixedVelocity);
  13071. shot ("wrapper-velocity-default", true);
  13072. engine->editSong ([this] (lynx::Song& song) {
  13073. if (auto* r = ref (song))
  13074. {
  13075. r->velocityMode = lynx::prefs::pluginVelocityFixed;
  13076. r->fixedVelocity = 96;
  13077. }
  13078. });
  13079. next (5);
  13080. return;
  13081. }
  13082. if (phase == 5 && elapsed() >= 400)
  13083. {
  13084. expect ("velocity_change_keeps_the_running_plugin", find() == instance);
  13085. shot ("wrapper-velocity-fixed", true);
  13086. engine->undo();
  13087. expect ("velocity_undo", refNow().velocityMode == lynx::prefs::pluginVelocityFollow && find() == instance);
  13088. // the preset menu's "Play a note when a preset loads": off by default, a user setting
  13089. expect ("audition_off_by_default", ! lynx::pluginpresetui::auditionOnLoad());
  13090. lynx::pluginpresetui::setAuditionOnLoad (true);
  13091. expect ("audition_menu_opened", lynx::PluginWindows::showPresetMenu (*instance));
  13092. next (6);
  13093. return;
  13094. }
  13095. if (phase == 6 && elapsed() >= 500) // the menu, as drawn
  13096. {
  13097. auto found = false;
  13098. auto& desktop = juce::Desktop::getInstance();
  13099. for (int c = desktop.getNumComponents(); --c >= 0 && ! found;)
  13100. if (auto* menu = desktop.getComponent (c); dynamic_cast<juce::TopLevelWindow*> (menu) == nullptr && menu->isVisible()
  13101. && menu->getHeight() > 60 && shots != juce::File())
  13102. {
  13103. const auto image = menu->createComponentSnapshot (menu->getLocalBounds(), true, 1.0f);
  13104. juce::FileOutputStream out (shots.getChildFile ("preset-menu-audition.png"));
  13105. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  13106. }
  13107. step ("shot_preset-menu-audition=" + juce::String ((int) found));
  13108. juce::PopupMenu::dismissAllActiveMenus();
  13109. // a preset loaded while the song is stopped: the note waits a moment, sounds, ends
  13110. const auto asked = engine->auditionPreset (*instance);
  13111. expect ("audition_only_for_channel_instruments", asked == instrument);
  13112. expect ("audition_waits_first", ! instrument || engine->auditionState() == 1);
  13113. next (7);
  13114. return;
  13115. }
  13116. if (phase == 7 && elapsed() >= 300)
  13117. {
  13118. expect ("audition_sounds", ! instrument || engine->auditionState() == 2);
  13119. next (8);
  13120. return;
  13121. }
  13122. if (phase == 8 && elapsed() >= 700)
  13123. {
  13124. expect ("audition_ends", engine->auditionState() == 0);
  13125. engine->getTransport().playing.store (true); // the song plays: no audition
  13126. expect ("no_audition_while_playing", ! engine->auditionPreset (*instance) && engine->auditionState() == 0);
  13127. engine->getTransport().playing.store (false);
  13128. lynx::pluginpresetui::setAuditionOnLoad (false);
  13129. expect ("audition_setting_off_again", ! lynx::pluginpresetui::auditionOnLoad());
  13130. finish ({});
  13131. }
  13132. }
  13133. void finish (const juce::String& failure)
  13134. {
  13135. stopTimer();
  13136. if (failure.isNotEmpty())
  13137. step ("failed=" + failure);
  13138. ok = ok && failure.isEmpty();
  13139. step (ok ? "result=OK" : "result=FAILED");
  13140. lynx::PluginWindows::closeAll();
  13141. done (ok);
  13142. }
  13143. };
  13144. auto* test = new Test();
  13145. test->reportPath = reportPath;
  13146. if (shotsPath.isNotEmpty())
  13147. {
  13148. test->shots = juce::File (shotsPath);
  13149. test->shots.createDirectory();
  13150. }
  13151. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13152. test->done = [this, test] (bool ok) {
  13153. setApplicationReturnValue (ok ? 0 : 1);
  13154. juce::MessageManager::callAsync ([this, test] {
  13155. lynx::setMainWindowForOwnership (nullptr);
  13156. test->other = nullptr;
  13157. test->mainWindow = nullptr;
  13158. test->engine = nullptr;
  13159. delete test;
  13160. quit();
  13161. });
  13162. };
  13163. test->engine = std::make_unique<lynx::AudioEngine> (false);
  13164. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  13165. test->mainWindow->setBounds (20, 20, 300, 200);
  13166. test->mainWindow->setVisible (true);
  13167. lynx::setMainWindowForOwnership (test->mainWindow.get());
  13168. auto& host = test->engine->getPluginHost();
  13169. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  13170. std::optional<juce::PluginDescription> chosen;
  13171. for (const auto& type : host.getKnownPlugins().getTypes())
  13172. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath
  13173. || (pluginPath.endsWithIgnoreCase (".lv2") && type.pluginFormatName == "LV2")) // (round 190rf: an LV2 bundle's plugin, known by URI)
  13174. {
  13175. chosen = type;
  13176. break;
  13177. }
  13178. if (! chosen)
  13179. {
  13180. test->step ("result=FAILED (no plugin)");
  13181. test->done (false);
  13182. return;
  13183. }
  13184. test->instrument = chosen->isInstrument;
  13185. lynx::PluginRef ref;
  13186. ref.id = chosen->createIdentifierString().toStdString();
  13187. ref.name = chosen->name.toStdString();
  13188. test->engine->editSong ([&] (lynx::Song& song) {
  13189. if (test->instrument)
  13190. {
  13191. lynx::ChannelDef c;
  13192. c.name = ref.name;
  13193. c.instrument = lynx::InstrumentKind::plugin;
  13194. c.plugin = ref;
  13195. test->channelIndex = (int) song.channels.size();
  13196. song.channels.push_back (c);
  13197. }
  13198. else
  13199. {
  13200. while (song.mixer.size() < 2)
  13201. song.mixer.emplace_back();
  13202. lynx::EffectSlot slot;
  13203. slot.kind = lynx::EffectKind::plugin;
  13204. slot.plugin = ref;
  13205. song.mixer[1].effects.push_back (slot);
  13206. }
  13207. });
  13208. test->engine->markSaved();
  13209. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  13210. test->next (0);
  13211. test->startTimerHz (20);
  13212. }
  13213. void runReloadTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath, bool waitKill)
  13214. {
  13215. struct Test final : juce::Timer
  13216. {
  13217. juce::String reportPath, report;
  13218. juce::File shots;
  13219. std::unique_ptr<lynx::AudioEngine> engine;
  13220. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  13221. bool instrument = false, waitKill = false, ok = true;
  13222. int channelIndex = -1, phase = 0, round = 0;
  13223. juce::uint32 phaseStart = 0;
  13224. int firstPid = 0, pid = 0, historyBefore = 0;
  13225. bool modifiedBefore = false;
  13226. float captured = -1.0f;
  13227. juce::AudioPluginInstance* instance = nullptr;
  13228. std::vector<lynx::ChannelDef> channelsBefore;
  13229. std::function<void (bool)> done;
  13230. lynx::AudioEngine::HostedSlot where() const { return instrument ? lynx::AudioEngine::HostedSlot { channelIndex, -1, -1 } : lynx::AudioEngine::HostedSlot { -1, 1, 0 }; }
  13231. void step (const juce::String& line)
  13232. {
  13233. report << line << "\n";
  13234. juce::File (reportPath).replaceWithText (report);
  13235. }
  13236. void expect (const juce::String& name, bool value)
  13237. {
  13238. step (name + "=" + juce::String ((int) value));
  13239. ok = ok && value;
  13240. }
  13241. void next (int to)
  13242. {
  13243. phase = to;
  13244. phaseStart = juce::Time::getMillisecondCounter();
  13245. }
  13246. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  13247. juce::AudioPluginInstance* find()
  13248. {
  13249. if (instrument)
  13250. {
  13251. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  13252. return &p->getInstance();
  13253. }
  13254. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  13255. return &p->getInstance();
  13256. return nullptr;
  13257. }
  13258. // a few blocks through the plugin (the offline engine has no audio thread): they carry parameter changes to
  13259. // the plugin's process and its values back
  13260. void pump (int blocks)
  13261. {
  13262. std::vector<float> l (512), r (512);
  13263. lynx::EffectParams none {};
  13264. for (int b = 0; b < blocks; ++b)
  13265. {
  13266. std::fill (l.begin(), l.end(), 0.0f);
  13267. std::fill (r.begin(), r.end(), 0.0f);
  13268. if (instrument)
  13269. {
  13270. if (auto in = engine->getChannelInstrument (channelIndex))
  13271. in->render (l.data(), r.data(), 512, 1.0f, 1.0f);
  13272. }
  13273. else if (auto fx = engine->getEffect (1, 0))
  13274. fx->process (l.data(), r.data(), 512, none, 120.0);
  13275. }
  13276. }
  13277. juce::AudioProcessorParameter* firstParam()
  13278. {
  13279. if (instance != nullptr)
  13280. for (auto* candidate : instance->getParameters())
  13281. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  13282. return candidate;
  13283. return nullptr;
  13284. }
  13285. void openWindow()
  13286. {
  13287. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  13288. : std::shared_ptr<void> (engine->getEffect (1, 0));
  13289. lynx::PluginWindows::WrapperContext context { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  13290. if (instrument)
  13291. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  13292. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  13293. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  13294. }, instrument, instrument ? -1 : 1, instrument ? -1 : 0, {}, {} };
  13295. context.reload = [] {}; // (the test reloads by itself; with it the window shows the notice)
  13296. lynx::PluginWindows::open (owner, *instance, instance->getName(), std::move (context));
  13297. }
  13298. void shot (const char* name, bool settingsPage = false)
  13299. {
  13300. if (shots != juce::File() && instance != nullptr)
  13301. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  13302. }
  13303. void timerCallback() override
  13304. {
  13305. if (phase == 0) // waiting for the engine to host the plugin
  13306. {
  13307. instance = find();
  13308. if (instance == nullptr)
  13309. {
  13310. if (elapsed() > 20000)
  13311. finish ("not hosted");
  13312. return;
  13313. }
  13314. pid = firstPid = lynx::sandboxedPluginProcessId (*instance);
  13315. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName + " pid=" + juce::String (pid));
  13316. expect ("separate_process", lynx::isSandboxedPlugin (*instance) && pid != 0);
  13317. expect ("running", ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  13318. // a setting that is captured (what a save or a backup does), then one that is not
  13319. if (auto* param = firstParam())
  13320. {
  13321. param->setValue (param->getValue() > 0.5f ? 0.13f : 0.87f);
  13322. pump (4);
  13323. engine->capturePluginStates();
  13324. captured = param->getValue();
  13325. param->setValue (captured > 0.5f ? 0.31f : 0.69f);
  13326. pump (4);
  13327. step ("param=" + param->getName (64) + " captured=" + juce::String (captured, 4) + " then=" + juce::String (param->getValue(), 4));
  13328. }
  13329. else
  13330. {
  13331. engine->capturePluginStates();
  13332. step ("param=none");
  13333. }
  13334. channelsBefore = engine->getSong().channels;
  13335. historyBefore = engine->getHistoryPosition();
  13336. modifiedBefore = engine->isModified();
  13337. if (shots != juce::File())
  13338. openWindow();
  13339. next (1);
  13340. return;
  13341. }
  13342. if (phase == 1 && elapsed() >= 600) // the plugin's process goes
  13343. {
  13344. shot (round == 0 ? "window-running" : "window-reloaded");
  13345. if (waitKill && round == 0)
  13346. {
  13347. juce::File (reportPath + ".pid").replaceWithText (juce::String (pid));
  13348. step ("waiting_for_kill pid=" + juce::String (pid));
  13349. }
  13350. else
  13351. lynx::crashSandboxedPluginForTest (*instance);
  13352. next (2);
  13353. return;
  13354. }
  13355. if (phase == 2) // LYNX notices
  13356. {
  13357. if (! engine->hostedPluginDown (where()))
  13358. {
  13359. pump (1); // (as the audio thread would: a block that gets no answer marks it too)
  13360. if (elapsed() > (waitKill && round == 0 ? 120000 : 10000))
  13361. finish ("the plugin never went down");
  13362. return;
  13363. }
  13364. step ("down_after_ms=" + juce::String (elapsed()));
  13365. const auto down = engine->downHostedPlugins();
  13366. expect ("listed_down", down.size() == 1 && down.front() == where());
  13367. expect ("listed_by_name", engine->downHostedPlugins (nameInSong()).size() == 1 && engine->downHostedPlugins ("no such plugin").empty());
  13368. next (3);
  13369. return;
  13370. }
  13371. if (phase == 3 && elapsed() >= 1500) // nothing reloads by itself
  13372. {
  13373. expect ("still_down_without_asking", engine->hostedPluginDown (where()) && find() == instance
  13374. && lynx::sandboxedPluginProcessId (*instance) == pid);
  13375. shot (round == 0 ? "reload-notice" : "reload-notice-again");
  13376. if (shots != juce::File() && round == 0)
  13377. {
  13378. lynx::PluginWindows::close (*instance);
  13379. lynx::PluginWindows::promptReload (*engine, where(), {});
  13380. next (4);
  13381. return;
  13382. }
  13383. next (5);
  13384. return;
  13385. }
  13386. if (phase == 4 && elapsed() >= 500) // the prompt a click on the channel / slot shows
  13387. {
  13388. auto found = false;
  13389. for (int c = juce::Desktop::getInstance().getNumComponents(); --c >= 0;)
  13390. if (auto* alert = dynamic_cast<juce::AlertWindow*> (juce::Desktop::getInstance().getComponent (c)))
  13391. {
  13392. const auto image = alert->createComponentSnapshot (alert->getLocalBounds(), true, 1.0f);
  13393. juce::FileOutputStream out (shots.getChildFile ("reload-prompt.png"));
  13394. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  13395. alert->exitModalState (0); // Close: nothing reloads
  13396. break;
  13397. }
  13398. step ("shot_reload-prompt=" + juce::String ((int) found));
  13399. next (45);
  13400. return;
  13401. }
  13402. if (phase == 45 && elapsed() >= 300)
  13403. {
  13404. expect ("still_down_after_close", engine->hostedPluginDown (where()));
  13405. next (5);
  13406. return;
  13407. }
  13408. if (phase == 5) // Reload, as the notice's button / the prompt / the menu item do
  13409. {
  13410. auto* old = instance;
  13411. const auto running = lynx::PluginWindows::reload (*engine, { where() });
  13412. instance = find();
  13413. const auto newPid = instance != nullptr ? lynx::sandboxedPluginProcessId (*instance) : 0;
  13414. expect ("reloaded", running == 1 && instance != nullptr && ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  13415. expect ("new_process", newPid != 0 && newPid != pid);
  13416. step ("pid=" + juce::String (newPid) + " same_object=" + juce::String ((int) (instance == old)));
  13417. expect ("old_window_closed", ! lynx::PluginWindows::isOpen (*old) || instance == old);
  13418. pid = newPid;
  13419. if (instance != nullptr)
  13420. {
  13421. pump (4);
  13422. if (auto* param = firstParam(); param != nullptr && captured >= 0.0f)
  13423. {
  13424. step ("param_after_reload=" + juce::String (param->getValue(), 4));
  13425. expect ("state_captured_last", std::abs (param->getValue() - captured) < 0.02f);
  13426. }
  13427. }
  13428. expect ("song_untouched", engine->getSong().channels == channelsBefore);
  13429. expect ("no_undo_step", engine->getHistoryPosition() == historyBefore && engine->isModified() == modifiedBefore);
  13430. if (instance == nullptr)
  13431. {
  13432. finish ("no instance after the reload");
  13433. return;
  13434. }
  13435. if (shots != juce::File())
  13436. openWindow();
  13437. if (round == 0) // once more: a plugin that crashes again waits for the user again
  13438. {
  13439. round = 1;
  13440. next (1);
  13441. return;
  13442. }
  13443. next (6);
  13444. return;
  13445. }
  13446. if (phase == 6 && elapsed() >= 400) // an edit and its undo keep the reloaded plugin
  13447. {
  13448. shot ("window-reloaded-twice");
  13449. auto* before = find();
  13450. engine->editSong ([] (lynx::Song& song) { song.bpm += 1.0f; });
  13451. engine->undo();
  13452. expect ("undo_keeps_the_reloaded_plugin", find() == before && ! engine->hostedPluginDown (where()));
  13453. lynx::PluginWindows::closeAll();
  13454. finish ({});
  13455. }
  13456. }
  13457. std::string nameInSong() const
  13458. {
  13459. const auto& song = engine->getSong();
  13460. return instrument ? song.channels[(size_t) channelIndex].plugin.name : song.mixer[1].effects[0].plugin.name;
  13461. }
  13462. void finish (const juce::String& failure)
  13463. {
  13464. stopTimer();
  13465. if (failure.isNotEmpty())
  13466. step ("failed=" + failure);
  13467. ok = ok && failure.isEmpty();
  13468. step (ok ? "result=OK" : "result=FAILED");
  13469. lynx::PluginWindows::closeAll();
  13470. done (ok);
  13471. }
  13472. };
  13473. lynx::setPluginSandboxAlerts (true); // (the deaths are recorded as in the app; no box: there is no main component)
  13474. auto* test = new Test();
  13475. test->reportPath = reportPath;
  13476. test->waitKill = waitKill;
  13477. if (shotsPath.isNotEmpty())
  13478. {
  13479. test->shots = juce::File (shotsPath);
  13480. test->shots.createDirectory();
  13481. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  13482. }
  13483. juce::File (reportPath + ".pid").deleteFile();
  13484. test->done = [this, test] (bool ok) {
  13485. setApplicationReturnValue (ok ? 0 : 1);
  13486. juce::MessageManager::callAsync ([this, test] {
  13487. lynx::setMainWindowForOwnership (nullptr);
  13488. test->mainWindow = nullptr;
  13489. test->engine = nullptr;
  13490. delete test;
  13491. quit();
  13492. });
  13493. };
  13494. test->engine = std::make_unique<lynx::AudioEngine> (false);
  13495. if (shotsPath.isNotEmpty())
  13496. {
  13497. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  13498. test->mainWindow->setBounds (20, 20, 300, 200);
  13499. test->mainWindow->setVisible (true);
  13500. lynx::setMainWindowForOwnership (test->mainWindow.get());
  13501. }
  13502. auto& host = test->engine->getPluginHost();
  13503. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  13504. std::optional<juce::PluginDescription> chosen;
  13505. for (const auto& type : host.getKnownPlugins().getTypes())
  13506. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath
  13507. || (pluginPath.endsWithIgnoreCase (".lv2") && type.pluginFormatName == "LV2")) // (round 190rf: an LV2 bundle's plugin, known by URI)
  13508. {
  13509. chosen = type;
  13510. break;
  13511. }
  13512. if (! chosen)
  13513. {
  13514. test->step ("result=FAILED (no plugin)");
  13515. test->done (false);
  13516. return;
  13517. }
  13518. test->instrument = chosen->isInstrument;
  13519. lynx::PluginRef ref;
  13520. ref.separateProcess = true;
  13521. ref.id = chosen->createIdentifierString().toStdString();
  13522. ref.name = chosen->name.toStdString();
  13523. test->engine->editSong ([&] (lynx::Song& song) {
  13524. if (test->instrument)
  13525. {
  13526. lynx::ChannelDef c;
  13527. c.name = ref.name;
  13528. c.instrument = lynx::InstrumentKind::plugin;
  13529. c.plugin = ref;
  13530. test->channelIndex = (int) song.channels.size();
  13531. song.channels.push_back (c);
  13532. }
  13533. else
  13534. {
  13535. while (song.mixer.size() < 2)
  13536. song.mixer.emplace_back();
  13537. lynx::EffectSlot slot;
  13538. slot.kind = lynx::EffectKind::plugin;
  13539. slot.plugin = ref;
  13540. song.mixer[1].effects.push_back (slot);
  13541. }
  13542. });
  13543. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  13544. test->next (0);
  13545. test->startTimerHz (20);
  13546. }
  13547. void runPlugWinTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only, int seconds)
  13548. {
  13549. struct Test final : juce::Timer
  13550. {
  13551. juce::String reportPath, report;
  13552. std::unique_ptr<lynx::AudioEngine> engine;
  13553. bool instrument = false;
  13554. int phase = 0, ticks = 0, seconds = 15, dockStep = 0;
  13555. juce::uint32 phaseStartMs = 0; // (phase 1 counts real time: the timer's ticks ran faster than 20 Hz here)
  13556. juce::AudioPluginInstance* instance = nullptr;
  13557. juce::AudioProcessorParameter* checked = nullptr;
  13558. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  13559. lynx::Workspace* workspace = nullptr; // LYNX_PLUGWIN_DOCK=1: the real main window's desktop (issue #116)
  13560. int channelIndex = -1; // an instrument: its channel (added after the song's own channels)
  13561. int stepMs = 3000; // dock mode: each state held that long (screenshots)
  13562. bool keysDone = false;
  13563. bool dockOk = true;
  13564. std::function<void (bool)> done;
  13565. // LYNX_PLUGWIN_DROP=<sample> (issue #174): a Sample browser window beside the plugin window with that file
  13566. // selected. The report gives the row's and the editor's places on screen with what LYNX sees there (for a
  13567. // real drag by xdotool / SendInput in that time), and, before the plugin is removed, whether the plugin took
  13568. // the file (its saved state names it).
  13569. juce::File dropFile;
  13570. std::unique_ptr<juce::DocumentWindow> dropWindow;
  13571. lynx::BrowserComponent* dropBrowser = nullptr;
  13572. int dropStage = 0;
  13573. juce::uint32 dropReadyMs = 0; // (the Browser may take long to list a big library: the time counts from here)
  13574. void dropTick (int elapsedMs)
  13575. {
  13576. if (dropStage == 0 && elapsedMs >= 1000)
  13577. {
  13578. lynx::externaldrag::install();
  13579. auto content = lynx::BrowserComponent::makeSampleBrowserContent (*engine, [this] (lynx::BrowserComponent& b) { dropBrowser = &b; });
  13580. dropWindow = std::make_unique<juce::DocumentWindow> ("LYNX test sample browser", juce::Colours::darkgrey, 0);
  13581. dropWindow->setContentOwned (content.release(), false);
  13582. dropWindow->setBounds (20, 240, 340, 520);
  13583. dropWindow->setVisible (true);
  13584. if (dropBrowser != nullptr)
  13585. {
  13586. dropBrowser->showFilterForSnapshot (dropFile.getParentDirectory(), lynx::browserview::ContentFilter::all);
  13587. step ("drop_locate=" + juce::String ((int) dropBrowser->locateFile (dropFile)));
  13588. }
  13589. dropStage = 1;
  13590. }
  13591. else if (dropStage == 1 && elapsedMs >= 2500)
  13592. {
  13593. using namespace lynx::externaldrag;
  13594. const auto row = dropBrowser != nullptr ? dropBrowser->selectedRowScreenBounds() : juce::Rectangle<int>();
  13595. const auto from = row.getCentre();
  13596. // (physical pixels too: SendInput / xdotool work in those)
  13597. auto physical = [] (juce::Point<int> p) {
  13598. const auto q = juce::Desktop::getInstance().getDisplays().logicalToPhysical (p);
  13599. return " phys=" + juce::String (q.x) + "," + juce::String (q.y);
  13600. };
  13601. step ("drop_source=" + juce::String (from.x) + "," + juce::String (from.y) + " place=" + placeName (placeAt (from)) + physical (from));
  13602. if (const auto pid = lynx::sandboxedPluginProcessId (*instance); pid != 0)
  13603. step ("drop_target_pid=" + juce::String (pid)); // (its window is the other process's)
  13604. else if (auto* editor = instance->getActiveEditor())
  13605. {
  13606. const auto to = editor->getScreenBounds().getCentre();
  13607. step ("drop_target=" + juce::String (to.x) + "," + juce::String (to.y) + " place=" + placeName (placeAt (to)) + physical (to));
  13608. }
  13609. const auto files = filesOf (juce::String (lynx::BrowserComponent::dragDescription) + "|" + dropFile.getFullPathName(), nullptr);
  13610. step ("drop_files=" + files.joinIntoString (";"));
  13611. dropStage = 2;
  13612. dropReadyMs = juce::Time::getMillisecondCounter();
  13613. }
  13614. }
  13615. void dropResult()
  13616. {
  13617. juce::MemoryBlock state;
  13618. instance->getStateInformation (state);
  13619. const auto name = dropFile.getFileNameWithoutExtension().toStdString();
  13620. auto holds = [&name] (const juce::MemoryBlock& block) {
  13621. const auto* bytes = static_cast<const char*> (block.getData());
  13622. return ! name.empty() && std::search (bytes, bytes + block.getSize(), name.begin(), name.end()) != bytes + block.getSize();
  13623. };
  13624. auto received = holds (state);
  13625. // (JUCE's VST3 host keeps the plugin's own state base64-encoded inside an XML of its own)
  13626. auto xml = juce::AudioProcessor::getXmlFromBinary (state.getData(), (int) state.getSize());
  13627. if (xml == nullptr)
  13628. xml = juce::parseXML (state.toString());
  13629. if (! received && xml != nullptr)
  13630. for (auto* e : xml->getChildIterator())
  13631. {
  13632. juce::MemoryBlock inner;
  13633. if (inner.fromBase64Encoding (e->getAllSubText().trim()) && holds (inner))
  13634. received = true;
  13635. }
  13636. step ("drop_received=" + juce::String ((int) received));
  13637. }
  13638. // issue #116 (with LYNX_DOCKED_PLUGINS=1 and LYNX_PLUGWIN_DOCK=1), FL's f116 sequence for every floating
  13639. // panel: the docked plugin window goes behind a clicked panel and comes back in front when clicked; a
  13640. // panel called by its key comes in front too; Detached reopens it as a window of its own, which stays above
  13641. // every panel clicked (it is owned by the main window).
  13642. const std::array<lynx::workspace::Panel, 4> dockPanels { lynx::workspace::Panel::channelRack, lynx::workspace::Panel::playlist,
  13643. lynx::workspace::Panel::pianoRoll, lynx::workspace::Panel::mixer };
  13644. const int dockSteps = 2 * 4 + 18; // (the last one reports dock_result)
  13645. int danceChannel = -1; // issue #116 slice 4: a dance channel's dancer over the docked plugin
  13646. lynx::MainComponent* ui = nullptr; // dock mode: the real main window's contents
  13647. struct ScaleSpy final : juce::ComponentPeer::ScaleFactorListener
  13648. {
  13649. int calls = 0;
  13650. double last = 0.0;
  13651. void nativeScaleFactorChanged (double s) override { ++calls; last = s; }
  13652. } scaleSpy;
  13653. juce::ComponentPeer* spiedPeer = nullptr;
  13654. void* panelHandle (lynx::workspace::Panel p) const { return workspace->getFrame (p).getWindowHandle(); }
  13655. void dockCheck (int at)
  13656. {
  13657. using lynx::workspace::Panel;
  13658. auto* main = mainWindow->getWindowHandle();
  13659. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  13660. auto expect = [this] (const juce::String& name, bool value) {
  13661. step (name + "=" + juce::String ((int) value));
  13662. dockOk = dockOk && value;
  13663. };
  13664. auto id = [] (Panel p) { return juce::String (lynx::workspace::panelId (p)); };
  13665. if (at == 0)
  13666. {
  13667. expect ("docked", lynx::PluginWindows::isDocked (*instance));
  13668. expect ("plugin_native_child", plug != nullptr && lynx::nativechild::parentOf (plug) == main);
  13669. for (auto p : dockPanels)
  13670. {
  13671. auto* h = panelHandle (p);
  13672. expect (id (p) + "_visible", workspace->isPanelVisible (p));
  13673. expect (id (p) + "_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  13674. expect ("plugin_above_" + id (p) + "_when_opened", lynx::nativechild::isAbove (plug, h));
  13675. }
  13676. expect ("browser_plain", ! workspace->isNativePanel (Panel::browser));
  13677. }
  13678. if (at < 2 * 4)
  13679. {
  13680. const auto p = dockPanels[at / 2];
  13681. if (at % 2 == 0)
  13682. {
  13683. workspace->activate (p); // a click on the panel
  13684. expect (id (p) + "_above_plugin_after_its_click", lynx::nativechild::isAbove (panelHandle (p), plug));
  13685. // the plugin stays above the panels nobody clicked
  13686. for (auto other : dockPanels)
  13687. if (other != p)
  13688. expect ("plugin_above_" + id (other) + "_after_" + id (p) + "_click", lynx::nativechild::isAbove (plug, panelHandle (other)));
  13689. }
  13690. else
  13691. {
  13692. lynx::PluginWindows::open ({}, *instance, {}); // (open again = a click on the plugin)
  13693. expect ("plugin_above_" + id (p) + "_after_plugin_click", lynx::nativechild::isAbove (plug, panelHandle (p)));
  13694. }
  13695. return;
  13696. }
  13697. if (at == 8)
  13698. {
  13699. // a layout change elsewhere (a panel resized, the Browser shown) keeps the plugin in front; a panel
  13700. // called by its key comes in front of it
  13701. workspace->hide (Panel::browser);
  13702. workspace->show (Panel::browser);
  13703. for (auto p : dockPanels)
  13704. expect ("plugin_above_" + id (p) + "_after_layout_change", lynx::nativechild::isAbove (plug, panelHandle (p)));
  13705. workspace->show (Panel::mixer);
  13706. expect ("mixer_above_plugin_after_show", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  13707. }
  13708. else if (at == 9)
  13709. {
  13710. // the setup wizard (Options › Setup wizard; first start) in front of the native panels and the plugin
  13711. ui->showSetupWizard();
  13712. }
  13713. else if (at == 10)
  13714. {
  13715. auto* overlay = ui->setupOverlayForTest();
  13716. auto* h = overlay != nullptr ? overlay->getWindowHandle() : nullptr;
  13717. expect ("setup_overlay_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  13718. expect ("setup_overlay_above_plugin", lynx::nativechild::isAbove (h, plug));
  13719. for (auto p : dockPanels)
  13720. expect ("setup_overlay_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  13721. workspace->activate (Panel::playlist); // (a panel brought in front by code: the overlay stays in front)
  13722. lynx::PluginWindows::open ({}, *instance, {});
  13723. expect ("setup_overlay_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::playlist)));
  13724. }
  13725. else if (at == 11)
  13726. {
  13727. ui->closeSetupWizardForSnapshot();
  13728. expect ("setup_overlay_closed", ui->setupOverlayForTest() == nullptr);
  13729. // drops: JUCE's list of windows in the native stacking order once a drag starts
  13730. workspace->activate (Panel::mixer);
  13731. workspace->hide (Panel::browser);
  13732. workspace->show (Panel::browser);
  13733. lynx::matchWindowOrderToScreen();
  13734. auto children = lynx::nativechild::attachedChildren (main);
  13735. auto& desktop = juce::Desktop::getInstance();
  13736. int last = -1;
  13737. bool ordered = children.size() >= 5;
  13738. for (auto* c : children)
  13739. if (c->isVisible())
  13740. {
  13741. int at2 = -1;
  13742. for (int k = 0; k < desktop.getNumComponents(); ++k)
  13743. if (desktop.getComponent (k) == c)
  13744. at2 = k;
  13745. ordered = ordered && at2 > last;
  13746. last = at2;
  13747. }
  13748. expect ("drop_order_matches_screen", ordered);
  13749. }
  13750. else if (at == 12)
  13751. {
  13752. // the main window's scale changes (a display with another scale): every native child placed again in
  13753. // physical pixels, the docked editor's window told (JUCE tells child windows nothing by itself)
  13754. for (int i = 0; i < juce::ComponentPeer::getNumPeers(); ++i)
  13755. if (auto* peer = juce::ComponentPeer::getPeer (i); peer != nullptr && peer->getNativeHandle() == plug)
  13756. spiedPeer = peer;
  13757. if (spiedPeer != nullptr)
  13758. spiedPeer->addScaleFactorListener (&scaleSpy);
  13759. lynx::nativechild::notifyScaleListenersForTest (*mainWindow);
  13760. juce::Desktop::getInstance().setGlobalScaleFactor (1.25f); // and LYNX's own UI zoom
  13761. }
  13762. else if (at == 13)
  13763. {
  13764. bool placed = true;
  13765. for (auto* c : lynx::nativechild::attachedChildren (main))
  13766. placed = placed && (! c->isVisible() || lynx::nativechild::placedPhysically (*c));
  13767. expect ("native_children_placed_at_125", placed);
  13768. expect ("docked_editor_told_the_scale", scaleSpy.calls > 0 && spiedPeer != nullptr
  13769. && std::abs (scaleSpy.last - spiedPeer->getPlatformScaleFactor()) < 0.001);
  13770. if (spiedPeer != nullptr && juce::ComponentPeer::isValidPeer (spiedPeer))
  13771. spiedPeer->removeScaleFactorListener (&scaleSpy);
  13772. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  13773. lynx::PluginWindows::setDetached (*instance, true);
  13774. }
  13775. else if (at == 14)
  13776. {
  13777. expect ("detached_reopened", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance));
  13778. expect ("detached_owned_by_main", plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  13779. expect ("detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  13780. for (auto p : dockPanels)
  13781. workspace->activate (p);
  13782. }
  13783. else if (at == 15)
  13784. {
  13785. // (an owned top-level window: above the main window and so above all its child windows)
  13786. expect ("detached_stays_above_clicked_panels", plug != nullptr && lynx::nativechild::ownerOf (plug) == main
  13787. && lynx::nativechild::parentOf (plug) != main && lynx::PluginWindows::isOpen (*instance));
  13788. lynx::PluginWindows::setDetached (*instance, false);
  13789. }
  13790. else if (at == 16)
  13791. {
  13792. // issue #116 slice 4: a Fruity Dance dancer standing on the docked plugin window, in front of it
  13793. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  13794. juce::Rectangle<int> over;
  13795. for (auto* c : lynx::nativechild::attachedChildren (main))
  13796. if (c->getWindowHandle() == plug)
  13797. over = ui->getLocalArea (nullptr, c->getScreenBounds());
  13798. expect ("dance_stage", stage != nullptr && ! over.isEmpty());
  13799. lynx::dance::Settings s;
  13800. s.move = lynx::dance::held; // (a still pose: the pixels tested below stay where they are)
  13801. s.x = over.getCentreX();
  13802. s.y = over.getCentreY() + 70;
  13803. const auto state = lynx::dance::toState (s);
  13804. engine->editSongStructural ([this, state] (lynx::Song& song) {
  13805. lynx::ChannelDef c;
  13806. c.name = "Fruity Dance";
  13807. c.instrument = lynx::InstrumentKind::fruitydance;
  13808. c.pluginState = state;
  13809. danceChannel = (int) song.channels.size();
  13810. song.channels.push_back (c);
  13811. });
  13812. engine->dispatchPendingMessages();
  13813. if (stage != nullptr)
  13814. stage->update();
  13815. }
  13816. else if (at == 17)
  13817. {
  13818. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  13819. auto* w = stage != nullptr ? stage->windowOf (danceChannel) : nullptr;
  13820. auto* h = w != nullptr ? w->getWindowHandle() : nullptr;
  13821. expect ("dancer_window_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  13822. expect ("dancer_window_layered", lynx::nativechild::isLayered (h));
  13823. expect ("dancer_above_plugin", lynx::nativechild::isAbove (h, plug));
  13824. for (auto p : dockPanels)
  13825. expect ("dancer_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  13826. // panels and the plugin brought in front (clicks, keys): the dancer stays in front of them
  13827. workspace->activate (Panel::mixer);
  13828. workspace->show (Panel::pianoRoll);
  13829. lynx::PluginWindows::open ({}, *instance, {});
  13830. expect ("dancer_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::mixer))
  13831. && lynx::nativechild::isAbove (h, panelHandle (Panel::pianoRoll)));
  13832. // the mouse: the dancer's body takes it, its window's transparent pixels let it through
  13833. if (w != nullptr)
  13834. {
  13835. const auto picture = w->createComponentSnapshot (w->getLocalBounds(), true, 1.0f);
  13836. const auto body = stage->bodyOf (danceChannel) - (w->getScreenPosition() - stage->getScreenPosition());
  13837. juce::Point<int> solid { -1, -1 }, clear { -1, -1 };
  13838. for (int y = body.getCentreY() - 10; y < body.getBottom() && solid.x < 0; ++y)
  13839. for (int x = body.getX(); x < body.getRight() && solid.x < 0; ++x)
  13840. if (picture.getBounds().contains (x, y) && picture.getPixelAt (x, y).getAlpha() == 255)
  13841. solid = { x, y };
  13842. for (int y = 0; y < picture.getHeight() && clear.x < 0; y += 2)
  13843. for (int x = 0; x < picture.getWidth() && clear.x < 0; x += 2)
  13844. if (picture.getPixelAt (x, y).getAlpha() == 0 && ! body.expanded (8).contains (x, y))
  13845. clear = { x, y };
  13846. step ("dancer_window=" + w->getBounds().toString() + " solid=" + solid.toString() + " clear=" + clear.toString());
  13847. auto* atSolid = lynx::nativechild::windowAt (*w, solid);
  13848. auto* atClear = lynx::nativechild::windowAt (*w, clear);
  13849. expect ("dancer_takes_its_body_clicks", solid.x >= 0 && atSolid == h);
  13850. expect ("dancer_lets_clicks_through", clear.x >= 0 && atClear != nullptr && atClear != h);
  13851. expect ("stage_leaves_the_mouse", ! stage->hitTest (stage->bodyOf (danceChannel).getCentreX(), stage->bodyOf (danceChannel).getCentreY()));
  13852. }
  13853. }
  13854. else if (at == 18)
  13855. {
  13856. // no dance channel: no dancer window (nothing drawn, no cost)
  13857. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  13858. engine->editSongStructural ([this] (lynx::Song& song) {
  13859. if (danceChannel >= 0 && danceChannel < (int) song.channels.size())
  13860. song.channels.erase (song.channels.begin() + danceChannel);
  13861. });
  13862. engine->dispatchPendingMessages();
  13863. if (stage != nullptr)
  13864. stage->update();
  13865. expect ("dancer_window_gone", stage != nullptr && stage->windowCount() == 0);
  13866. }
  13867. else if (at == 19 || at == 20)
  13868. {
  13869. // round 190ev (issue #152, "flickering windows"): on Windows a docked panel no longer fades by its
  13870. // window's alpha (each fade switched its drawing surface twice and the panel flashed); it shows and
  13871. // hides at once, as FL's docked windows. Elsewhere round 190i's fade stays.
  13872. auto& frame = workspace->getFrame (Panel::mixer);
  13873. if (at == 19)
  13874. {
  13875. workspace->show (Panel::mixer);
  13876. expect ("mixer_above_plugin_when_shown", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  13877. workspace->hide (Panel::mixer);
  13878. expect ("mixer_hides_at_once", ! frame.isVisible() && workspace->nativeFadeDirection (Panel::mixer) == 0
  13879. && frame.getAlpha() == 1.0f && ! lynx::nativechild::isLayered (frame.getWindowHandle()));
  13880. }
  13881. else
  13882. {
  13883. workspace->show (Panel::mixer);
  13884. expect ("mixer_shows_at_once", frame.isVisible() && frame.getAlpha() == 1.0f && workspace->nativeFadeDirection (Panel::mixer) == 0
  13885. && ! lynx::nativechild::isLayered (frame.getWindowHandle())
  13886. && lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  13887. }
  13888. }
  13889. else if (at >= 21 && at <= 23)
  13890. {
  13891. // round 190ev (issue #152, "the Channel rack almost never comes to the front"): LYNX's own editor
  13892. // windows (here a channel's settings) are docked like FL's plugin windows, so a click on the rack
  13893. // brings the rack in front of them and a click on one brings it back; a click inside a docked
  13894. // plugin's own view (a native window JUCE never hears of) brings that plugin window in front.
  13895. auto docked = [] {
  13896. auto& desktop = juce::Desktop::getInstance();
  13897. for (int i = 0; i < desktop.getNumComponents(); ++i)
  13898. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible() && (bool) c->getProperties()["lynxDockedWindow"])
  13899. return c;
  13900. return (juce::Component*) nullptr;
  13901. };
  13902. auto* rack = panelHandle (Panel::channelRack);
  13903. if (at == 21)
  13904. {
  13905. lynx::openChannelSettings (*engine, 0);
  13906. auto* ed = docked();
  13907. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  13908. expect ("editor_docked", h != nullptr && lynx::nativechild::parentOf (h) == main && lynx::nativechild::ownerOf (h) == nullptr);
  13909. expect ("editor_above_rack_when_opened", h != nullptr && lynx::nativechild::isAbove (h, rack));
  13910. workspace->activate (Panel::channelRack); // a click on the rack
  13911. expect ("rack_above_editor_after_its_click", h != nullptr && lynx::nativechild::isAbove (rack, h));
  13912. // a real click (a message to the editor's own window) on its title bar, at a point where the editor
  13913. // can be seen. Round 190fc (0.1.27 RC M1): JUCE takes a button-down only where the system says its
  13914. // window is the one under the point (HWNDComponentPeer::contains asks WindowFromPoint), so the old
  13915. // fixed point (60, 8) was dropped whenever the rack, raised just above, covered it there: the
  13916. // check read 0 while real clicks (on what can be seen) raise the editor.
  13917. if (h != nullptr && ed != nullptr)
  13918. {
  13919. juce::Point<int> at (-1, -1);
  13920. for (int x = 30; x < ed->getWidth() - 40 && at.x < 0; x += 12)
  13921. if (lynx::nativechild::windowAt (*ed, { x, 8 }) == h)
  13922. at = { x, 8 };
  13923. step (juce::String ("editor_title_visible_at=") + juce::String (at.x));
  13924. if (at.x >= 0)
  13925. {
  13926. const auto scale = ed->getPeer() != nullptr ? ed->getPeer()->getPlatformScaleFactor() * (double) ed->getDesktopScaleFactor() : 1.0;
  13927. lynx::nativechild::postClickForTest (h, (at.toDouble() * scale).roundToInt());
  13928. }
  13929. }
  13930. }
  13931. else if (at == 22)
  13932. {
  13933. auto* ed = docked();
  13934. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  13935. expect ("editor_above_rack_after_its_click", h != nullptr && lynx::nativechild::isAbove (h, rack));
  13936. workspace->activate (Panel::channelRack);
  13937. expect ("rack_above_plugin_after_its_click", lynx::nativechild::isAbove (rack, plug));
  13938. auto* view = lynx::nativechild::innermostChild (plug);
  13939. step (juce::String ("plugin_view_window=") + (view != nullptr ? "1" : "0"));
  13940. if (view != nullptr) // a click in the plugin's own view, near its top-left corner
  13941. lynx::nativechild::postClickForTest (view, { 2, 2 });
  13942. }
  13943. else
  13944. {
  13945. if (lynx::nativechild::innermostChild (plug) != nullptr)
  13946. expect ("plugin_above_rack_after_click_in_its_view", lynx::nativechild::isAbove (plug, rack));
  13947. lynx::closeChannelSettings();
  13948. // FL's Tools > Macros > Switch all plugin editors to > Detached (round 190i)
  13949. lynx::PluginWindows::setAllDetached (*engine, true);
  13950. }
  13951. }
  13952. else if (at == 24)
  13953. {
  13954. expect ("macro_detached_the_open_editor", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance)
  13955. && plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  13956. expect ("macro_detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  13957. lynx::PluginWindows::setAllDetached (*engine, false); // ... > Attached
  13958. }
  13959. else
  13960. {
  13961. expect ("docked_again", lynx::PluginWindows::isDocked (*instance) && engineRef() != nullptr && ! engineRef()->detached);
  13962. step (juce::String ("dock_result=") + (dockOk ? "OK" : "FAILED"));
  13963. }
  13964. }
  13965. const lynx::PluginRef* engineRef() const
  13966. {
  13967. const auto& song = engine->getSong();
  13968. if (instrument)
  13969. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  13970. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  13971. }
  13972. void step (const juce::String& line)
  13973. {
  13974. report << line << "\n";
  13975. juce::File (reportPath).replaceWithText (report);
  13976. }
  13977. juce::AudioPluginInstance* find()
  13978. {
  13979. if (instrument)
  13980. {
  13981. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  13982. return &p->getInstance();
  13983. }
  13984. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  13985. return &p->getInstance();
  13986. return nullptr;
  13987. }
  13988. void timerCallback() override
  13989. {
  13990. ++ticks;
  13991. if (phase == 0) // waiting for the engine to host the plugin
  13992. {
  13993. instance = find();
  13994. if (instance == nullptr)
  13995. {
  13996. if (ticks > 200)
  13997. {
  13998. step ("result=FAILED (not hosted)");
  13999. stopTimer();
  14000. done (false);
  14001. }
  14002. return;
  14003. }
  14004. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  14005. step ("programs=" + juce::String (instance->getNumPrograms()));
  14006. for (int p = 0; p < juce::jmin (5, instance->getNumPrograms()); ++p)
  14007. step ("program" + juce::String (p) + "=" + instance->getProgramName (p));
  14008. step ("save_formats=" + lynx::pluginpresetui::saveWildcard (*instance));
  14009. // preset round trip: save, change the first parameter, load, compare
  14010. juce::AudioProcessorParameter* param = nullptr;
  14011. for (auto* candidate : instance->getParameters())
  14012. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  14013. {
  14014. param = candidate;
  14015. break;
  14016. }
  14017. if (param != nullptr)
  14018. {
  14019. step ("param=" + param->getName (64));
  14020. checked = param;
  14021. const auto file = lynx::pluginpresetui::folderFor (instance->getName()).getChildFile ("plugwintest.lynxpreset");
  14022. juce::String error;
  14023. const auto before = param->getValue();
  14024. const auto saved = lynx::pluginpresetui::save (*instance, file, "plugwintest", error);
  14025. param->setValueNotifyingHost (before > 0.5f ? 0.1f : 0.9f);
  14026. const auto changed = param->getValue();
  14027. const auto loaded = saved && lynx::pluginpresetui::load (*instance, file, error);
  14028. step ("preset_roundtrip saved=" + juce::String ((int) saved) + " loaded=" + juce::String ((int) loaded) + " param0 before="
  14029. + juce::String (before, 4) + " changed=" + juce::String (changed, 4) + " after=" + juce::String (param->getValue(), 4)
  14030. + (error.isNotEmpty() ? " error=" + error : juce::String()));
  14031. for (const auto* ext : { "fxp", "fxb", "vstpreset" })
  14032. {
  14033. juce::String e2;
  14034. const auto f2 = file.withFileExtension (ext);
  14035. const auto ok2 = lynx::pluginpresetui::save (*instance, f2, "plugwintest", e2) && lynx::pluginpresetui::load (*instance, f2, e2);
  14036. step (juce::String ("preset_") + ext + "=" + juce::String ((int) ok2) + (e2.isNotEmpty() ? " (" + e2 + ")" : juce::String()));
  14037. f2.deleteFile();
  14038. }
  14039. step ("browser_lists=" + juce::String (lynx::pluginpresetui::userPresets (instance->getName()).size()));
  14040. }
  14041. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  14042. : std::shared_ptr<void> (engine->getEffect (1, 0));
  14043. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  14044. { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  14045. if (instrument)
  14046. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  14047. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  14048. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  14049. }, instrument, instrument ? -1 : 1, instrument ? -1 : 0 }); // (round 190rv: an effect's insert / slot, as the Mixer opens it)
  14050. owner.reset();
  14051. step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  14052. phase = 1;
  14053. ticks = 0;
  14054. phaseStartMs = juce::Time::getMillisecondCounter();
  14055. return;
  14056. }
  14057. if (phase == 1 && ticks >= 30 && ! keysDone && juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_KEYS", {}).isNotEmpty() && instance->getActiveEditor() != nullptr)
  14058. keysDone = ! lynx::pluginKeysTestTick (*instance->getActiveEditor(),
  14059. [this] (bool on) {
  14060. engine->editSong ([this, on] (lynx::Song& song) {
  14061. (instrument ? song.channels[(size_t) channelIndex].plugin : song.mixer[1].effects[0].plugin).hostKeysFirst = on;
  14062. });
  14063. },
  14064. [this] (const juce::String& line) { step (line); });
  14065. const auto elapsedMs = (int) (juce::Time::getMillisecondCounter() - phaseStartMs);
  14066. if (phase == 1 && ticks == 20 && checked != nullptr)
  14067. step ("param_after_1s=" + juce::String (checked->getValue(), 4));
  14068. // round 190in: LYNX_PLUGWIN_MENU=<png>: FL's ▸ wrapper menu of the open window (two columns for a channel)
  14069. if (const auto menuShot = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_MENU", {}); phase == 1 && ticks == 10 && menuShot.isNotEmpty())
  14070. if (const auto menu = lynx::PluginWindows::wrapperMenuForSnapshot (*instance))
  14071. {
  14072. juce::PopupMenu left, right;
  14073. auto* to = &left;
  14074. for (juce::PopupMenu::MenuItemIterator it (*menu); it.next();)
  14075. {
  14076. to->addItem (it.getItem());
  14077. if (it.getItem().shouldBreakAfter)
  14078. to = &right;
  14079. }
  14080. juce::StringArray names { "Plugin" };
  14081. std::vector<juce::PopupMenu> menus { left };
  14082. if (right.getNumItems() > 0)
  14083. {
  14084. names.add ("Channel");
  14085. menus.push_back (right);
  14086. }
  14087. LynxApplication::saveMenus (names, menus, menuShot);
  14088. step ("wrapper_menu_items=" + juce::String (left.getNumItems()) + "+" + juce::String (right.getNumItems()));
  14089. }
  14090. // (3 s apart: time for screenshots of each state)
  14091. if (phase == 1 && workspace != nullptr && dockStep < dockSteps && elapsedMs >= (dockStep + 1) * stepMs)
  14092. dockCheck (dockStep++);
  14093. if (phase == 1 && dropFile.existsAsFile())
  14094. dropTick (elapsedMs);
  14095. // (with LYNX_PLUGWIN_DROP: `seconds` after the drop places were reported, time for the drag)
  14096. const auto dropDone = ! dropFile.existsAsFile()
  14097. || (dropStage == 2 && (int) (juce::Time::getMillisecondCounter() - dropReadyMs) >= seconds * 1000);
  14098. if (phase == 1 && elapsedMs >= seconds * 1000 && dropDone && (workspace == nullptr || dockStep >= dockSteps)) // remove the plugin from the song
  14099. {
  14100. if (dropFile.existsAsFile())
  14101. dropResult();
  14102. engine->editSong ([this] (lynx::Song& song) {
  14103. if (instrument)
  14104. {
  14105. if (channelIndex >= 0 && channelIndex < (int) song.channels.size())
  14106. song.channels.erase (song.channels.begin() + channelIndex);
  14107. }
  14108. else
  14109. song.mixer[1].effects.clear();
  14110. });
  14111. step ("removed");
  14112. phase = 2;
  14113. ticks = 0;
  14114. return;
  14115. }
  14116. if (phase == 2 && ticks >= 40)
  14117. {
  14118. const auto open = lynx::PluginWindows::isOpen (*instance);
  14119. step ("window_open_after_remove=" + juce::String ((int) open));
  14120. step (open || ! dockOk ? "result=FAILED" : "result=OK");
  14121. stopTimer();
  14122. lynx::PluginWindows::closeAll();
  14123. done (! open && dockOk);
  14124. }
  14125. }
  14126. };
  14127. // round 190in: LYNX_PLUGWIN_ZOOM=<percent>: LYNX's interface zoom for the run (the wrapper's header at 150 %)
  14128. if (const auto zoom = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_ZOOM", {}).getIntValue(); zoom >= 50 && zoom <= 300)
  14129. juce::Desktop::getInstance().setGlobalScaleFactor ((float) zoom / 100.0f);
  14130. auto* test = new Test();
  14131. test->reportPath = reportPath;
  14132. test->seconds = seconds;
  14133. if (const auto drop = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DROP", {}); drop.isNotEmpty())
  14134. test->dropFile = juce::File (drop);
  14135. test->done = [this, test] (bool ok) {
  14136. setApplicationReturnValue (ok ? 0 : 1);
  14137. juce::MessageManager::callAsync ([this, test] {
  14138. lynx::setMainWindowForOwnership (nullptr);
  14139. lynx::PluginWindows::setDockWorkspace (nullptr);
  14140. test->dropWindow = nullptr; // (its Browser before the engine)
  14141. test->workspace = nullptr;
  14142. test->mainWindow = nullptr; // (dock mode: the main component with it, before the engine)
  14143. test->engine = nullptr;
  14144. delete test;
  14145. quit();
  14146. });
  14147. };
  14148. test->engine = std::make_unique<lynx::AudioEngine> (false);
  14149. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  14150. test->mainWindow->setBounds (20, 20, 300, 200);
  14151. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DOCK", {}) == "1" && lynx::nativechild::dockingEnabled())
  14152. {
  14153. // the real main window's contents (it docks plugin windows in its own desktop), so the panels are real
  14154. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14155. auto* ui = new lynx::MainComponent (*test->engine, false);
  14156. test->mainWindow->setUsingNativeTitleBar (true);
  14157. test->mainWindow->setContentOwned (ui, false);
  14158. test->mainWindow->setBounds (20, 20, 1500, 900);
  14159. test->workspace = &ui->workspaceForTest();
  14160. test->ui = ui;
  14161. if (const auto ms = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_STEP_MS", {}).getIntValue(); ms > 0)
  14162. test->stepMs = ms;
  14163. }
  14164. test->mainWindow->setVisible (true);
  14165. lynx::setMainWindowForOwnership (test->mainWindow.get());
  14166. if (test->workspace != nullptr)
  14167. {
  14168. using lynx::workspace::Panel;
  14169. for (auto p : { Panel::playlist, Panel::mixer, Panel::pianoRoll, Panel::channelRack })
  14170. test->workspace->show (p);
  14171. test->step ("dock_test=2 rack_visible=" + juce::String ((int) test->workspace->isPanelVisible (Panel::channelRack)));
  14172. }
  14173. auto& host = test->engine->getPluginHost();
  14174. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  14175. std::optional<juce::PluginDescription> chosen;
  14176. for (const auto& type : host.getKnownPlugins().getTypes())
  14177. if ((juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath
  14178. || (pluginPath.endsWithIgnoreCase (".lv2") && type.pluginFormatName == "LV2")) // (round 190rf: an LV2 bundle's plugin, known by URI)
  14179. && (only.isEmpty() || type.name == only))
  14180. {
  14181. chosen = type;
  14182. break;
  14183. }
  14184. if (! chosen)
  14185. {
  14186. test->step ("result=FAILED (no plugin)");
  14187. test->done (false);
  14188. return;
  14189. }
  14190. test->instrument = chosen->isInstrument;
  14191. lynx::PluginRef ref;
  14192. ref.separateProcess = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_SEPARATE", {}) == "1"; // (issue #96's other-process check)
  14193. ref.id = chosen->createIdentifierString().toStdString();
  14194. ref.name = chosen->name.toStdString();
  14195. test->engine->editSong ([&] (lynx::Song& song) {
  14196. if (test->instrument)
  14197. {
  14198. lynx::ChannelDef c;
  14199. c.name = ref.name;
  14200. c.instrument = lynx::InstrumentKind::plugin;
  14201. c.plugin = ref;
  14202. test->channelIndex = (int) song.channels.size();
  14203. song.channels.push_back (c);
  14204. }
  14205. else
  14206. {
  14207. while (song.mixer.size() < 2)
  14208. song.mixer.emplace_back();
  14209. lynx::EffectSlot slot;
  14210. slot.kind = lynx::EffectKind::plugin;
  14211. slot.plugin = ref;
  14212. song.mixer[1].effects.push_back (slot);
  14213. }
  14214. });
  14215. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  14216. test->startTimerHz (20);
  14217. }
  14218. void runEditorCrashTest (const juce::String& pluginPath, const juce::String& reportPath)
  14219. {
  14220. struct CrashTest final : juce::Timer
  14221. {
  14222. juce::String reportPath, report;
  14223. std::unique_ptr<lynx::PluginHost> host;
  14224. juce::AudioPluginInstance* plugin = nullptr;
  14225. std::shared_ptr<juce::AudioPluginInstance> keep; // a window whose plugin nobody else holds is closed as orphaned
  14226. std::function<void (bool)> done;
  14227. int ticks = 0, crashesBefore = 0;
  14228. void step (const juce::String& line)
  14229. {
  14230. report << line << "\n";
  14231. juce::File (reportPath).replaceWithText (report); // at each step: a crash leaves the last one
  14232. }
  14233. void timerCallback() override
  14234. {
  14235. ++ticks;
  14236. const auto crashes = lynx::PluginWindows::editorCrashCount() - crashesBefore;
  14237. const auto open = lynx::PluginWindows::isOpen (*plugin);
  14238. if ((crashes > 0 && ! open) || ticks >= 50) // 100 ms ticks: up to 5 s
  14239. {
  14240. stopTimer();
  14241. step ("editor_crashes=" + juce::String (crashes) + " window_open=" + juce::String ((int) open) + " ticks=" + juce::String (ticks));
  14242. bool traced = false;
  14243. if (crashes > 0)
  14244. {
  14245. const auto last = lynx::PluginWindows::editorCrashes().back();
  14246. traced = last.traceFile.existsAsFile() && last.traceFile.loadFileAsString().contains ("LYNX Test Crash");
  14247. step ("plugin=" + last.plugin + " detail=" + last.detail + " trace=" + last.traceFile.getFileName() + " traced="
  14248. + juce::String ((int) traced));
  14249. last.traceFile.deleteFile();
  14250. }
  14251. // still alive: one more message through the loop after the fault
  14252. juce::MessageManager::callAsync ([this, ok = crashes == 1 && ! open && traced] {
  14253. step ("message_loop_after_fault=1");
  14254. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  14255. done (ok);
  14256. });
  14257. }
  14258. }
  14259. };
  14260. auto* test = new CrashTest();
  14261. test->reportPath = reportPath;
  14262. test->done = [this, test] (bool ok)
  14263. {
  14264. setApplicationReturnValue (ok ? 0 : 1);
  14265. juce::MessageManager::callAsync ([this, test] { lynx::PluginWindows::closeAll(); delete test; quit(); });
  14266. };
  14267. #if ! JUCE_WINDOWS
  14268. test->step ("result=SKIPPED (Windows only: on macOS / Linux a plugin fault is a signal, see docs/analise/REA_rodada174a.md)");
  14269. test->done (true);
  14270. return;
  14271. #else
  14272. _putenv_s ("LYNX_TEST_CRASH", "editor");
  14273. test->host = std::make_unique<lynx::PluginHost> (false);
  14274. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  14275. std::shared_ptr<juce::AudioPluginInstance> instance;
  14276. for (const auto& type : test->host->getKnownPlugins().getTypes())
  14277. {
  14278. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName())
  14279. continue;
  14280. juce::String error;
  14281. instance = std::shared_ptr<juce::AudioPluginInstance> (lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error).release());
  14282. test->step ("plugin=" + type.name + (instance == nullptr ? " error=" + error : juce::String()));
  14283. break;
  14284. }
  14285. if (instance == nullptr || ! instance->hasEditor())
  14286. {
  14287. test->step ("result=FAILED (no plugin with an editor)");
  14288. test->done (false);
  14289. return;
  14290. }
  14291. lynx::preparePlugin (*instance, 48000.0, 512);
  14292. test->plugin = instance.get();
  14293. test->keep = instance;
  14294. test->crashesBefore = lynx::PluginWindows::editorCrashCount();
  14295. lynx::PluginWindows::open (instance, *instance, instance->getName()); // (the window keeps the plugin alive)
  14296. test->step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  14297. test->startTimer (100);
  14298. #endif
  14299. }
  14300. void runEditorTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only)
  14301. {
  14302. struct EditorTest final : juce::Timer
  14303. {
  14304. juce::String reportPath, report;
  14305. std::unique_ptr<lynx::PluginHost> host;
  14306. std::unique_ptr<juce::AudioPluginInstance> plugin;
  14307. std::unique_ptr<juce::DocumentWindow> window;
  14308. std::function<void (bool)> done;
  14309. void step (const juce::String& line)
  14310. {
  14311. report << line << "\n";
  14312. juce::File (reportPath).replaceWithText (report); // written at each step: a crash leaves the last one
  14313. }
  14314. void timerCallback() override
  14315. {
  14316. stopTimer();
  14317. window = nullptr;
  14318. step ("step=closed");
  14319. plugin = nullptr;
  14320. step ("result=OK");
  14321. done (true);
  14322. }
  14323. };
  14324. auto* test = new EditorTest();
  14325. test->reportPath = reportPath;
  14326. test->done = [this, test] (bool ok)
  14327. {
  14328. setApplicationReturnValue (ok ? 0 : 1);
  14329. juce::MessageManager::callAsync ([this, test] { delete test; quit(); });
  14330. };
  14331. test->host = std::make_unique<lynx::PluginHost> (false);
  14332. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  14333. test->step ("exe=" + juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
  14334. for (const auto& type : test->host->getKnownPlugins().getTypes())
  14335. {
  14336. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  14337. || (only.isNotEmpty() && type.name != only))
  14338. continue;
  14339. juce::String error;
  14340. test->plugin = lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error);
  14341. test->step ("plugin=" + type.name + (test->plugin == nullptr ? " error=" + error : juce::String()));
  14342. break;
  14343. }
  14344. if (test->plugin == nullptr)
  14345. {
  14346. test->step ("result=FAILED");
  14347. test->done (false);
  14348. return;
  14349. }
  14350. lynx::preparePlugin (*test->plugin, 48000.0, 512);
  14351. test->step ("step=create_editor");
  14352. test->window = std::make_unique<juce::DocumentWindow> (test->plugin->getName(), juce::Colours::black, juce::DocumentWindow::closeButton);
  14353. test->window->setUsingNativeTitleBar (true);
  14354. if (auto* editor = test->plugin->createEditorIfNeeded())
  14355. test->window->setContentOwned (editor, true);
  14356. else
  14357. test->step ("no_editor");
  14358. test->step ("step=show");
  14359. test->window->centreWithSize (test->window->getWidth(), test->window->getHeight());
  14360. test->window->setVisible (true);
  14361. test->step ("step=shown");
  14362. test->startTimer (4000);
  14363. }
  14364. void runFitTest (const juce::String& reportPath, int percent)
  14365. {
  14366. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14367. struct FitTest final : juce::Timer
  14368. {
  14369. juce::String path, report;
  14370. bool ok = true;
  14371. int step = 0, percent = 150;
  14372. std::unique_ptr<juce::DocumentWindow> tall, big;
  14373. std::function<void()> done;
  14374. // `whole`: the window must fit entirely (a resizable one); else its title bar and close button must be on the screen
  14375. void check (const juce::String& what, juce::Component& w, bool whole)
  14376. {
  14377. juce::BorderSize<int> frame;
  14378. if (auto* peer = w.getPeer())
  14379. if (const auto f = peer->getFrameSizeIfPresent())
  14380. frame = *f;
  14381. auto outer = frame.addedTo (w.getBounds());
  14382. const auto* display = juce::Desktop::getInstance().getDisplays().getDisplayForRect (outer);
  14383. const auto area = display != nullptr ? display->userArea : outer;
  14384. #if JUCE_LINUX
  14385. // round 164: a compositor that draws the frame itself (WSLg's Weston) reports its invisible shadow in
  14386. // the frame (59 px on top, 38 around at 100%): only what is visible is checked, give or take 4 px
  14387. const auto shadow = frame.getLeft() >= 16 ? frame.getLeft() : 0;
  14388. outer = outer.reduced (shadow);
  14389. const auto slack = shadow > 0 ? 4 : 0;
  14390. #else
  14391. const auto slack = 0;
  14392. #endif
  14393. const auto passed = outer.getY() >= area.getY() - slack && outer.getRight() <= area.getRight() + slack && outer.getX() >= area.getX() - slack
  14394. && (! whole || outer.getBottom() <= area.getBottom() + 1 + slack);
  14395. report << (passed ? "ok " : "FAIL ") << what << " window=" << outer.toString() << " (frame " << frame.getTop() << ","
  14396. << frame.getLeft() << ") screen=" << area.toString() << "\n";
  14397. ok = ok && passed;
  14398. }
  14399. void start()
  14400. {
  14401. report << "scale=" << percent << "%\n";
  14402. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  14403. // a tool window taller than the screen, centred (its title bar would be above the screen)
  14404. tall = std::make_unique<juce::DocumentWindow> ("LYNX fit test - tall", lynx::theme::colour::bg2, juce::DocumentWindow::closeButton);
  14405. tall->setUsingNativeTitleBar (true);
  14406. auto* content = new juce::Component();
  14407. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  14408. content->setSize (500, area.getHeight() + 200);
  14409. tall->setContentOwned (content, true);
  14410. tall->setCentrePosition (area.getCentre());
  14411. tall->setVisible (true);
  14412. lynx::keepAboveMainWindow (*tall);
  14413. // LYNX_FITTEST_MS: how long each window stays (default 700 ms; longer to take screenshots of them)
  14414. startTimer (juce::jlimit (300, 60000, juce::SystemStats::getEnvironmentVariable ("LYNX_FITTEST_MS", "700").getIntValue()));
  14415. }
  14416. void timerCallback() override
  14417. {
  14418. ++step;
  14419. if (step == 1)
  14420. {
  14421. check ("tall tool window: title bar and close button on the screen", *tall, false);
  14422. tall.reset();
  14423. // round 164: a fixed-size LYNX tool window whose content is taller than the screen: it scrolls
  14424. auto content = std::make_unique<juce::Component>();
  14425. const auto screen = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  14426. content->setSize (520, screen.getHeight() + 300);
  14427. lynx::openToolWindow (std::move (content), "LYNX fit test - fixed size", "fittest-fixed");
  14428. return;
  14429. }
  14430. if (step == 2)
  14431. {
  14432. if (auto* w = lynx::findToolWindow ("fittest-fixed"))
  14433. {
  14434. check ("fixed-size tool window taller than the screen: fits (its content scrolls)", *w, true);
  14435. const auto scrolls = w->getContentComponent() != nullptr && w->getContentComponent()->getNumChildComponents() > 0
  14436. && dynamic_cast<juce::Viewport*> (w->getContentComponent()->getChildComponent (0)) != nullptr;
  14437. report << (scrolls ? "ok " : "FAIL ") << "its content is in a scrolling viewport\n";
  14438. ok = ok && scrolls;
  14439. }
  14440. else
  14441. {
  14442. report << "FAIL fixed-size tool window not found\n";
  14443. ok = false;
  14444. }
  14445. lynx::closeAllToolWindows();
  14446. // a resizable window that fits at 100%, then the zoom goes up (the main window's case)
  14447. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  14448. big = std::make_unique<juce::DocumentWindow> ("LYNX fit test - zoom", lynx::theme::colour::bg2, juce::DocumentWindow::allButtons);
  14449. big->setUsingNativeTitleBar (true);
  14450. big->setResizable (true, false);
  14451. big->setResizeLimits (400, 300, 10000, 10000);
  14452. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  14453. big->setBounds (area.getX() + 40, area.getY() + 60, area.getWidth() * 9 / 10 - 40, area.getHeight() * 9 / 10 - 60);
  14454. big->setVisible (true);
  14455. return;
  14456. }
  14457. if (step == 3)
  14458. {
  14459. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  14460. juce::Timer::callAfterDelay (200, [] { lynx::fitAllWindowsOnScreen(); });
  14461. return;
  14462. }
  14463. if (step == 4)
  14464. {
  14465. check ("resizable window after the zoom change: fits the screen", *big, true);
  14466. big.reset();
  14467. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  14468. juce::File (path).replaceWithText (report);
  14469. stopTimer();
  14470. if (done)
  14471. done();
  14472. }
  14473. }
  14474. };
  14475. static std::unique_ptr<FitTest> test;
  14476. test = std::make_unique<FitTest>();
  14477. test->path = reportPath;
  14478. test->percent = juce::jlimit (50, 300, percent);
  14479. test->done = [this] { juce::MessageManager::callAsync ([this] { test.reset(); quit(); }); };
  14480. test->start();
  14481. }
  14482. void runFocusTest (const juce::String& reportPath)
  14483. {
  14484. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14485. struct FocusTest final : juce::Timer
  14486. {
  14487. juce::String reportPath, report;
  14488. bool ok = true;
  14489. int stepIndex = 0;
  14490. std::unique_ptr<lynx::AudioEngine> engine;
  14491. lynx::MainComponent* ui = nullptr;
  14492. std::unique_ptr<juce::DocumentWindow> main;
  14493. std::function<void()> done;
  14494. void line (const juce::String& text)
  14495. {
  14496. report << text << "\n";
  14497. juce::File (reportPath).replaceWithText (report);
  14498. }
  14499. void check (const juce::String& what, bool passed)
  14500. {
  14501. line ((passed ? "ok " : "FAIL ") + what);
  14502. ok = ok && passed;
  14503. }
  14504. juce::ComponentPeer* mainPeer() const { return main != nullptr ? main->getPeer() : nullptr; }
  14505. bool focusInMain() const
  14506. {
  14507. auto* f = juce::Component::getCurrentlyFocusedComponent();
  14508. return f != nullptr && main->isParentOf (f);
  14509. }
  14510. // a click (press and release) at the middle of the panel's content, through the native window it is in
  14511. static void click (juce::Component& frame, bool right)
  14512. {
  14513. auto* peer = frame.getPeer();
  14514. if (peer == nullptr)
  14515. return;
  14516. const auto at = peer->getComponent().getLocalPoint (&frame, frame.getLocalBounds().getCentre().toFloat());
  14517. const auto button = right ? juce::ModifierKeys::rightButtonModifier : juce::ModifierKeys::leftButtonModifier;
  14518. const auto now = juce::Time::currentTimeMillis();
  14519. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (button), 1.0f, 0.0f, now);
  14520. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  14521. }
  14522. bool space()
  14523. {
  14524. auto* peer = mainPeer(); // (the system sends the key to the window with the focus: the main one)
  14525. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  14526. }
  14527. juce::TextEditor* firstField (juce::Component& c)
  14528. {
  14529. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && t->getWantsKeyboardFocus())
  14530. return t;
  14531. for (auto* child : c.getChildren())
  14532. if (auto* t = firstField (*child))
  14533. return t;
  14534. return nullptr;
  14535. }
  14536. // the user tabs away and comes back with a click in `panel`
  14537. void backWithClickIn (lynx::workspace::Panel panel, bool right)
  14538. {
  14539. auto& frame = ui->workspaceForTest().getFrame (panel);
  14540. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  14541. auto* peer = mainPeer();
  14542. line (name + ": native child window=" + juce::String ((int) lynx::nativechild::isAttached (frame)));
  14543. check (name + ": the main window has the keys before", ui->hasKeyboardFocus (true));
  14544. peer->handleFocusLoss(); // (another app is in front: the main window lost the system focus)
  14545. check (name + ": nothing in LYNX has the keys while it is in the background", ! focusInMain());
  14546. // the cause: JUCE answers the system's "activate?" from the panel's own component, which takes no focus on a click
  14547. line (name + ": JUCE's answer alone would activate the window=" + juce::String ((int) frame.getMouseClickGrabsKeyboardFocus()));
  14548. const auto activates = lynx::nativechild::clickActivatesWindow (frame, false);
  14549. check (name + ": a click in it activates the inactive main window", activates);
  14550. #if JUCE_WINDOWS
  14551. if (lynx::nativechild::isAttached (frame))
  14552. check (name + ": its native window answers WM_MOUSEACTIVATE with MA_ACTIVATE",
  14553. lynx::nativechild::mouseActivateAnswerForTest (frame, true) == 1 /* MA_ACTIVATE */);
  14554. #endif
  14555. if (activates)
  14556. peer->handleFocusGain(); // (the system activates the main window and gives it the focus)
  14557. click (frame, right);
  14558. }
  14559. void spacePlays (lynx::workspace::Panel panel, bool right)
  14560. {
  14561. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  14562. check (name + ": the main window has the keys after the click", ui->hasKeyboardFocus (true));
  14563. auto& transport = engine->getTransport();
  14564. if (transport.playing.load())
  14565. engine->stop();
  14566. const auto used = space();
  14567. check (name + ": Space starts playback", used && transport.playing.load());
  14568. engine->stop();
  14569. }
  14570. void timerCallback() override
  14571. {
  14572. using lynx::workspace::Panel;
  14573. auto& ws = ui->workspaceForTest();
  14574. switch (stepIndex++)
  14575. {
  14576. case 0:
  14577. line ("docking=" + juce::String ((int) lynx::nativechild::dockingEnabled()));
  14578. ws.show (Panel::playlist);
  14579. ws.show (Panel::pianoRoll);
  14580. ui->grabKeyboardFocus();
  14581. break;
  14582. case 1: backWithClickIn (Panel::playlist, false); break;
  14583. case 2: spacePlays (Panel::playlist, false); ui->grabKeyboardFocus(); break;
  14584. case 3: backWithClickIn (Panel::pianoRoll, false); break;
  14585. case 4: spacePlays (Panel::pianoRoll, false); ui->grabKeyboardFocus(); break;
  14586. case 5: backWithClickIn (Panel::playlist, true); break;
  14587. case 6:
  14588. juce::PopupMenu::dismissAllActiveMenus(); // (the right click's menu)
  14589. spacePlays (Panel::playlist, true);
  14590. break;
  14591. case 7:
  14592. {
  14593. // a text field (the Browser's search box) keeps the keys through a switch to another app and back:
  14594. // nothing in LYNX takes them from it (no periodic grab); inside the active window the click's
  14595. // activation answer is unchanged, and a click in the Playlist ends the typing as before (issue #9,
  14596. // as FL ends typing in its search field)
  14597. auto* field = firstField (*ui);
  14598. line ("text field found=" + juce::String ((int) (field != nullptr)));
  14599. if (field != nullptr)
  14600. {
  14601. auto& frame = ws.getFrame (Panel::playlist);
  14602. field->grabKeyboardFocus();
  14603. check ("the text field has the keys", field->hasKeyboardFocus (false));
  14604. mainPeer()->handleFocusLoss();
  14605. mainPeer()->handleFocusGain(); // (back with Alt+Tab, or a click that activates the window)
  14606. check ("the text field gets the keys back with the window", field->hasKeyboardFocus (false));
  14607. check ("active window: a click in a panel does not activate it again", ! lynx::nativechild::clickActivatesWindow (frame, true));
  14608. click (frame, false);
  14609. check ("a click in the Playlist ends the typing: the main window has the keys", ui->hasKeyboardFocus (true) && ! field->hasKeyboardFocus (false));
  14610. }
  14611. line (ok ? "result=OK" : "result=FAILED");
  14612. stopTimer();
  14613. done();
  14614. break;
  14615. }
  14616. default:
  14617. break;
  14618. }
  14619. }
  14620. };
  14621. auto* test = new FocusTest();
  14622. test->reportPath = reportPath;
  14623. startFocusTestWindow (*test);
  14624. test->startTimer (600);
  14625. }
  14626. // --simplekeytest (round 190fc, 0.1.27 RC H2): in the Simple layout Space often did nothing after a click in the
  14627. // window (the dock, a track header, the grid, the Lyrics button) or after a demo opened from Welcome › Start from. The
  14628. // main window in the Simple layout; each step clicks as the system would (through the native window under the point)
  14629. // and presses Space where the system sends it (the native window of the component with the focus): playback must
  14630. // start, except while a text field the user clicked into has the keys (it types). Shows a window (Windows: GUI lock).
  14631. void runSimpleKeyTest (const juce::String& reportPath)
  14632. {
  14633. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14634. struct KeyTest final : juce::Timer
  14635. {
  14636. juce::String reportPath, report;
  14637. bool ok = true;
  14638. int stepIndex = 0, instrumentTrack = 0;
  14639. std::unique_ptr<lynx::AudioEngine> engine;
  14640. lynx::MainComponent* ui = nullptr;
  14641. std::unique_ptr<juce::DocumentWindow> main;
  14642. std::function<void()> done;
  14643. void line (const juce::String& text)
  14644. {
  14645. report << text << "\n";
  14646. juce::File (reportPath).replaceWithText (report);
  14647. }
  14648. void check (const juce::String& what, bool passed)
  14649. {
  14650. line ((passed ? "ok " : "FAIL ") + what);
  14651. ok = ok && passed;
  14652. }
  14653. static juce::String describe (juce::Component* c)
  14654. {
  14655. if (c == nullptr)
  14656. return "nothing";
  14657. juce::String path;
  14658. for (auto* p = c; p != nullptr && path.length() < 160; p = p->getParentComponent())
  14659. {
  14660. auto name = p->getComponentID().isNotEmpty() ? p->getComponentID() : p->getName();
  14661. if (name.isEmpty())
  14662. name = juce::String (typeid (*p).name()).fromLastOccurrenceOf ("::", false, false).substring (0, 28);
  14663. path << (path.isEmpty() ? "" : " < ") << name;
  14664. }
  14665. return path;
  14666. }
  14667. // the first showing component with this ID in the main window or a native child window of it
  14668. juce::Component* find (const juce::String& id)
  14669. {
  14670. std::function<juce::Component* (juce::Component&)> in = [&] (juce::Component& root) -> juce::Component* {
  14671. if (root.getComponentID() == id && root.isShowing())
  14672. return &root;
  14673. for (auto* c : root.getChildren())
  14674. if (auto* f = in (*c))
  14675. return f;
  14676. return nullptr;
  14677. };
  14678. if (auto* f = in (*main))
  14679. return f;
  14680. if (auto* peer = main->getPeer())
  14681. for (auto* attached : lynx::nativechild::attachedChildren (peer->getNativeHandle()))
  14682. if (auto* f = in (*attached))
  14683. return f;
  14684. return nullptr;
  14685. }
  14686. // a click (press and release) at `local` in `c`, through the native window it is in
  14687. juce::String lastHit;
  14688. void click (juce::Component& c, juce::Point<int> local)
  14689. {
  14690. auto* peer = c.getPeer();
  14691. if (peer == nullptr)
  14692. return;
  14693. const auto at = peer->getComponent().getLocalPoint (&c, local.toFloat());
  14694. lastHit = describe (peer->getComponent().getComponentAt (at.roundToInt()));
  14695. line (" click at " + local.toString() + " in " + describe (&c).upToFirstOccurrenceOf (" < ", false, false) + " -> " + lastHit);
  14696. const auto now = juce::Time::currentTimeMillis();
  14697. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, now);
  14698. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  14699. }
  14700. void click (juce::Component& c) { click (c, c.getLocalBounds().getCentre()); }
  14701. // Space where the system sends it: the native window of the focused component (else the main one)
  14702. bool space()
  14703. {
  14704. // Windows: posted to the window with the system's focus, as a real key goes (the system's own routing)
  14705. if (lynx::nativechild::pressSpaceForTest (main->getWindowHandle()))
  14706. return true;
  14707. auto* focused = juce::Component::getCurrentlyFocusedComponent();
  14708. auto* peer = focused != nullptr && focused->getPeer() != nullptr ? focused->getPeer() : main->getPeer();
  14709. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  14710. }
  14711. void spacePlays (const juce::String& after)
  14712. {
  14713. line (" keys at: " + describe (juce::Component::getCurrentlyFocusedComponent()));
  14714. auto& transport = engine->getTransport();
  14715. if (transport.playing.load())
  14716. engine->stop();
  14717. space();
  14718. check ("Space plays after " + after, transport.playing.load());
  14719. engine->stop();
  14720. }
  14721. void timerCallback() override
  14722. {
  14723. auto* simple = ui->getSimpleWorkflowForSnapshot();
  14724. auto& playlist = ui->getPlaylistForSnapshot();
  14725. switch (stepIndex++)
  14726. {
  14727. case 0:
  14728. ui->setLayoutStyle (lynx::layoutstyle::Style::simple);
  14729. ui->grabKeyboardFocus();
  14730. break;
  14731. case 1:
  14732. check ("the Simple workflow is up", simple != nullptr);
  14733. if (simple == nullptr)
  14734. return finish();
  14735. spacePlays ("the layout came up");
  14736. simple->showWelcome();
  14737. break;
  14738. case 2:
  14739. if (auto* demo = find ("tour.welcome.demo"))
  14740. click (*demo); // Welcome › Open a demo song: the Start from list
  14741. else
  14742. check ("Welcome > Open a demo song found", false);
  14743. break;
  14744. case 3:
  14745. {
  14746. if (! simple->isStartFromShowing()) // (X11: a child window just mapped may miss the first click)
  14747. if (auto* demo = find ("tour.welcome.demo"))
  14748. {
  14749. line (" the first click was not taken: once more");
  14750. click (*demo);
  14751. }
  14752. check ("Start from is up", simple->isStartFromShowing());
  14753. if (auto* start = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot()))
  14754. check ("a demo song opens from it", start->openForSnapshot (1));
  14755. break;
  14756. }
  14757. case 4:
  14758. check ("Start from closed with the demo open", ! simple->isStartFromShowing() && ! engine->getSong().playlist.empty());
  14759. spacePlays ("a demo opened from Welcome > Start from");
  14760. instrumentTrack = [] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  14761. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  14762. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  14763. return t;
  14764. return 0;
  14765. } (engine->getSong());
  14766. line ("instrument track: " + juce::String (instrumentTrack));
  14767. playlist.selectTrack (instrumentTrack);
  14768. simple->trackSelected (instrumentTrack);
  14769. break;
  14770. case 5:
  14771. if (auto* dock = simple->dockForSnapshot(); dock != nullptr && dock->isShowing())
  14772. {
  14773. click (*dock, { dock->getWidth() - 6, dock->getHeight() - 6 }); // (its empty corner)
  14774. spacePlays ("a click in the dock");
  14775. }
  14776. else
  14777. check ("the dock shows", false);
  14778. break;
  14779. case 6:
  14780. if (auto* tab = find ("simple.dock.keyboard"))
  14781. {
  14782. click (*tab);
  14783. spacePlays ("a click on a dock tab (Keyboard)");
  14784. }
  14785. if (auto* tab = find ("simple.dock.editor"))
  14786. {
  14787. click (*tab);
  14788. spacePlays ("a click on a dock tab (Editor)");
  14789. }
  14790. break;
  14791. case 7:
  14792. if (auto* lyrics = find ("simple.lyrics"))
  14793. {
  14794. click (*lyrics);
  14795. spacePlays ("a click on the Lyrics button");
  14796. }
  14797. else
  14798. check ("the Lyrics button found", false);
  14799. break;
  14800. case 8:
  14801. {
  14802. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  14803. click (playlist, { juce::jmax (4, playlist.headerWidth / 2), lane.getCentreY() });
  14804. spacePlays ("a click on a track header");
  14805. click (playlist, lane.getCentre() + juce::Point<int> (40, 0));
  14806. spacePlays ("a click in the Playlist grid");
  14807. break;
  14808. }
  14809. case 9:
  14810. {
  14811. // a text field the user clicks into keeps its typing keys; a click outside gives Space back
  14812. // a dock knob clicked keeps the arrow keys, and Space still plays from it
  14813. for (auto tab : { lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::instrument })
  14814. {
  14815. juce::Component* knob = nullptr;
  14816. std::function<void (juce::Component&)> seek = [&] (juce::Component& c) {
  14817. if (knob == nullptr && c.isShowing() && (bool) c.getProperties().getWithDefault ("lynxClickKeepsKeys", false))
  14818. knob = &c;
  14819. for (auto* child : c.getChildren())
  14820. seek (*child);
  14821. };
  14822. if (auto* dock = simple->dockForSnapshot())
  14823. {
  14824. dock->setTab (tab);
  14825. seek (*dock);
  14826. }
  14827. if (knob != nullptr)
  14828. {
  14829. click (*knob);
  14830. spacePlays ("a click on a dock knob");
  14831. break;
  14832. }
  14833. }
  14834. if (auto* dock = simple->dockForSnapshot())
  14835. dock->setTab (lynx::SimpleDock::Tab::instrument);
  14836. juce::TextEditor* field = nullptr;
  14837. std::function<void (juce::Component&)> look = [&] (juce::Component& c) {
  14838. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && field == nullptr)
  14839. field = t;
  14840. for (auto* child : c.getChildren())
  14841. look (*child);
  14842. };
  14843. if (auto* dock = simple->dockForSnapshot())
  14844. look (*dock);
  14845. line ("text field in the dock found=" + juce::String ((int) (field != nullptr)));
  14846. if (field != nullptr)
  14847. {
  14848. click (*field);
  14849. const auto before = field->getText();
  14850. space();
  14851. check ("Space types into the text field the user clicked", field->getText() != before && ! engine->getTransport().playing.load());
  14852. engine->stop();
  14853. field->clear();
  14854. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  14855. click (playlist, lane.getCentre() + juce::Point<int> (60, 0));
  14856. spacePlays ("a click in the grid after typing");
  14857. }
  14858. // H1: the first-song tour's card in front of the native panels, taking no keys (started on the demo
  14859. // as it is: Help's question about a new project is a dialog)
  14860. if (auto* tour = simple->tourForSnapshot())
  14861. tour->start();
  14862. break;
  14863. }
  14864. case 10:
  14865. {
  14866. auto* tour = simple->tourForSnapshot();
  14867. auto* card = tour != nullptr ? tour->cardForSnapshot() : nullptr;
  14868. check ("the tour runs", tour != nullptr && tour->isRunning() && card != nullptr && card->isVisible());
  14869. if (card == nullptr)
  14870. return finish();
  14871. auto& frame = ui->workspaceForTest().getFrame (lynx::workspace::Panel::playlist);
  14872. const auto native = lynx::nativechild::dockingEnabled() && lynx::nativechild::isAttached (frame);
  14873. line ("playlist native child window=" + juce::String ((int) native) + ", tour card native child window="
  14874. + juce::String ((int) lynx::nativechild::isAttached (*card)));
  14875. if (native)
  14876. {
  14877. check ("the tour card is a native child window of the main window (not under the panels)", lynx::nativechild::isAttached (*card));
  14878. #if JUCE_WINDOWS
  14879. check ("the tour card is above the Playlist's native window", lynx::nativechild::isAbove (card->getWindowHandle(), frame.getWindowHandle()));
  14880. juce::Component* layer = nullptr;
  14881. for (auto* c : lynx::nativechild::attachedChildren (main->getPeer()->getNativeHandle()))
  14882. if (c != nullptr && c->getComponentID() == "tour.layer")
  14883. layer = c;
  14884. check ("the ring's layer is above the Playlist too", layer != nullptr && lynx::nativechild::isAbove (layer->getWindowHandle(), frame.getWindowHandle()));
  14885. check ("the ring's layer lets clicks through to the Playlist",
  14886. layer != nullptr && lynx::nativechild::windowAt (*layer, layer->getLocalBounds().getCentre()) != layer->getWindowHandle());
  14887. #endif
  14888. }
  14889. check ("the tour card took no keys", ! card->hasKeyboardFocus (true));
  14890. spacePlays ("the tour came up");
  14891. if (auto* next = card->findChildWithID ("tour.next"); next != nullptr && next->isShowing())
  14892. {
  14893. click (*next);
  14894. check ("a click on the card took no keys", ! card->hasKeyboardFocus (true));
  14895. spacePlays ("a click on the tour card");
  14896. }
  14897. finish();
  14898. break;
  14899. }
  14900. default:
  14901. break;
  14902. }
  14903. }
  14904. void finish()
  14905. {
  14906. line (ok ? "result=OK" : "result=FAILED");
  14907. stopTimer();
  14908. done();
  14909. }
  14910. };
  14911. auto* test = new KeyTest();
  14912. test->reportPath = reportPath;
  14913. startFocusTestWindow (*test);
  14914. // Windows: kept above other apps' windows for its few seconds (JUCE takes a button-down only where the system finds
  14915. // its window under the point, and the test clicks through LYNX's own peers, not the system's input)
  14916. #if JUCE_WINDOWS
  14917. test->main->setAlwaysOnTop (true); // (Linux: JUCE makes the X11 window again for it; the private X server has no other windows)
  14918. #endif
  14919. test->startTimer (700);
  14920. }
  14921. template <typename Test>
  14922. void startFocusTestWindow (Test& t)
  14923. {
  14924. auto* test = &t;
  14925. test->engine = std::make_unique<lynx::AudioEngine> (false);
  14926. test->main = std::make_unique<juce::DocumentWindow> ("LYNX focus test", lynx::theme::window, juce::DocumentWindow::allButtons);
  14927. test->main->setUsingNativeTitleBar (true);
  14928. test->ui = new lynx::MainComponent (*test->engine, false);
  14929. test->main->setContentOwned (test->ui, true);
  14930. test->main->setResizable (true, true);
  14931. test->main->centreWithSize (1280, 760);
  14932. test->main->setVisible (true);
  14933. lynx::setMainWindowForOwnership (test->main.get());
  14934. test->done = [this, test] {
  14935. setApplicationReturnValue (test->ok ? 0 : 1);
  14936. juce::MessageManager::callAsync ([this, test] {
  14937. lynx::setMainWindowForOwnership (nullptr);
  14938. test->main = nullptr;
  14939. delete test;
  14940. quit();
  14941. });
  14942. };
  14943. }
  14944. void runWindowTest (const juce::String& reportPath)
  14945. {
  14946. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  14947. struct WindowTest final : juce::Timer
  14948. {
  14949. juce::String reportPath, report;
  14950. bool ok = true;
  14951. int stepIndex = 0;
  14952. std::unique_ptr<lynx::AudioEngine> engine;
  14953. lynx::MainComponent* ui = nullptr;
  14954. std::unique_ptr<juce::DocumentWindow> main, pluginLike;
  14955. juce::TextEditor* pluginField = nullptr;
  14956. std::unique_ptr<juce::AlertWindow> nameDialog;
  14957. std::function<void()> done;
  14958. void line (const juce::String& text)
  14959. {
  14960. report << text << "\n";
  14961. juce::File (reportPath).replaceWithText (report);
  14962. }
  14963. void check (const juce::String& what, bool passed)
  14964. {
  14965. line ((passed ? "ok " : "FAIL ") + what);
  14966. ok = ok && passed;
  14967. }
  14968. bool isAbove (juce::Component* w) { return w != nullptr && lynx::isAboveMainWindow (*w); }
  14969. bool focusIn (juce::Component* w)
  14970. {
  14971. auto* f = juce::Component::getCurrentlyFocusedComponent();
  14972. return w != nullptr && f != nullptr && (f == w || w->isParentOf (f));
  14973. }
  14974. void timerCallback() override
  14975. {
  14976. switch (stepIndex++)
  14977. {
  14978. case 0:
  14979. line ("foreground=" + juce::String (juce::Process::isForegroundProcess() ? 1 : 0));
  14980. ui->openQuickAddForTest();
  14981. break;
  14982. case 1:
  14983. {
  14984. auto* w = lynx::findToolWindow ("quickadd");
  14985. check ("quick-add palette open", w != nullptr);
  14986. check ("quick-add palette active", w != nullptr && w->isActiveWindow());
  14987. check ("quick-add palette owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  14988. check ("quick-add palette above the main window", isAbove (w));
  14989. auto* f = juce::Component::getCurrentlyFocusedComponent();
  14990. check ("quick-add search box has the keyboard focus", focusIn (w) && dynamic_cast<juce::TextEditor*> (f) != nullptr && f->hasKeyboardFocus (false) && w->isActiveWindow());
  14991. lynx::closeAllToolWindows();
  14992. lynx::openAudioEditor (*engine);
  14993. break;
  14994. }
  14995. case 2:
  14996. {
  14997. auto* w = lynx::findToolWindow ("audioeditor");
  14998. check ("audio editor open", w != nullptr);
  14999. check ("audio editor active", w != nullptr && w->isActiveWindow());
  15000. check ("audio editor owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  15001. check ("audio editor above the main window", isAbove (w));
  15002. lynx::forceForegroundForTest (*main); // the user clicks the main window
  15003. break;
  15004. }
  15005. case 3:
  15006. {
  15007. auto* w = lynx::findToolWindow ("audioeditor");
  15008. check ("audio editor stays above the main window after clicking it", isAbove (w));
  15009. lynx::closeAllToolWindows();
  15010. // a plugin editor's window: its own controls keep the keyboard focus
  15011. pluginLike = std::make_unique<juce::DocumentWindow> ("Plugin", juce::Colours::black, juce::DocumentWindow::closeButton);
  15012. pluginLike->setUsingNativeTitleBar (true);
  15013. auto* field = new juce::TextEditor();
  15014. field->setSize (300, 120);
  15015. pluginLike->setContentOwned (field, true);
  15016. pluginLike->centreWithSize (300, 120);
  15017. pluginLike->setVisible (true);
  15018. lynx::keepAboveMainWindow (*pluginLike);
  15019. pluginLike->toFront (true);
  15020. field->grabKeyboardFocus();
  15021. pluginField = field;
  15022. break;
  15023. }
  15024. case 4:
  15025. check ("plugin window active", pluginLike->isActiveWindow());
  15026. check ("plugin window keeps the keyboard focus", pluginField->hasKeyboardFocus (false) && pluginLike->isActiveWindow());
  15027. check ("plugin window above the main window", isAbove (pluginLike.get()));
  15028. pluginLike = nullptr;
  15029. lynx::forceForegroundForTest (*main);
  15030. juce::Component::unfocusAllComponents();
  15031. break;
  15032. case 5:
  15033. check ("main window takes the keyboard focus back when it is active", ui->hasKeyboardFocus (true));
  15034. // round 165q: a name dialog (F4's next empty pattern, Rename and color...) opens ready to type
  15035. nameDialog = lynx::makeNameAndColourDialog ("Rename pattern", "Pattern 2", 0xff808080u);
  15036. nameDialog->enterModalState (true, nullptr, false);
  15037. lynx::keepAboveMainWindow (*nameDialog);
  15038. break;
  15039. case 6:
  15040. {
  15041. auto* f = juce::Component::getCurrentlyFocusedComponent();
  15042. auto* field = dynamic_cast<juce::TextEditor*> (f);
  15043. check ("name dialog: its text field has the keyboard focus", field != nullptr && focusIn (nameDialog.get()));
  15044. if (field != nullptr)
  15045. field->keyPressed (juce::KeyPress ('x', {}, 'x'));
  15046. check ("name dialog: typing replaces the name", nameDialog->getTextEditorContents ("name") == "x");
  15047. nameDialog->exitModalState (0);
  15048. nameDialog = nullptr;
  15049. line (ok ? "result=OK" : "result=FAILED");
  15050. stopTimer();
  15051. done();
  15052. break;
  15053. }
  15054. default:
  15055. break;
  15056. }
  15057. }
  15058. };
  15059. auto* test = new WindowTest();
  15060. test->reportPath = reportPath;
  15061. test->engine = std::make_unique<lynx::AudioEngine> (false);
  15062. test->main = std::make_unique<juce::DocumentWindow> ("LYNX window test", lynx::theme::window, juce::DocumentWindow::allButtons);
  15063. test->main->setUsingNativeTitleBar (true);
  15064. test->ui = new lynx::MainComponent (*test->engine, false);
  15065. test->main->setContentOwned (test->ui, true);
  15066. test->main->setResizable (true, true);
  15067. test->main->centreWithSize (1280, 760);
  15068. test->main->setVisible (true);
  15069. lynx::setMainWindowForOwnership (test->main.get());
  15070. lynx::forceForegroundForTest (*test->main);
  15071. test->main->toFront (true);
  15072. test->done = [this, test] {
  15073. setApplicationReturnValue (test->ok ? 0 : 1);
  15074. juce::MessageManager::callAsync ([this, test] {
  15075. lynx::closeAllToolWindows();
  15076. lynx::setMainWindowForOwnership (nullptr);
  15077. test->main = nullptr;
  15078. delete test;
  15079. quit();
  15080. });
  15081. };
  15082. test->startTimer (1500);
  15083. }
  15084. // --minimizeclicktest (issue #188): see the option. The main window holds a component that counts its mouse-downs.
  15085. void runMinimizeClickTest (const juce::String& reportPath)
  15086. {
  15087. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15088. struct ClickPad final : juce::Component
  15089. {
  15090. int downs = 0;
  15091. void paint (juce::Graphics& g) override { g.fillAll (juce::Colours::darkslategrey); }
  15092. void mouseDown (const juce::MouseEvent&) override { ++downs; }
  15093. };
  15094. struct MinimizeTest final : juce::Timer
  15095. {
  15096. juce::String reportPath, report;
  15097. bool ok = true;
  15098. int stepIndex = 0, waits = 0;
  15099. std::unique_ptr<juce::DocumentWindow> main;
  15100. ClickPad* pad = nullptr;
  15101. juce::DocumentWindow* tool = nullptr;
  15102. juce::Point<int> inside, outside; // screen points: where the tool window is, and beside it
  15103. std::function<void()> done;
  15104. void line (const juce::String& text)
  15105. {
  15106. report << text << "\n";
  15107. juce::File (reportPath).replaceWithText (report);
  15108. }
  15109. void check (const juce::String& what, bool passed)
  15110. {
  15111. line ((passed ? "ok " : "FAIL ") + what);
  15112. ok = ok && passed;
  15113. }
  15114. // a left click at a screen point through the main window's peer: the path an X ButtonPress takes
  15115. bool clickReachesPad (juce::Point<int> screen)
  15116. {
  15117. auto* peer = main->getPeer();
  15118. if (peer == nullptr)
  15119. return false;
  15120. const auto before = pad->downs;
  15121. const auto local = peer->globalToLocal (screen.toFloat());
  15122. const auto now = juce::Time::currentTimeMillis();
  15123. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier),
  15124. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation, now);
  15125. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, juce::ModifierKeys(),
  15126. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation, now + 1);
  15127. return pad->downs == before + 1;
  15128. }
  15129. bool toolMinimised() const { return tool != nullptr && tool->getPeer() != nullptr && tool->getPeer()->isMinimised(); }
  15130. void timerCallback() override
  15131. {
  15132. switch (stepIndex)
  15133. {
  15134. case 0:
  15135. {
  15136. auto content = std::make_unique<juce::Component>();
  15137. content->setSize (420, 300);
  15138. tool = lynx::openToolWindow (std::move (content), "Tap tempo (test)", "minimizetest");
  15139. ++stepIndex;
  15140. return;
  15141. }
  15142. case 1:
  15143. {
  15144. check ("tool window open", tool != nullptr && tool->isShowing());
  15145. if (tool == nullptr)
  15146. break;
  15147. const auto r = tool->getScreenBounds();
  15148. inside = r.getCentre();
  15149. outside = { main->getScreenBounds().getX() + 40, main->getScreenBounds().getBottom() - 40 };
  15150. line ("main " + main->getScreenBounds().toString() + " tool " + r.toString());
  15151. lynx::matchWindowOrderToScreen();
  15152. check ("a click beside the tool window reaches the main window", clickReachesPad (outside));
  15153. check ("a click on the shown tool window does not reach the main window", ! clickReachesPad (inside));
  15154. tool->setMinimised (true);
  15155. ++stepIndex;
  15156. return;
  15157. }
  15158. case 2:
  15159. if (! toolMinimised() && ++waits < 20)
  15160. return;
  15161. check ("the window manager minimised the tool window", toolMinimised());
  15162. check ("the tool window stays visible for JUCE (as in the report)", tool->isVisible());
  15163. main->toFront (true); // a click on the main window: LYNX puts its secondary windows back above it in JUCE's list
  15164. lynx::matchWindowOrderToScreen();
  15165. ++stepIndex;
  15166. return;
  15167. case 3:
  15168. check ("a click where the minimised tool window was reaches the main window", clickReachesPad (inside));
  15169. check ("a click beside it still reaches the main window", clickReachesPad (outside));
  15170. tool->setMinimised (false);
  15171. waits = 0;
  15172. ++stepIndex;
  15173. return;
  15174. case 4:
  15175. if (toolMinimised() && ++waits < 20)
  15176. return;
  15177. tool->toFront (false);
  15178. lynx::matchWindowOrderToScreen();
  15179. ++stepIndex;
  15180. return;
  15181. case 5:
  15182. check ("the tool window is back", ! toolMinimised());
  15183. check ("a click on the restored tool window does not reach the main window", ! clickReachesPad (inside));
  15184. break;
  15185. default:
  15186. return;
  15187. }
  15188. line (ok ? "result=OK" : "result=FAILED");
  15189. stopTimer();
  15190. done();
  15191. }
  15192. };
  15193. auto* test = new MinimizeTest();
  15194. test->reportPath = reportPath;
  15195. test->main = std::make_unique<juce::DocumentWindow> ("LYNX minimise test", lynx::theme::window, juce::DocumentWindow::allButtons);
  15196. test->main->setUsingNativeTitleBar (true);
  15197. test->pad = new ClickPad();
  15198. test->pad->setSize (1200, 760);
  15199. test->main->setContentOwned (test->pad, true);
  15200. test->main->setTopLeftPosition (60, 60);
  15201. test->main->setVisible (true);
  15202. lynx::setMainWindowForOwnership (test->main.get());
  15203. test->main->toFront (true);
  15204. test->done = [this, test] {
  15205. setApplicationReturnValue (test->ok ? 0 : 1);
  15206. juce::MessageManager::callAsync ([this, test] {
  15207. lynx::closeAllToolWindows();
  15208. lynx::setMainWindowForOwnership (nullptr);
  15209. test->main = nullptr;
  15210. delete test;
  15211. quit();
  15212. });
  15213. };
  15214. test->startTimer (700);
  15215. }
  15216. // LYNX.exe --plugintest plugin.vst3 report.txt ["name"]: loads the plugin (or the one named in a shell), plays notes if it is an
  15217. // instrument (and runs audio through it if it is an effect) and measures the audio.
  15218. // Round 190fw: an instrument plugin file on channel 5 of an offline engine (Image-Line's "FL Studio VSTi", which
  15219. // runs FL Studio inside it). Without a project: four chords at 137 BPM, rendered (notes.wav), the plugin's state
  15220. // saved in <folder>/vstitest.lynx. With a project (one saved by LYNX with the plugin on a channel, e.g. after its
  15221. // window was used): that project. Then: the project loaded back from the file renders the same (reload.wav) and
  15222. // gives the same state back; the project's own notes removed, rendered at 100 and 150 BPM (tempo-100/150.wav), the
  15223. // onsets of what the plugin plays by itself must follow the host tempo; and the outputs the plugin offers.
  15224. void runVstiTest (const juce::String& pluginPath, const juce::String& folderPath, const juce::String& projectPath)
  15225. {
  15226. juce::String report;
  15227. auto ok = true;
  15228. const juce::File folder (folderPath);
  15229. folder.createDirectory();
  15230. const auto check = [&] (const juce::String& name, bool passed) {
  15231. report << name << "=" << (passed ? "OK" : "FAILED") << "\n";
  15232. ok = ok && passed;
  15233. };
  15234. struct Take
  15235. {
  15236. float peak = 0.0f;
  15237. std::vector<float> left;
  15238. };
  15239. // renders `song` with the plugin file known to the engine's host; `wav` (in the folder) gets the audio
  15240. const auto render = [&] (const lynx::Song& song, double seconds, const juce::String& wav, std::function<void (lynx::AudioEngine&)> after = {}) {
  15241. Take take;
  15242. lynx::AudioEngine engine (false);
  15243. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  15244. engine.setSong (song);
  15245. const auto file = folder.getChildFile (wav);
  15246. file.deleteFile();
  15247. std::unique_ptr<juce::AudioFormatWriter> writer;
  15248. if (auto stream = file.createOutputStream())
  15249. {
  15250. juce::WavAudioFormat format;
  15251. writer.reset (format.createWriterFor (stream.get(), 48000.0, 2, 24, {}, 0));
  15252. if (writer != nullptr)
  15253. stream.release();
  15254. }
  15255. lynx::AudioEngine::RenderOptions o;
  15256. o.seconds = seconds;
  15257. o.sampleRate = 48000.0;
  15258. o.output = writer.get();
  15259. o.capture = [&take] (const float* l, const float*, int n) { take.left.insert (take.left.end(), l, l + n); };
  15260. take.peak = engine.renderOffline (o);
  15261. writer.reset();
  15262. if (after)
  15263. after (engine);
  15264. return take;
  15265. };
  15266. // the channel that holds the plugin
  15267. const auto pluginChannel = [&] (const lynx::Song& song) {
  15268. for (std::size_t c = 0; c < song.channels.size(); ++c)
  15269. if (song.channels[c].instrument == lynx::InstrumentKind::plugin
  15270. && juce::String (song.channels[c].plugin.name).containsIgnoreCase (juce::File (pluginPath).getFileNameWithoutExtension().upToFirstOccurrenceOf (" (", false, false)))
  15271. return (int) c;
  15272. return -1;
  15273. };
  15274. lynx::Song song;
  15275. const auto saved = folder.getChildFile ("vstitest.lynx");
  15276. if (projectPath.isEmpty())
  15277. {
  15278. lynx::AudioEngine scanner (false);
  15279. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  15280. std::optional<juce::PluginDescription> type;
  15281. for (const auto& t : scanner.getPluginHost().getKnownPlugins().getTypes())
  15282. if (t.isInstrument && juce::File (t.fileOrIdentifier) == juce::File (pluginPath))
  15283. type = t;
  15284. check ("instrument_found", type.has_value());
  15285. if (! type)
  15286. {
  15287. juce::File (folder.getChildFile ("report.txt")).replaceWithText (report + "result=FAILED\n");
  15288. setApplicationReturnValue (1);
  15289. quit();
  15290. return;
  15291. }
  15292. report << "plugin=" << type->name << " (" << type->manufacturerName << ") outputs=" << type->numOutputChannels << "\n";
  15293. song = lynx::Song::makeDefault();
  15294. song.bpm = 137.0;
  15295. auto& c = song.channels[4];
  15296. c.instrument = lynx::InstrumentKind::plugin;
  15297. c.plugin = {};
  15298. c.plugin.id = type->createIdentifierString().toStdString();
  15299. c.plugin.name = type->name.toStdString();
  15300. c.name = type->name.toStdString();
  15301. c.volume = 1.0f;
  15302. for (std::size_t k = 0; k < song.channels.size(); ++k)
  15303. song.channels[k].muted = k != 4;
  15304. song.patterns[0].notes.clear();
  15305. for (int beat = 0; beat < 8; ++beat) // a chord per beat, two bars
  15306. for (int key : { 60, 64, 67 })
  15307. song.patterns[0].notes.push_back ({ (std::int64_t) beat * lynx::ppq, lynx::ppq / 2, 4, key + (beat / 4) * 5, 0.9f });
  15308. song.patterns[0].sortNotes();
  15309. const auto notes = render (song, 4.0, "notes.wav", [&song] (lynx::AudioEngine& engine) {
  15310. engine.capturePluginStates();
  15311. song = engine.getSong();
  15312. });
  15313. report << "notes_peak=" << notes.peak << "\n";
  15314. check ("notes_play", notes.peak > 0.001f && notes.peak < 10.0f);
  15315. juce::String error;
  15316. check ("project_saved", lynx::ProjectFile::save (song, saved, error));
  15317. }
  15318. else
  15319. {
  15320. juce::String error;
  15321. const auto loaded = lynx::ProjectFile::load (juce::File (projectPath), error);
  15322. check ("project_loaded", loaded.has_value());
  15323. if (loaded)
  15324. song = *loaded;
  15325. juce::File (projectPath).copyFileTo (saved);
  15326. }
  15327. const auto channel = pluginChannel (song);
  15328. check ("plugin_channel", channel >= 0);
  15329. if (channel >= 0)
  15330. {
  15331. const auto& plugin = song.channels[(std::size_t) channel].plugin;
  15332. juce::MemoryBlock state;
  15333. state.fromBase64Encoding (juce::String (plugin.state));
  15334. report << "channel=" << channel + 1 << " state_bytes=" << (int) state.getSize() << "\n";
  15335. check ("state_saved", state.getSize() > 0);
  15336. // the project read back from the file: the same sound, and the same state handed back
  15337. juce::String error;
  15338. const auto again = lynx::ProjectFile::load (saved, error);
  15339. check ("project_reloaded", again.has_value());
  15340. if (again)
  15341. {
  15342. std::string stateBack;
  15343. const auto first = render (*again, 4.0, "reload-a.wav");
  15344. const auto second = render (*again, 4.0, "reload-b.wav", [&] (lynx::AudioEngine& engine) {
  15345. engine.capturePluginStates();
  15346. stateBack = engine.getSong().channels[(std::size_t) channel].plugin.state;
  15347. });
  15348. // two loads of the same project: the same audio (sample for sample, or within -60 dB for a plugin
  15349. // with free-running modulation)
  15350. double energy = 0.0, difference = 0.0;
  15351. const auto n = std::min (first.left.size(), second.left.size());
  15352. for (std::size_t k = 0; k < n; ++k)
  15353. {
  15354. energy += (double) first.left[k] * first.left[k];
  15355. difference += ((double) first.left[k] - second.left[k]) * ((double) first.left[k] - second.left[k]);
  15356. }
  15357. const auto ratioDb = energy > 0.0 ? 10.0 * std::log10 (std::max (difference, 1e-30) / energy) : 0.0;
  15358. report << "reload_peak=" << first.peak << " reload_difference_db=" << juce::String (ratioDb, 1) << "\n";
  15359. check ("reload_plays", first.peak > 0.001f);
  15360. check ("reload_same_sound", energy > 0.0 && ratioDb < -60.0);
  15361. juce::MemoryBlock back;
  15362. back.fromBase64Encoding (juce::String (stateBack));
  15363. report << "state_back_bytes=" << (int) back.getSize() << " identical=" << (int) (back == state) << "\n";
  15364. check ("state_handed_back", back.getSize() > 0);
  15365. }
  15366. // the host tempo: what the plugin plays by itself (FL Studio's own patterns inside FL Studio VSTi) at two
  15367. // tempos, without the project's notes
  15368. auto self = song;
  15369. for (std::size_t k = 0; k < self.channels.size(); ++k)
  15370. self.channels[k].muted = (int) k != channel;
  15371. for (auto& pattern : self.patterns)
  15372. pattern.notes.erase (std::remove_if (pattern.notes.begin(), pattern.notes.end(), [channel] (const lynx::Note& n) { return n.channel == channel; }),
  15373. pattern.notes.end());
  15374. const auto onsets = [] (const std::vector<float>& x) {
  15375. // envelope rises over a threshold (10 ms hold-off of 60 ms): the times in seconds
  15376. std::vector<double> at;
  15377. float peak = 0.0f;
  15378. for (const auto v : x)
  15379. peak = std::max (peak, std::abs (v));
  15380. const auto threshold = peak * 0.3f;
  15381. auto quietFor = 1 << 30;
  15382. for (std::size_t k = 0; k < x.size(); ++k)
  15383. {
  15384. const auto loud = std::abs (x[k]) >= threshold;
  15385. if (loud && quietFor >= 48000 * 60 / 1000)
  15386. at.push_back ((double) k / 48000.0);
  15387. quietFor = loud ? 0 : quietFor + 1;
  15388. }
  15389. return at;
  15390. };
  15391. const auto medianGap = [] (const std::vector<double>& at) {
  15392. std::vector<double> gaps;
  15393. for (std::size_t k = 1; k < at.size(); ++k)
  15394. gaps.push_back (at[k] - at[k - 1]);
  15395. if (gaps.empty())
  15396. return 0.0;
  15397. std::sort (gaps.begin(), gaps.end());
  15398. return gaps[gaps.size() / 2];
  15399. };
  15400. self.bpm = 100.0;
  15401. const auto slow = render (self, 6.0, "tempo-100.wav");
  15402. self.bpm = 150.0;
  15403. const auto fast = render (self, 6.0, "tempo-150.wav");
  15404. const auto gapSlow = medianGap (onsets (slow.left)), gapFast = medianGap (onsets (fast.left));
  15405. report << "self_peak_100=" << slow.peak << " self_peak_150=" << fast.peak << " onsets_100=" << (int) onsets (slow.left).size()
  15406. << " onsets_150=" << (int) onsets (fast.left).size() << " gap_100=" << juce::String (gapSlow, 4) << " gap_150="
  15407. << juce::String (gapFast, 4) << "\n";
  15408. if (slow.peak > 0.001f && gapFast > 0.0)
  15409. {
  15410. report << "tempo_ratio=" << juce::String (gapSlow / gapFast, 3) << " (expected 1.5)\n";
  15411. check ("follows_host_tempo", std::abs (gapSlow / gapFast - 1.5) < 0.05);
  15412. }
  15413. else
  15414. report << "tempo: the plugin plays nothing by itself in this project\n";
  15415. // the outputs it offers (FL Studio VSTi (Multi): FL's mixer tracks as separate outputs)
  15416. lynx::AudioEngine engine (false);
  15417. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  15418. engine.setSong (song);
  15419. engine.renderOffline (0.2, 48000.0);
  15420. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (channel)))
  15421. {
  15422. report << "outputs=" << (int) instrument->outputs().size() << ":";
  15423. for (const auto& o : instrument->outputs())
  15424. report << " [" << o.name << "]";
  15425. report << "\n";
  15426. check ("outputs_listed", ! instrument->outputs().empty());
  15427. }
  15428. else
  15429. check ("instrument_loaded", false);
  15430. }
  15431. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  15432. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  15433. folder.getChildFile ("report.txt").replaceWithText (report);
  15434. setApplicationReturnValue (ok ? 0 : 1);
  15435. quit();
  15436. }
  15437. void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only = {})
  15438. {
  15439. juce::String report;
  15440. bool ok = false;
  15441. {
  15442. lynx::AudioEngine offline (false);
  15443. auto& host = offline.getPluginHost();
  15444. const auto added = host.addPluginFile (juce::File (pluginPath));
  15445. report << "plugins_in_file=" << added << "\n";
  15446. juce::PluginDescription instrument, effect;
  15447. bool hasInstrument = false, hasEffect = false;
  15448. for (const auto& type : host.getKnownPlugins().getTypes())
  15449. {
  15450. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  15451. || (only.isNotEmpty() && type.name != only))
  15452. continue;
  15453. report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
  15454. << ") in " << type.fileOrIdentifier << "\n";
  15455. if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
  15456. if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
  15457. }
  15458. auto song = lynx::Song::makeDefault();
  15459. if (hasInstrument)
  15460. {
  15461. auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
  15462. c.instrument = lynx::InstrumentKind::plugin;
  15463. c.plugin.id = instrument.createIdentifierString().toStdString();
  15464. c.plugin.name = instrument.name.toStdString();
  15465. c.volume = 1.0f;
  15466. for (int i = 0; i < 4; ++i) // one chord per beat
  15467. for (int key : { 60, 64, 67 })
  15468. song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
  15469. song.patterns[0].sortNotes();
  15470. }
  15471. if (hasEffect)
  15472. {
  15473. lynx::EffectSlot slot;
  15474. slot.kind = lynx::EffectKind::plugin;
  15475. slot.plugin.id = effect.createIdentifierString().toStdString();
  15476. slot.plugin.name = effect.name.toStdString();
  15477. song.mixer[0].effects.push_back (slot);
  15478. }
  15479. const auto effectSlot = (int) song.mixer[0].effects.size() - 1; // (the default master may hold effects already)
  15480. offline.setSong (song);
  15481. // after a render: the rack (and its plugins) is built when the engine is prepared
  15482. const auto peak = offline.renderOffline (3.0, 48000.0);
  15483. const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
  15484. const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, effectSlot).get());
  15485. report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
  15486. << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
  15487. if (host.getLoadFailures().size() > 0) // why: the host's own message (license, missing file, load failure)
  15488. report << "load_failures=" << host.getLoadFailures().joinIntoString (" | ") << "\n";
  15489. report << "peak=" << peak << "\n";
  15490. // plugins that crashed inside a call, were caught and switched off (round 111)
  15491. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  15492. for (const auto& c : lynx::pluginCrashes())
  15493. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  15494. offline.capturePluginStates();
  15495. const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
  15496. report << "state_bytes_base64=" << (int) stateSize << "\n";
  15497. ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
  15498. && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
  15499. }
  15500. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  15501. juce::File (reportPath).replaceWithText (report);
  15502. setApplicationReturnValue (ok ? 0 : 1);
  15503. quit();
  15504. }
  15505. // Round 190gg (B4): --crashguardtest plugin report.txt thread | ui. "thread": the plugin's own thread faults in its 40th
  15506. // block (Linux / macOS): that thread is parked, LYNX switches the plugin off (as the main window's timer does) and goes
  15507. // on; the other inserts play; Reload brings it back. "ui": the calls the UI makes into a plugin, under the guard: a
  15508. // preset load that crashes (the Plugin window's preset menu path) and making the editor (PluginWindows::open, the CLAP
  15509. // test plugin's "editor-create": a display is needed, e.g. Xvfb); each switches the plugin off, LYNX goes on.
  15510. void runCrashGuardThreadOrUiTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
  15511. {
  15512. juce::String report;
  15513. bool ok = true;
  15514. const auto expect = [&] (const char* name, bool value) {
  15515. report << name << "=" << (value ? 1 : 0) << "\n";
  15516. ok = ok && value;
  15517. };
  15518. const auto setEnv = [] (const char* name, const char* value) {
  15519. #if JUCE_WINDOWS
  15520. _putenv_s (name, value);
  15521. #else
  15522. setenv (name, value, 1);
  15523. #endif
  15524. };
  15525. const auto render = [] (lynx::AudioEngine& engine, double seconds, float* peak) {
  15526. lynx::AudioEngine::RenderOptions o;
  15527. o.seconds = seconds;
  15528. o.sampleRate = 48000.0;
  15529. o.pluginWarmUp = false;
  15530. if (peak != nullptr)
  15531. o.capture = [peak] (const float* l, const float* r, int n) {
  15532. for (int k = 0; k < n; ++k)
  15533. *peak = std::max (*peak, std::max (std::abs (l[k]), std::abs (r[k])));
  15534. };
  15535. return engine.renderOffline (o);
  15536. };
  15537. report << "mode=" << mode << "\nthread_guard=" << (lynx::crashguard::pluginThreadFaultsCaught() ? "on" : "off") << "\n";
  15538. setEnv ("LYNX_TEST_CRASH", mode == "thread" ? "thread" : "");
  15539. setEnv ("LYNX_TEST_CRASH_AFTER", "40");
  15540. const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
  15541. .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  15542. tmp.createDirectory();
  15543. {
  15544. lynx::AudioEngine offline (false);
  15545. auto& host = offline.getPluginHost();
  15546. host.addPluginFile (juce::File (pluginPath));
  15547. juce::PluginDescription effect;
  15548. bool found = false;
  15549. for (const auto& type : host.getKnownPlugins().getTypes())
  15550. if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  15551. {
  15552. effect = type;
  15553. found = true;
  15554. }
  15555. expect ("plugin_found", found);
  15556. auto song = lynx::Song::makeDefault();
  15557. lynx::EffectSlot slot;
  15558. slot.kind = lynx::EffectKind::plugin;
  15559. slot.plugin.id = effect.createIdentifierString().toStdString();
  15560. slot.plugin.name = effect.name.toStdString();
  15561. song.mixer[1].effects.push_back (slot);
  15562. offline.setSong (song);
  15563. const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
  15564. render (offline, 0.05, nullptr);
  15565. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  15566. render (offline, 0.05, nullptr);
  15567. auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  15568. expect ("plugin_loaded", first != nullptr);
  15569. const auto crashesBefore = lynx::pluginCrashCount();
  15570. if (mode == "thread")
  15571. {
  15572. const auto faultsBefore = lynx::crashguard::pluginThreadFaultCount();
  15573. float peak = 0.0f;
  15574. render (offline, 3.0, &peak); // (the plugin starts its faulting thread in its 40th block)
  15575. for (int i = 0; i < 200 && lynx::crashguard::pluginThreadFaultCount() == faultsBefore; ++i)
  15576. juce::Thread::sleep (10);
  15577. const auto faults = lynx::crashguard::pluginThreadFaults();
  15578. expect ("thread_fault_parked", lynx::crashguard::pluginThreadFaultCount() == faultsBefore + 1 && ! faults.empty());
  15579. if (! faults.empty())
  15580. report << "thread_fault=" << faults.back().where << " (" << lynx::crashguard::describe (faults.back().code) << ")\n";
  15581. expect ("not_yet_counted_as_a_call_crash", lynx::pluginCrashCount() == crashesBefore);
  15582. // what the main window's timer does
  15583. // (every instance of that module: the engine may hold more than the slot's, e.g. the offline render's)
  15584. if (first != nullptr)
  15585. report << "slot_file=" << first->getInstance().getPluginDescription().fileOrIdentifier << "\n";
  15586. const auto switched = lynx::switchOffPluginsOfThreadFaults();
  15587. report << "switched_off=" << switched << "\n";
  15588. expect ("plugin_switched_off", switched >= 1 && first != nullptr && first->hasCrashed() && lynx::pluginCrashCount() == crashesBefore + switched);
  15589. expect ("only_once", lynx::switchOffPluginsOfThreadFaults() == 0);
  15590. const auto down = offline.downHostedPlugins();
  15591. expect ("slot_down", down.size() == 1 && down[0] == where);
  15592. float after = 0.0f;
  15593. render (offline, 1.0, &after);
  15594. report << "peak_after=" << after << "\n";
  15595. expect ("audio_after_fault", after > 0.01f);
  15596. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
  15597. float others = 0.0f;
  15598. render (offline, 1.0, &others);
  15599. expect ("other_inserts_play", others > 0.01f);
  15600. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  15601. const auto running = offline.reloadHostedPlugins (down);
  15602. auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  15603. float reloaded = 0.0f;
  15604. render (offline, 1.0, &reloaded);
  15605. expect ("reloaded_plays", running == 1 && again != nullptr && again != first && ! again->hasCrashed() && reloaded > 0.01f);
  15606. }
  15607. else
  15608. {
  15609. // a preset that crashes the plugin (the preset menu's load), saved first from the running plugin
  15610. auto& instance = first->getInstance();
  15611. const auto preset = tmp.getChildFile ("crash.lynxpreset");
  15612. juce::String error;
  15613. expect ("preset_saved", lynx::pluginpresetui::save (instance, preset, "crash", error) && preset.existsAsFile());
  15614. setEnv ("LYNX_TEST_CRASH", "state");
  15615. const auto loaded = lynx::pluginpresetui::load (instance, preset, error);
  15616. setEnv ("LYNX_TEST_CRASH", "");
  15617. report << "preset_error=" << error << "\n";
  15618. expect ("preset_crash_caught", ! loaded && lynx::pluginCrashCount() == crashesBefore + 1 && first->hasCrashed());
  15619. expect ("preset_plugin_down", offline.hostedPluginDown (where) && lynx::pluginInstanceDown (instance));
  15620. expect ("not_called_again", ! lynx::callPluginFromUi (instance, "test", [] {}) && lynx::pluginCrashCount() == crashesBefore + 1);
  15621. float after = 0.0f;
  15622. render (offline, 1.0, &after);
  15623. expect ("audio_after_preset_crash", after > 0.01f);
  15624. // Reload; then its editor crashes as it is made (PluginWindows::open): no window, the plugin is down
  15625. setEnv ("LYNX_TEST_CRASH", "editor-create");
  15626. const auto running = offline.reloadHostedPlugins (offline.downHostedPlugins());
  15627. auto held = offline.getEffect (1, 0);
  15628. auto* again = dynamic_cast<lynx::PluginEffect*> (held.get());
  15629. expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
  15630. if (again != nullptr)
  15631. {
  15632. lynx::PluginWindows::open (held, again->getInstance(), "crash test", {});
  15633. expect ("editor_crash_caught", lynx::pluginCrashCount() == crashesBefore + 2 && again->hasCrashed());
  15634. expect ("no_window", ! lynx::PluginWindows::isOpen (again->getInstance()));
  15635. float editorAfter = 0.0f;
  15636. render (offline, 1.0, &editorAfter);
  15637. expect ("audio_after_editor_crash", editorAfter > 0.01f);
  15638. }
  15639. setEnv ("LYNX_TEST_CRASH", "");
  15640. }
  15641. }
  15642. setEnv ("LYNX_TEST_CRASH", "");
  15643. // LYNX's own faults (also on its own threads) stay crashes (child processes; the selftest runs the same)
  15644. const auto own = faultReportSelfTest();
  15645. report << "own_faults=" << own << "\n";
  15646. ok = ok && ! own.startsWith ("ERROR");
  15647. for (const auto& c : lynx::pluginCrashes())
  15648. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  15649. tmp.deleteRecursively();
  15650. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  15651. juce::File (reportPath).replaceWithText (report);
  15652. setApplicationReturnValue (ok ? 0 : 1);
  15653. quit();
  15654. }
  15655. // LYNX --crashguardtest plugin report.txt [process|memcpy] (round 190dt): see the dispatch in initialise().
  15656. void runCrashGuardTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
  15657. {
  15658. if (mode == "thread" || mode == "ui")
  15659. {
  15660. runCrashGuardThreadOrUiTest (pluginPath, reportPath, mode);
  15661. return;
  15662. }
  15663. juce::String report;
  15664. bool ok = true;
  15665. const auto expect = [&] (const char* name, bool value) {
  15666. report << name << "=" << (value ? 1 : 0) << "\n";
  15667. ok = ok && value;
  15668. };
  15669. const auto setEnv = [] (const char* name, const char* value) {
  15670. #if JUCE_WINDOWS
  15671. _putenv_s (name, value);
  15672. #else
  15673. setenv (name, value, 1);
  15674. #endif
  15675. };
  15676. // renders without the plugin warm-up (its silent blocks would count towards the crash)
  15677. const auto render = [] (lynx::AudioEngine& engine, double seconds, const std::function<void (const float*, const float*, int)>& capture) {
  15678. lynx::AudioEngine::RenderOptions o;
  15679. o.seconds = seconds;
  15680. o.sampleRate = 48000.0;
  15681. o.pluginWarmUp = false;
  15682. o.capture = capture;
  15683. return engine.renderOffline (o);
  15684. };
  15685. const auto peakOf = [] (float& peak) {
  15686. return [&peak] (const float* l, const float* r, int n) {
  15687. for (int k = 0; k < n; ++k)
  15688. peak = std::max (peak, std::max (std::abs (l[k]), std::abs (r[k])));
  15689. };
  15690. };
  15691. report << "guard=" << (lynx::crashguard::pluginFaultsCaught() ? "on" : "off") << "\nmode=" << mode << "\n";
  15692. setEnv ("LYNX_TEST_CRASH", mode == "memcpy" ? "memcpy" : "process");
  15693. setEnv ("LYNX_TEST_CRASH_AFTER", "40");
  15694. const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
  15695. .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  15696. tmp.createDirectory();
  15697. std::optional<lynx::Song> saved;
  15698. std::string savedState;
  15699. {
  15700. lynx::AudioEngine offline (false);
  15701. auto& host = offline.getPluginHost();
  15702. host.addPluginFile (juce::File (pluginPath));
  15703. juce::PluginDescription effect;
  15704. bool found = false;
  15705. for (const auto& type : host.getKnownPlugins().getTypes())
  15706. if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  15707. {
  15708. effect = type;
  15709. found = true;
  15710. }
  15711. expect ("plugin_found", found);
  15712. // the plugin on insert 1 (the kick's); the clap and the hat play on inserts 2 and 3
  15713. auto song = lynx::Song::makeDefault();
  15714. lynx::EffectSlot slot;
  15715. slot.kind = lynx::EffectKind::plugin;
  15716. slot.plugin.id = effect.createIdentifierString().toStdString();
  15717. slot.plugin.name = effect.name.toStdString();
  15718. song.mixer[1].effects.push_back (slot);
  15719. offline.setSong (song);
  15720. const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
  15721. // the rack is published at the engine's rate and an offline render runs at its own (48 kHz) without publishing:
  15722. // one edit after a first render puts the rack (and the plugin) at the render's rate, so later edits keep it
  15723. render (offline, 0.05, {}); // (a few blocks, far from the 40th)
  15724. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  15725. render (offline, 0.05, {});
  15726. auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  15727. expect ("plugin_loaded", first != nullptr);
  15728. offline.capturePluginStates();
  15729. savedState = offline.getSong().mixer[1].effects[0].plugin.state;
  15730. expect ("state_captured", ! savedState.empty());
  15731. // the crash: 3 s, the plugin faults in its 40th block
  15732. const auto crashesBefore = lynx::pluginCrashCount();
  15733. juce::int64 position = 0, crashAt = -1;
  15734. float peakAfter = 0.0f;
  15735. const auto afterPeak = peakOf (peakAfter);
  15736. const auto peak = render (offline, 3.0, [&] (const float* l, const float* r, int n) {
  15737. if (crashAt < 0 && lynx::pluginCrashCount() != crashesBefore)
  15738. crashAt = position;
  15739. else if (crashAt >= 0)
  15740. afterPeak (l, r, n);
  15741. position += n;
  15742. });
  15743. report << "peak=" << peak << "\ncrash_at_sample=" << crashAt << "\npeak_after_crash=" << peakAfter << "\n";
  15744. const auto crashes = lynx::pluginCrashes();
  15745. expect ("crash_caught", lynx::pluginCrashCount() == crashesBefore + 1 && ! crashes.empty() && ! crashes.back().onLoad);
  15746. if (! crashes.empty())
  15747. report << "crash=" << crashes.back().plugin << " (" << lynx::crashguard::describe (crashes.back().code) << ")\n";
  15748. expect ("slot_marked_crashed", first != nullptr && offline.getEffect (1, 0).get() == first && first->hasCrashed());
  15749. const auto down = offline.downHostedPlugins();
  15750. expect ("slot_down", down.size() == 1 && down[0] == where);
  15751. expect ("audio_after_crash", crashAt >= 0 && peakAfter > 0.01f);
  15752. // the other inserts: with the kick (through the crashed slot) silent, the clap and the hat still play
  15753. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
  15754. float othersPeak = 0.0f;
  15755. render (offline, 1.0, peakOf (othersPeak));
  15756. report << "other_inserts_peak=" << othersPeak << "\n";
  15757. expect ("other_inserts_play", othersPeak > 0.01f);
  15758. expect ("nothing_reloads_by_itself", offline.hostedPluginDown (where) && offline.getEffect (1, 0).get() == first);
  15759. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  15760. // the project saves with the settings the plugin had before it crashed, and opens again
  15761. offline.capturePluginStates();
  15762. expect ("state_kept", offline.getSong().mixer[1].effects[0].plugin.state == savedState);
  15763. const auto file = tmp.getChildFile ("crashed.lynx");
  15764. juce::String error;
  15765. expect ("project_saved", lynx::ProjectFile::save (offline.getSong(), file, error) && file.existsAsFile());
  15766. saved = lynx::ProjectFile::load (file, error);
  15767. expect ("project_reopens", saved.has_value() && saved->mixer.size() > 1 && saved->mixer[1].effects.size() == 1
  15768. && saved->mixer[1].effects[0].plugin.state == savedState);
  15769. // Reload (the prompt's button, round 190ao): a new instance; the module's block count is past 40 now
  15770. const auto running = offline.reloadHostedPlugins (down);
  15771. auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  15772. expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
  15773. float reloadedPeak = 0.0f;
  15774. render (offline, 1.0, peakOf (reloadedPeak));
  15775. report << "reloaded_peak=" << reloadedPeak << "\n";
  15776. expect ("reloaded_plays", reloadedPeak > 0.01f && lynx::pluginCrashCount() == crashesBefore + 1 && again != nullptr && ! again->hasCrashed());
  15777. }
  15778. // the saved project opens again with the plugin crashing on its saved settings: left out, the rest plays, the
  15779. // settings stay in the project
  15780. setEnv ("LYNX_TEST_CRASH", "state");
  15781. if (saved.has_value())
  15782. {
  15783. lynx::AudioEngine reopened (false);
  15784. reopened.getPluginHost().addPluginFile (juce::File (pluginPath));
  15785. const auto before = lynx::pluginCrashCount();
  15786. reopened.setSong (*saved);
  15787. float reopenedPeak = 0.0f;
  15788. render (reopened, 1.0, peakOf (reopenedPeak));
  15789. const auto crashes = lynx::pluginCrashes();
  15790. report << "reopened_peak=" << reopenedPeak << "\n";
  15791. if (reopened.getPluginHost().getLoadFailures().size() > 0)
  15792. report << "load_failures=" << reopened.getPluginHost().getLoadFailures().joinIntoString (" | ") << "\n";
  15793. expect ("state_crash_caught", lynx::pluginCrashCount() == before + 1 && ! crashes.empty() && crashes.back().onLoad);
  15794. expect ("state_crash_left_out", dynamic_cast<lynx::PluginEffect*> (reopened.getEffect (1, 0).get()) == nullptr);
  15795. expect ("state_crash_project_plays", reopenedPeak > 0.01f);
  15796. reopened.capturePluginStates();
  15797. expect ("state_crash_settings_kept", reopened.getSong().mixer[1].effects.size() == 1
  15798. && reopened.getSong().mixer[1].effects[0].plugin.state == savedState);
  15799. }
  15800. setEnv ("LYNX_TEST_CRASH", "");
  15801. // LYNX's own faults inside a guarded call stay crashes (child processes; the selftest runs the same)
  15802. const auto own = faultReportSelfTest();
  15803. report << "own_faults=" << own << "\n";
  15804. ok = ok && ! own.startsWith ("ERROR");
  15805. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  15806. for (const auto& c : lynx::pluginCrashes())
  15807. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << (c.onLoad ? ", loading its state" : "") << ")\n";
  15808. tmp.deleteRecursively();
  15809. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  15810. juce::File (reportPath).replaceWithText (report);
  15811. setApplicationReturnValue (ok ? 0 : 1);
  15812. quit();
  15813. }
  15814. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108): a hosted CLAP
  15815. // instrument with the wrapper's MPE switch on gets each note on its own member channel, its fine pitch / Mod X /
  15816. // Mod Y as tuning / brightness / pressure note expressions before the note on, and a sounding note's expression
  15817. // on that note's channel alone. The plugin writes down what it received; no window, no audio device.
  15818. // Round 190hy: see --mpeplaytest190hy. Note A (C4, 1 s): its pitch curve holds 0 for 0.5 s, rises an octave over
  15819. // 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
  15820. // rendered audio's zero crossings (a silent logging plugin: its log shows the expressions instead).
  15821. void runMpePlayTest190hy (const juce::String& pluginPath, const juce::String& reportPath)
  15822. {
  15823. const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  15824. log.deleteFile();
  15825. #if JUCE_WINDOWS
  15826. _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
  15827. #else
  15828. setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
  15829. #endif
  15830. juce::String report;
  15831. auto ok = false;
  15832. const auto wavFile = juce::File (reportPath).withFileExtension ("wav");
  15833. constexpr double rate = 44100.0;
  15834. {
  15835. lynx::AudioEngine offline (false);
  15836. auto& host = offline.getPluginHost();
  15837. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  15838. const auto wanted = juce::File (pluginPath).hasFileExtension ("clap") ? "CLAP" : "VST3";
  15839. std::optional<juce::PluginDescription> type;
  15840. for (const auto& t : host.getKnownPlugins().getTypes())
  15841. if (t.pluginFormatName == wanted && t.isInstrument && ! type)
  15842. type = t;
  15843. report << "format=" << wanted << " found=" << (type ? type->name : juce::String ("none")) << "\n";
  15844. if (type)
  15845. {
  15846. lynx::Song s;
  15847. s.mixer = lynx::Song::defaultMixer (2);
  15848. s.bpm = 120.0;
  15849. lynx::ChannelDef c;
  15850. c.name = type->name.toStdString();
  15851. c.instrument = lynx::InstrumentKind::plugin;
  15852. c.plugin.id = type->createIdentifierString().toStdString();
  15853. c.plugin.name = type->name.toStdString();
  15854. c.plugin.mpe = true;
  15855. c.mixerTrack = 1;
  15856. s.channels.push_back (c);
  15857. s.patterns.emplace_back();
  15858. auto& p = s.patterns[0];
  15859. lynx::Note a;
  15860. a.channel = 0;
  15861. a.key = 60;
  15862. a.length = 2 * lynx::ppq;
  15863. a.velocity = 0.8f;
  15864. lynx::NoteCurves curves;
  15865. curves.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { (float) lynx::ppq, 0.0f }, { 1.5f * (float) lynx::ppq, 1200.0f },
  15866. { 2.0f * (float) lynx::ppq, 1200.0f } };
  15867. a.curves = curves;
  15868. auto b = a;
  15869. b.key = 67;
  15870. b.start = 2 * lynx::ppq;
  15871. b.length = lynx::ppq;
  15872. b.curves.clear();
  15873. p.notes = { a, b };
  15874. p.lengthTicks = 16 * lynx::ppq; // (one pass: the notes play once in the 1.2 s rendered)
  15875. offline.setSong (std::move (s));
  15876. wavFile.deleteFile();
  15877. juce::WavAudioFormat wav;
  15878. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (wavFile.createOutputStream().release(), rate, 2, 24, {}, 0));
  15879. const auto peak = writer != nullptr ? offline.renderOffline (1.6, rate, writer.get()) : 0.0f;
  15880. writer.reset();
  15881. report << "peak=" << peak << "\n";
  15882. ok = writer == nullptr && wavFile.existsAsFile();
  15883. }
  15884. } // (the plugin writes its log, if any, as it is destroyed)
  15885. // the frequency of [from, to) seconds of the left channel from its rising zero crossings
  15886. juce::AudioBuffer<float> audio;
  15887. {
  15888. juce::AudioFormatManager formats;
  15889. formats.registerBasicFormats();
  15890. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (wavFile)); reader != nullptr)
  15891. {
  15892. audio.setSize (1, (int) reader->lengthInSamples);
  15893. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, false);
  15894. }
  15895. }
  15896. const auto frequency = [&audio] (double from, double to) {
  15897. const auto* x = audio.getReadPointer (0);
  15898. const auto n = audio.getNumSamples();
  15899. long first = -1, last = -1;
  15900. auto crossings = 0;
  15901. for (auto i = juce::jmax (1, (int) (from * rate)); i < juce::jmin (n, (int) (to * rate)); ++i)
  15902. if (x[i - 1] <= 0.0f && x[i] > 0.0f)
  15903. {
  15904. if (first < 0)
  15905. first = i;
  15906. else
  15907. ++crossings, last = i;
  15908. }
  15909. return crossings > 0 ? crossings * rate / (double) (last - first) : 0.0;
  15910. };
  15911. if (audio.getNumSamples() > 0 && audio.getMagnitude (0, 0, audio.getNumSamples()) > 0.001f)
  15912. {
  15913. 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);
  15914. report << "a_before_hz=" << before << " a_rising_hz=" << during << " a_after_hz=" << after << " b_hz=" << next << "\n";
  15915. report << "a_after_over_before=" << (before > 0.0 ? after / before : 0.0) << " (an octave: 2)\n";
  15916. report << "b_over_a_before=" << (before > 0.0 ? next / before : 0.0) << " (a fifth: 1.498)\n";
  15917. }
  15918. else
  15919. report << "audio=silent\n";
  15920. if (log.existsAsFile())
  15921. report << "--- plugin log ---\n" << log.loadFileAsString();
  15922. report << "result=" << (ok ? "RENDERED" : "FAILED") << "\n";
  15923. juce::File (reportPath).replaceWithText (report);
  15924. setApplicationReturnValue (ok ? 0 : 1);
  15925. quit();
  15926. }
  15927. void runMpeTest (const juce::String& pluginPath, const juce::String& reportPath)
  15928. {
  15929. const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  15930. log.deleteFile();
  15931. #if JUCE_WINDOWS
  15932. _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
  15933. #else
  15934. setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
  15935. #endif
  15936. juce::String report;
  15937. auto failures = 0;
  15938. {
  15939. lynx::AudioEngine engine (false);
  15940. auto& host = engine.getPluginHost();
  15941. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  15942. std::optional<juce::PluginDescription> clap;
  15943. for (const auto& type : host.getKnownPlugins().getTypes())
  15944. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  15945. clap = type;
  15946. lynx::PluginRef ref;
  15947. if (clap)
  15948. {
  15949. ref.id = clap->createIdentifierString().toStdString();
  15950. ref.name = clap->name.toStdString();
  15951. }
  15952. ref.mpe = true;
  15953. juce::String error;
  15954. auto instrument = clap ? host.makeInstrument (ref, 48000.0, &error) : nullptr;
  15955. report << "instrument_loaded=" << (instrument != nullptr ? "yes" : "no") << (error.isNotEmpty() ? " (" + error + ")" : juce::String()) << "\n";
  15956. if (instrument != nullptr)
  15957. {
  15958. std::vector<float> l (256), r (256);
  15959. auto block = [&] { instrument->render (l.data(), r.data(), 256, 1.0f, 1.0f); };
  15960. block(); // (the zone's setup)
  15961. instrument->setNextNoteFinePitch (30.0f); // +30 cents
  15962. instrument->setNextNoteModulation (0.75f, 1.0f); // timbre 0.75, full pressure
  15963. instrument->noteOn (60, 0.8f);
  15964. instrument->noteOn (64, 0.5f); // a second note: its own channel, centre values
  15965. block();
  15966. instrument->noteExpression (60, (int) lynx::vfx::Prop::pitch, 200.0f, 0.0f);
  15967. instrument->noteExpression (64, (int) lynx::vfx::Prop::modX, 0.25f, 0.0f);
  15968. instrument->noteExpression (60, (int) lynx::vfx::Prop::modY, 0.75f, 0.0f);
  15969. block();
  15970. instrument->noteOff (60);
  15971. instrument->noteOff (64);
  15972. block();
  15973. }
  15974. else
  15975. ++failures;
  15976. } // (the plugin writes its log as it is destroyed)
  15977. struct Line
  15978. {
  15979. juce::String kind;
  15980. int a = 0, b = 0, c = 0, d = 0;
  15981. };
  15982. std::vector<Line> lines;
  15983. for (const auto& text : juce::StringArray::fromLines (log.loadFileAsString()))
  15984. {
  15985. const auto t = juce::StringArray::fromTokens (text, " ", "");
  15986. if (t.size() >= 3)
  15987. 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 });
  15988. }
  15989. report << "plugin_events=" << (int) lines.size() << "\n";
  15990. // the first line at or after `from` that matches (−1 = none); `value` within `tolerance` (thousandths)
  15991. auto find = [&lines] (const juce::String& kind, int a, int b, int value, int tolerance, int from = 0) {
  15992. for (auto i = (std::size_t) from; i < lines.size(); ++i)
  15993. {
  15994. const auto& x = lines[i];
  15995. const auto v = kind == "expr" ? x.d : x.c;
  15996. if (x.kind == kind && x.a == a && x.b == b && std::abs (v - value) <= tolerance)
  15997. return (int) i;
  15998. }
  15999. return -1;
  16000. };
  16001. auto check = [&] (const char* what, bool ok) {
  16002. report << what << "=" << (ok ? "ok" : "FAILED") << "\n";
  16003. failures += ok ? 0 : 1;
  16004. };
  16005. // (CLAP expression ids: 2 tuning in semitones, 5 brightness, 6 pressure; channels 0-based: the first member = 1)
  16006. const auto on60 = find ("on", 1, 60, 800, 5), on64 = find ("on", 2, 64, 500, 5);
  16007. check ("zone_setup_sent", find ("midi", 176, 6, 15, 0) >= 0 && find ("midi", 177, 6, 48, 0) >= 0);
  16008. check ("notes_on_their_own_channels", on60 >= 0 && on64 > on60);
  16009. const auto tune = find ("expr", 2, 1, 300, 3), bright = find ("expr", 5, 1, 756, 4), press = find ("expr", 6, 1, 1000, 1);
  16010. check ("expression_before_the_note_on", tune >= 0 && bright >= 0 && press >= 0 && tune < on60 && bright < on60 && press < on60);
  16011. 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);
  16012. const auto later = std::max (on60, on64) + 1;
  16013. check ("sounding_note_expression", later > 0 && find ("expr", 2, 1, 2000, 3, later) >= 0 && find ("expr", 5, 2, 252, 4, later) >= 0
  16014. && find ("expr", 6, 1, 504, 4, later) >= 0);
  16015. check ("other_note_untouched", later > 0 && find ("expr", 2, 2, 2000, 3, later) < 0 && find ("expr", 6, 2, 504, 4, later) < 0);
  16016. check ("notes_off_on_their_channels", find ("off", 1, 60, 0, 100000) >= 0 && find ("off", 2, 64, 0, 100000) >= 0);
  16017. auto expressionAsMidi = false; // (a CLAP-dialect plugin gets no raw bend / pressure / CC 74 on a member channel)
  16018. for (const auto& x : lines)
  16019. if (x.kind == "midi" && (x.a & 0x0f) != 0 && ((x.a & 0xf0) == 0xe0 || (x.a & 0xf0) == 0xd0 || ((x.a & 0xf0) == 0xb0 && x.b == 74)))
  16020. expressionAsMidi = true;
  16021. check ("no_duplicate_midi_expression", ! expressionAsMidi);
  16022. report << "--- plugin log ---\n" << log.loadFileAsString() << "result=" << (failures == 0 ? "OK" : "FAILED") << "\n";
  16023. juce::File (reportPath).replaceWithText (report);
  16024. setApplicationReturnValue (failures == 0 ? 0 : 1);
  16025. quit();
  16026. }
  16027. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c, PR #29): a
  16028. // CLAP effect on the Master that asks for a restart every 8 blocks while an export renders on a thread of its own
  16029. // (the message thread is free to run the restarts, as with the Export window). The plugin aborts the process when
  16030. // start / stop_processing run off the audio thread or activate / deactivate off the main thread (issue #46, as u-he
  16031. // Presswerk does; an export at 44.1 kHz and prepare calls from the export's thread check the latter) and counts deactivations that
  16032. // landed inside its process() call (must be none), the restarts must happen, and the delay compensation must end on
  16033. // the latency the plugin reports after its last restart.
  16034. void runClapRestartTest (const juce::String& pluginPath, const juce::String& reportPath)
  16035. {
  16036. struct Run
  16037. {
  16038. std::unique_ptr<lynx::AudioEngine> engine;
  16039. juce::String report;
  16040. int slot = -1;
  16041. std::thread render;
  16042. std::atomic<bool> done { false };
  16043. double renderSeconds = 0.0;
  16044. };
  16045. auto run = std::make_shared<Run>();
  16046. const auto counters = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  16047. counters.deleteFile();
  16048. #if JUCE_WINDOWS
  16049. _putenv_s ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8());
  16050. #else
  16051. setenv ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8(), 1);
  16052. #endif
  16053. const auto fail = [this, reportPath] (juce::String report) {
  16054. report << "result=FAILED\n";
  16055. juce::File (reportPath).replaceWithText (report);
  16056. setApplicationReturnValue (1);
  16057. quit();
  16058. };
  16059. run->engine = std::make_unique<lynx::AudioEngine> (false);
  16060. auto& host = run->engine->getPluginHost();
  16061. run->report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  16062. std::optional<juce::PluginDescription> clap;
  16063. for (const auto& type : host.getKnownPlugins().getTypes())
  16064. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  16065. clap = type;
  16066. if (! clap)
  16067. {
  16068. fail (run->report + "no CLAP plugin in the file\n");
  16069. return;
  16070. }
  16071. auto song = lynx::Song::makeDefault();
  16072. lynx::EffectSlot slot;
  16073. slot.kind = lynx::EffectKind::plugin;
  16074. slot.plugin.id = clap->createIdentifierString().toStdString();
  16075. slot.plugin.name = clap->name.toStdString();
  16076. slot.smartDisable = false; // (processed every block, as with music playing: the export itself is silent)
  16077. song.mixer[0].effects = { slot }; // alone on the Master: the delay compensation is the plugin's latency
  16078. run->slot = (int) song.mixer[0].effects.size() - 1;
  16079. run->engine->setSong (song);
  16080. run->engine->renderOffline (0.1, 48000.0); // builds the rack (and the plugin) on the message thread
  16081. if (dynamic_cast<lynx::PluginEffect*> (run->engine->getEffect (0, run->slot).get()) == nullptr)
  16082. {
  16083. fail (run->report + "effect_loaded=no\n");
  16084. return;
  16085. }
  16086. auto effect = std::dynamic_pointer_cast<lynx::PluginEffect> (run->engine->getEffect (0, run->slot));
  16087. run->render = std::thread ([run, effect] () mutable {
  16088. const auto start = juce::Time::getMillisecondCounterHiRes();
  16089. run->engine->renderOffline (30.0, 48000.0);
  16090. run->renderSeconds = (juce::Time::getMillisecondCounterHiRes() - start) * 0.001;
  16091. // issue #46: an export at another rate / block size prepares the plugin from the export's thread; the
  16092. // plugin aborts unless activate / deactivate reach the main thread
  16093. auto& instance = effect->getInstance();
  16094. instance.prepareToPlay (44100.0, 1024);
  16095. instance.releaseResources();
  16096. instance.prepareToPlay (48000.0, 512);
  16097. run->engine->renderOffline (3.0, 44100.0); // (the engine rebuilds its rack at that rate)
  16098. // The engine has replaced this instance (made for 48 kHz) by then, so this is its last reference: it is
  16099. // deleted here, on the export's thread, and its deactivate / destroy go to the message thread, which this
  16100. // waits for. That has to happen before `done`: once the message thread sees it, it blocks in join() until
  16101. // this thread ends, and an instance deleted after that waited 10 s for it and then deactivated the plugin
  16102. // right here, off the main thread (the plugin aborts: about 1 run in 40 under load, round 190au).
  16103. effect.reset();
  16104. run->done = true;
  16105. });
  16106. // after the render: a second for the restarts still queued and the engine's timer (the new PDC plan)
  16107. auto finish = std::make_shared<std::function<void()>>();
  16108. *finish = [this, run, counters, reportPath, fail, finish] {
  16109. if (! run->done)
  16110. {
  16111. juce::Timer::callAfterDelay (50, *finish);
  16112. return;
  16113. }
  16114. run->render.join();
  16115. juce::Timer::callAfterDelay (1000, [this, run, counters, reportPath, fail] {
  16116. auto report = run->report;
  16117. int pluginLatency = -1;
  16118. if (const auto effect = run->engine->getEffect (0, run->slot)) // (not held past the engine's reset)
  16119. pluginLatency = effect->latencySamples();
  16120. const auto pdc = run->engine->getLatencySamples();
  16121. report << "render_seconds=" << juce::String (run->renderSeconds, 2) << "\n"
  16122. << "plugin_latency=" << pluginLatency << "\npdc_total=" << pdc << "\n"
  16123. << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  16124. run->engine.reset(); // destroys the plugin: it writes its counters
  16125. // one line per plugin instance (the engine may have made more than one): none may have been
  16126. // deactivated inside process(), and the one that rendered must have restarted
  16127. int overlapped = 0, inactive = 0, requests = 0, activations = 0, lines = 0, wrongThread = 0, misordered = 0, unstopped = 0;
  16128. bool otherRate = false;
  16129. for (const auto& line : juce::StringArray::fromLines (counters.loadFileAsString()))
  16130. {
  16131. juce::StringPairArray values;
  16132. for (const auto& token : juce::StringArray::fromTokens (line, " ", ""))
  16133. if (token.contains ("="))
  16134. values.set (token.upToFirstOccurrenceOf ("=", false, false), token.fromFirstOccurrenceOf ("=", false, false));
  16135. if (values.size() == 0)
  16136. continue;
  16137. ++lines;
  16138. report << "instance: " << line << "\n";
  16139. overlapped += values["overlapped"].getIntValue();
  16140. inactive += values["inactive_blocks"].getIntValue();
  16141. // issue #46: activate / deactivate on the main thread, start / stop_processing on the audio thread
  16142. // (the plugin aborts the process otherwise, as u-he's do), in order, every start stopped
  16143. wrongThread += values["wrong_thread"].getIntValue();
  16144. misordered += values["misordered"].getIntValue();
  16145. unstopped += values["starts"].getIntValue() - values["stops"].getIntValue();
  16146. otherRate = otherRate || values["last_rate"].getIntValue() == 44100;
  16147. if (values["requests"].getIntValue() > requests)
  16148. {
  16149. requests = values["requests"].getIntValue();
  16150. activations = values["activations"].getIntValue();
  16151. }
  16152. }
  16153. report << "wrong_thread=" << wrongThread << "\nmisordered=" << misordered << "\nunstopped=" << unstopped
  16154. << "\nactivated_at_44100=" << (otherRate ? "yes" : "no") << "\n";
  16155. const auto ok = lines > 0 && requests > 0 && activations > requests / 2 && overlapped == 0 && inactive == 0
  16156. && wrongThread == 0 && misordered == 0 && unstopped == 0 && otherRate
  16157. && pluginLatency > 0 && pdc == pluginLatency && lynx::pluginCrashCount() == 0;
  16158. if (! ok)
  16159. {
  16160. fail (report);
  16161. return;
  16162. }
  16163. report << "result=OK\n";
  16164. juce::File (reportPath).replaceWithText (report);
  16165. setApplicationReturnValue (0);
  16166. quit();
  16167. });
  16168. };
  16169. juce::Timer::callAfterDelay (50, *finish);
  16170. }
  16171. // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
  16172. // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
  16173. // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
  16174. void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
  16175. {
  16176. juce::String report;
  16177. bool ok = false;
  16178. {
  16179. lynx::AudioEngine offline (false);
  16180. auto& host = offline.getPluginHost();
  16181. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  16182. std::optional<juce::PluginDescription> vst2;
  16183. for (const auto& type : host.getKnownPlugins().getTypes())
  16184. if (type.pluginFormatName == "VST")
  16185. vst2 = type;
  16186. auto render = [&] (float gain, float& tempoSeen, int& adopted) {
  16187. lynx::FlVst2State state;
  16188. state.flags = 8;
  16189. state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
  16190. std::memcpy (state.chunk.data() + 4, &gain, 4);
  16191. auto song = lynx::Song::makeDefault();
  16192. song.bpm = 137.0;
  16193. auto& f = song.channels[4].plugin.foreign;
  16194. f.format = lynx::ForeignPlugin::Format::vst2;
  16195. f.vst2Id = (std::uint32_t) vst2->uniqueId;
  16196. f.name = "Some other name"; // found by the VST2 ID
  16197. f.state = lynx::writeFlVst2State (state);
  16198. song.channels[4].volume = 1.0f;
  16199. song.patterns[0].notes.clear();
  16200. song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
  16201. for (std::size_t c = 0; c < song.channels.size(); ++c)
  16202. if (c != 4)
  16203. song.channels[c].muted = true;
  16204. adopted = host.adoptFlPlugins (song);
  16205. offline.setSong (song);
  16206. const auto peak = offline.renderOffline (1.0, 48000.0);
  16207. offline.capturePluginStates();
  16208. juce::MemoryBlock saved;
  16209. saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
  16210. lynx::FlVst2State back;
  16211. tempoSeen = 0.0f;
  16212. if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
  16213. && back.chunk.size() >= 12)
  16214. std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
  16215. return peak;
  16216. };
  16217. if (vst2)
  16218. {
  16219. report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
  16220. float tempoA = 0, tempoB = 0;
  16221. int adoptedA = 0, adoptedB = 0;
  16222. const auto quiet = render (0.1f, tempoA, adoptedA);
  16223. const auto loud = render (0.4f, tempoB, adoptedB);
  16224. report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
  16225. << " tempo_seen=" << tempoB * 1000.0f << "\n";
  16226. ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
  16227. && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
  16228. }
  16229. }
  16230. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  16231. juce::File (reportPath).replaceWithText (report);
  16232. setApplicationReturnValue (ok ? 0 : 1);
  16233. quit();
  16234. }
  16235. // LYNX --vst3noteidtest "LYNX Test Synth.vst3" report.txt (round 190fg, cmake/LynxPatchJuce.cmake fix 26): the VST3
  16236. // test synth (tools/testplugin/lynx_test_synth_vst3.cpp: voices kept by noteId, its log the ids it got) plays two
  16237. // 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).
  16238. // 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
  16239. // 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).
  16240. void runVst3NoteIdTest (const juce::String& pluginPath, const juce::String& reportPath)
  16241. {
  16242. juce::String report;
  16243. bool ok = false;
  16244. const auto logBase = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-noteid-" + juce::String (juce::Time::currentTimeMillis()));
  16245. // (read by each new instance)
  16246. #if JUCE_WINDOWS
  16247. _putenv_s ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8());
  16248. #else
  16249. setenv ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8(), 1);
  16250. #endif
  16251. struct E
  16252. {
  16253. bool on = false;
  16254. int key = 0, id = -1;
  16255. };
  16256. // (the lines each render added: a running instance keeps its log file open, so the files stay until the end)
  16257. std::map<juce::String, int> linesRead;
  16258. const auto readLog = [&logBase, &linesRead] {
  16259. std::vector<E> events;
  16260. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  16261. {
  16262. juce::StringArray lines;
  16263. f.readLines (lines);
  16264. auto& done = linesRead[f.getFullPathName()];
  16265. for (int i = done; i < lines.size(); ++i)
  16266. {
  16267. const auto p = juce::StringArray::fromTokens (lines[i], " ", {});
  16268. if (p.size() >= 5 && p[0].startsWith ("E"))
  16269. events.push_back ({ p[1] == "on", p[2].getIntValue(), p[4].getIntValue() });
  16270. }
  16271. done = lines.size() - (lines.isEmpty() || lines[lines.size() - 1].isNotEmpty() ? 0 : 1);
  16272. }
  16273. return events;
  16274. };
  16275. {
  16276. lynx::AudioEngine offline (false);
  16277. auto& host = offline.getPluginHost();
  16278. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  16279. std::optional<juce::PluginDescription> vst3;
  16280. for (const auto& type : host.getKnownPlugins().getTypes())
  16281. if (type.pluginFormatName == "VST3" && type.isInstrument)
  16282. vst3 = type;
  16283. const auto render = [&] (bool tags) {
  16284. auto song = lynx::Song::makeDefault();
  16285. song.bpm = 120.0;
  16286. auto& c = song.channels[0];
  16287. c.instrument = lynx::InstrumentKind::plugin;
  16288. c.plugin.id = vst3->createIdentifierString().toStdString();
  16289. c.plugin.name = vst3->name.toStdString();
  16290. for (std::size_t k = 1; k < song.channels.size(); ++k)
  16291. song.channels[k].muted = true;
  16292. auto& notes = song.patterns[0].notes;
  16293. notes.clear();
  16294. const auto beat = (std::int64_t) lynx::ppq;
  16295. notes.push_back ({ 0, 4 * beat, 0, 60, 0.8f }); // A
  16296. notes.push_back ({ 2 * beat, 4 * beat, 0, 60, 0.8f }); // B
  16297. notes.push_back ({ 8 * beat, 6 * beat, 0, 64, 0.8f }); // C
  16298. notes.push_back ({ 10 * beat, 2 * beat, 0, 64, 0.8f }); // D (inside C)
  16299. song.patterns[0].sortNotes();
  16300. song.patterns[0].lengthTicks = 16 * beat;
  16301. offline.setSong (song);
  16302. offline.dispatchPendingMessages();
  16303. if (! tags)
  16304. juce::lynxNoteTagHook = nullptr; // (fix 14 alone: the oldest sounding id; the next instance sets it again)
  16305. offline.renderOffline (7.9, 48000.0); // (C ends at 7 s; the 8 s pattern does not loop yet)
  16306. return readLog();
  16307. };
  16308. const auto check = [&report] (const char* name, const std::vector<E>& events, bool expectOwn) {
  16309. // ons and offs of each key in the order the plugin got them
  16310. std::map<int, std::vector<int>> ons, offs;
  16311. for (const auto& e : events)
  16312. (e.on ? ons : offs)[e.key].push_back (e.id);
  16313. const auto& a = ons[60]; const auto& o60 = offs[60];
  16314. const auto& c = ons[64]; const auto& o64 = offs[64];
  16315. report << name << ": key 60 ons";
  16316. for (auto id : a) report << " " << id;
  16317. report << " offs";
  16318. for (auto id : o60) report << " " << id;
  16319. report << "; key 64 ons";
  16320. for (auto id : c) report << " " << id;
  16321. report << " offs";
  16322. for (auto id : o64) report << " " << id;
  16323. report << "\n";
  16324. if (a.size() != 2 || o60.size() != 2 || c.size() != 2 || o64.size() != 2 || a[0] < 0 || c[0] < 0)
  16325. return false;
  16326. const auto fifo = o60[0] == a[0] && o60[1] == a[1]; // A ends first: A's id either way
  16327. // LIFO: D (c[1]) ends first; its own id with the tags, C's (the oldest) without
  16328. const auto lifo = expectOwn ? (o64[0] == c[1] && o64[1] == c[0]) : (o64[0] == c[0] && o64[1] == c[1]);
  16329. return fifo && lifo;
  16330. };
  16331. if (vst3)
  16332. {
  16333. report << "plugin=" << vst3->name << "\n";
  16334. const auto withTags = render (true);
  16335. const auto okTags = check ("with_tags", withTags, true);
  16336. const auto withoutTags = render (false);
  16337. const auto okBefore = check ("fix14_only", withoutTags, false);
  16338. report << "own_ids=" << (okTags ? "yes" : "NO") << " fix14_only_oldest=" << (okBefore ? "yes" : "NO") << "\n";
  16339. ok = okTags && okBefore;
  16340. }
  16341. }
  16342. if (ok) // (a failure leaves the logs for a look: their path is in the report)
  16343. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  16344. f.deleteFile();
  16345. else
  16346. report << "synth_logs=" << logBase.getFullPathName() << ".*\n";
  16347. #if JUCE_WINDOWS
  16348. _putenv_s ("LYNX_TEST_SYNTH_LOG", "");
  16349. #else
  16350. unsetenv ("LYNX_TEST_SYNTH_LOG");
  16351. #endif
  16352. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  16353. juce::File (reportPath).replaceWithText (report);
  16354. setApplicationReturnValue (ok ? 0 : 1);
  16355. quit();
  16356. }
  16357. // Round 181c: a wrapper MIDI option changed on a running plugin must act like the same option on a new one. For each
  16358. // option: a control engine whose plugin is created with the option set (proves the test can see it), then an engine
  16359. // whose plugin is already running when the option changes through editSong, as the wrapper page does it. What the
  16360. // plugin received comes from the test plugin's own log. The running instance must also stay the same one.
  16361. void runWrapperMidiTest (const juce::String& pluginPath, const juce::String& reportPath)
  16362. {
  16363. juce::String report;
  16364. auto ok = true;
  16365. const juce::File logFile (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_VST2_MIDILOG", {}));
  16366. struct Event { juce::String instance; int status, data1, data2; };
  16367. auto take = [&] {
  16368. std::vector<Event> out;
  16369. juce::StringArray lines;
  16370. logFile.readLines (lines);
  16371. for (const auto& line : lines)
  16372. {
  16373. const auto p = juce::StringArray::fromTokens (line, " ", {});
  16374. if (p.size() == 4)
  16375. out.push_back ({ p[0], p[1].getIntValue(), p[2].getIntValue(), p[3].getIntValue() });
  16376. }
  16377. logFile.deleteFile();
  16378. return out;
  16379. };
  16380. auto count = [] (const std::vector<Event>& events, int status, int data1, int data2) {
  16381. int n = 0;
  16382. for (const auto& e : events)
  16383. n += (e.status & 0xF0) == status && (data1 < 0 || e.data1 == data1) && (data2 < 0 || e.data2 == data2) ? 1 : 0;
  16384. return n;
  16385. };
  16386. struct Option
  16387. {
  16388. const char* name;
  16389. std::function<void (lynx::PluginRef&)> before, change;
  16390. std::function<juce::String (const std::vector<Event>&)> seen;
  16391. };
  16392. const Option options[] = {
  16393. { "Send note release velocity off", {}, [] (lynx::PluginRef& r) { r.releaseVelocity = false; },
  16394. [&] (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)); } },
  16395. { "Send pitch bend range on", {}, [] (lynx::PluginRef& r) { r.sendBendRange = true; },
  16396. [&] (const std::vector<Event>& e) { return "rpn_range_12=" + juce::String (count (e, 0xB0, 6, 12)); } },
  16397. { "Pitch bend range 24", [] (lynx::PluginRef& r) { r.sendBendRange = true; }, [] (lynx::PluginRef& r) { r.bendRange = 24; },
  16398. [&] (const std::vector<Event>& e) { return "rpn_range_24=" + juce::String (count (e, 0xB0, 6, 24)); } },
  16399. { "Send MOD X as polyphonic aftertouch on", {}, [] (lynx::PluginRef& r) { r.modXAftertouch = true; },
  16400. [&] (const std::vector<Event>& e) { return "aftertouch=" + juce::String (count (e, 0xA0, 69, -1)); } },
  16401. { "Send All Notes Off when playback stops off", {}, [] (lynx::PluginRef& r) { r.allNotesOffOnStop = false; },
  16402. [&] (const std::vector<Event>& e) { return "cc123=" + juce::String (count (e, 0xB0, 123, -1)); } },
  16403. };
  16404. // each phase has its own engine: an engine keeps the running instance across setSong, so one engine would
  16405. // carry the control's plugin into the "before" phase
  16406. lynx::AudioEngine scanner (false);
  16407. auto& host = scanner.getPluginHost();
  16408. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  16409. std::optional<juce::PluginDescription> vst2;
  16410. for (const auto& type : host.getKnownPlugins().getTypes())
  16411. if (type.pluginFormatName == "VST")
  16412. vst2 = type;
  16413. if (! vst2 || logFile.getFullPathName().isEmpty())
  16414. ok = false;
  16415. else
  16416. for (const auto& option : options)
  16417. {
  16418. auto makeSong = [&] (bool changed) {
  16419. auto song = lynx::Song::makeDefault();
  16420. auto& channel = song.channels[0];
  16421. channel.instrument = lynx::InstrumentKind::plugin;
  16422. channel.plugin = {};
  16423. channel.plugin.id = vst2->createIdentifierString().toStdString();
  16424. channel.plugin.name = vst2->name.toStdString();
  16425. if (option.before)
  16426. option.before (channel.plugin);
  16427. if (changed)
  16428. option.change (channel.plugin);
  16429. song.patterns[0].notes.clear();
  16430. lynx::Note note;
  16431. note.start = 0;
  16432. note.length = lynx::ppq;
  16433. note.channel = 0;
  16434. note.key = 69;
  16435. note.velocity = 1.0f;
  16436. note.release = 0.25f; // 32 of 127
  16437. note.modX = 0.75f;
  16438. song.patterns[0].notes.push_back (note);
  16439. for (std::size_t c = 1; c < song.channels.size(); ++c)
  16440. song.channels[c].muted = true;
  16441. return song;
  16442. };
  16443. // a block of the song, then a note held across "playback stopped", as the options act on either
  16444. auto play = [&] (lynx::AudioEngine& engine) {
  16445. logFile.deleteFile();
  16446. engine.renderOffline (1.0, 48000.0);
  16447. if (auto instrument = engine.getChannelInstrument (0))
  16448. {
  16449. instrument->noteOn (60, 1.0f);
  16450. instrument->transportStopped();
  16451. }
  16452. engine.renderOffline (0.1, 48000.0);
  16453. return take();
  16454. };
  16455. auto newEngine = [&] {
  16456. auto engine = std::make_unique<lynx::AudioEngine> (false);
  16457. engine->getPluginHost().addPluginFile (juce::File (pluginPath));
  16458. return engine;
  16459. };
  16460. std::vector<Event> control;
  16461. {
  16462. auto engine = newEngine();
  16463. engine->setSong (makeSong (true));
  16464. control = play (*engine);
  16465. }
  16466. auto engine = newEngine();
  16467. engine->setSong (makeSong (false));
  16468. const auto before = play (*engine);
  16469. const auto instrumentBefore = engine->getChannelInstrument (0).get();
  16470. engine->capturePluginStates(); // as the wrapper page does
  16471. engine->editSong ([&] (lynx::Song& song) { option.change (song.channels[0].plugin); });
  16472. const auto after = play (*engine);
  16473. const auto sameInstance = engine->getChannelInstrument (0).get() == instrumentBefore;
  16474. // the counts differ between phases (how many blocks the note spans, how many instances the phase made):
  16475. // what matters is whether each kind of event is there at all
  16476. auto shape = [] (const juce::String& seen) {
  16477. juce::String out;
  16478. for (const auto& token : juce::StringArray::fromTokens (seen, " ", {}))
  16479. out << token.upToFirstOccurrenceOf ("=", false, false) << (token.fromFirstOccurrenceOf ("=", false, false).getIntValue() > 0 ? "=yes " : "=no ");
  16480. return out;
  16481. };
  16482. auto instances = [] (const std::vector<Event>& events) {
  16483. std::set<juce::String> made;
  16484. for (const auto& e : events)
  16485. made.insert (e.instance);
  16486. return (int) made.size();
  16487. };
  16488. const auto a = option.seen (control) + " instances=" + juce::String (instances (control)),
  16489. b = option.seen (before) + " instances=" + juce::String (instances (before)),
  16490. c = option.seen (after) + " instances=" + juce::String (instances (after));
  16491. const auto visible = shape (option.seen (control)) != shape (option.seen (before));
  16492. const auto works = shape (option.seen (after)) == shape (option.seen (control));
  16493. report << option.name << ": control " << a << " | before " << b << " | after the change " << c << " | same_instance=" << (int) sameInstance
  16494. << " | test_sees_the_option=" << (int) visible << " | " << (! visible ? "NOT PROVEN" : works ? "acts on the plugin" : "DEAD until re-created") << "\n";
  16495. ok = ok && visible && works;
  16496. }
  16497. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  16498. juce::File (reportPath).replaceWithText (report);
  16499. setApplicationReturnValue (ok ? 0 : 1);
  16500. quit();
  16501. }
  16502. // LYNX.exe --wrappershot "LYNX Test Drums.dll" <folder> (round 188d): the wrapper's Processing tab drawn offscreen
  16503. // (no window, no focus) for the FL | LYNX review: wrap-default.png (a fresh plugin), wrap-automap.png (Auto map
  16504. // outputs, output 3 off: FL's shot b23), wrap-settings.png. Scale 1.5 (FL's shots are at 150 %).
  16505. // (round 190oh, --wrappershot190oh: the steps run from a timer, so the editors' windows get their messages)
  16506. struct WrapperShot190oh final : juce::Timer
  16507. {
  16508. std::function<bool()> step; // false: done
  16509. void timerCallback() override
  16510. {
  16511. if (! step())
  16512. stopTimer();
  16513. }
  16514. };
  16515. std::unique_ptr<WrapperShot190oh> wrapperShot190oh;
  16516. void runWrapperShot190oh (const juce::String& pluginPath, const juce::String& folderPath, bool openEditors)
  16517. {
  16518. struct State
  16519. {
  16520. juce::File folder;
  16521. juce::String report;
  16522. bool ok = true;
  16523. std::shared_ptr<lynx::AudioEngine> engine;
  16524. std::optional<juce::PluginDescription> type;
  16525. int phase = 0, wait = 0;
  16526. void expect (const char* name, bool value)
  16527. {
  16528. report << name << "=" << (value ? 1 : 0) << "\n";
  16529. ok = ok && value;
  16530. }
  16531. static lynx::PluginRef* find (lynx::Song& s)
  16532. {
  16533. return s.mixer.size() < 2 || s.mixer[1].effects.empty() ? nullptr : &s.mixer[1].effects[0].plugin;
  16534. }
  16535. std::shared_ptr<lynx::PluginEffect> effect() { return std::dynamic_pointer_cast<lynx::PluginEffect> (engine->getEffect (1, 0)); }
  16536. bool save (const juce::String& name, float scale)
  16537. {
  16538. auto fx = effect();
  16539. if (fx == nullptr)
  16540. return false;
  16541. const auto image = lynx::wrapperSettingsSnapshot (*engine, &State::find, fx->getInstance(), false, 0, scale, 1, 0);
  16542. auto file = folder.getChildFile (name);
  16543. file.deleteFile();
  16544. juce::FileOutputStream out (file);
  16545. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  16546. }
  16547. void open()
  16548. {
  16549. if (auto fx = effect())
  16550. {
  16551. lynx::PluginWindows::WrapperContext context;
  16552. context.engine = engine.get();
  16553. context.find = &State::find;
  16554. context.track = 1;
  16555. context.slot = 0;
  16556. lynx::PluginWindows::open (fx, fx->getInstance(), type->name, context);
  16557. }
  16558. }
  16559. // what the open editor was marked with and (Windows) the DPI awareness of its window and of the windows
  16560. // inside it (the plugin's own)
  16561. void describe (const char* tag)
  16562. {
  16563. auto fx = effect();
  16564. if (fx == nullptr)
  16565. return;
  16566. auto& instance = fx->getInstance();
  16567. auto* editor = instance.getActiveEditor();
  16568. report << tag << ".editor=" << (editor != nullptr ? 1 : 0);
  16569. if (editor != nullptr)
  16570. report << " size=" << editor->getWidth() << "x" << editor->getHeight()
  16571. << " unaware_mark=" << (int) (bool) editor->getProperties()["lynxDpiUnaware"]
  16572. << " dims_mark=" << (int) (bool) editor->getProperties()["lynxScaleEditorDimensions"];
  16573. report << " docked=" << (int) lynx::PluginWindows::isDocked (instance);
  16574. int windows = 0;
  16575. if (const auto unaware = lynx::platform::dpiUnawareWindowCount (lynx::PluginWindows::hostWindowHandle (instance), windows); unaware >= 0)
  16576. {
  16577. report << " windows=" << windows << " unaware_windows=" << unaware;
  16578. expect ((juce::String (tag) + "_unaware_as_set").toRawUTF8(),
  16579. juce::String (tag) == "default" ? unaware == 0 : (windows > 0 && unaware == windows));
  16580. }
  16581. report << "\n";
  16582. lynx::PluginWindows::close (instance);
  16583. }
  16584. void change()
  16585. {
  16586. engine->editSong ([] (lynx::Song& s) {
  16587. s.mixer[1].effects[0].plugin.dpiAware = false;
  16588. s.mixer[1].effects[0].plugin.scaleEditorDimensions = true;
  16589. });
  16590. engine->renderOffline (0.05, 48000.0); // ("DPI aware" reloads the plugin)
  16591. }
  16592. };
  16593. auto st = std::make_shared<State>();
  16594. st->folder = juce::File (folderPath);
  16595. st->folder.createDirectory();
  16596. st->engine = std::make_shared<lynx::AudioEngine> (false);
  16597. st->engine->getPluginHost().addPluginFile (juce::File (pluginPath));
  16598. for (const auto& t : st->engine->getPluginHost().getKnownPlugins().getTypes())
  16599. if (! st->type && (juce::File (t.fileOrIdentifier) == juce::File (pluginPath) || juce::File (pluginPath).isAChildOf (juce::File (t.fileOrIdentifier))
  16600. || juce::File (t.fileOrIdentifier).isAChildOf (juce::File (pluginPath))))
  16601. st->type = t;
  16602. st->expect ("plugin_found", st->type.has_value());
  16603. if (st->type)
  16604. {
  16605. st->report << "plugin=" << st->type->name << " (" << st->type->pluginFormatName << ")\n";
  16606. auto song = lynx::Song::makeDefault();
  16607. auto slot = lynx::makeEffectSlot (lynx::EffectKind::plugin);
  16608. slot.plugin.id = st->type->createIdentifierString().toStdString();
  16609. slot.plugin.name = st->type->name.toStdString();
  16610. song.mixer[1].effects = { slot };
  16611. st->engine->setSong (song);
  16612. st->engine->renderOffline (0.05, 48000.0);
  16613. const auto* ref = State::find (const_cast<lynx::Song&> (st->engine->getSong()));
  16614. st->expect ("fl_defaults", ref != nullptr && ref->dpiAware && ! ref->scaleEditorDimensions);
  16615. st->expect ("shot_default_100", st->save ("gui-default.png", 1.0f));
  16616. st->expect ("shot_default_150", st->save ("gui-default@150.png", 1.5f));
  16617. }
  16618. auto finish = [this, st] {
  16619. st->folder.getChildFile ("report.txt").replaceWithText (st->report + "result=" + (st->ok ? "OK" : "FAIL") + "\n");
  16620. st->engine.reset();
  16621. setApplicationReturnValue (st->ok ? 0 : 1);
  16622. quit();
  16623. };
  16624. if (! st->type || ! openEditors)
  16625. {
  16626. if (st->type)
  16627. {
  16628. st->change();
  16629. st->expect ("shot_changed_100", st->save ("gui-changed.png", 1.0f));
  16630. st->expect ("shot_changed_150", st->save ("gui-changed@150.png", 1.5f));
  16631. }
  16632. finish();
  16633. return;
  16634. }
  16635. // with --open: open the editor (default settings), look after 1 s, close; change; open again, look, close
  16636. wrapperShot190oh = std::make_unique<WrapperShot190oh>();
  16637. wrapperShot190oh->step = [st, finish] {
  16638. if (st->wait-- > 0)
  16639. return true;
  16640. switch (st->phase++)
  16641. {
  16642. case 0: st->open(); st->wait = 10; return true;
  16643. case 1: st->describe ("default"); st->wait = 3; return true;
  16644. case 2:
  16645. st->change();
  16646. st->expect ("shot_changed_100", st->save ("gui-changed.png", 1.0f));
  16647. st->expect ("shot_changed_150", st->save ("gui-changed@150.png", 1.5f));
  16648. st->open();
  16649. st->wait = 10;
  16650. return true;
  16651. case 3: st->describe ("changed"); st->wait = 3; return true;
  16652. default: finish(); return false;
  16653. }
  16654. };
  16655. wrapperShot190oh->startTimer (100);
  16656. }
  16657. void runWrapperShot (const juce::String& pluginPath, const juce::String& folderPath)
  16658. {
  16659. const juce::File folder (folderPath);
  16660. folder.createDirectory();
  16661. auto ok = false;
  16662. lynx::AudioEngine engine (false);
  16663. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  16664. std::optional<juce::PluginDescription> vst2;
  16665. for (const auto& type : engine.getPluginHost().getKnownPlugins().getTypes())
  16666. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  16667. vst2 = type; // (the profile may know other test plugins)
  16668. if (vst2 && ! vst2->isInstrument)
  16669. {
  16670. // an effect (round 188d): on insert 1, with insert 2 routed there as a sidechain (FL's k65 / k78 shots):
  16671. // wrap-fx-default.png, wrap-fx-automap.png (Auto map inputs and outputs)
  16672. auto song = lynx::Song::makeDefault();
  16673. if (song.mixer.size() < 4)
  16674. song.mixer.resize (4);
  16675. auto slot = lynx::makeEffectSlot (lynx::EffectKind::plugin);
  16676. slot.plugin.id = vst2->createIdentifierString().toStdString();
  16677. slot.plugin.name = vst2->name.toStdString();
  16678. song.mixer[1].effects = { slot };
  16679. lynx::mixerops::sidechainTo (song, 2, 1);
  16680. engine.setSong (song);
  16681. engine.renderOffline (0.05, 48000.0);
  16682. if (auto fx = std::dynamic_pointer_cast<lynx::PluginEffect> (engine.getEffect (1, 0)))
  16683. {
  16684. auto find = [] (lynx::Song& s) -> lynx::PluginRef* {
  16685. return s.mixer.size() < 2 || s.mixer[1].effects.empty() ? nullptr : &s.mixer[1].effects[0].plugin;
  16686. };
  16687. auto save = [&] (const char* name) {
  16688. const auto image = lynx::wrapperSettingsSnapshot (engine, find, fx->getInstance(), false, 1, 1.5f, 1, 0);
  16689. juce::FileOutputStream out (folder.getChildFile (name));
  16690. out.setPosition (0);
  16691. out.truncate();
  16692. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  16693. };
  16694. ok = save ("wrap-fx-default.png");
  16695. engine.editSong ([] (lynx::Song& s) {
  16696. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.inputs, 2);
  16697. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.outputs, 2);
  16698. s.mixer[1].effects[0].sidechain = lynx::mixerops::sidechainIndexSource (s, 1, 1);
  16699. });
  16700. ok = ok && save ("wrap-fx-automap.png") && engine.getSong().mixer[1].effects[0].sidechain == 2;
  16701. }
  16702. }
  16703. else if (vst2)
  16704. {
  16705. auto song = lynx::Song::makeDefault();
  16706. auto& channel = song.channels[0];
  16707. channel.instrument = lynx::InstrumentKind::plugin;
  16708. channel.plugin = {};
  16709. channel.plugin.id = vst2->createIdentifierString().toStdString();
  16710. channel.plugin.name = vst2->name.toStdString();
  16711. channel.mixerTrack = 5;
  16712. engine.setSong (song);
  16713. engine.renderOffline (0.05, 48000.0); // (the plugin is hosted by then)
  16714. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  16715. {
  16716. auto find = [] (lynx::Song& s) -> lynx::PluginRef* { return s.channels.empty() ? nullptr : &s.channels[0].plugin; };
  16717. auto save = [&] (const char* name, int tab) {
  16718. const auto image = lynx::wrapperSettingsSnapshot (engine, find, instrument->getInstance(), true, tab, 1.5f);
  16719. juce::FileOutputStream out (folder.getChildFile (name));
  16720. out.setPosition (0);
  16721. out.truncate();
  16722. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  16723. };
  16724. ok = save ("wrap-default.png", 1) && save ("wrap-settings.png", 0);
  16725. engine.editSong ([] (lynx::Song& s) {
  16726. lynx::autoMapOutputs (s.channels[0].plugin.outputs, 8);
  16727. s.channels[0].plugin.outputs.resize (8);
  16728. s.channels[0].plugin.outputs[2].active = 0;
  16729. s.channels[0].plugin.processInactive = false; // (as an LED click does, FL's b23)
  16730. });
  16731. ok = ok && save ("wrap-automap.png", 1);
  16732. }
  16733. }
  16734. setApplicationReturnValue (ok ? 0 : 1);
  16735. quit();
  16736. }
  16737. // LYNX.exe --multiouttest "LYNX Test Drums.dll" report.txt (round 188d, issue #114): a multi-output VST2
  16738. // (tools/testplugin/lynx_test_drums_vst2.c: key 36 = output 1 at 110 Hz, key 37 = output 2 at 220 Hz) on a
  16739. // channel routed to insert 1; the wrapper's Processing › Connections as FL plays them [EXEC fl188d]: every output
  16740. // on the channel's insert by default, an offset to another insert, an inactive output silent, the channel's
  16741. // volume on all of them. Measured on the master with insert 1 muted or not.
  16742. void runMultiOutTest (const juce::String& pluginPath, const juce::String& reportPath)
  16743. {
  16744. juce::String report;
  16745. auto ok = true;
  16746. lynx::AudioEngine scanner (false);
  16747. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  16748. std::optional<juce::PluginDescription> vst2;
  16749. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  16750. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  16751. vst2 = type; // (the profile may know other test plugins)
  16752. struct Case
  16753. {
  16754. const char* name;
  16755. std::vector<lynx::PluginOutputRoute> routes;
  16756. bool muteInsert1;
  16757. float volume;
  16758. bool kick, snare; // expected on the master
  16759. };
  16760. const Case cases[] = {
  16761. { "defaults", {}, false, -1.0f, true, true },
  16762. { "defaults, insert 1 muted", {}, true, -1.0f, false, false },
  16763. { "auto map, insert 1 muted", { { 0, 1 }, { 1, 1 } }, true, -1.0f, false, true },
  16764. { "auto map", { { 0, 1 }, { 1, 1 } }, false, -1.0f, true, true },
  16765. { "output 2 inactive", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, false },
  16766. { "output 1 inactive", { { 0, 0 } }, false, -1.0f, false, true },
  16767. { "auto map, channel volume 0", { { 0, 1 }, { 1, 1 } }, false, 0.0f, false, false },
  16768. { "output 2 inactive, Process inactive inputs and outputs on", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, true },
  16769. };
  16770. auto tone = [] (const std::vector<float>& x, double hz) {
  16771. // Goertzel magnitude over the buffer (normalised to a sine's amplitude)
  16772. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 48000.0;
  16773. double s1 = 0.0, s2 = 0.0;
  16774. for (const auto v : x)
  16775. {
  16776. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  16777. s2 = s1;
  16778. s1 = s0;
  16779. }
  16780. 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());
  16781. };
  16782. if (! vst2)
  16783. ok = false;
  16784. else
  16785. for (const auto& c : cases)
  16786. {
  16787. lynx::AudioEngine engine (false);
  16788. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  16789. auto song = lynx::Song::makeDefault();
  16790. auto& channel = song.channels[0];
  16791. channel.instrument = lynx::InstrumentKind::plugin;
  16792. channel.plugin = {};
  16793. channel.plugin.id = vst2->createIdentifierString().toStdString();
  16794. channel.plugin.name = vst2->name.toStdString();
  16795. channel.plugin.outputs = c.routes;
  16796. // (FL's "Process inactive inputs and outputs" plays an inactive output: off but for the case named so)
  16797. channel.plugin.processInactive = juce::String (c.name).contains ("Process inactive");
  16798. channel.mixerTrack = 1;
  16799. if (c.volume >= 0.0f)
  16800. channel.volume = c.volume;
  16801. for (std::size_t k = 1; k < song.channels.size(); ++k)
  16802. song.channels[k].muted = true;
  16803. if (song.mixer.size() < 4)
  16804. song.mixer.resize (4);
  16805. song.mixer[1].muted = c.muteInsert1;
  16806. song.patterns[0].notes.clear();
  16807. for (const auto key : { 36, 37 })
  16808. {
  16809. lynx::Note note;
  16810. note.start = 0;
  16811. note.length = lynx::ppq;
  16812. note.channel = 0;
  16813. note.key = key;
  16814. note.velocity = 1.0f;
  16815. song.patterns[0].notes.push_back (note);
  16816. }
  16817. engine.setSong (song);
  16818. std::vector<float> master;
  16819. lynx::AudioEngine::RenderOptions options;
  16820. options.seconds = 0.25;
  16821. options.sampleRate = 48000.0;
  16822. options.capture = [&master] (const float* l, const float*, int n) { master.insert (master.end(), l, l + n); };
  16823. engine.renderOffline (options);
  16824. const auto kick = tone (master, 110.0), snare = tone (master, 220.0);
  16825. const auto pass = (kick > 0.01) == c.kick && (snare > 0.01) == c.snare;
  16826. report << c.name << ": kick_110Hz=" << juce::String (kick, 4) << " snare_220Hz=" << juce::String (snare, 4) << " expected kick="
  16827. << (int) c.kick << " snare=" << (int) c.snare << (pass ? " OK" : " FAILED") << "\n";
  16828. ok = ok && pass;
  16829. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  16830. if (&c == &cases[0])
  16831. {
  16832. report << "outputs=" << (int) instrument->outputs().size();
  16833. for (const auto& o : instrument->outputs())
  16834. report << " [" << o.name << " ch" << o.channel << "x" << o.channels << "]";
  16835. report << "\n";
  16836. ok = ok && instrument->outputs().size() == 8 && instrument->outputs()[1].name == "Snare";
  16837. }
  16838. }
  16839. // round 189j: "LYNX Test SC.dll" next to it (tools/testplugin/lynx_test_sc_vst2.c) as an effect on insert 1
  16840. const auto sc = juce::File (pluginPath).getSiblingFile ("LYNX Test SC.dll");
  16841. if (sc.existsAsFile())
  16842. ok = runEffectConnectionsTest (sc, report) && ok;
  16843. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  16844. juce::File (reportPath).replaceWithText (report);
  16845. setApplicationReturnValue (ok ? 0 : 1);
  16846. quit();
  16847. }
  16848. // Round 189j: a hosted effect's Processing › Connections against FL 2026's own renders of the same projects
  16849. // [EXEC fxconn189j: FL /R renders of LYNX's .flp exports, docs/analise/REA_rodada189j.md]. Insert 1: a 440 Hz
  16850. // sampler and "LYNX Test SC" (output 1 = input 1, output 2 = input 2); inserts 2 (1000 Hz) and 3 (1500 Hz) routed
  16851. // to insert 1 at level 0 only; insert 4 a 2500 Hz reference on the Master; insert 1 routed to the Master and at
  16852. // level 0 to inserts 5 (panned left) and 6 (right). Each tone's level per side, in dB from the reference's, must be
  16853. // FL's within 0.5 dB (absent: 50 dB under it).
  16854. bool runEffectConnectionsTest (const juce::File& scFile, juce::String& report)
  16855. {
  16856. lynx::AudioEngine scanner (false);
  16857. scanner.getPluginHost().addPluginFile (scFile);
  16858. std::optional<juce::PluginDescription> sc;
  16859. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  16860. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == scFile)
  16861. sc = type;
  16862. report << "effect_plugin=" << (sc ? sc->name : juce::String ("not found")) << "\n";
  16863. if (! sc)
  16864. return false;
  16865. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-fxconn189j");
  16866. dir.createDirectory();
  16867. const double tones[] = { 440.0, 1000.0, 1500.0, 2500.0 };
  16868. for (const auto hz : tones)
  16869. {
  16870. const auto wav = dir.getChildFile ("sine" + juce::String ((int) hz) + ".wav");
  16871. if (wav.existsAsFile())
  16872. continue;
  16873. juce::AudioBuffer<float> sine (1, 44100 * 3);
  16874. for (int i = 0; i < sine.getNumSamples(); ++i)
  16875. sine.setSample (0, i, 0.25f * (float) std::sin (2.0 * juce::MathConstants<double>::pi * hz * i / 44100.0));
  16876. juce::WavAudioFormat format;
  16877. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  16878. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  16879. {
  16880. out.release();
  16881. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  16882. writer->writeFromAudioSampleBuffer (sine, 0, sine.getNumSamples());
  16883. }
  16884. }
  16885. using Route = lynx::PluginOutputRoute;
  16886. constexpr float none = -999.0f;
  16887. struct Case
  16888. {
  16889. const char* name;
  16890. std::vector<Route> inputs, outputs;
  16891. int tweak; // 1 no Master route, 2 insert 1 fader at 0.4, 3 Process inactive off, 4 Master route level 0, 5 route
  16892. // to 7 too, 6 insert 2 fader at 0.4, 7 insert 2 muted, 8 insert 2 panned left
  16893. float level[3][2]; // 440 / 1000 / 1500 Hz, left / right: dB from the reference, FL's
  16894. };
  16895. const Route d { 0, 1 };
  16896. const Case cases[] = {
  16897. { "e00 FL defaults", { d, d }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  16898. { "e01 input 1 at 1", { { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  16899. { "e02 input 1 at 2", { { 2, 1 } }, {}, 0, { { 0, 0 }, { none, none }, { 0, 0 } } },
  16900. { "e03 input 2 at 1", { d, { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  16901. { "e04 output 2 at 1 (Master)", { d, { 1, 1 } }, { d, { 1, 1 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  16902. { "e05 output 2 at 2 (insert 5)", { d, { 1, 1 } }, { d, { 2, 1 } }, 0, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  16903. { "e06 output 1 at 1", {}, { { 1, 1 } }, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  16904. { "e07 output 2 at 5 (past the list)", { d, { 1, 1 } }, { d, { 5, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  16905. { "e08 inputs 1 and 2 at 1", { { 1, 1 }, { 1, 1 } }, {}, 0, { { none, none }, { 6.1f, 6.1f }, { none, none } } },
  16906. { "e09 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  16907. { "e10 input 1 at 5 (past the list)", { { 5, 1 } }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  16908. { "e11 output 2 at 3 (insert 6)", { d, { 1, 1 } }, { d, { 3, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  16909. { "e13 no Master route, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 1, { { none, none }, { 3.0f, none }, { none, none } } },
  16910. { "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 } } },
  16911. { "e15 input 2 inactive", { d, { 1, 0 } }, { d, d }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  16912. { "e16 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  16913. { "e18 route to 7 too, output 2 at 3", { d, { 1, 1 } }, { d, { 3, 1 } }, 5, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  16914. { "e19 Master route at 0, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 4, { { none, none }, { 0, 0 }, { none, none } } },
  16915. { "e22 input 1 at 1 inactive", { { 1, 0 } }, {}, 3, { { 0, 0 }, { none, none }, { none, none } } },
  16916. { "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 } } },
  16917. { "e24 input 1 at 1, insert 2 fader 0.4", { { 1, 1 } }, {}, 6, { { 0, 0 }, { -12.7f, -12.7f }, { none, none } } },
  16918. { "e25 input 1 at 1, insert 2 muted", { { 1, 1 } }, {}, 7, { { 0, 0 }, { none, none }, { none, none } } },
  16919. { "e26 input 1 at 1, insert 2 panned left", { { 1, 1 } }, {}, 8, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  16920. };
  16921. auto goertzel = [] (const std::vector<float>& x, double hz) {
  16922. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 44100.0;
  16923. double s1 = 0.0, s2 = 0.0;
  16924. for (const auto v : x)
  16925. {
  16926. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  16927. s2 = s1;
  16928. s1 = s0;
  16929. }
  16930. 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());
  16931. return a > 1e-7 ? 20.0 * std::log10 (a) : -140.0;
  16932. };
  16933. auto ok = true;
  16934. for (const auto& c : cases)
  16935. {
  16936. lynx::AudioEngine engine (false);
  16937. engine.getPluginHost().addPluginFile (scFile);
  16938. auto song = lynx::Song::makeDefault();
  16939. song.bpm = 120.0;
  16940. song.channels.clear();
  16941. song.automations.clear();
  16942. for (auto& p : song.patterns)
  16943. p.notes.clear();
  16944. for (int k = 0; k < 4; ++k)
  16945. {
  16946. lynx::ChannelDef ch;
  16947. ch.name = "S" + std::to_string ((int) tones[k]);
  16948. ch.instrument = lynx::InstrumentKind::sampler;
  16949. ch.samplePath = dir.getChildFile ("sine" + juce::String ((int) tones[k]) + ".wav").getFullPathName().toStdString();
  16950. ch.mixerTrack = k + 1;
  16951. song.channels.push_back (ch);
  16952. lynx::Note note;
  16953. note.start = 0;
  16954. note.length = 8 * lynx::ppq;
  16955. note.channel = k;
  16956. note.key = 60;
  16957. note.velocity = 0.78f;
  16958. song.patterns[0].notes.push_back (note);
  16959. }
  16960. if (song.mixer.size() < 10)
  16961. song.mixer.resize (10);
  16962. for (auto& t : song.mixer)
  16963. {
  16964. t.effects.clear();
  16965. t.sends.clear();
  16966. t.toMaster = true;
  16967. }
  16968. lynx::EffectSlot fx;
  16969. fx.kind = lynx::EffectKind::plugin;
  16970. fx.plugin.id = sc->createIdentifierString().toStdString();
  16971. fx.plugin.name = sc->name.toStdString();
  16972. fx.plugin.inputs = c.inputs;
  16973. fx.plugin.outputs = c.outputs;
  16974. fx.plugin.processInactive = c.tweak != 3;
  16975. auto& one = song.mixer[1];
  16976. one.effects.push_back (fx);
  16977. one.sends = { { 5, 0.0f }, { 6, 0.0f } };
  16978. for (const int t : { 2, 3 })
  16979. {
  16980. song.mixer[(std::size_t) t].toMaster = false;
  16981. song.mixer[(std::size_t) t].sends = { { 1, 0.0f } };
  16982. }
  16983. song.mixer[5].pan = -1.0f;
  16984. song.mixer[6].pan = 1.0f;
  16985. one.toMaster = c.tweak != 1;
  16986. if (c.tweak == 2)
  16987. one.volume = 0.4f;
  16988. if (c.tweak == 4)
  16989. one.masterLevel = 0.0f;
  16990. if (c.tweak == 6)
  16991. song.mixer[2].volume = 0.4f;
  16992. song.mixer[2].muted = c.tweak == 7;
  16993. song.mixer[2].pan = c.tweak == 8 ? -1.0f : 0.0f;
  16994. if (c.tweak == 5)
  16995. {
  16996. one.sends = { { 7, 0.0f }, { 5, 0.0f }, { 6, 0.0f } };
  16997. song.mixer[7].pan = 0.5f;
  16998. }
  16999. // (input 2's index sets the slot's side input source, as the Connections page and the import do)
  17000. if (c.inputs.size() > 1 && c.inputs[1].offset > 0)
  17001. one.effects[0].sidechain = lynx::mixerops::sidechainIndexSource (song, 1, c.inputs[1].offset);
  17002. engine.setSong (song);
  17003. std::vector<float> left, right;
  17004. lynx::AudioEngine::RenderOptions options;
  17005. options.seconds = 1.2;
  17006. options.sampleRate = 44100.0;
  17007. options.capture = [&] (const float* l, const float* r, int n) {
  17008. left.insert (left.end(), l, l + n);
  17009. right.insert (right.end(), r, r + n);
  17010. };
  17011. engine.renderOffline (options);
  17012. const auto from = (std::size_t) 22050, to = (std::size_t) 44100;
  17013. if (right.size() < to)
  17014. {
  17015. report << c.name << ": rendered " << (int) right.size() << " samples FAILED\n";
  17016. ok = false;
  17017. continue;
  17018. }
  17019. const std::vector<float> l (left.begin() + (std::ptrdiff_t) from, left.begin() + (std::ptrdiff_t) to);
  17020. const std::vector<float> r (right.begin() + (std::ptrdiff_t) from, right.begin() + (std::ptrdiff_t) to);
  17021. const auto ref = 0.5 * (goertzel (l, 2500.0) + goertzel (r, 2500.0));
  17022. auto pass = ref > -60.0;
  17023. report << c.name << ": ref=" << juce::String (ref, 1);
  17024. for (int k = 0; k < 3; ++k)
  17025. for (int side = 0; side < 2; ++side)
  17026. {
  17027. const auto got = goertzel (side == 0 ? l : r, tones[k]) - ref;
  17028. const auto want = c.level[k][side];
  17029. const auto good = want == none ? got < -50.0 : std::abs (got - want) < 0.5;
  17030. pass = pass && good;
  17031. report << " " << (int) tones[k] << (side == 0 ? "L" : "R") << "=" << (got < -50.0 ? juce::String ("-") : juce::String (got, 1))
  17032. << (good ? "" : "(FL " + (want == none ? juce::String ("-") : juce::String (want, 1)) + ")");
  17033. }
  17034. report << (pass ? " OK" : " FAILED") << "\n";
  17035. ok = ok && pass;
  17036. }
  17037. return ok;
  17038. }
  17039. // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
  17040. // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
  17041. // that the plugin comes back with the changed parameter.
  17042. void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
  17043. {
  17044. juce::String report;
  17045. bool ok = false;
  17046. {
  17047. lynx::AudioEngine offline (false);
  17048. auto& host = offline.getPluginHost();
  17049. host.addPluginFile (juce::File (pluginPath));
  17050. const juce::PluginDescription* vst3 = nullptr;
  17051. const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
  17052. for (const auto& type : types)
  17053. if (type.pluginFormatName == "VST3" && type.isInstrument)
  17054. vst3 = &type;
  17055. if (vst3 != nullptr)
  17056. {
  17057. juce::String error;
  17058. auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
  17059. auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
  17060. if (parameter != nullptr)
  17061. {
  17062. const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
  17063. parameter->setValueNotifyingHost (target);
  17064. juce::MemoryBlock juceState;
  17065. plugin->getStateInformation (juceState);
  17066. report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
  17067. // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
  17068. std::vector<std::uint8_t> flState;
  17069. auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
  17070. auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
  17071. put32 (id);
  17072. put32 ((std::uint32_t) data.getSize());
  17073. put32 (0);
  17074. flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
  17075. };
  17076. put32 (1);
  17077. record (1, juce::MemoryBlock (64, true));
  17078. // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
  17079. // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
  17080. juce::MemoryBlock slots;
  17081. const auto paramId = [&] (int i) {
  17082. const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
  17083. return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
  17084. };
  17085. const bool reorder = plugin->getParameters().size() >= 3;
  17086. if (reorder)
  17087. {
  17088. for (auto v : { 2u, paramId (2), paramId (0) })
  17089. slots.append (&v, 4);
  17090. report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
  17091. }
  17092. if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
  17093. for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
  17094. if (auto* child = xml->getChildByName (tag))
  17095. {
  17096. juce::MemoryBlock data;
  17097. data.fromBase64Encoding (child->getAllSubText());
  17098. record (id, data);
  17099. report << tag << "_bytes=" << (int) data.getSize() << "\n";
  17100. }
  17101. if (reorder)
  17102. record (4, slots);
  17103. plugin.reset();
  17104. auto song = lynx::Song::makeDefault();
  17105. auto& f = song.channels[4].plugin.foreign;
  17106. f.format = lynx::ForeignPlugin::Format::vst3;
  17107. f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
  17108. f.state = flState;
  17109. {
  17110. std::vector<std::uint8_t> comp, ctrl;
  17111. report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
  17112. << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
  17113. }
  17114. for (int k = 0; k < 3; ++k)
  17115. {
  17116. lynx::Automation a;
  17117. a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
  17118. song.automations.push_back (a);
  17119. }
  17120. const auto adopted = host.adoptFlPlugins (song);
  17121. report << "adopted=" << adopted << "\n";
  17122. juce::String mapped;
  17123. for (const auto& a : song.automations)
  17124. if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
  17125. mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
  17126. report << "slot_positions=" << mapped << "\n";
  17127. const auto slotsOk = ! reorder || mapped == "2,0,1";
  17128. offline.setSong (song);
  17129. if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
  17130. {
  17131. const auto value = loaded->getInstance().getParameters()[0]->getValue();
  17132. report << "restored_value=" << value << "\n";
  17133. ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
  17134. }
  17135. }
  17136. }
  17137. }
  17138. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  17139. juce::File (reportPath).replaceWithText (report);
  17140. setApplicationReturnValue (ok ? 0 : 1);
  17141. quit();
  17142. }
  17143. void runDemoSongs (const juce::String& folderPath)
  17144. {
  17145. const juce::File folder (folderPath);
  17146. folder.createDirectory();
  17147. bool ok = true;
  17148. for (int d = 1; d < lynx::demos::count; ++d)
  17149. {
  17150. juce::String error;
  17151. ok = lynx::ProjectFile::save (lynx::demos::make (d), folder.getChildFile (lynx::demos::fileName (d)), error) && ok;
  17152. }
  17153. setApplicationReturnValue (ok ? 0 : 1);
  17154. quit();
  17155. }
  17156. // --perfgen (round perfgate190id): each synthetic project of the performance gate written as <folder>/<name>.lynx, its
  17157. // audio as 16-bit WAVs in <folder>/<name>/ (written once: the same code makes the same audio). The report gives, per
  17158. // project, the .lynx size, the time to write it (ProjectFile::save, which reads it back) and to read it
  17159. // (ProjectFile::load), the medians of 5, and a hash of its text.
  17160. void runPerfGen (const juce::String& folderPath, const juce::String& reportPath, const juce::String& only)
  17161. {
  17162. const juce::File folder (folderPath);
  17163. folder.createDirectory();
  17164. const auto wanted = juce::StringArray::fromTokens (only, ",", "");
  17165. juce::String report;
  17166. bool ok = true;
  17167. auto median = [] (std::vector<double> v) {
  17168. std::sort (v.begin(), v.end());
  17169. return v[v.size() / 2];
  17170. };
  17171. auto all = lynx::perfprojects::names();
  17172. if (wanted.contains ("q3big")) // (round 190ry: only when asked for)
  17173. all.push_back ("q3big");
  17174. for (const auto& name : all)
  17175. {
  17176. if (! wanted.isEmpty() && ! wanted.contains (juce::String (name)))
  17177. continue;
  17178. lynx::Song song;
  17179. lynx::perfprojects::Samples samples;
  17180. const auto audioFolder = folder.getChildFile (juce::String (name));
  17181. lynx::perfprojects::make (name, song, samples, audioFolder.getFullPathName().toStdString());
  17182. for (const auto& [path, data] : samples)
  17183. {
  17184. const juce::File wav { juce::String (path) };
  17185. if (wav.existsAsFile())
  17186. continue;
  17187. wav.getParentDirectory().createDirectory();
  17188. const auto frames = (int) data->frames();
  17189. juce::AudioBuffer<float> audio (2, frames);
  17190. audio.copyFrom (0, 0, data->leftData(), frames);
  17191. audio.copyFrom (1, 0, data->rightData(), frames);
  17192. juce::WavAudioFormat format;
  17193. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  17194. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), data->sampleRate, 2, 16, {}, 0) : nullptr)
  17195. {
  17196. out.release();
  17197. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  17198. ok = writer->writeFromAudioSampleBuffer (audio, 0, frames) && ok;
  17199. }
  17200. else
  17201. ok = false;
  17202. }
  17203. const auto file = folder.getChildFile (juce::String (name) + ".lynx");
  17204. std::vector<double> saveMs, loadMs;
  17205. juce::String error;
  17206. bool loadedOk = true;
  17207. for (int rep = 0; rep < 5; ++rep)
  17208. {
  17209. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  17210. ok = lynx::ProjectFile::save (song, file, error) && ok;
  17211. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  17212. const auto loaded = lynx::ProjectFile::load (file, error);
  17213. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  17214. loadedOk = loadedOk && loaded.has_value() && loaded->channels.size() == song.channels.size()
  17215. && loaded->playlist.size() == song.playlist.size() && loaded->automations.size() == song.automations.size();
  17216. saveMs.push_back (t1 - t0);
  17217. loadMs.push_back (t2 - t1);
  17218. }
  17219. ok = ok && loadedOk;
  17220. const auto text = file.loadFileAsString();
  17221. std::uint64_t h = 1469598103934665603ull;
  17222. for (auto* c = text.toRawUTF8(); *c != 0; ++c)
  17223. h = (h ^ (std::uint8_t) *c) * 1099511628211ull;
  17224. report << name << ": channels=" << (int) song.channels.size() << " inserts=" << (int) song.mixer.size() - 1
  17225. << " clips=" << (int) song.playlist.size() << " automations=" << (int) song.automations.size()
  17226. << " wavs=" << (int) samples.size() << " lynx_kb=" << juce::String ((double) file.getSize() / 1024.0, 1)
  17227. << " save_ms=" << juce::String (median (saveMs), 2) << " load_ms=" << juce::String (median (loadMs), 2)
  17228. << " roundtrip=" << (loadedOk ? "OK" : "FAILED") << " text_hash=" << juce::String::toHexString ((juce::int64) h)
  17229. << (error.isNotEmpty() ? " error=" + error : juce::String()) << "\n";
  17230. }
  17231. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  17232. if (reportPath.isNotEmpty())
  17233. juce::File (reportPath).replaceWithText (report);
  17234. else
  17235. std::fputs (report.toRawUTF8(), stdout);
  17236. setApplicationReturnValue (ok ? 0 : 1);
  17237. quit();
  17238. }
  17239. void runShowcase (const juce::String& outputPath, int currentPattern)
  17240. {
  17241. const auto song = lynx::makeShowcaseSong (currentPattern);
  17242. juce::String error;
  17243. const auto ok = lynx::ProjectFile::save (song, juce::File (outputPath), error);
  17244. setApplicationReturnValue (ok ? 0 : 1);
  17245. quit();
  17246. }
  17247. // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
  17248. // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
  17249. // to check that LYNX keeps going (silence, without waiting longer than the timeout).
  17250. // --sandboxtest: plays an instrument (a note) or an effect (a 440 Hz tone through it); render() adds into l / r
  17251. struct TestVoice
  17252. {
  17253. explicit TestVoice (std::unique_ptr<juce::AudioPluginInstance> p)
  17254. {
  17255. if (p->acceptsMidi() && p->getTotalNumInputChannels() == 0)
  17256. instrument = std::make_unique<lynx::PluginInstrument> (std::move (p), 512);
  17257. else
  17258. effect = std::move (p);
  17259. }
  17260. void noteOn()
  17261. {
  17262. if (instrument != nullptr)
  17263. instrument->noteOn (60, 0.9f);
  17264. }
  17265. void render (float* l, float* r, int n, float gainLeft, float gainRight)
  17266. {
  17267. if (instrument != nullptr)
  17268. {
  17269. instrument->render (l, r, n, gainLeft, gainRight);
  17270. return;
  17271. }
  17272. const auto channels = juce::jmax (2, effect->getTotalNumInputChannels(), effect->getTotalNumOutputChannels());
  17273. juce::AudioBuffer<float> block (channels, 512);
  17274. juce::MidiBuffer midi;
  17275. for (int done = 0; done < n; done += 512)
  17276. {
  17277. const auto k = juce::jmin (512, n - done);
  17278. block.setSize (channels, k, false, false, true);
  17279. for (int i = 0; i < k; ++i)
  17280. {
  17281. const auto v = 0.25f * (float) std::sin (phase);
  17282. phase += 2.0 * juce::MathConstants<double>::pi * 440.0 / 48000.0;
  17283. for (int c = 0; c < channels; ++c)
  17284. block.setSample (c, i, v);
  17285. }
  17286. effect->processBlock (block, midi);
  17287. for (int i = 0; i < k; ++i)
  17288. {
  17289. l[done + i] += gainLeft * block.getSample (0, i);
  17290. r[done + i] += gainRight * block.getSample (1, i);
  17291. }
  17292. }
  17293. }
  17294. void release()
  17295. {
  17296. instrument.reset();
  17297. effect.reset();
  17298. }
  17299. std::unique_ptr<lynx::PluginInstrument> instrument;
  17300. std::unique_ptr<juce::AudioPluginInstance> effect;
  17301. double phase = 0.0;
  17302. };
  17303. void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
  17304. {
  17305. juce::String report;
  17306. bool ok = false;
  17307. lynx::setPluginSandboxAlerts (false);
  17308. const juce::File log (reportPath + ".log");
  17309. auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
  17310. log.deleteFile();
  17311. {
  17312. lynx::PluginHost host (false);
  17313. host.addPluginFile (juce::File (pluginPath));
  17314. const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
  17315. // the file's instrument, else its first effect (round 161: effects too, e.g. a Windows effect through yabridge)
  17316. const juce::PluginDescription* instrument = nullptr;
  17317. for (const auto& type : types)
  17318. if (type.isInstrument)
  17319. instrument = &type;
  17320. for (const auto& type : types)
  17321. if (instrument == nullptr && ! type.isInstrument)
  17322. instrument = &type;
  17323. step ("host");
  17324. juce::String error;
  17325. auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
  17326. report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
  17327. step ("created");
  17328. if (remote != nullptr)
  17329. {
  17330. auto& proxy = *remote;
  17331. TestVoice voice (std::move (remote));
  17332. std::vector<float> l (48000), r (48000);
  17333. auto peakOf = [&] {
  17334. float peak = 0.0f;
  17335. for (std::size_t k = 0; k < l.size(); ++k)
  17336. peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
  17337. return peak;
  17338. };
  17339. const auto start = juce::Time::getMillisecondCounterHiRes();
  17340. voice.noteOn();
  17341. voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  17342. const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
  17343. const auto peak = peakOf();
  17344. step ("played");
  17345. if (juce::JUCEApplication::getCommandLineParameters().contains ("--expect-crash"))
  17346. {
  17347. // a plugin that crashes while playing (round 161 test plugin): LYNX notices, mutes it and keeps running
  17348. const auto dead = lynx::isSandboxedPluginDead (proxy);
  17349. std::fill (l.begin(), l.end(), 0.0f);
  17350. std::fill (r.begin(), r.end(), 0.0f);
  17351. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  17352. report << "peak=" << peak << " render_1s_ms=" << renderMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
  17353. ok = dead && peak > 1e-4f && renderMs < 2000.0 && peakOf() == 0.0f;
  17354. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  17355. juce::File (reportPath).replaceWithText (report);
  17356. setApplicationReturnValue (ok ? 0 : 1);
  17357. quit();
  17358. return;
  17359. }
  17360. report << "plugin=" << proxy.getName() << (instrument->isInstrument ? " (instrument)" : " (effect)") << " parameters="
  17361. << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
  17362. if (juce::JUCEApplication::getCommandLineParameters().contains ("--editor") && proxy.hasEditor())
  17363. {
  17364. // the plugin's own window, opened by the child process (4 s on screen); the child must stay responsive
  17365. std::unique_ptr<juce::AudioProcessorEditor> editor (proxy.createEditorIfNeeded());
  17366. juce::Thread::sleep (4000);
  17367. juce::MemoryBlock state;
  17368. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  17369. proxy.getStateInformation (state);
  17370. report << "editor_shown=1 state_with_editor_ms=" << (juce::Time::getMillisecondCounterHiRes() - t0) << " dead=" << (lynx::isSandboxedPluginDead (proxy) ? 1 : 0) << "\n";
  17371. editor.reset();
  17372. }
  17373. // parameter -> state -> in-process plugin
  17374. bool stateOk = false;
  17375. if (! proxy.getParameters().isEmpty())
  17376. {
  17377. auto* p = proxy.getParameters()[0];
  17378. const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
  17379. p->setValue (target);
  17380. std::fill (l.begin(), l.end(), 0.0f);
  17381. voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
  17382. juce::MemoryBlock state;
  17383. proxy.getStateInformation (state);
  17384. if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  17385. {
  17386. local->setStateInformation (state.getData(), (int) state.getSize());
  17387. const auto back = local->getParameters()[0]->getValue();
  17388. // the same steps without the sandbox: some plugins quantise the value or keep it out of their state
  17389. auto control = target;
  17390. if (auto a = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  17391. {
  17392. a->enableAllBuses();
  17393. a->prepareToPlay (48000.0, 512);
  17394. a->getParameters()[0]->setValue (target);
  17395. juce::AudioBuffer<float> block (juce::jmax (2, a->getTotalNumInputChannels(), a->getTotalNumOutputChannels()), 512);
  17396. block.clear();
  17397. juce::MidiBuffer none;
  17398. a->processBlock (block, none);
  17399. juce::MemoryBlock direct;
  17400. a->getStateInformation (direct);
  17401. if (auto b = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  17402. {
  17403. b->setStateInformation (direct.getData(), (int) direct.getSize());
  17404. control = b->getParameters()[0]->getValue();
  17405. }
  17406. a->releaseResources();
  17407. }
  17408. report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << " in_process_control=" << control << "\n";
  17409. stateOk = std::abs (back - control) < 0.02f;
  17410. }
  17411. }
  17412. step ("state");
  17413. // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
  17414. lynx::hangSandboxedPluginForTest (proxy);
  17415. juce::Thread::sleep (200);
  17416. std::fill (l.begin(), l.end(), 1.0f);
  17417. std::fill (r.begin(), r.end(), 1.0f);
  17418. const auto hangStart = juce::Time::getMillisecondCounterHiRes();
  17419. voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
  17420. std::fill (l.begin(), l.end(), 0.0f);
  17421. std::fill (r.begin(), r.end(), 0.0f);
  17422. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  17423. const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
  17424. const auto dead = lynx::isSandboxedPluginDead (proxy);
  17425. const auto hangPeak = peakOf();
  17426. report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << hangPeak << "\n";
  17427. // crashed child (round 161): a second instance aborts; LYNX notices, mutes it and keeps running
  17428. bool crashOk = false;
  17429. if (auto second = lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error))
  17430. {
  17431. auto& proxy2 = *second;
  17432. TestVoice voice2 (std::move (second));
  17433. voice2.noteOn();
  17434. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  17435. lynx::crashSandboxedPluginForTest (proxy2);
  17436. const auto crashStart = juce::Time::getMillisecondCounterHiRes();
  17437. while (! lynx::isSandboxedPluginDead (proxy2) && juce::Time::getMillisecondCounterHiRes() - crashStart < 5000.0)
  17438. {
  17439. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  17440. juce::Thread::sleep (5);
  17441. }
  17442. const auto crashMs = juce::Time::getMillisecondCounterHiRes() - crashStart;
  17443. std::fill (l.begin(), l.end(), 0.0f);
  17444. std::fill (r.begin(), r.end(), 0.0f);
  17445. voice2.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  17446. const auto crashDead = lynx::isSandboxedPluginDead (proxy2);
  17447. report << "crash_ms=" << crashMs << " crash_dead=" << (crashDead ? 1 : 0) << " crash_peak_after=" << peakOf() << "\n";
  17448. crashOk = crashDead && crashMs < 3000.0;
  17449. // issue #159: freeing the crashed plugin doesn't wait on its pipe (JUCE waited up to 10 s there for
  17450. // the gone child, on the message thread when the rack freed it); its teardown ends on its own
  17451. const auto freeStart = juce::Time::getMillisecondCounterHiRes();
  17452. voice2.release();
  17453. const auto freeMs = juce::Time::getMillisecondCounterHiRes() - freeStart;
  17454. const auto endedAll = lynx::finishSandboxTeardowns (15000);
  17455. report << "crashed_free_ms=" << freeMs << " teardown_done=" << (endedAll ? 1 : 0) << "\n";
  17456. crashOk = crashOk && freeMs < 250.0 && endedAll;
  17457. }
  17458. step ("crash");
  17459. ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && hangPeak == 0.0f && crashOk;
  17460. }
  17461. }
  17462. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  17463. juce::File (reportPath).replaceWithText (report);
  17464. setApplicationReturnValue (ok ? 0 : 1);
  17465. quit();
  17466. }
  17467. // --timertest (round 174f): a view's polling timer follows the view and its parents, and survives a minimised window
  17468. void runTimerTest (const juce::File& report)
  17469. {
  17470. struct Ticks final : juce::Timer
  17471. {
  17472. void timerCallback() override {}
  17473. } timer;
  17474. juce::Component top, parent, view;
  17475. parent.addChildComponent (view);
  17476. top.addChildComponent (parent);
  17477. top.setSize (320, 200);
  17478. lynx::ui::TimerWhileShowing watch (view, timer, 30);
  17479. juce::String text;
  17480. auto failures = 0;
  17481. auto expect = [&] (const char* step, bool running) {
  17482. const auto ok = timer.isTimerRunning() == running;
  17483. failures += ok ? 0 : 1;
  17484. text << step << ": timer " << (timer.isTimerRunning() ? "running" : "stopped") << (ok ? "" : " FAIL") << "\n";
  17485. };
  17486. expect ("never shown", false);
  17487. view.setVisible (true);
  17488. parent.setVisible (true);
  17489. expect ("view and parent visible, not on the desktop", false);
  17490. top.addToDesktop (juce::ComponentPeer::windowHasTitleBar);
  17491. top.setVisible (true);
  17492. expect ("window shown", true);
  17493. parent.setVisible (false);
  17494. expect ("parent hidden", false);
  17495. parent.setVisible (true);
  17496. expect ("parent shown", true);
  17497. view.setVisible (false);
  17498. expect ("view hidden", false);
  17499. top.getPeer()->setMinimised (true);
  17500. view.setVisible (true);
  17501. expect ("view shown while minimised", true);
  17502. top.getPeer()->setMinimised (false);
  17503. expect ("window restored", true);
  17504. top.setVisible (false);
  17505. expect ("window hidden", false);
  17506. top.setVisible (true);
  17507. expect ("window shown again", true);
  17508. top.removeFromDesktop();
  17509. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  17510. report.replaceWithText (text);
  17511. setApplicationReturnValue (failures == 0 ? 0 : 1);
  17512. quit();
  17513. }
  17514. // --cachetest (round 174f): PlaylistComponent::cacheSelfTest on the project, the Playlist off screen at 1466 x 930
  17515. void runCacheTest (const juce::File& project, const juce::File& report)
  17516. {
  17517. engine = std::make_unique<lynx::AudioEngine>();
  17518. juce::String error;
  17519. auto ok = false;
  17520. // (round 190nq: a Live set, FL Studio Mobile project or DAWproject takes the same import, issue #193's set)
  17521. if (project.hasFileExtension ("flp;als;flm;dawproject"))
  17522. ok = engine->importFlpFile (project, error);
  17523. else if (auto song = lynx::ProjectFile::load (project, error))
  17524. {
  17525. engine->setSong (std::move (*song));
  17526. ok = true;
  17527. }
  17528. juce::String text = "project: " + project.getFullPathName() + "\n";
  17529. if (ok)
  17530. {
  17531. text << "video tracks: " << (int) engine->getSong().videoTracks.size() << "\n";
  17532. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  17533. playlist->setBounds (0, 0, 1466, 930);
  17534. playlist->setVisible (true);
  17535. text << playlist->cacheSelfTest ([] { lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000); }, report.getParentDirectory());
  17536. }
  17537. else
  17538. text << "result=ERROR " << error << "\n";
  17539. report.replaceWithText (text);
  17540. setApplicationReturnValue (ok && text.contains ("result=OK") ? 0 : 1);
  17541. quit();
  17542. }
  17543. // --picturetest (round 190bm): ui/PictureCheck.h on the Playlist and the Mixer, at a window's usual size, at a 4K
  17544. // screen's, and wider than a GPU bitmap can be (16384 px)
  17545. void runPictureTest (const juce::File& report, const juce::File& project)
  17546. {
  17547. engine = std::make_unique<lynx::AudioEngine>();
  17548. juce::String error, text;
  17549. if (project != juce::File())
  17550. {
  17551. auto ok = false;
  17552. if (project.hasFileExtension ("flp"))
  17553. ok = engine->importFlpFile (project, error);
  17554. else if (auto song = lynx::ProjectFile::load (project, error))
  17555. {
  17556. engine->setSong (std::move (*song));
  17557. ok = true;
  17558. }
  17559. text << "project: " << project.getFullPathName() << (ok ? "" : " (not loaded: " + error + ")") << "\n";
  17560. }
  17561. #if JUCE_WINDOWS
  17562. text << "native image: " << juce::NativeImageType().create (juce::Image::RGB, 8, 8, true)->createType()->getTypeID()
  17563. << " (software = " << juce::SoftwareImageType().getTypeID() << ")\n";
  17564. #endif
  17565. auto failures = 0;
  17566. struct Size
  17567. {
  17568. int width, height;
  17569. std::vector<float> scales;
  17570. };
  17571. const auto folder = report.getParentDirectory();
  17572. 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 } } })
  17573. {
  17574. const auto label = [&size] (const char* name) { return juce::String (name) + " " + juce::String (size.width) + " x " + juce::String (size.height); };
  17575. {
  17576. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  17577. playlist->setBounds (0, 0, size.width, size.height);
  17578. playlist->setVisible (true);
  17579. {
  17580. juce::Image warm (juce::Image::RGB, 64, 64, true); // (one paint asks for the waveforms, then they are waited for)
  17581. juce::Graphics g (warm);
  17582. playlist->paintEntireComponent (g, true);
  17583. }
  17584. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  17585. text << lynx::ui::picturecheck::run (*playlist, label ("Playlist"), size.scales, failures, folder);
  17586. }
  17587. {
  17588. auto mixer = std::make_unique<lynx::MixerComponent> (*engine);
  17589. mixer->setBounds (0, 0, size.width, juce::jmin (size.height, 700));
  17590. mixer->setVisible (true);
  17591. text << lynx::ui::picturecheck::run (*mixer, label ("Mixer"), size.scales, failures, folder);
  17592. }
  17593. }
  17594. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  17595. report.replaceWithText (text);
  17596. setApplicationReturnValue (failures == 0 ? 0 : 1);
  17597. quit();
  17598. }
  17599. // --uiperf (round 161): opens the project in the normal window, plays it, and drives the heavy UI cases of round 151
  17600. // through the window's own event path — the default layout, the Mixer maximised (meters while playing, then
  17601. // scrolled), the Playlist maximised (scroll down, scroll sideways, zoom in and out) and the Channel rack scrolled.
  17602. // Every frame is painted right after its event (ComponentPeer::performAnyPendingRepaintsNow) and timed; the report
  17603. // has, per case, the time to show it and the frames' mean / p95 / max, how many took longer than 16 ms, and the
  17604. // process CPU. The same on every OS, so Linux (X11, XWayland) and Windows numbers can be put side by side.
  17605. void runUiPerf (const juce::File& project, const juce::File& report)
  17606. {
  17607. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  17608. lynx::crashguard::startMainProfiler (profile.toStdString()); // (stopped in shutdown)
  17609. startupOptions = lynx::StartupOptions::load();
  17610. engine = std::make_unique<lynx::AudioEngine>();
  17611. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  17612. crashEngine = engine.get();
  17613. createMainWindow();
  17614. mainWindow->reveal();
  17615. // LYNX_UIPERF_SIZE=WxH, LYNX_UIPERF_SCALE=<percent> (round 179a): a large window, a HiDPI desktop's scale
  17616. if (const auto scale = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SCALE", {}).getIntValue(); scale > 0)
  17617. juce::Desktop::getInstance().setGlobalScaleFactor ((float) scale / 100.0f);
  17618. if (const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SIZE", {}), "x", ""); size.size() == 2)
  17619. mainWindow->setBounds (0, 0, size[0].getIntValue(), size[1].getIntValue());
  17620. juce::String error;
  17621. auto ok = false;
  17622. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  17623. if (project.hasFileExtension ("flp;als;flm;band;blx")) // (round 190gr: a Live set, its Session clips in the grid)
  17624. ok = engine->importFlpFile (project, error);
  17625. else if (auto song = lynx::ProjectFile::load (project, error))
  17626. {
  17627. engine->setSong (std::move (*song));
  17628. ok = true;
  17629. }
  17630. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  17631. if (! ok)
  17632. {
  17633. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  17634. setApplicationReturnValue (1);
  17635. quit();
  17636. return;
  17637. }
  17638. // LYNX_UIPERF_STANDIN=1 (round 190qe): no audio device here (Xvfb under WSL): the self-tests' stand-in device plays the
  17639. // song, so the "playing" steps move (the playhead of UX-A10's check above all)
  17640. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_STANDIN", {}) == "1" && engine->getDeviceManager().getCurrentAudioDevice() == nullptr)
  17641. if (const auto e = engine->openStandInDevice (48000.0, 512); e.isNotEmpty())
  17642. std::fprintf (stderr, "uiperf: stand-in device: %s\n", e.toRawUTF8());
  17643. // LYNX_UIPERF_MUTE=1: the Master fader down (the meters of the inserts still move): a run on a desktop someone uses
  17644. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_MUTE", {}) == "1")
  17645. engine->editSong ([] (lynx::Song& s) { if (! s.mixer.empty()) s.mixer[0].volume = 0.0f; }, false);
  17646. struct Step
  17647. {
  17648. juce::String name;
  17649. std::function<void()> setup;
  17650. std::function<void (int)> action; // per frame; none: the step watches the window for `frames` ms
  17651. int frames;
  17652. std::function<juce::String()> finish = {}; // round 173f: after the step, its own lines for the report
  17653. };
  17654. struct UiPerf final : juce::Timer
  17655. {
  17656. LynxApplication& app;
  17657. juce::File report;
  17658. juce::String text;
  17659. std::vector<Step> steps;
  17660. std::size_t step = 0;
  17661. int frame = -1;
  17662. std::vector<double> times, rendered; // whole frames (event + paint + blit, when this timer paints) / the window's paints
  17663. std::vector<double> frames; // round 173f: the time of every frame the window painted (ui/FrameProbe.h)
  17664. double paintedPixels = 0.0; // round 190ge: the dirty area of those frames, summed (overdraw / repaint storms)
  17665. double setupMs = 0.0, wallStart = 0.0;
  17666. double cpuStart = 0.0; // process CPU seconds (std::clock is wall time on Windows)
  17667. bool threadsWanted = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_THREADS", {}) == "1";
  17668. std::vector<lynx::ThreadCpu> threadsStart;
  17669. double messageCpuStart = 0.0; // the message thread's CPU seconds
  17670. // round 190jx: LYNX_UIPERF_PEER_PID=<pid> (Linux): another process's CPU over each step too (the X server, which
  17671. // draws the overlay's marks there)
  17672. int peerPid = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_PEER_PID", "0").getIntValue();
  17673. double peerCpuStart = 0.0;
  17674. static double peerCpuSeconds (int pid)
  17675. {
  17676. if (pid <= 0)
  17677. return 0.0;
  17678. const auto stat = juce::File ("/proc/" + juce::String (pid) + "/stat").loadFileAsString();
  17679. const auto fields = juce::StringArray::fromTokens (stat.fromLastOccurrenceOf (")", false, false), " ", "");
  17680. // (after the name: state is field 0, utime 11, stime 12, in clock ticks)
  17681. return fields.size() > 12 ? (fields[11].getDoubleValue() + fields[12].getDoubleValue()) / 100.0 : 0.0;
  17682. }
  17683. int presentsStart = 0; // round 190jy: Direct2D presents of every LYNX window (Windows)
  17684. double audioLoadSum = 0.0; // the device's CPU use (AudioDeviceManager::getCpuUsage), summed per tick
  17685. int audioLoadTicks = 0;
  17686. // round 190kb: exact CPU cycles, the worker pool's waiting, the callbacks' deadlines, the Direct2D presents
  17687. std::uint64_t cyclesStart = 0;
  17688. lynx::WorkerPool::Stats poolStart;
  17689. lynx::RtStats::Snapshot rtStart; // (presentsStart: 190jy's, above)
  17690. std::map<std::string, std::pair<long long, long long>> tickersStart; // round 190kr
  17691. int coveredStart = 0;
  17692. // round 190os: LYNX_UIPERF_STALLS=<folder>, each step's wall-clock thread samples and frame times there
  17693. // (crashguard::startStallSampler; perf190os/s/stalls.py)
  17694. juce::String stallsFolder = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_STALLS", {});
  17695. UiPerf (LynxApplication& a, juce::File r) : app (a), report (std::move (r))
  17696. {
  17697. lynx::WorkerPool::nameCurrentThread ("LYNX message thread"); // (round 190kb: the threads' lines)
  17698. }
  17699. juce::ComponentPeer* peer() const { return app.mainWindow != nullptr ? app.mainWindow->getPeer() : nullptr; }
  17700. double paintNow() const
  17701. {
  17702. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  17703. if (auto* p = peer())
  17704. p->performAnyPendingRepaintsNow();
  17705. return juce::Time::getMillisecondCounterHiRes() - t0;
  17706. }
  17707. void timerCallback() override
  17708. {
  17709. if (step >= steps.size())
  17710. {
  17711. stopTimer();
  17712. finish();
  17713. return;
  17714. }
  17715. auto& s = steps[step];
  17716. if (frame < 0)
  17717. {
  17718. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  17719. if (s.setup)
  17720. s.setup();
  17721. paintNow();
  17722. setupMs = juce::Time::getMillisecondCounterHiRes() - t0;
  17723. times.clear();
  17724. rendered.clear();
  17725. frames.clear();
  17726. paintedPixels = 0.0;
  17727. wallStart = juce::Time::getMillisecondCounterHiRes();
  17728. cpuStart = lynx::processCpuSeconds();
  17729. messageCpuStart = lynx::threadCpuSeconds();
  17730. peerCpuStart = peerCpuSeconds (peerPid);
  17731. // round 190os: LYNX_UIPERF_UIPRIO="<priority>[,m]" — the UI's helper threads (Direct2D's swap chain
  17732. // waiters, the vblank and timer threads; with ",m" the message thread too) at that Windows thread
  17733. // priority, for the stall A/B
  17734. if (const auto prio = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_UIPRIO", {}); prio.isNotEmpty())
  17735. text << " (UI threads at priority " << prio.getIntValue() << ": "
  17736. << lynx::setThreadPriorities ({ "swap chain", "VBlank", "Timer" }, prio.endsWith (",m"), prio.getIntValue()) << " set)\n";
  17737. // LYNX_UIPERF_DRVPRIO=<priority>: the graphics driver's own threads in this process (NVIDIA, AMD, Intel)
  17738. if (const auto prio = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DRVPRIO", {}); prio.isNotEmpty())
  17739. text << " (driver threads at priority " << prio.getIntValue() << ": "
  17740. << lynx::setThreadPriorities ({ "module:nvwgf2um", "module:amdxx", "module:atidxx", "module:igd10", "module:igd12" }, false, prio.getIntValue()) << " set)\n";
  17741. if (stallsFolder.isNotEmpty())
  17742. lynx::crashguard::startStallSampler ({ "swap chain", "VBlank", "Timer" }, 2000, &app.engine->getOverloadGuard().stateTag());
  17743. presentsStart = uiPerfPresents();
  17744. if (threadsWanted) // round 190ih: LYNX_UIPERF_THREADS=1, the CPU of every thread over the step
  17745. threadsStart = lynx::threadCpuList();
  17746. lynx::grossBeatPaintStats (true);
  17747. cyclesStart = lynx::processCpuCycles();
  17748. tickersStart = lynx::ui::FrameTicker::perOwner();
  17749. coveredStart = lynx::nativechild::coveredSkips().load();
  17750. if (const auto* pool = app.engine->getWorkerPool())
  17751. poolStart = pool->stats();
  17752. rtStart = app.engine->getRtStats().snapshot();
  17753. audioLoadSum = 0.0;
  17754. audioLoadTicks = 0;
  17755. frame = 0;
  17756. return;
  17757. }
  17758. audioLoadSum += app.engine->getDeviceManager().getCpuUsage();
  17759. ++audioLoadTicks;
  17760. if (s.action)
  17761. s.action (frame);
  17762. if (const auto ms = paintNow(); ms > 0.25) // (nothing to paint: not a frame)
  17763. times.push_back (ms);
  17764. ++frame;
  17765. if (s.action ? frame < s.frames : juce::Time::getMillisecondCounterHiRes() - wallStart < (double) s.frames)
  17766. return;
  17767. const auto wall = juce::Time::getMillisecondCounterHiRes() - wallStart;
  17768. const auto cpu = 1000.0 * (lynx::processCpuSeconds() - cpuStart);
  17769. const auto messageCpu = 1000.0 * (lynx::threadCpuSeconds() - messageCpuStart);
  17770. text << s.name << ": show " << juce::String (setupMs, 1) << " ms\n"
  17771. << " painted frames: " << stats (rendered) << "\n"
  17772. << " timed here (event + paint + blit): " << stats (times)
  17773. << "\n window frames (probe): " << lynx::ui::FrameStats::of (frames, wall).describe()
  17774. << ", painted " << juce::String (wall > 0.0 ? paintedPixels / wall / 1000.0 : 0.0, 2) << " Mpx/s"
  17775. << "\n CPU " << juce::String (wall > 0.0 ? 100.0 * cpu / wall : 0.0, 0) << "% (process, " << juce::String (wall / 1000.0, 1) << " s), message thread "
  17776. << juce::String (wall > 0.0 ? 100.0 * messageCpu / wall : 0.0, 1) << "%, audio device "
  17777. << juce::String (audioLoadTicks > 0 ? 100.0 * audioLoadSum / audioLoadTicks : 0.0, 1) << "%\n";
  17778. if (peerPid > 0 && wall > 0.0)
  17779. text << " peer process " << peerPid << " CPU " << juce::String (100.0 * 1000.0 * (peerCpuSeconds (peerPid) - peerCpuStart) / wall, 1) << "%\n";
  17780. // round 190jy: every LYNX window's Direct2D presents (the main window's and each native child's) and how
  17781. // the docked LYNX editors were drawn
  17782. {
  17783. int native = 0, inMain = 0, hidden = 0;
  17784. for (auto* w : lynx::dockedEditorWindows())
  17785. if (w != nullptr)
  17786. (! w->isVisible() ? hidden : lynx::isEditorInMainWindow (*w) ? inMain : native) += 1;
  17787. text << " presents " << juce::String (wall > 0.0 ? 1000.0 * (uiPerfPresents() - presentsStart) / wall : 0.0, 1)
  17788. << "/s; docked editors: " << native << " own windows, " << inMain << " in the main window, " << hidden << " hidden\n";
  17789. }
  17790. const auto cycleRate = lynx::cpuCyclesPerSecond();
  17791. if (cycleRate > 0.0 && wall > 0.0)
  17792. text << " CPU cycles " << juce::String (100.0 * (double) (lynx::processCpuCycles() - cyclesStart) / cycleRate / (wall / 1000.0), 1)
  17793. << "% (process, exact); presents " << juce::String (1000.0 * (uiPerfPresents() - presentsStart) / wall, 1) << "/s\n";
  17794. if (const auto* pool = app.engine->getWorkerPool(); pool != nullptr && wall > 0.0)
  17795. {
  17796. // round 190kb: per second of the step (time in ms/s = tenths of a percent of one core)
  17797. const auto p = pool->stats();
  17798. const auto& a = poolStart;
  17799. const auto perS = [wall] (std::uint64_t v) { return juce::String (1000.0 * (double) v / wall, 0); };
  17800. const auto msS = [wall] (std::uint64_t ns) { return juce::String ((double) ns / 1.0e6 * 1000.0 / wall, 2); };
  17801. text << " pool: rounds " << perS (p.rounds - a.rounds) << "/s; workers work " << msS (p.workNs - a.workNs)
  17802. << " ms/s, spin " << msS (p.spinNs - a.spinNs) << " ms/s (" << perS (p.spins - a.spins) << "/s: found "
  17803. << perS (p.spinFound - a.spinFound) << ", parked " << perS (p.spinParked - a.spinParked) << ", timed out "
  17804. << perS (p.spinTimedOut - a.spinTimedOut) << "), sleeps " << perS (p.sleeps - a.sleeps) << "/s (early "
  17805. << perS (p.earlyWakes - a.earlyWakes) << "); waits " << msS (p.waitNs - a.waitNs) << " ms/s (" << perS (p.waits - a.waits)
  17806. << "/s, yields " << perS (p.waitYields - a.waitYields) << ", sleeps " << perS (p.waitSleeps - a.waitSleeps) << " = " << msS (p.waitSleepNs - a.waitSleepNs) << " ms/s"
  17807. << "); caller wait " << msS (p.callerWaitNs - a.callerWaitNs) << " ms/s (sleeps " << perS (p.callerSleeps - a.callerSleeps) << "/s)\n";
  17808. }
  17809. {
  17810. const auto r = app.engine->getRtStats().snapshot();
  17811. text << " callbacks " << juce::String ((juce::int64) (r.callbacks - rtStart.callbacks)) << ", over the deadline "
  17812. << juce::String ((juce::int64) (r.overBudget - rtStart.overBudget)) << ", 80-100 % " << juce::String ((juce::int64) (r.nearBudget - rtStart.nearBudget))
  17813. << ", late " << juce::String ((juce::int64) (r.lateCalls - rtStart.lateCalls)) << "\n";
  17814. // round 190ok (P24): Settings › Audio › "Safe overloads" (core/OverloadGuard.h), since the start
  17815. const auto& guard = app.engine->getOverloadGuard();
  17816. text << " safe overloads " << (guard.isEnabled() ? "on" : "off") << ": engaged " << (juce::int64) guard.timesEngaged()
  17817. << " times" << (guard.engaged() ? " (now)" : "") << ", yielded " << juce::String (guard.yieldedMs(), 0) << " ms"
  17818. // round 190px: the render-ahead thread's catch-up paced while the UI starved
  17819. << ", render-ahead paced " << (juce::int64) guard.timesPaced() << " times (" << juce::String (guard.pacedMs(), 0) << " ms)";
  17820. // round 190os: the last release in this step — why, and how long after the callbacks kept their
  17821. // deadline again
  17822. if (const auto at = guard.lastReleaseAtMs(); at >= wallStart && guard.lastReleaseReason() != lynx::OverloadGuard::notReleased)
  17823. {
  17824. const char* why[] { "", "the transport stopped", "the load dropped", "a probe passed" };
  17825. text << "; let go " << juce::String (at - wallStart, 0) << " ms into the step (" << why[juce::jlimit (0, 3, guard.lastReleaseReason())]
  17826. << ", " << juce::String (guard.lastReleaseLagMs(), 0) << " ms after the callbacks kept their deadline)";
  17827. }
  17828. text << "\n";
  17829. }
  17830. if (threadsWanted && wall > 0.0)
  17831. {
  17832. // (round 190kb: and each thread's exact cycles in brackets, as % of one core; sorted by them where known)
  17833. std::vector<std::pair<double, juce::String>> rows;
  17834. for (const auto& t : lynx::threadCpuList())
  17835. {
  17836. auto before = 0.0;
  17837. std::uint64_t cyclesBefore = 0;
  17838. for (const auto& b : threadsStart)
  17839. if (b.id == t.id)
  17840. before = b.seconds, cyclesBefore = b.cycles;
  17841. const auto used = t.seconds - before;
  17842. const auto exact = cycleRate > 0.0 ? 100.0 * (double) (t.cycles - cyclesBefore) / cycleRate / (wall / 1000.0) : -1.0;
  17843. if (used > 0.0005 || exact > 0.05)
  17844. rows.push_back ({ exact >= 0.0 ? exact : 100.0 * 1000.0 * used / wall,
  17845. juce::String (t.id) + " " + (t.name.empty() ? juce::String ("(unnamed)") : juce::String (t.name)) + " "
  17846. + juce::String (100.0 * 1000.0 * used / wall, 1) + "%" + (exact >= 0.0 ? " [" + juce::String (exact, 1) + "%]" : juce::String()) });
  17847. }
  17848. std::sort (rows.begin(), rows.end(), [] (const auto& a, const auto& b) { return a.first > b.first; });
  17849. text << " threads:";
  17850. for (std::size_t k = 0; k < rows.size() && k < 16; ++k)
  17851. text << " " << rows[k].second << ";";
  17852. text << "\n";
  17853. }
  17854. if (const auto gb = lynx::grossBeatPaintStats (false); gb.isNotEmpty())
  17855. text << " " << gb << "\n";
  17856. // round 190kr: LYNX_UIPERF_TICKERS=1, the live views' frame steps per second (run / moved) and the steps
  17857. // left out because the view's docked panel was covered
  17858. if (lynx::ui::FrameTicker::perOwnerWanted() && wall > 0.0)
  17859. {
  17860. text << " tickers:";
  17861. for (const auto& [name, counts] : lynx::ui::FrameTicker::perOwner())
  17862. {
  17863. const auto before = tickersStart.count (name) != 0 ? tickersStart.at (name) : std::pair<long long, long long> {};
  17864. if (counts.first != before.first)
  17865. text << " " << juce::String (name).fromLastOccurrenceOf ("::", false, false).retainCharacters ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_")
  17866. << " " << juce::String (1000.0 * (double) (counts.first - before.first) / wall, 0) << "/" << juce::String (1000.0 * (double) (counts.second - before.second) / wall, 0);
  17867. }
  17868. text << "; covered skips " << juce::String (1000.0 * (double) (lynx::nativechild::coveredSkips().load() - coveredStart) / wall, 0) << "/s\n";
  17869. }
  17870. if (stallsFolder.isNotEmpty())
  17871. {
  17872. juce::File (stallsFolder).createDirectory();
  17873. lynx::crashguard::stopStallSampler (juce::File (stallsFolder).getChildFile ("stall-" + juce::String ((int) step) + ".txt").getFullPathName().toStdString());
  17874. juce::String list;
  17875. for (const auto t : frames)
  17876. list << juce::String (t, 3) << "\n";
  17877. juce::File (stallsFolder).getChildFile ("frames-" + juce::String ((int) step) + ".txt").replaceWithText (list);
  17878. text << " stall samples: " << stallsFolder << " (step " << (int) step << ")\n";
  17879. }
  17880. if (s.finish)
  17881. text << s.finish();
  17882. juce::File (report).replaceWithText (text);
  17883. ++step;
  17884. frame = -1;
  17885. }
  17886. static juce::String stats (std::vector<double> sorted)
  17887. {
  17888. std::sort (sorted.begin(), sorted.end());
  17889. 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()))]; };
  17890. double sum = 0.0;
  17891. int over = 0, over33 = 0;
  17892. for (auto t : sorted)
  17893. {
  17894. sum += t;
  17895. over += t > 16.0 ? 1 : 0;
  17896. over33 += t > 33.0 ? 1 : 0; // (round 190ry: two frames missed at 60 Hz)
  17897. }
  17898. return juce::String ((int) sorted.size()) + ", mean " + juce::String (sorted.empty() ? 0.0 : sum / (double) sorted.size(), 1)
  17899. + " ms, p95 " + juce::String (at (0.95), 1) + " ms, max " + juce::String (sorted.empty() ? 0.0 : sorted.back(), 1)
  17900. + " ms, >16 ms " + juce::String (over) + ", p99 " + juce::String (at (0.99), 1) + " ms, >33 ms " + juce::String (over33);
  17901. }
  17902. void finish()
  17903. {
  17904. // the cost of asking where the mouse is (X11: a round trip to the display server)
  17905. const auto q0 = juce::Time::getMillisecondCounterHiRes();
  17906. for (int i = 0; i < 100; ++i)
  17907. juce::ignoreUnused (juce::Desktop::getInstance().getMainMouseSource().getScreenPosition());
  17908. text << "mouse position query: " << juce::String ((juce::Time::getMillisecondCounterHiRes() - q0) / 100.0, 3) << " ms\n";
  17909. app.mainWindow->onFrame = nullptr;
  17910. app.mainWindow->watchFrames ({});
  17911. app.engine->stop();
  17912. text << "result=OK\n";
  17913. report.replaceWithText (text);
  17914. app.setApplicationReturnValue (0);
  17915. app.quit();
  17916. }
  17917. };
  17918. auto* ui = &mainWindow->getContent();
  17919. auto wheelAt = [this] (juce::Component& target, float dx, float dy, juce::ModifierKeys mods) {
  17920. auto* peer = mainWindow->getPeer();
  17921. if (peer == nullptr || ! target.isShowing())
  17922. return;
  17923. juce::ModifierKeys::currentModifiers = mods;
  17924. const auto local = peer->globalToLocal (target.localPointToGlobal (target.getLocalBounds().getCentre()).toFloat());
  17925. juce::MouseWheelDetails wheel { dx, dy, false, false, false };
  17926. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  17927. juce::ModifierKeys::currentModifiers = {};
  17928. };
  17929. auto run = std::make_unique<UiPerf> (*this, report);
  17930. mainWindow->onFrame = [r = run.get()] (double ms) { if (r->frame >= 0) r->rendered.push_back (ms); };
  17931. // round 173f: every frame the window paints; a fader drag's moves count as shown when a frame covers the fader
  17932. auto drag = std::make_shared<UiPerfDrag>();
  17933. auto latency = std::make_shared<UiPerfLatency>(); // (round 190ry)
  17934. mainWindow->watchFrames ([r = run.get(), drag, latency] (double now, juce::Rectangle<int> area) {
  17935. if (r->frame >= 0)
  17936. {
  17937. r->frames.push_back (now);
  17938. r->paintedPixels += (double) area.getWidth() * (double) area.getHeight();
  17939. }
  17940. drag->framePainted (now, area);
  17941. latency->framePainted (now, area);
  17942. });
  17943. run->text << "project: " << project.getFullPathName() << "\n"
  17944. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  17945. << juce::SystemStats::getCpuModel() << ", window " << mainWindow->getWidth() << "x" << mainWindow->getHeight()
  17946. << ", scale " << juce::String (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
  17947. ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale : 1.0, 2)
  17948. << ", audio device " << (engine->getDeviceManager().getCurrentAudioDevice() != nullptr ? engine->getDeviceManager().getCurrentAudioDevice()->getName() : juce::String ("none")) << "\n"
  17949. << "load " << juce::String (loadMs / 1000.0, 2) << " s\n";
  17950. const auto none = juce::ModifierKeys();
  17951. // discussion #10 (round 173f): the reporter's screen — the Channel Rack and the Mixer open, the pattern playing —
  17952. // watched as it is, then insert 3's fader dragged up and down with the mouse (125 moves a second through the
  17953. // window's own mouse path, the frames painted as the window paints them)
  17954. const auto dragTrack = engine->getSong().mixer.size() > 3 ? 3 : 1;
  17955. run->steps.push_back ({ "rack + mixer, pattern playing", [this, ui] {
  17956. ui->showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  17957. engine->getTransport().songMode = false;
  17958. engine->rewind();
  17959. engine->play();
  17960. }, {}, 4000 });
  17961. run->steps.push_back ({ "fader drag by mouse, rack + mixer, pattern playing", [this, ui, drag, dragTrack] {
  17962. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  17963. const auto rail = strips.faderRailForSnapshot (dragTrack);
  17964. drag->start (*mainWindow, strips, rail, engine.get(), dragTrack);
  17965. }, {}, 3000, [drag] { return drag->stop(); } });
  17966. run->steps.push_back ({ "song stopped during the drag", {}, {}, 500, [drag] { return drag->release(); } });
  17967. run->steps.push_back ({ "after the drag (released)", {}, {}, 600, [drag] { return drag->released(); } });
  17968. run->steps.push_back ({ "desktop, playing", [this, ui] { ui->showDesktopForSnapshot (false); engine->rewind(); engine->play(); }, {}, 3000 });
  17969. run->steps.push_back ({ "mixer maximised, playing", [ui] { ui->selectTabForSnapshot (3); }, {}, 3000 });
  17970. // round 177a: only the meters move, so the strips' picture must stay valid, also with a folded group's tab and VCA
  17971. // strips on screen (their levels are drawn over the picture, like the inserts' meters)
  17972. run->steps.push_back ({ "mixer meters over the picture, playing", [this, ui] {
  17973. ui->selectTabForSnapshot (3);
  17974. engine->getTransport().songMode = false;
  17975. engine->rewind();
  17976. engine->play();
  17977. ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  17978. }, {}, 6000, [this, ui, report] {
  17979. const auto [spoiled, refills] = ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  17980. if (juce::FileOutputStream out (report.withFileExtension ("png")); out.openedOk())
  17981. {
  17982. out.setPosition (0);
  17983. out.truncate();
  17984. juce::PNGImageFormat().writeImageToStream (mainWindow->createComponentSnapshot (mainWindow->getLocalBounds()), out);
  17985. }
  17986. return juce::String (" mixer picture: spoiled ") + juce::String (spoiled) + " times, drawn again " + juce::String (refills) + " times\n";
  17987. } });
  17988. // (round 190my: the wheel goes to a strip's blank body near the Mixer's centre — since 293333ae6's Current strip the
  17989. // centre itself can be a control, which the wheel would turn instead of scrolling; trace 190my: the strips then
  17990. // move from x -56 to -325 in a 1113 px view. Strips that fit their view can't scroll: the step uses Extra large
  17991. // then, e.g. at a wide window.)
  17992. auto scrollLayout = std::make_shared<std::optional<lynx::mixerlayout::Layout>>();
  17993. auto scrollTrace = std::make_shared<juce::String>();
  17994. run->steps.push_back ({ "mixer scroll",
  17995. [ui, scrollLayout, scrollTrace] {
  17996. scrollTrace->clear();
  17997. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  17998. const auto* holder = strips.getParentComponent();
  17999. if (holder != nullptr && strips.getWidth() <= holder->getWidth() + 200)
  18000. {
  18001. *scrollLayout = lynx::MixerStrips::layout;
  18002. strips.setLayout (lynx::mixerlayout::Layout::extraLarge);
  18003. }
  18004. },
  18005. [this, ui, scrollTrace] (int f) {
  18006. auto& mixer = ui->getMixerForSnapshot();
  18007. auto& strips = mixer.getStripsForSnapshot();
  18008. auto* peer = mainWindow->getPeer();
  18009. if (peer == nullptr || ! strips.isShowing())
  18010. return;
  18011. const auto centre = strips.getLocalPoint (&mixer, mixer.getLocalBounds().getCentre());
  18012. const auto at = strips.wheelScrollPointForPerf (centre, strips.getParentComponent() != nullptr
  18013. ? strips.getLocalArea (strips.getParentComponent(), strips.getParentComponent()->getLocalBounds())
  18014. : strips.getLocalBounds());
  18015. const auto local = peer->globalToLocal (strips.localPointToGlobal (at).toFloat());
  18016. juce::ModifierKeys::currentModifiers = {};
  18017. juce::MouseWheelDetails wheel { 0.0f, f < 30 ? -0.25f : 0.25f, false, false, false };
  18018. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  18019. if (f == 0 || f == 29)
  18020. {
  18021. auto* under = peer->getComponent().getComponentAt (local.roundToInt());
  18022. const auto* holder = strips.getParentComponent();
  18023. *scrollTrace << " mixer scroll frame " << f << ": wheel at " << at.toString() << " (strips), under it "
  18024. << (under == &strips ? juce::String ("the strips") : under != nullptr ? juce::String (typeid (*under).name()) : juce::String ("nothing"))
  18025. << ", view " << (holder != nullptr ? holder->getBounds().toString() : juce::String()) << ", strips at x " << strips.getX() << "\n";
  18026. }
  18027. }, 60,
  18028. [ui, scrollLayout, scrollTrace] {
  18029. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  18030. const auto width = strips.getWidth();
  18031. juce::String used = scrollLayout->has_value() ? "Extra large (the strips fit the view in their layout)" : "the project's layout";
  18032. if (scrollLayout->has_value())
  18033. strips.setLayout (**scrollLayout);
  18034. scrollLayout->reset();
  18035. return juce::String (" mixer scroll: strips ") + juce::String (width) + " px, " + used + "\n" + *scrollTrace;
  18036. } });
  18037. // a fader dragged while the song plays (round 171c, discussion #10): 4 mouse moves per frame on insert 1's fader,
  18038. // through the old path (a whole snapshot per move) and through editLevels
  18039. auto faderMove = [this] (bool levels, int f) {
  18040. for (int k = 0; k < 4; ++k)
  18041. {
  18042. const auto v = 0.5f + 0.3f * std::sin ((float) (f * 4 + k) * 0.05f);
  18043. const auto edit = [v] (lynx::Song& s) { if (s.mixer.size() > 1) s.mixer[1].volume = v; };
  18044. if (levels)
  18045. engine->editLevels (edit, false); // (no undo step: in a real drag only the press saves one)
  18046. else
  18047. engine->editSong (edit, false);
  18048. }
  18049. };
  18050. run->steps.push_back ({ "mixer fader drag, playing, rebuild per move (before 171c)", {}, [faderMove] (int f) { faderMove (false, f); }, 60 });
  18051. run->steps.push_back ({ "mixer fader drag, playing, live levels (171c)", {}, [faderMove, this] (int f) { faderMove (true, f); if (f == 59) engine->flushLevels(); }, 60 });
  18052. // F8's Plugin picker (round 171c): opening it (the "show" time = building it + its first paint), its pictures
  18053. // loading while it stays open, pointing at the tiles, then closing it
  18054. run->steps.push_back ({ "plugin picker open (F8)", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 2500 });
  18055. run->steps.push_back ({ "plugin picker, pointing at tiles", {}, [ui] (int f) {
  18056. // (round 175b: the picker is its own window)
  18057. if (auto* picker = ui->pluginPickerForSnapshot(); picker != nullptr && picker->getPeer() != nullptr)
  18058. {
  18059. const auto p = picker->localPointToGlobal (juce::Point<int> (60 + (f * 37) % juce::jmax (1, picker->getWidth() - 120),
  18060. 90 + (f * 53) % juce::jmax (1, picker->getHeight() - 200)));
  18061. const auto local = picker->getPeer()->globalToLocal (p.toFloat());
  18062. picker->getPeer()->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, {}, 0.0f, 0.0f,
  18063. juce::Time::currentTimeMillis());
  18064. }
  18065. }, 60 });
  18066. run->steps.push_back ({ "plugin picker close", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 300 });
  18067. run->steps.push_back ({ "playlist maximised, playing", [ui] { ui->selectTabForSnapshot (2); }, {}, 3000 });
  18068. run->steps.push_back ({ "playlist scroll down/up", [this] { engine->stop(); },
  18069. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
  18070. run->steps.push_back ({ "playlist scroll sideways", {},
  18071. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
  18072. // round 174f: Ctrl+wheel zoom, a notch every third frame (~20 a second), three in then three out, as dupmon drives it
  18073. run->steps.push_back ({ "playlist zoom (Ctrl+wheel)", {},
  18074. [wheelAt, ui] (int f) {
  18075. if (f % 3 == 0)
  18076. wheelAt (ui->getPlaylistForSnapshot(), 0.0f, (f / 9) % 2 == 0 ? 0.15f : -0.15f, juce::ModifierKeys (juce::ModifierKeys::ctrlModifier));
  18077. }, 120 });
  18078. run->steps.push_back ({ "playlist after the zoom (settles)", {}, {}, 500 });
  18079. // round 190qe (TOP-NEXT R1): "edgescroll" — a clip held 20 px past the Playlist's right edge for 2 s: the view runs on
  18080. // 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
  18081. // (compare "playlist maximised, playing"); the move is undone after. "UX-A10" — the overview strip's window dragged
  18082. // sideways for 5 s while the song plays: the playhead drawn must move every frame (no stall, then jump, as FL's)
  18083. {
  18084. struct FeelPerf
  18085. {
  18086. double startScroll = 0.0, startMs = 0.0, ppt = 1.0;
  18087. juce::Point<int> press, held;
  18088. std::vector<double> playheads;
  18089. int stalls = 0, longestStall = 0, run = 0;
  18090. };
  18091. auto feel = std::make_shared<FeelPerf>();
  18092. auto inject = [this] (juce::Component& target, juce::Point<int> p, bool down) {
  18093. auto* peer = mainWindow->getPeer();
  18094. if (peer == nullptr)
  18095. return;
  18096. const auto mods = down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys();
  18097. juce::ModifierKeys::currentModifiers = mods;
  18098. const auto local = peer->globalToLocal (target.localPointToGlobal (p).toFloat());
  18099. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, mods, juce::MouseInputSource::defaultPressure,
  18100. juce::MouseInputSource::defaultOrientation, juce::Time::currentTimeMillis());
  18101. };
  18102. run->steps.push_back ({ "playlist edgescroll: a clip held 20 px past the right edge (2 s)", [this, ui, feel, inject] {
  18103. engine->stop();
  18104. ui->selectTabForSnapshot (2);
  18105. auto& pl = ui->getPlaylistForSnapshot();
  18106. const auto grid = pl.gridAreaForSnapshot();
  18107. // the first clip at least 24 px wide fully in view
  18108. const auto& list = engine->getSong().playlist;
  18109. for (int i = 0; i < (int) list.size(); ++i)
  18110. if (const auto b = pl.clipBoundsForSnapshot (i); b.getWidth() >= 24 && grid.contains (b) && b.getHeight() >= 12)
  18111. {
  18112. feel->press = { b.getX() + 12, b.getBottom() - 4 };
  18113. break;
  18114. }
  18115. feel->held = { grid.getRight() - 1 + 20, feel->press.y };
  18116. feel->startScroll = pl.viewNowForTests().scroll;
  18117. feel->ppt = pl.viewNowForTests().pixelsPerUnit;
  18118. inject (pl, feel->press, false);
  18119. inject (pl, feel->press, true);
  18120. inject (pl, { (feel->press.x + feel->held.x) / 2, feel->press.y }, true);
  18121. inject (pl, feel->held, true);
  18122. feel->startMs = juce::Time::getMillisecondCounterHiRes();
  18123. }, {}, 2000, [this, ui, feel, inject] {
  18124. auto& pl = ui->getPlaylistForSnapshot();
  18125. const auto ms = juce::Time::getMillisecondCounterHiRes() - feel->startMs;
  18126. const auto moved = (pl.viewNowForTests().scroll - feel->startScroll) * feel->ppt;
  18127. inject (pl, feel->held, false);
  18128. juce::ModifierKeys::currentModifiers = {};
  18129. engine->undo();
  18130. return " edge scroll: " + juce::String (moved, 0) + " px in " + juce::String (ms / 1000.0, 2) + " s = "
  18131. + 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 "
  18132. + feel->press.toString() + ")\n";
  18133. } });
  18134. run->steps.push_back ({ "playlist overview drag while playing (UX-A10, 5 s)", [this, ui, feel, inject] {
  18135. ui->selectTabForSnapshot (2);
  18136. auto& pl = ui->getPlaylistForSnapshot();
  18137. pl.setViewForSnapshot (64.0, 0, 0);
  18138. engine->getTransport().songMode = true;
  18139. engine->rewind();
  18140. engine->play();
  18141. auto& strip = pl.overviewForSnapshot();
  18142. const auto w = strip.windowAreaForSnapshot();
  18143. feel->press = pl.getLocalPoint (&strip, juce::Point<int> ((int) w.getCentreX(), (int) w.getCentreY()));
  18144. feel->playheads.clear();
  18145. feel->stalls = feel->longestStall = feel->run = 0;
  18146. inject (pl, feel->press, false);
  18147. inject (pl, feel->press, true);
  18148. },
  18149. [ui, feel, inject] (int f) {
  18150. auto& pl = ui->getPlaylistForSnapshot();
  18151. // 2 px a frame to the right for 2.5 s, then back
  18152. const auto dx = f < 150 ? 2 * f : 2 * (300 - f);
  18153. inject (pl, feel->press.translated (dx, 0), true);
  18154. const auto now = pl.playheadTickForSnapshot();
  18155. if (! feel->playheads.empty() && now == feel->playheads.back())
  18156. {
  18157. feel->longestStall = juce::jmax (feel->longestStall, ++feel->run);
  18158. ++feel->stalls;
  18159. }
  18160. else
  18161. feel->run = 0;
  18162. feel->playheads.push_back (now);
  18163. }, 300, [this, ui, feel, inject] {
  18164. auto& pl = ui->getPlaylistForSnapshot();
  18165. inject (pl, feel->press, false);
  18166. juce::ModifierKeys::currentModifiers = {};
  18167. engine->stop();
  18168. const auto ok = feel->longestStall < 2;
  18169. return " UX-A10: " + juce::String ((int) feel->playheads.size()) + " frames, the playhead stood still on "
  18170. + juce::String (feel->stalls) + " (longest run " + juce::String (feel->longestStall) + " frames) "
  18171. + (ok ? "OK" : "STALLS") + "\n";
  18172. } });
  18173. }
  18174. run->steps.push_back ({ "whole window repainted", {}, [this] (int) { mainWindow->repaint(); }, 40 });
  18175. run->steps.push_back ({ "channel rack scroll", [ui] { ui->selectTabForSnapshot (0); },
  18176. [wheelAt, ui, none] (int f) { wheelAt (ui->getRackViewportForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  18177. // round 190ge: the other main views while the pattern plays, then every view with the transport stopped and
  18178. // nothing moving (an idle view should paint nothing: its frames and painted area are the repaint storms), then
  18179. // the Clip-launch grid playing
  18180. auto playPattern = [this] {
  18181. engine->getTransport().songMode = false;
  18182. engine->rewind();
  18183. engine->play();
  18184. };
  18185. run->steps.push_back ({ "piano roll maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (1); playPattern(); }, {}, 3000 });
  18186. // round 190jx: the moving playheads alone, for the overlay's A/B (LYNX_UIPERF_ONLY="overlay A/B", LYNX_OVERLAY=0|1):
  18187. // the Playlist with the song playing and the Piano roll with the pattern playing, LYNX_UIPERF_PLAY_MS each (10 s)
  18188. {
  18189. const auto playMs = juce::jmax (1000, juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_PLAY_MS", "10000").getIntValue());
  18190. run->steps.push_back ({ "overlay A/B: playlist maximised, song playing", [this, ui] {
  18191. ui->selectTabForSnapshot (2);
  18192. engine->getTransport().songMode = true;
  18193. engine->rewind();
  18194. engine->play();
  18195. }, {}, playMs });
  18196. // round 190ok (P24): LYNX_UIPERF_RECOVERY=1 — the song stopped after it, 3 s: the safe-overload guard lets go
  18197. // and the callbacks keep their deadline again (the report's "safe overloads" line: no "(now)")
  18198. // (round 190os: and when the guard let go after the stop was asked)
  18199. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_RECOVERY", "0") == "1")
  18200. {
  18201. auto stopAt = std::make_shared<double> (0.0);
  18202. run->steps.push_back ({ "overlay A/B: playlist maximised, stopped after the song (recovery)", [this, stopAt] {
  18203. *stopAt = juce::Time::getMillisecondCounterHiRes();
  18204. engine->stop();
  18205. }, {}, 3000, [this, stopAt] {
  18206. const auto& guard = engine->getOverloadGuard();
  18207. const auto at = guard.lastReleaseAtMs();
  18208. return at >= *stopAt && guard.lastReleaseReason() != lynx::OverloadGuard::notReleased
  18209. ? " safe overloads let go " + juce::String (at - *stopAt, 1) + " ms after the stop\n"
  18210. : juce::String (" safe overloads: not let go after the stop\n");
  18211. } });
  18212. }
  18213. // round 190os: LYNX_UIPERF_LOAD_ENDS=<ms> — the song played again, and that many ms in every note and every
  18214. // playlist clip removed while the transport keeps running: the notes stop, the tails die out and the overload ends while playing.
  18215. // The report's "safe overloads" line says when the guard let go after the callbacks kept their deadline.
  18216. if (const auto endsMs = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_LOAD_ENDS", "0").getIntValue(); endsMs > 0)
  18217. {
  18218. auto emptiedAt = std::make_shared<double> (0.0);
  18219. run->steps.push_back ({ "overlay A/B: playlist maximised, the load ends while playing", [this, ui, endsMs, emptiedAt] {
  18220. ui->selectTabForSnapshot (2);
  18221. engine->getTransport().songMode = true;
  18222. engine->rewind();
  18223. engine->play();
  18224. juce::Timer::callAfterDelay (endsMs, [this, emptiedAt] {
  18225. *emptiedAt = juce::Time::getMillisecondCounterHiRes();
  18226. engine->editSong ([] (lynx::Song& song) {
  18227. for (auto& pattern : song.patterns)
  18228. pattern.notes.clear();
  18229. song.playlist.clear(); // (its audio and automation clips too)
  18230. }, false);
  18231. });
  18232. }, {}, endsMs + 4000, [this, emptiedAt] {
  18233. const auto& guard = engine->getOverloadGuard();
  18234. const auto at = guard.lastReleaseAtMs();
  18235. const auto playing = engine->getTransport().playing.load();
  18236. engine->stop();
  18237. return " notes removed (still playing: " + juce::String (playing ? "yes" : "no") + "); safe overloads "
  18238. + (at >= *emptiedAt && *emptiedAt > 0.0 ? "let go " + juce::String (at - *emptiedAt, 0) + " ms after it, "
  18239. + juce::String (guard.lastReleaseLagMs(), 0) + " ms after the callbacks kept their deadline\n"
  18240. : juce::String ("not let go after it\n"));
  18241. } });
  18242. }
  18243. run->steps.push_back ({ "overlay A/B: piano roll maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (1); playPattern(); }, {}, playMs,
  18244. [this] { engine->stop(); return juce::String(); } });
  18245. }
  18246. run->steps.push_back ({ "channel rack maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (0); playPattern(); }, {}, 3000 });
  18247. const char* idleViews[] { "channel rack", "piano roll", "playlist", "mixer" };
  18248. for (int view = 0; view < 4; ++view)
  18249. run->steps.push_back ({ juce::String ("idle: ") + idleViews[view] + ", stopped", [this, ui, view] { engine->stop(); ui->selectTabForSnapshot (view); }, {}, 3000 });
  18250. run->steps.push_back ({ "idle: desktop, stopped", [this, ui] { engine->stop(); ui->showDesktopForSnapshot (false); }, {}, 3000 });
  18251. // round 190im (R1, DE-124): the automation editor window open over the Playlist, stopped and then playing (its
  18252. // timer only while it plays, its playhead columns only); closed after
  18253. {
  18254. int automation = -1;
  18255. for (const auto& c : engine->getSong().playlist)
  18256. if (c.kind == lynx::ClipKind::automation && c.automation >= 0 && automation < 0)
  18257. automation = c.automation;
  18258. if (automation >= 0)
  18259. {
  18260. run->steps.push_back ({ "automation editor open, stopped", [this, ui, automation] {
  18261. engine->stop();
  18262. ui->selectTabForSnapshot (2);
  18263. lynx::openAutomationEditor (*engine, automation);
  18264. }, {}, 3000 });
  18265. run->steps.push_back ({ "automation editor open, song playing", [this] {
  18266. engine->getTransport().songMode = true;
  18267. engine->rewind();
  18268. engine->play();
  18269. }, {}, 3000, [this] {
  18270. engine->stop();
  18271. auto& desktop = juce::Desktop::getInstance();
  18272. for (int i = desktop.getNumComponents(); --i >= 0;)
  18273. if (auto* w = dynamic_cast<juce::DocumentWindow*> (desktop.getComponent (i)); w != nullptr && w->getName().startsWith ("Automation - "))
  18274. w->closeButtonPressed();
  18275. return juce::String();
  18276. } });
  18277. }
  18278. }
  18279. run->steps.push_back ({ "clip grid, song playing", [this, ui] {
  18280. ui->selectTabForSnapshot (2);
  18281. ui->setClipLaunchWorkflow (true);
  18282. ui->setClipGridView (lynx::PlaylistArea::GridView::grid);
  18283. engine->getTransport().songMode = true;
  18284. engine->rewind();
  18285. engine->play();
  18286. }, {}, 3000 });
  18287. // round 190gr: the grid's clips launched (every scene that has clips, one after the other: the playing cells'
  18288. // progress bars move, the launches blink until their grid point)
  18289. run->steps.push_back ({ "clip grid, clips launched", [this] {
  18290. engine->getTransport().songMode = true;
  18291. if (const auto& grid = engine->getSong().clipGrid)
  18292. for (int scene = 0; scene < juce::jmin (8, (int) grid->scenes.size()); ++scene)
  18293. engine->launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, scene });
  18294. }, {}, 3000, [this] {
  18295. int playing = 0;
  18296. if (const auto* state = engine->launcherState())
  18297. for (const auto& t : state->tracks)
  18298. playing += t.playing.load() >= 0 ? 1 : 0;
  18299. engine->launcherCommand ({ lynx::launcher::Command::Type::stopAll });
  18300. return " tracks playing a clip: " + juce::String (playing) + "\n";
  18301. } });
  18302. run->steps.push_back ({ "idle: clip grid, stopped", [this] { engine->stop(); }, {}, 3000, [ui] { ui->setClipLaunchWorkflow (false); return juce::String(); } });
  18303. // round 190jn: the Clip-launch layout's Arrangement (Live's look: 19 px lanes, colour blocks, dark waveforms) playing,
  18304. // then idle
  18305. run->steps.push_back ({ "clip arrangement, song playing", [this, ui] {
  18306. ui->selectTabForSnapshot (2);
  18307. ui->setClipLaunchWorkflow (true);
  18308. ui->setClipGridView (lynx::PlaylistArea::GridView::song);
  18309. engine->getTransport().songMode = true;
  18310. engine->rewind();
  18311. engine->play();
  18312. }, {}, 3000 });
  18313. run->steps.push_back ({ "idle: clip arrangement, stopped", [this] { engine->stop(); }, {}, 3000, [ui] {
  18314. ui->setClipGridView (lynx::PlaylistArea::GridView::grid);
  18315. ui->setClipLaunchWorkflow (false);
  18316. return juce::String();
  18317. } });
  18318. // round 190ih: the plugin windows with live parts — Gross Beat (its locator), the Formula Controller (its monitor),
  18319. // the Envelope Controller (its meters and key line) — idle with the song stopped, then Gross Beat while it plays
  18320. // (CPU and frames; the windows are their own, so the main window's painted area stays the main window's)
  18321. run->steps.push_back ({ "idle: Gross Beat + Formula + Envelope controller windows, stopped", [this] {
  18322. engine->stop();
  18323. auto& song = engine->getSong();
  18324. int gbTrack = -1, gbSlot = -1;
  18325. for (int t = 0; t < (int) song.mixer.size() && gbTrack < 0; ++t)
  18326. for (int k = 0; k < (int) song.mixer[(std::size_t) t].effects.size(); ++k)
  18327. if (song.mixer[(std::size_t) t].effects[(std::size_t) k].kind == lynx::EffectKind::grossBeat)
  18328. {
  18329. gbTrack = t;
  18330. gbSlot = k;
  18331. break;
  18332. }
  18333. const auto last = (int) song.mixer.size() - 1;
  18334. const auto formulaSlot = last >= 1 ? (int) song.mixer[(std::size_t) last].effects.size() : -1;
  18335. engine->editSong ([last] (lynx::Song& s) {
  18336. if (last >= 1 && s.mixer[(std::size_t) last].effects.size() < (std::size_t) lynx::maxEffectSlots)
  18337. s.mixer[(std::size_t) last].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::formulaController));
  18338. lynx::ChannelDef env;
  18339. env.name = "Envelope Controller";
  18340. env.instrument = lynx::InstrumentKind::controller;
  18341. env.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  18342. s.channels.push_back (env);
  18343. }, false);
  18344. engine->dispatchPendingMessages();
  18345. // LYNX_UIPERF_WINDOWS: which of them (G Gross Beat, F Formula, E Envelope Controller; default all)
  18346. const auto which = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_WINDOWS", "GFE");
  18347. if (gbTrack >= 0 && which.containsChar ('G'))
  18348. lynx::NativeEffectWindows::open (*engine, gbTrack, gbSlot);
  18349. if (formulaSlot >= 0 && which.containsChar ('F'))
  18350. lynx::FormulaControllerWindows::open (*engine, last, formulaSlot);
  18351. if (which.containsChar ('E'))
  18352. lynx::openChannelSettings (*engine, (int) engine->getSong().channels.size() - 1);
  18353. }, {}, 3000 });
  18354. // round 190ih: LYNX_UIPERF_GBAB=n — n cycles over Gross Beat's live-display variants, playing, 2.5 s each, in one
  18355. // process (other load hits every variant alike): the names carry the LYNX_GB_DIAG mask
  18356. if (const auto cycles = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_GBAB", "0").getIntValue(); cycles > 0)
  18357. {
  18358. run->steps.push_back ({ "Gross Beat A/B start", [this] {
  18359. engine->getTransport().songMode = true;
  18360. engine->rewind();
  18361. engine->play();
  18362. }, {}, 1500 });
  18363. // (off, the default, 30 / s, off, 10 / s; LYNX_UIPERF_GBAB_MASKS="1,2,0" picks others, e.g. round 190iy's
  18364. // locator on the GPU overlay (0) against the repaint path (2))
  18365. std::vector<int> masks { 1, 0, 30 << 8, 1, 10 << 8 };
  18366. if (const auto list = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_GBAB_MASKS", {}); list.isNotEmpty())
  18367. {
  18368. masks.clear();
  18369. for (const auto& m : juce::StringArray::fromTokens (list, ",", {}))
  18370. masks.push_back (m.trim().getIntValue());
  18371. }
  18372. for (int c = 0; c < cycles; ++c)
  18373. for (const int mask : masks)
  18374. run->steps.push_back ({ "Gross Beat A/B mask " + juce::String (mask) + " cycle " + juce::String (c + 1),
  18375. [this, mask] {
  18376. lynx::setGrossBeatDiagnostics (mask);
  18377. if (! engine->getTransport().playing.load()) // (the song ended: again)
  18378. {
  18379. engine->rewind();
  18380. engine->play();
  18381. }
  18382. }, {}, 2500 });
  18383. }
  18384. // round 190jy (queue item 44): LYNX_UIPERF_DOCKAB=n — the docked LYNX editors with live displays, playing, each set
  18385. // hidden / a native child window / drawn by the main window, n cycles of 2.5 s steps in one process.
  18386. // LYNX_UIPERF_DOCKAB_SETS (default "G,L,M,GLM"): G Gross Beat, L Fruity Limiter, M Maximus (both on the master).
  18387. if (const auto cycles = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKAB", "0").getIntValue(); cycles > 0)
  18388. {
  18389. auto sets = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKAB_SETS", "G,L,M,GLM"), ",", {});
  18390. auto shown = std::make_shared<std::vector<juce::Component::SafePointer<juce::DocumentWindow>>>();
  18391. auto keepPlaying = [this] {
  18392. engine->getTransport().songMode = true;
  18393. if (! engine->getTransport().playing.load()) // (the song ended: again)
  18394. {
  18395. engine->rewind();
  18396. engine->play();
  18397. }
  18398. };
  18399. for (const auto& set : sets)
  18400. {
  18401. const auto name = set.trim();
  18402. run->steps.push_back ({ "dock A/B " + name + " open", [this, name, shown, keepPlaying] {
  18403. lynx::NativeEffectWindows::closeAll();
  18404. for (auto* w : lynx::dockedEditorWindows()) // (a channel's settings window of the set before)
  18405. if (w != nullptr)
  18406. w->closeButtonPressed();
  18407. shown->clear();
  18408. auto& song = engine->getSong();
  18409. auto openKind = [this] (lynx::EffectKind kind) {
  18410. auto& so = engine->getSong();
  18411. for (int t = 0; t < (int) so.mixer.size(); ++t)
  18412. for (int k = 0; k < (int) so.mixer[(std::size_t) t].effects.size(); ++k)
  18413. if (so.mixer[(std::size_t) t].effects[(std::size_t) k].kind == kind)
  18414. {
  18415. lynx::NativeEffectWindows::open (*engine, t, k);
  18416. return;
  18417. }
  18418. // (not in the project: on the master, after its effects)
  18419. if (so.mixer.empty() || so.mixer[0].effects.size() >= (std::size_t) lynx::maxEffectSlots)
  18420. return;
  18421. const auto slot = (int) so.mixer[0].effects.size();
  18422. engine->editSong ([kind] (lynx::Song& s2) { s2.mixer[0].effects.push_back (lynx::makeEffectSlot (kind)); }, false);
  18423. engine->dispatchPendingMessages();
  18424. lynx::NativeEffectWindows::open (*engine, 0, slot);
  18425. };
  18426. juce::ignoreUnused (song);
  18427. if (name.containsChar ('G'))
  18428. openKind (lynx::EffectKind::grossBeat);
  18429. if (name.containsChar ('L'))
  18430. openKind (lynx::EffectKind::fruityLimiter);
  18431. if (name.containsChar ('M'))
  18432. openKind (lynx::EffectKind::maximus);
  18433. // S: a Slicex channel (a 2 s tone in 4 regions) that plays the notes of the project's busiest
  18434. // channel, its settings window open (its deck's play line moves while it sounds)
  18435. if (name.containsChar ('S'))
  18436. {
  18437. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-uiperf-slicex.wav");
  18438. {
  18439. juce::AudioBuffer<float> tone (2, 96000);
  18440. for (int i = 0; i < tone.getNumSamples(); ++i)
  18441. tone.setSample (0, i, 0.3f * (float) std::sin (juce::MathConstants<double>::twoPi * (200.0 + 200.0 * (i / 24000)) * i / 48000.0));
  18442. tone.copyFrom (1, 0, tone, 0, 0, tone.getNumSamples());
  18443. wav.deleteFile();
  18444. if (auto out = std::unique_ptr<juce::OutputStream> (wav.createOutputStream()))
  18445. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), 48000.0, 2, 16, {}, 0)))
  18446. {
  18447. out.release();
  18448. writer->writeFromAudioSampleBuffer (tone, 0, tone.getNumSamples());
  18449. }
  18450. }
  18451. int busiest = -1;
  18452. {
  18453. std::map<int, int> count;
  18454. for (const auto& pat : engine->getSong().patterns)
  18455. for (const auto& n : pat.notes)
  18456. ++count[n.channel];
  18457. int best = 0;
  18458. for (const auto& [ch, n] : count)
  18459. if (n > best)
  18460. best = n, busiest = ch;
  18461. }
  18462. const auto index = (int) engine->getSong().channels.size();
  18463. engine->editSong ([&wav, busiest, index] (lynx::Song& s2) {
  18464. lynx::ChannelDef ch;
  18465. ch.name = "Slicex (uiperf)";
  18466. ch.instrument = lynx::InstrumentKind::slicex;
  18467. ch.samplePath = wav.getFullPathName().toStdString();
  18468. auto state = lynx::slicex::fresh();
  18469. lynx::slicex::setDeckFile (state, 0, ch.samplePath, 4);
  18470. lynx::slicex::setDeckBeats (state, 0, 0.0, 4.0);
  18471. ch.pluginState = lynx::slicex::write (state);
  18472. s2.channels.push_back (ch);
  18473. for (auto& pat : s2.patterns)
  18474. {
  18475. std::vector<lynx::Note> copies;
  18476. for (const auto& n : pat.notes)
  18477. if (n.channel == busiest)
  18478. {
  18479. auto c = n;
  18480. c.channel = index;
  18481. c.key = 60 + (int) (copies.size() % 4); // (the four slices in turn)
  18482. copies.push_back (c);
  18483. }
  18484. pat.notes.insert (pat.notes.end(), copies.begin(), copies.end());
  18485. pat.sortNotes();
  18486. }
  18487. }, false);
  18488. engine->dispatchPendingMessages();
  18489. lynx::openChannelSettings (*engine, index);
  18490. }
  18491. for (auto* w : lynx::dockedEditorWindows())
  18492. shown->emplace_back (w);
  18493. keepPlaying();
  18494. }, {}, 1500 });
  18495. static const char* variantNames[] = { "hidden", "own window", "main window" };
  18496. for (int c = 0; c < cycles; ++c)
  18497. for (int v = 0; v < 3; ++v)
  18498. run->steps.push_back ({ "dock A/B " + name + " " + variantNames[v] + " cycle " + juce::String (c + 1), [v, shown, keepPlaying] {
  18499. if (v > 0)
  18500. lynx::moveDockedEditors (v == 2);
  18501. for (auto& w : *shown)
  18502. if (w != nullptr && w->isVisible() != (v > 0))
  18503. w->setVisible (v > 0);
  18504. keepPlaying();
  18505. }, {}, 2500 });
  18506. }
  18507. run->steps.push_back ({ "dock A/B close", [this, shown] {
  18508. engine->stop();
  18509. shown->clear();
  18510. lynx::NativeEffectWindows::closeAll();
  18511. for (auto* w : lynx::dockedEditorWindows())
  18512. if (w != nullptr)
  18513. w->closeButtonPressed();
  18514. }, {}, 500 });
  18515. }
  18516. // round 190jy: LYNX_UIPERF_DOCKCHECK=1 — the checks of a docked editor drawn by the main window (ui/DockPaintCheck.h),
  18517. // on screen in this main window; LYNX_UIPERF_DOCKCHECK_SHOTS=<folder> keeps the two on-screen pictures compared
  18518. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKCHECK", {}) == "1")
  18519. {
  18520. auto check = std::make_shared<std::unique_ptr<lynx::dockpaint::Check>>();
  18521. auto lines = std::make_shared<juce::String>();
  18522. for (int i = 0; i < lynx::dockpaint::Check::count(); ++i)
  18523. run->steps.push_back ({ "dock check " + juce::String (i), [this, ui, check, lines, i] {
  18524. if (*check == nullptr)
  18525. *check = std::make_unique<lynx::dockpaint::Check> (*engine, *ui, *mainWindow,
  18526. juce::File (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKCHECK_SHOTS", {})));
  18527. *lines = (*check)->step (i);
  18528. }, {}, 700, [lines] { return *lines; } });
  18529. }
  18530. run->steps.push_back ({ "Gross Beat window, song playing", [this] {
  18531. engine->getTransport().songMode = true;
  18532. engine->rewind();
  18533. engine->play();
  18534. }, {}, 3000, [this] {
  18535. engine->stop();
  18536. lynx::NativeEffectWindows::closeAll();
  18537. lynx::FormulaControllerWindows::closeAll();
  18538. return juce::String();
  18539. } });
  18540. // round 190kb: LYNX_UIPERF_SPINAB=n — the worker pool's waiting policies (WorkerPool::Tuning) A/B inside one
  18541. // process while the song plays with live editor windows: per set (LYNX_UIPERF_SPINAB_SETS, default "G,GLM": G
  18542. // Gross Beat, L Fruity Limiter, M Maximus; on the master when the project has none), n cycles over every
  18543. // variant (LYNX_UIPERF_SPINAB_VARIANTS="name:spec;…", spec as LYNX_POOL) with the windows hidden and shown,
  18544. // 2.5 s steps, the order turning every cycle. Run with LYNX_UIPERF_THREADS=1 for the threads' lines.
  18545. if (const auto cycles = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SPINAB", "0").getIntValue(); cycles > 0)
  18546. {
  18547. auto sets = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SPINAB_SETS", "G,GLM"), ",", {});
  18548. struct Variant
  18549. {
  18550. juce::String name, spec;
  18551. };
  18552. std::vector<Variant> variants;
  18553. for (const auto& v : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable (
  18554. "LYNX_UIPERF_SPINAB_VARIANTS", "old:spin=60,adaptive=0,wait=0;new:spin=60,adaptive=1,dry=4,wait=1,waitspin=30"),
  18555. ";", {}))
  18556. if (v.containsChar (':'))
  18557. variants.push_back ({ v.upToFirstOccurrenceOf (":", false, false).trim(), v.fromFirstOccurrenceOf (":", false, false).trim() });
  18558. auto shown = std::make_shared<std::vector<juce::Component::SafePointer<juce::Component>>>();
  18559. // every step plays the same part of the song (LYNX_UIPERF_SPINAB_AT: a fraction of the song, default 0.4): the
  18560. // audio work differs from part to part far more than between the variants (a first run without this put the
  18561. // variants of one cycle in different parts and read the parts)
  18562. auto at = std::make_shared<double> (0.0);
  18563. const auto atFraction = juce::jlimit (0.0, 0.95, juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SPINAB_AT", "0.4").getDoubleValue());
  18564. auto keepPlaying = [this, at] {
  18565. engine->getTransport().songMode = true;
  18566. engine->seek (*at);
  18567. if (! engine->getTransport().playing.load())
  18568. engine->play();
  18569. };
  18570. for (const auto& set : sets)
  18571. {
  18572. const auto name = set.trim();
  18573. run->steps.push_back ({ "spin A/B " + name + " open", [this, name, shown, keepPlaying, at, atFraction] {
  18574. *at = atFraction * engine->getTransport().songEnd.load();
  18575. lynx::NativeEffectWindows::closeAll();
  18576. shown->clear();
  18577. std::vector<juce::Component*> before;
  18578. auto& desktop = juce::Desktop::getInstance();
  18579. for (int i = 0; i < desktop.getNumComponents(); ++i)
  18580. before.push_back (desktop.getComponent (i));
  18581. auto openKind = [this] (lynx::EffectKind kind) {
  18582. auto& so = engine->getSong();
  18583. for (int t = 0; t < (int) so.mixer.size(); ++t)
  18584. for (int k = 0; k < (int) so.mixer[(std::size_t) t].effects.size(); ++k)
  18585. if (so.mixer[(std::size_t) t].effects[(std::size_t) k].kind == kind)
  18586. {
  18587. lynx::NativeEffectWindows::open (*engine, t, k);
  18588. return;
  18589. }
  18590. // (not in the project: on the master, after its effects)
  18591. if (so.mixer.empty() || so.mixer[0].effects.size() >= (std::size_t) lynx::maxEffectSlots)
  18592. return;
  18593. const auto slot = (int) so.mixer[0].effects.size();
  18594. engine->editSong ([kind] (lynx::Song& s2) { s2.mixer[0].effects.push_back (lynx::makeEffectSlot (kind)); }, false);
  18595. engine->dispatchPendingMessages();
  18596. lynx::NativeEffectWindows::open (*engine, 0, slot);
  18597. };
  18598. if (name.containsChar ('G'))
  18599. openKind (lynx::EffectKind::grossBeat);
  18600. if (name.containsChar ('L'))
  18601. openKind (lynx::EffectKind::fruityLimiter);
  18602. if (name.containsChar ('M'))
  18603. openKind (lynx::EffectKind::maximus);
  18604. for (int i = 0; i < desktop.getNumComponents(); ++i)
  18605. if (auto* c = desktop.getComponent (i); std::find (before.begin(), before.end(), c) == before.end())
  18606. shown->emplace_back (c);
  18607. keepPlaying();
  18608. }, {}, 1500, [shown, at] { return " windows of the set: " + juce::String ((int) shown->size()) + ", every step from tick " + juce::String (*at, 0) + "\n"; } });
  18609. for (int c = 0; c < cycles; ++c)
  18610. for (int k = 0; k < (int) variants.size() * 2; ++k)
  18611. {
  18612. // (the variants in turn, starting one further each cycle; hidden / shown swapped every cycle)
  18613. const auto& v = variants[(std::size_t) ((k / 2 + c) % (int) variants.size())];
  18614. const auto visible = ((k % 2) == 1) != ((c % 2) == 1);
  18615. run->steps.push_back ({ "spin A/B " + name + " " + v.name + (visible ? " shown" : " hidden") + " cycle " + juce::String (c + 1),
  18616. [spec = v.spec, visible, shown, keepPlaying] {
  18617. lynx::WorkerPool::tuning().apply (spec.toRawUTF8());
  18618. for (auto& w : *shown)
  18619. if (w != nullptr && w->isVisible() != visible)
  18620. w->setVisible (visible);
  18621. keepPlaying();
  18622. }, {}, 2500 });
  18623. }
  18624. }
  18625. run->steps.push_back ({ "spin A/B close", [this, shown] {
  18626. engine->stop();
  18627. shown->clear();
  18628. lynx::NativeEffectWindows::closeAll();
  18629. lynx::WorkerPool::tuning().apply (juce::SystemStats::getEnvironmentVariable ("LYNX_POOL", "").toRawUTF8());
  18630. }, {}, 500 });
  18631. }
  18632. // round 190iv: the Simple layout (its toolbar) idle and while the song plays
  18633. run->steps.push_back ({ "idle: simple layout, stopped", [this, ui] {
  18634. engine->stop();
  18635. ui->setLayoutStyle (lynx::layoutstyle::Style::simple, false);
  18636. }, {}, 3000 });
  18637. run->steps.push_back ({ "simple layout, song playing", [this] {
  18638. engine->getTransport().songMode = true;
  18639. engine->rewind();
  18640. engine->play();
  18641. }, {}, 3000, [this, ui] {
  18642. engine->stop();
  18643. ui->setLayoutStyle (lynx::layoutstyle::Style::pattern, false);
  18644. return juce::String();
  18645. } });
  18646. // round 190ry (Q3 fluidity, 0.1.32): the Piano roll, the Playlist and the clip grid scrolled and zoomed while
  18647. // playing; input -> paint of a note click, a knob turned, a mute button, a clip dragged and keys typed in the
  18648. // Browser's search box; the open time of the main views, the Settings window and its pages, the menus, the command
  18649. // palette, and 30 effect windows (then the song playing with them open). LYNX_UIPERF_ONLY="q3" runs these alone.
  18650. {
  18651. auto paintAll = [] {
  18652. auto& desktop = juce::Desktop::getInstance();
  18653. for (int k = 0; k < desktop.getNumComponents(); ++k)
  18654. if (auto* c = desktop.getComponent (k); c != nullptr && c->isShowing())
  18655. if (auto* p = c->getPeer())
  18656. p->performAnyPendingRepaintsNow();
  18657. };
  18658. auto mouse = [this] (juce::Component& target, juce::Point<int> p, juce::ModifierKeys mods) {
  18659. auto* peer = mainWindow->getPeer();
  18660. if (peer == nullptr)
  18661. return;
  18662. juce::ModifierKeys::currentModifiers = mods;
  18663. const auto local = peer->globalToLocal (target.localPointToGlobal (p).toFloat());
  18664. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, mods, juce::MouseInputSource::defaultPressure,
  18665. juce::MouseInputSource::defaultOrientation, juce::Time::currentTimeMillis());
  18666. };
  18667. auto inWindow = [this] (juce::Component& c, juce::Rectangle<int> r) { return mainWindow->getLocalArea (&c, r); };
  18668. const auto left = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  18669. const auto ctrl = juce::ModifierKeys (juce::ModifierKeys::ctrlModifier);
  18670. const auto ctrlLeft = juce::ModifierKeys (juce::ModifierKeys::ctrlModifier | juce::ModifierKeys::leftButtonModifier);
  18671. auto playSong = [this] (bool song) {
  18672. engine->getTransport().songMode = song;
  18673. engine->rewind();
  18674. engine->play();
  18675. };
  18676. // --- scroll and zoom while playing ----------------------------------------------------------------------
  18677. run->steps.push_back ({ "q3 playlist scroll down/up, song playing", [ui, playSong] { ui->selectTabForSnapshot (2); playSong (true); },
  18678. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
  18679. run->steps.push_back ({ "q3 playlist scroll sideways, song playing", {},
  18680. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
  18681. run->steps.push_back ({ "q3 playlist zoom (Ctrl+wheel), song playing", {},
  18682. [wheelAt, ui, ctrl] (int f) {
  18683. if (f % 3 == 0)
  18684. wheelAt (ui->getPlaylistForSnapshot(), 0.0f, (f / 9) % 2 == 0 ? 0.15f : -0.15f, ctrl);
  18685. }, 120 });
  18686. run->steps.push_back ({ "q3 piano roll scroll down/up, pattern playing", [this, ui, playSong] {
  18687. engine->stop();
  18688. ui->selectTabForSnapshot (1);
  18689. playSong (false);
  18690. },
  18691. [wheelAt, ui, none] (int f) { wheelAt (ui->getPianoRollForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
  18692. run->steps.push_back ({ "q3 piano roll scroll sideways, pattern playing", {},
  18693. [wheelAt, ui, none] (int f) { wheelAt (ui->getPianoRollForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
  18694. run->steps.push_back ({ "q3 piano roll zoom (Ctrl+wheel), pattern playing", {},
  18695. [wheelAt, ui, ctrl] (int f) {
  18696. if (f % 3 == 0)
  18697. wheelAt (ui->getPianoRollForSnapshot(), 0.0f, (f / 9) % 2 == 0 ? 0.15f : -0.15f, ctrl);
  18698. }, 120 });
  18699. run->steps.push_back ({ "q3 mixer scroll sideways, song playing", [this, ui, playSong] {
  18700. engine->stop();
  18701. ui->selectTabForSnapshot (3);
  18702. playSong (true);
  18703. },
  18704. [wheelAt, ui, none] (int f) { wheelAt (ui->getMixerForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  18705. // --- input -> paint --------------------------------------------------------------------------------------
  18706. // Ctrl+click on a note (every tool: the note joins / leaves the selection), two notes in turn so no click
  18707. // makes a double-click
  18708. run->steps.push_back ({ "q3 latency: Ctrl+click on a note (piano roll)", [this, ui] {
  18709. engine->stop();
  18710. ui->selectTabForSnapshot (1);
  18711. },
  18712. [ui, mouse, inWindow, latency, ctrl, ctrlLeft] (int f) {
  18713. if (f % 8 != 4)
  18714. return;
  18715. auto& pr = ui->getPianoRollForSnapshot();
  18716. const auto a = pr.firstVisibleNoteForSnapshot();
  18717. if (a.index < 0)
  18718. return;
  18719. const auto b = pr.firstVisibleNoteForSnapshot (a.index, { pr.getWidth(), pr.getHeight() });
  18720. const auto& n = (f / 8) % 2 == 0 || b.index < 0 ? a : b;
  18721. mouse (pr, n.bounds.getCentre(), ctrl); // (over the note first, as a real mouse)
  18722. latency->arm (inWindow (pr, n.bounds));
  18723. mouse (pr, n.bounds.getCentre(), ctrlLeft);
  18724. mouse (pr, n.bounds.getCentre(), ctrl);
  18725. juce::ModifierKeys::currentModifiers = {};
  18726. }, 192, [latency] { return latency->take ("a note's selection"); } });
  18727. // a knob: the pan knob of insert 1's strip dragged up 3 px a move (one move every 6 frames), then released
  18728. run->steps.push_back ({ "q3 latency: mixer pan knob drag", [this, ui, mouse, left] {
  18729. ui->selectTabForSnapshot (3);
  18730. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  18731. const auto pan = strips.panAreaForSnapshot (1);
  18732. mouse (strips, pan.getCentre(), {});
  18733. mouse (strips, pan.getCentre(), left);
  18734. juce::ignoreUnused (this);
  18735. },
  18736. [ui, mouse, inWindow, latency, left] (int f) {
  18737. if (f % 6 != 3)
  18738. return;
  18739. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  18740. const auto pan = strips.panAreaForSnapshot (1);
  18741. latency->arm (inWindow (strips, pan.expanded (4)));
  18742. mouse (strips, pan.getCentre().translated (0, -3 * (1 + (f / 6) % 12)), left);
  18743. }, 150, [this, ui, mouse, latency] {
  18744. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  18745. mouse (strips, strips.panAreaForSnapshot (1).getCentre(), {});
  18746. juce::ModifierKeys::currentModifiers = {};
  18747. const auto pan = engine->getSong().mixer.size() > 1 ? engine->getSong().mixer[1].pan : 0.0f;
  18748. engine->undo();
  18749. return latency->take ("the knob") + " pan of insert 1 at the release " + juce::String (pan, 3) + "\n";
  18750. } });
  18751. // a button: insert 1's mute, clicked every 30 frames (no double-click), an even number of times
  18752. run->steps.push_back ({ "q3 latency: mixer mute click", {},
  18753. [ui, mouse, inWindow, latency, left] (int f) {
  18754. if (f % 30 != 15)
  18755. return;
  18756. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  18757. const auto m = strips.muteAreaForSnapshot (1);
  18758. mouse (strips, m.getCentre(), {});
  18759. latency->arm (inWindow (strips, m));
  18760. mouse (strips, m.getCentre(), left);
  18761. mouse (strips, m.getCentre(), {});
  18762. juce::ModifierKeys::currentModifiers = {};
  18763. }, 240, [this, latency] {
  18764. return latency->take ("the mute button") + " insert 1 muted at the end: "
  18765. + (engine->getSong().mixer.size() > 1 && engine->getSong().mixer[1].muted ? "yes" : "no") + "\n";
  18766. } });
  18767. // a clip dragged sideways in the Playlist, 24 px a move (one every 6 frames), then dropped and undone
  18768. auto clipPress = std::make_shared<juce::Point<int>>();
  18769. run->steps.push_back ({ "q3 latency: playlist clip drag", [this, ui, mouse, left, clipPress] {
  18770. ui->selectTabForSnapshot (2);
  18771. auto& pl = ui->getPlaylistForSnapshot();
  18772. pl.setViewForSnapshot (64.0, 0, 0);
  18773. const auto grid = pl.gridAreaForSnapshot();
  18774. *clipPress = {};
  18775. for (int i = 0; i < (int) engine->getSong().playlist.size(); ++i)
  18776. if (const auto b = pl.clipBoundsForSnapshot (i); b.getWidth() >= 24 && grid.contains (b) && b.getHeight() >= 12
  18777. && b.getRight() < grid.getCentreX())
  18778. {
  18779. *clipPress = { b.getX() + 12, b.getBottom() - 4 };
  18780. break;
  18781. }
  18782. mouse (pl, *clipPress, {});
  18783. mouse (pl, *clipPress, left);
  18784. },
  18785. [ui, mouse, inWindow, latency, left, clipPress] (int f) {
  18786. if (f % 6 != 3 || clipPress->isOrigin())
  18787. return;
  18788. auto& pl = ui->getPlaylistForSnapshot();
  18789. const auto grid = pl.gridAreaForSnapshot();
  18790. latency->arm (inWindow (pl, grid.withY (clipPress->y - 20).withHeight (40)));
  18791. mouse (pl, clipPress->translated (24 * (1 + (f / 6) % 10), 0), left);
  18792. }, 120, [this, ui, mouse, latency, clipPress] {
  18793. auto& pl = ui->getPlaylistForSnapshot();
  18794. mouse (pl, *clipPress, {});
  18795. juce::ModifierKeys::currentModifiers = {};
  18796. engine->undo();
  18797. const auto moved = engine->getPublishCount();
  18798. return latency->take ("the dragged clip") + " (pressed at " + clipPress->toString() + ", song published "
  18799. + juce::String ((juce::int64) moved) + " times)\n";
  18800. } });
  18801. // keys typed in the Browser's search box (one every 6 frames), then taken back with Backspace
  18802. auto typed = std::make_shared<int> (0);
  18803. run->steps.push_back ({ "q3 latency: typing in the Browser's search box", [ui, typed] {
  18804. ui->showDesktopForSnapshot (false);
  18805. ui->runActionForSnapshot ("browser.search");
  18806. *typed = 0;
  18807. },
  18808. [this, ui, inWindow, latency, typed] (int f) {
  18809. static const juce::String text ("kick drum loop");
  18810. if (f % 6 != 3 || *typed >= text.length())
  18811. return;
  18812. auto& browser = ui->getBrowserForSnapshot();
  18813. std::function<juce::TextEditor* (juce::Component&)> findBox = [&findBox] (juce::Component& c) -> juce::TextEditor* {
  18814. for (auto* child : c.getChildren())
  18815. if (auto* t = dynamic_cast<juce::TextEditor*> (child); t != nullptr && t->isShowing())
  18816. return t;
  18817. else if (auto* deeper = findBox (*child))
  18818. return deeper;
  18819. return nullptr;
  18820. };
  18821. if (auto* box = browser.isShowing() ? findBox (browser) : nullptr)
  18822. {
  18823. latency->arm (inWindow (browser, browser.getLocalBounds()));
  18824. const auto c = text[*typed];
  18825. box->keyPressed (juce::KeyPress ((int) c, {}, c));
  18826. ++*typed;
  18827. }
  18828. }, 96, [this, ui, latency, typed] {
  18829. auto text = latency->take ("a key in the search box") + " search box: \"" + ui->getBrowserForSnapshot().searchTextForSnapshot() + "\"\n";
  18830. ui->getBrowserForSnapshot().setSearchForSnapshot ({});
  18831. return text;
  18832. } });
  18833. // --- open times ------------------------------------------------------------------------------------------
  18834. const char* views[] { "channel rack", "piano roll", "playlist", "mixer" };
  18835. for (int tab : { 3, 1, 0, 2 })
  18836. run->steps.push_back ({ juce::String ("q3 open: ") + views[tab] + " maximised", [this, ui, tab, paintAll] {
  18837. engine->stop();
  18838. ui->selectTabForSnapshot (tab);
  18839. paintAll();
  18840. }, {}, 600 });
  18841. run->steps.push_back ({ "q3 open: Settings window (General)", [this, paintAll] {
  18842. lynx::closeSettings();
  18843. lynx::showSettings (*engine, lynx::SettingsPage::general);
  18844. paintAll();
  18845. }, {}, 1500 });
  18846. const char* pages[] { "Project", "Info", "Files", "General", "Audio", "MIDI", "Theme", "LYNX extras", "Link" };
  18847. for (int page = 0; page <= (int) lynx::SettingsPage::link; ++page)
  18848. run->steps.push_back ({ juce::String ("q3 open: Settings page ") + pages[page], [page, paintAll] {
  18849. lynx::switchSettingsPage ((lynx::SettingsPage) page);
  18850. paintAll();
  18851. }, {}, 600 });
  18852. run->steps.push_back ({ "q3 open: Settings closed", [paintAll] { lynx::closeSettings(); paintAll(); }, {}, 400 });
  18853. const auto menuNames = ui->getMenuNamesForSnapshot();
  18854. for (int m = 0; m < menuNames.size(); ++m)
  18855. run->steps.push_back ({ "q3 open: menu " + menuNames[m], [ui, m, paintAll] {
  18856. auto menu = ui->getMenuForSnapshot (m);
  18857. menu.showMenuAsync (juce::PopupMenu::Options().withTargetScreenArea (ui->getScreenBounds().withSize (40, 20).translated (40 * m, 0)));
  18858. paintAll();
  18859. }, {}, 500, [] { juce::PopupMenu::dismissAllActiveMenus(); return juce::String(); } });
  18860. run->steps.push_back ({ "q3 open: command palette", [ui, paintAll] {
  18861. ui->runActionForSnapshot ("view.commandPalette");
  18862. paintAll();
  18863. }, {}, 600, [ui] {
  18864. const auto ms = ui->paletteOpenMsForSnapshot();
  18865. ui->closeActionSearchForSnapshot();
  18866. return " palette's own open time " + juce::String (ms, 1) + " ms\n";
  18867. } });
  18868. // 30 effect windows (the first effects that have a LYNX editor), then the song playing with them open
  18869. auto opened = std::make_shared<int> (0);
  18870. run->steps.push_back ({ "q3 open: 30 effect windows", [this, opened, paintAll] {
  18871. engine->stop();
  18872. *opened = 0;
  18873. const auto& mixer = engine->getSong().mixer;
  18874. for (int t = 0; t < (int) mixer.size() && *opened < 30; ++t)
  18875. for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size() && *opened < 30; ++s)
  18876. if (lynx::NativeEffectWindows::canOpen (mixer[(std::size_t) t].effects[(std::size_t) s]))
  18877. {
  18878. lynx::NativeEffectWindows::open (*engine, t, s);
  18879. ++*opened;
  18880. }
  18881. paintAll();
  18882. }, {}, 1500, [opened] { return " effect windows opened: " + juce::String (*opened) + "\n"; } });
  18883. run->steps.push_back ({ "q3 30 effect windows open, song playing", [ui, playSong] { ui->selectTabForSnapshot (2); playSong (true); }, {}, 4000 });
  18884. run->steps.push_back ({ "q3 effect windows closed", [this, paintAll] {
  18885. engine->stop();
  18886. lynx::NativeEffectWindows::closeAll();
  18887. paintAll();
  18888. }, {}, 500 });
  18889. // --- the clip grid (last: the Clip-launch layout stays until the step ends) -------------------------------
  18890. run->steps.push_back ({ "q3 open: Clip-launch layout", [ui, paintAll] {
  18891. ui->selectTabForSnapshot (2);
  18892. ui->setClipLaunchWorkflow (true);
  18893. ui->setClipGridView (lynx::PlaylistArea::GridView::grid);
  18894. paintAll();
  18895. }, {}, 1500 });
  18896. run->steps.push_back ({ "q3 clip grid scroll down/up, clips launched", [this] {
  18897. engine->getTransport().songMode = true;
  18898. if (const auto& grid = engine->getSong().clipGrid)
  18899. for (int scene = 0; scene < juce::jmin (8, (int) grid->scenes.size()); ++scene)
  18900. engine->launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, scene });
  18901. },
  18902. [wheelAt, ui, none] (int f) {
  18903. if (auto* grid = ui->getClipGridForSnapshot())
  18904. wheelAt (*grid, 0.0f, f < 40 ? -0.15f : 0.15f, none);
  18905. }, 80 });
  18906. run->steps.push_back ({ "q3 clip grid scroll sideways, clips launched", {},
  18907. [wheelAt, ui, none] (int f) {
  18908. if (auto* grid = ui->getClipGridForSnapshot())
  18909. wheelAt (*grid, f < 40 ? -0.15f : 0.15f, 0.0f, none);
  18910. }, 80, [this, ui] {
  18911. engine->launcherCommand ({ lynx::launcher::Command::Type::stopAll });
  18912. engine->stop();
  18913. return juce::String();
  18914. } });
  18915. run->steps.push_back ({ "q3 open: Pattern layout again", [ui, paintAll] { ui->setClipLaunchWorkflow (false); paintAll(); }, {}, 800 });
  18916. }
  18917. // LYNX_UIPERF_ONLY=text: only the steps whose name has that text (round 190ry: "a|b|c", any of them)
  18918. if (const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_ONLY", {}); only.isNotEmpty())
  18919. {
  18920. const auto any = juce::StringArray::fromTokens (only, "|", "");
  18921. run->steps.erase (std::remove_if (run->steps.begin(), run->steps.end(), [&any] (const auto& s) {
  18922. for (const auto& t : any)
  18923. if (t.isNotEmpty() && juce::String (s.name).contains (t))
  18924. return false;
  18925. return true;
  18926. }), run->steps.end());
  18927. }
  18928. // let the window draw the project first
  18929. perf = std::move (run);
  18930. juce::Timer::callAfterDelay (1500, [this] { if (perf != nullptr) perf->startTimer (16); });
  18931. }
  18932. // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
  18933. // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
  18934. // --rtstress --backuptest N (round 177d): while the project plays, a device's MIDI clock (10/s) and active sensing
  18935. // (3/s) arrive, and the project counts as changed. N > 0 also forces a backup every N seconds on top of the timed ones.
  18936. // The report tells how many backups were written, when, and what the MIDI counters did.
  18937. struct BackupTest final : juce::Timer
  18938. {
  18939. lynx::AudioEngine* engine = nullptr;
  18940. lynx::MainComponent* ui = nullptr;
  18941. double everyMs = 0.0, startMs = 0.0, lastForcedMs = 0.0, longestCallMs = 0.0;
  18942. int ticks = 0, forced = 0;
  18943. std::uint64_t seenOver = 0, seenNear = 0;
  18944. juce::String misses; // each callback over (or near) its deadline: how long after the last forced backup
  18945. void timerCallback() override
  18946. {
  18947. engine->injectMidiInput (juce::MidiMessage (0xf8));
  18948. if (++ticks % 3 == 0)
  18949. engine->injectMidiInput (juce::MidiMessage (0xfe));
  18950. const auto now = juce::Time::getMillisecondCounterHiRes();
  18951. const auto s = engine->getRtStats().snapshot();
  18952. if (s.overBudget != seenOver || s.nearBudget != seenNear)
  18953. {
  18954. misses << " +" << juce::String ((now - lastForcedMs) / 1000.0, 1) << " s after the last forced backup (or the start): over +"
  18955. << (juce::int64) (s.overBudget - seenOver) << ", near +" << (juce::int64) (s.nearBudget - seenNear) << "\n";
  18956. seenOver = s.overBudget;
  18957. seenNear = s.nearBudget;
  18958. }
  18959. if (everyMs > 0.0 && now - lastForcedMs >= everyMs)
  18960. {
  18961. lastForcedMs = now;
  18962. ++forced;
  18963. ui->backupNowForTest();
  18964. longestCallMs = juce::jmax (longestCallMs, juce::Time::getMillisecondCounterHiRes() - now);
  18965. }
  18966. }
  18967. };
  18968. std::unique_ptr<BackupTest> backupTest;
  18969. void startBackupTest()
  18970. {
  18971. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  18972. const auto at = cli.indexOf ("--backuptest");
  18973. auto* ui = mainWindow != nullptr ? dynamic_cast<lynx::MainComponent*> (mainWindow->getContentComponent()) : nullptr;
  18974. if (at < 0 || ui == nullptr)
  18975. return;
  18976. backupTest = std::make_unique<BackupTest>();
  18977. backupTest->engine = engine.get();
  18978. backupTest->ui = ui;
  18979. backupTest->everyMs = cli[at + 1].getDoubleValue() * 1000.0;
  18980. backupTest->startMs = backupTest->lastForcedMs = juce::Time::getMillisecondCounterHiRes();
  18981. // (the project counts as changed, so a backup has something to write; the Master's fader is down, so a long run
  18982. // makes no sound: everything else is processed as usual)
  18983. engine->editSong ([] (lynx::Song& s) {
  18984. if (! s.mixer.empty())
  18985. s.mixer[0].volume = 0.0f;
  18986. });
  18987. backupTest->startTimer (100);
  18988. }
  18989. juce::String finishBackupTest()
  18990. {
  18991. if (backupTest == nullptr)
  18992. return {};
  18993. backupTest->stopTimer();
  18994. juce::String text;
  18995. const auto played = engine->getMidiPlayed();
  18996. text << " backup test: MIDI light count " << (int) engine->getMidiActivity() << ", played count " << (int) played << " (clock and active sensing only)\n";
  18997. text << " backup test: " << backupTest->forced << " forced, longest forced call on the message thread "
  18998. << juce::String (backupTest->longestCallMs, 1) << " ms\n";
  18999. if (backupTest->misses.isNotEmpty())
  19000. text << " backup test: callbacks over or near the deadline (seen within 100 ms):\n" << backupTest->misses;
  19001. auto files = lynx::autosaveFolder().findChildFiles (juce::File::findFiles, false, "*.lynx");
  19002. text << " backup test: " << files.size() << " file(s) in the backup folder:\n";
  19003. for (const auto& f : files)
  19004. text << " " << juce::String ((f.getLastModificationTime().toMilliseconds() - juce::Time::getCurrentTime().toMilliseconds()) / 1000) << " s before the end: "
  19005. << f.getFileName() << " (" << f.getSize() << " bytes)\n";
  19006. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 1));
  19007. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  19008. text << " backup test: after a played note, played count " << (int) engine->getMidiPlayed() << "\n";
  19009. backupTest.reset();
  19010. return text;
  19011. }
  19012. void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize,
  19013. const juce::String& deviceType, const juce::String& deviceName, const juce::String& recordTo = {})
  19014. {
  19015. startupOptions = lynx::StartupOptions::load();
  19016. engine = std::make_unique<lynx::AudioEngine>();
  19017. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  19018. crashEngine = engine.get();
  19019. // the user's saved device stays as it was: this run's choices are undone before quitting
  19020. savedDeviceState = engine->getDeviceManager().createStateXml();
  19021. auto& devices = engine->getDeviceManager();
  19022. const auto driverFile = addDriverFileDeviceType();
  19023. const auto type = deviceType.isEmpty() && driverFile ? juce::String (lynx::dllAsioTypeName) : deviceType;
  19024. if (type.isNotEmpty() && devices.getCurrentAudioDeviceType() != type)
  19025. devices.setCurrentAudioDeviceType (type, true);
  19026. if (bufferSize > 0 || deviceName.isNotEmpty())
  19027. {
  19028. auto setup = devices.getAudioDeviceSetup();
  19029. if (bufferSize > 0)
  19030. setup.bufferSize = bufferSize;
  19031. if (deviceName.isNotEmpty())
  19032. setup.outputDeviceName = deviceName;
  19033. const auto error = devices.setAudioDeviceSetup (setup, true);
  19034. if (error.isNotEmpty())
  19035. report.replaceWithText ("device error: " + error + "\n");
  19036. }
  19037. createMainWindow();
  19038. if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
  19039. mainWindow->reveal();
  19040. juce::String error;
  19041. auto ok = false;
  19042. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  19043. if (project.hasFileExtension ("flp"))
  19044. ok = engine->importFlpFile (project, error);
  19045. else if (auto song = lynx::ProjectFile::load (project, error))
  19046. {
  19047. engine->setSong (std::move (*song));
  19048. ok = true;
  19049. }
  19050. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  19051. if (! ok)
  19052. {
  19053. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  19054. restoreSavedDeviceState();
  19055. setApplicationReturnValue (1);
  19056. quit();
  19057. return;
  19058. }
  19059. if (recordTo.isNotEmpty())
  19060. engine->setAudioRecordingArmed (true); // opens the input of the driver
  19061. // let the window draw the project, then play from the start with fresh statistics
  19062. juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs, recordTo] {
  19063. if (engine == nullptr)
  19064. return;
  19065. engine->stop();
  19066. engine->rewind();
  19067. engine->getRtStats().reset();
  19068. engine->takeUiPulse();
  19069. if (recordTo.isNotEmpty())
  19070. engine->setRecording (true);
  19071. // --log folder: the audio logger records what the Master plays during the run (realtime vs export checks)
  19072. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  19073. if (const auto at = cli.indexOf ("--log"); at >= 0 && at + 1 < cli.size())
  19074. engine->getAudioLogger().start (juce::File (cli[at + 1].unquoted()), engine->getDeviceManager().getCurrentAudioDevice() != nullptr
  19075. ? engine->getDeviceManager().getCurrentAudioDevice()->getCurrentSampleRate() : 44100.0);
  19076. engine->play();
  19077. startBackupTest();
  19078. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
  19079. if (engine == nullptr)
  19080. return;
  19081. const auto backupReport = finishBackupTest();
  19082. engine->stop();
  19083. juce::String recording;
  19084. if (engine->getAudioLogger().isLogging())
  19085. {
  19086. recording << " logged: " << engine->getAudioLogger().currentFile().getFullPathName() << "\n";
  19087. engine->getAudioLogger().stop();
  19088. }
  19089. if (recordTo.isNotEmpty())
  19090. recording = finishStressTake (juce::File (recordTo), seconds);
  19091. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  19092. const auto s = engine->getRtStats().snapshot();
  19093. juce::String text;
  19094. text << "project: " << project.getFullPathName() << "\n"
  19095. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  19096. << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
  19097. << juce::SystemStats::getCpuModel() << "\n"
  19098. << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
  19099. << engine->describeRealtime();
  19100. const auto pulse = engine->takeUiPulse();
  19101. text << " UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
  19102. << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
  19103. text << " load histogram (share of the deadline: callbacks):";
  19104. for (std::size_t b = 0; b < s.histogram.size(); ++b)
  19105. if (s.histogram[b] > 0)
  19106. text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
  19107. text << "\n";
  19108. text << recording << backupReport;
  19109. // --settingsshot file.png (round 161): Options > Audio settings of this run's device, as a picture
  19110. if (const auto at = cli.indexOf ("--settingsshot"); at >= 0 && at + 1 < cli.size())
  19111. {
  19112. auto page = lynx::makeSettingsPanel (*engine, lynx::SettingsPage::audio);
  19113. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  19114. {
  19115. juce::Graphics g (image);
  19116. g.fillAll (lynx::theme::panel);
  19117. page->paintEntireComponent (g, false);
  19118. }
  19119. const juce::File shot (cli[at + 1].unquoted());
  19120. shot.deleteFile();
  19121. if (auto out = shot.createOutputStream())
  19122. juce::PNGImageFormat().writeImageToStream (image, *out);
  19123. }
  19124. text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
  19125. report.replaceWithText (text);
  19126. restoreSavedDeviceState();
  19127. setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
  19128. quit();
  19129. });
  19130. });
  19131. }
  19132. // --bendrectest (round 167a): see the command line above
  19133. void runBendRecordTest (const juce::File& report, bool songMode)
  19134. {
  19135. engine = std::make_unique<lynx::AudioEngine>();
  19136. auto text = std::make_shared<juce::String>();
  19137. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  19138. auto finish = [this] (int code) {
  19139. setApplicationReturnValue (code);
  19140. quit();
  19141. };
  19142. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  19143. if (device == nullptr)
  19144. {
  19145. step ("result=ERROR no audio device");
  19146. finish (1);
  19147. return;
  19148. }
  19149. step ("device=" + device->getTypeName() + " | " + device->getName() + " | mode " + (songMode ? "song" : "pattern"));
  19150. auto song = lynx::Song::makeDefault();
  19151. song.bpm = 120.0;
  19152. song.mode = songMode ? lynx::PlayMode::song : lynx::PlayMode::pattern;
  19153. engine->setSong (std::move (song));
  19154. auto o = engine->getRecordOptions();
  19155. o.mode = lynx::RecordMode::overdub;
  19156. o.recordNotes = true;
  19157. o.recordAutomation = true;
  19158. o.countInBars = 0;
  19159. o.waitForInput = false;
  19160. o.quantiseAutomation = false;
  19161. o.punchLoopRegion = false;
  19162. o.preRollBars = o.postRollBars = 0;
  19163. engine->setRecordOptions (o);
  19164. engine->stop();
  19165. engine->rewind();
  19166. engine->setRecording (true);
  19167. engine->startPlayback();
  19168. // 2 s of wheel at ~100 messages a second: 0 → +1 (0.5 s), +1 → −1 (1 s), −1 → 0 (0.5 s)
  19169. auto sent = std::make_shared<std::vector<std::pair<double, float>>>();
  19170. auto t0 = std::make_shared<double> (juce::Time::getMillisecondCounterHiRes());
  19171. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 100));
  19172. auto tick = std::make_shared<std::function<void()>>();
  19173. *tick = [this, sent, t0, tick, step, finish, songMode] {
  19174. if (engine == nullptr)
  19175. return;
  19176. const auto ms = juce::Time::getMillisecondCounterHiRes() - *t0;
  19177. if (ms < 2000.0)
  19178. {
  19179. const auto x = ms / 1000.0;
  19180. 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);
  19181. const auto wheel = juce::jlimit (0, 16383, 8192 + juce::roundToInt (v * 8191.0f));
  19182. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, wheel));
  19183. sent->push_back ({ ms, (float) (wheel - 8192) / 8192.0f });
  19184. juce::Timer::callAfterDelay (10, *tick);
  19185. return;
  19186. }
  19187. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, 8192));
  19188. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  19189. juce::Timer::callAfterDelay (400, [this, sent, step, finish, songMode] {
  19190. if (engine == nullptr)
  19191. return;
  19192. engine->stop();
  19193. juce::Timer::callAfterDelay (600, [this, sent, step, finish, songMode] {
  19194. if (engine == nullptr)
  19195. return;
  19196. engine->setRecording (false);
  19197. const auto& s = engine->getSong();
  19198. // the channel's pitch bend (MIDI channel 1), recorded as a lane or a clip
  19199. std::vector<std::pair<std::int64_t, float>> got;
  19200. juce::String where = "nothing";
  19201. for (const auto& a : s.automations)
  19202. if (a.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (a.target.param))
  19203. {
  19204. where = "automation clip \"" + juce::String (a.name) + "\"";
  19205. for (const auto& pt : a.points)
  19206. got.push_back ({ pt.tick, pt.value });
  19207. }
  19208. for (const auto& p : s.patterns)
  19209. for (const auto& lane : p.events)
  19210. if (lane.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (lane.target.param))
  19211. {
  19212. where = "pattern \"" + juce::String (p.name) + "\" event lane";
  19213. for (const auto& e : lane.events)
  19214. got.push_back ({ e.tick, e.value });
  19215. }
  19216. int notes = 0;
  19217. for (const auto& p : s.patterns)
  19218. notes += (int) p.notes.size();
  19219. float lo = 1.0f, hi = 0.0f;
  19220. for (const auto& [t, v] : got)
  19221. lo = std::min (lo, v), hi = std::max (hi, v);
  19222. // ticks: in order, spread over the ~2 s sweep (8 beats of 96 ticks at 120 bpm ≈ 4 beats)
  19223. const auto span = got.empty() ? 0 : got.back().first - got.front().first;
  19224. const auto sorted = std::is_sorted (got.begin(), got.end(), [] (const auto& a, const auto& b) { return a.first < b.first; });
  19225. step ("sent=" + juce::String ((int) sent->size()) + " wheel messages over 2 s");
  19226. step ("recorded=" + juce::String ((int) got.size()) + " points in " + where + ", value " + juce::String (lo, 3) + " .. "
  19227. + juce::String (hi, 3) + " (0.5 = centre), ticks " + juce::String (span) + " apart, " + (sorted ? "in order" : "OUT OF ORDER")
  19228. + ", notes " + juce::String (notes));
  19229. if (! got.empty())
  19230. step ("last=" + juce::String (got.back().second, 3));
  19231. // song mode: a clip over the take, ending back at the centre. Pattern mode: the take loops the 1-bar pattern
  19232. // (4.6 beats of take), so the lane spans the bar and the last wheel message (the centre) lands inside it
  19233. const auto centred = std::any_of (got.begin(), got.end(), [] (const auto& p) { return std::abs (p.second - 0.5f) < 0.02f; });
  19234. const auto ok = got.size() >= 20 && hi > 0.97f && lo < 0.03f && sorted && notes >= 1
  19235. && (songMode ? span > lynx::ppq * 3 && span < lynx::ppq * 6 && std::abs (got.back().second - 0.5f) < 0.02f
  19236. : span > lynx::ppq * 2 && span <= lynx::ppq * 4 && centred);
  19237. step (ok ? "result=OK" : "result=FAILED");
  19238. finish (ok ? 0 : 1);
  19239. });
  19240. });
  19241. };
  19242. juce::Timer::callAfterDelay (300, *tick);
  19243. }
  19244. // --countinrectest (round 170d): see the command line above.
  19245. void runCountInRecordTest (const juce::File& report)
  19246. {
  19247. engine = std::make_unique<lynx::AudioEngine>();
  19248. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  19249. struct StandIn final : juce::AudioIODevice
  19250. {
  19251. StandIn() : juce::AudioIODevice ("countin", "test") {}
  19252. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  19253. juce::StringArray getInputChannelNames() override { return {}; }
  19254. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  19255. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  19256. int getDefaultBufferSize() override { return 512; }
  19257. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  19258. void close() override {}
  19259. bool isOpen() override { return true; }
  19260. void start (juce::AudioIODeviceCallback*) override {}
  19261. void stop() override {}
  19262. bool isPlaying() override { return true; }
  19263. juce::String getLastError() override { return {}; }
  19264. int getCurrentBufferSizeSamples() override { return 512; }
  19265. double getCurrentSampleRate() override { return 48000.0; }
  19266. int getCurrentBitDepth() override { return 32; }
  19267. juce::BigInteger getActiveOutputChannels() const override
  19268. {
  19269. juce::BigInteger b;
  19270. b.setRange (0, 2, true);
  19271. return b;
  19272. }
  19273. juce::BigInteger getActiveInputChannels() const override { return {}; }
  19274. int getOutputLatencyInSamples() override { return 256; }
  19275. int getInputLatencyInSamples() override { return 0; }
  19276. };
  19277. auto device = std::make_shared<StandIn>();
  19278. auto text = std::make_shared<juce::String>();
  19279. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  19280. auto finish = [this] (int code) {
  19281. setApplicationReturnValue (code);
  19282. quit();
  19283. };
  19284. constexpr std::int64_t bar = 4 * lynx::ppq; // 120 BPM, 4/4
  19285. lynx::Song song; // (as --cliplooptest: one synth channel on insert 1, an empty pattern)
  19286. song.bpm = 120.0;
  19287. song.mixer = lynx::Song::defaultMixer (2);
  19288. song.channels.resize (1);
  19289. song.channels[0].mixerTrack = 1;
  19290. song.patterns.emplace_back();
  19291. song.mode = lynx::PlayMode::song;
  19292. song.currentPattern = 0;
  19293. engine->setSong (song);
  19294. engine->getTransport().metronome.store (true);
  19295. auto o = engine->getRecordOptions();
  19296. o.mode = lynx::RecordMode::overdub;
  19297. o.countInBars = 1;
  19298. o.catchWindow = lynx::ppq / 4;
  19299. o.compensateOutput = true;
  19300. o.recordNotes = true;
  19301. o.recordAudio = false;
  19302. o.recordAutomation = false;
  19303. o.waitForInput = false;
  19304. o.quantise = 0;
  19305. o.placeSongClip = true;
  19306. o.recordingMarkers = false;
  19307. o.punchLoopRegion = false;
  19308. o.preRollBars = o.postRollBars = 0;
  19309. engine->setRecordOptions (o);
  19310. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  19311. 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");
  19312. // an event heard at output sample `heard` (counted from the first block after Play), sent as MIDI input
  19313. struct Event
  19314. {
  19315. std::int64_t heard;
  19316. juce::MidiMessage message;
  19317. };
  19318. struct Pass
  19319. {
  19320. std::vector<float> out;
  19321. std::vector<Event> events;
  19322. std::int64_t playingAt = -1; // the first sample of the block the song started in
  19323. int block = 0, blocks = 0;
  19324. std::function<void()> done;
  19325. };
  19326. constexpr int n = 512;
  19327. constexpr double rate = 48000.0;
  19328. // one pass: the take recorded from bar 3, `blocks` blocks driven by hand, 8 at a time between the engine's timer
  19329. // ticks (the take is committed there); then stopped and its results left to the timer
  19330. auto runPass = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  19331. *runPass = [this] (std::shared_ptr<Pass> pass) {
  19332. auto& cb = engine->deviceCallback();
  19333. std::vector<float> l (n), r (n);
  19334. float* outs[] = { l.data(), r.data() };
  19335. juce::AudioIODeviceCallbackContext context;
  19336. if (pass->block == 0)
  19337. {
  19338. engine->stop();
  19339. engine->seek ((double) (2 * bar));
  19340. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context); // (the seek, stopped)
  19341. engine->setRecording (true);
  19342. engine->startPlayback(); // the count-in starts
  19343. }
  19344. for (int k = 0; k < 8 && pass->block < pass->blocks; ++k, ++pass->block)
  19345. {
  19346. // the events heard in this block: stamped the way the engine's clock maps time to heard samples
  19347. const auto blockStart = (std::int64_t) pass->block * n;
  19348. const auto clock = engine->liveClock();
  19349. const auto compMs = 1000.0 * (n + 256) / rate;
  19350. for (auto& e : pass->events)
  19351. if (e.heard >= blockStart && e.heard < blockStart + n)
  19352. {
  19353. auto m = e.message;
  19354. m.setTimeStamp ((clock.timeMs + compMs + (double) (e.heard - blockStart) * 1000.0 / rate) * 0.001);
  19355. engine->injectMidiInput (m);
  19356. }
  19357. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context);
  19358. pass->out.insert (pass->out.end(), l.begin(), l.end());
  19359. if (pass->playingAt < 0 && engine->getTransport().playing.load())
  19360. pass->playingAt = blockStart;
  19361. }
  19362. };
  19363. // (the recursion through the message loop; written out so each step lets the engine's timer run)
  19364. auto drive = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  19365. // (round 190rf: the step holds itself weakly, the timer's call strongly: a strong self-capture never freed the passes'
  19366. // takes, ~4 MB, LeakSanitizer in the sanitizer sweep)
  19367. *drive = [this, runPass, weakDrive = std::weak_ptr (drive), device] (std::shared_ptr<Pass> pass) { // (the stand-in lives while the passes run)
  19368. if (engine == nullptr)
  19369. return;
  19370. (*runPass) (pass);
  19371. if (pass->block < pass->blocks)
  19372. {
  19373. if (auto self = weakDrive.lock())
  19374. juce::Timer::callAfterDelay (40, [pass, self] { (*self) (pass); });
  19375. return;
  19376. }
  19377. engine->stop();
  19378. juce::Timer::callAfterDelay (300, [this, pass] {
  19379. if (engine == nullptr)
  19380. return;
  19381. engine->setRecording (false);
  19382. juce::Timer::callAfterDelay (200, [pass] { pass->done(); });
  19383. });
  19384. };
  19385. auto onsets = [] (const std::vector<float>& out) {
  19386. std::vector<std::int64_t> at;
  19387. std::int64_t last = -100000;
  19388. for (std::size_t i = 0; i < out.size(); ++i)
  19389. if (std::abs (out[i]) > 0.02f && (std::int64_t) i - last > 4000)
  19390. {
  19391. at.push_back ((std::int64_t) i);
  19392. last = (std::int64_t) i;
  19393. }
  19394. else if (std::abs (out[i]) > 0.02f)
  19395. last = (std::int64_t) i;
  19396. return at;
  19397. };
  19398. // the graph is (re)built on the message thread: start once it has settled
  19399. juce::Timer::callAfterDelay (1500, [this, step, finish, drive, onsets] {
  19400. if (engine == nullptr)
  19401. return;
  19402. auto first = std::make_shared<Pass>();
  19403. first->blocks = (int) (rate * 18.0 / n); // count-in + 8 bars
  19404. first->done = [this, weakFirst = std::weak_ptr (first), step, finish, drive, onsets] { // (round 190rf: not itself)
  19405. const auto first = weakFirst.lock();
  19406. if (first == nullptr)
  19407. return;
  19408. const auto clicks = onsets (first->out);
  19409. juce::String list;
  19410. for (std::size_t i = 0; i < std::min<std::size_t> (clicks.size(), 8); ++i)
  19411. list << clicks[i] << " ";
  19412. step ("pass 1: clicks heard at samples " + list + "…, the song started in the block at " + juce::String (first->playingAt));
  19413. // the bar-3 downbeat: the click at the block the song started in
  19414. std::int64_t down = -1;
  19415. for (auto c : clicks)
  19416. if (std::abs (c - first->playingAt) < n)
  19417. down = c;
  19418. if (down < 0 || engine->getSong().patterns[0].notes.size() != 0)
  19419. {
  19420. step ("result=FAILED no downbeat click found (or notes recorded without input)");
  19421. finish (1);
  19422. return;
  19423. }
  19424. const auto ms = [down] (double t) { return down + (std::int64_t) std::llround (t * rate / 1000.0); };
  19425. auto second = std::make_shared<Pass>();
  19426. second->blocks = first->blocks;
  19427. auto add = [&second] (std::int64_t at, int key, bool on) {
  19428. second->events.push_back ({ at, on ? juce::MidiMessage::noteOn (1, key, (juce::uint8) 100) : juce::MidiMessage::noteOff (1, key) });
  19429. };
  19430. for (int key : { 60, 64, 67 }) // the chord, 15 ms early, held half a second
  19431. {
  19432. add (ms (-15.0), key, true);
  19433. add (ms (500.0), key, false);
  19434. }
  19435. add (ms (-1500.0), 62, true); // beat 2 of the count-in bar (bar 2)
  19436. add (ms (-1250.0), 62, false);
  19437. add (ms (503.0), 77, true); // 3 ms after beat 2
  19438. add (ms (603.0), 77, false);
  19439. for (int b = 1; b <= 6; ++b) // a note a bar ("it stopped after two bars")
  19440. {
  19441. add (ms (b * 2000.0), 70 + b, true);
  19442. add (ms (b * 2000.0 + 250.0), 70 + b, false);
  19443. }
  19444. second->done = [this, step, finish] {
  19445. const auto& s = engine->getSong();
  19446. const auto& p = s.patterns[0];
  19447. const lynx::Clip* clip = nullptr;
  19448. for (const auto& c : s.playlist)
  19449. if (c.kind == lynx::ClipKind::pattern && c.pattern == 0)
  19450. clip = &c;
  19451. const auto origin = clip != nullptr ? clip->start - clip->offset : -1;
  19452. step ("pass 2: " + juce::String ((int) p.notes.size()) + " notes recorded, clip at " + juce::String (clip != nullptr ? clip->start : -1));
  19453. auto ok = clip != nullptr && origin == bar && p.notes.size() == 11;
  19454. // where each one was heard (song ticks): 0.5 ms = ~1 tick
  19455. const std::vector<std::pair<int, double>> want = { { 60, 2.0 * bar }, { 64, 2.0 * bar }, { 67, 2.0 * bar },
  19456. { 62, 2.0 * bar - 3 * lynx::ppq }, { 77, 2.0 * bar + lynx::ppq + 3.0 * 1.92 },
  19457. { 71, 3.0 * bar }, { 72, 4.0 * bar }, { 73, 5.0 * bar },
  19458. { 74, 6.0 * bar }, { 75, 7.0 * bar }, { 76, 8.0 * bar } };
  19459. for (const auto& [key, tick] : want)
  19460. {
  19461. const lynx::Note* found = nullptr;
  19462. for (const auto& note : p.notes)
  19463. if (note.key == key)
  19464. found = &note;
  19465. const auto at = found != nullptr ? (double) (origin + found->start) : -1.0;
  19466. const auto good = found != nullptr && std::abs (at - tick) <= 2.0;
  19467. ok = ok && good;
  19468. step ("key " + juce::String (key) + ": heard at tick " + juce::String (tick, 2) + ", recorded at " + juce::String (at, 0)
  19469. + (good ? " ok" : " WRONG"));
  19470. }
  19471. const auto* chord = [&p] () -> const lynx::Note* {
  19472. for (const auto& note : p.notes)
  19473. if (note.key == 60)
  19474. return &note;
  19475. return nullptr;
  19476. }();
  19477. if (chord != nullptr)
  19478. step ("chord length " + juce::String (chord->length) + " ticks (caught 15 ms early, released 500 ms after bar 3: 960)");
  19479. step (ok ? "result=OK" : "result=FAILED");
  19480. finish (ok ? 0 : 1);
  19481. };
  19482. (*drive) (second);
  19483. };
  19484. (*drive) (first);
  19485. });
  19486. }
  19487. // --cliplooptest (round 167q): see the command line above.
  19488. // --slicexedittest (round 190aj): see the command line above
  19489. void runDirectWaveEditTest (const juce::String& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
  19490. {
  19491. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19492. juce::StringArray lines;
  19493. {
  19494. lynx::AudioEngine offline (false);
  19495. lynx::MainComponent ui (offline, false);
  19496. ui.setSize (1280, 720);
  19497. if (project == "new")
  19498. {
  19499. if (auto c = lynx::natives::makeChannel (lynx::InstrumentKind::directwave, {}))
  19500. offline.editSong ([c] (lynx::Song& s) { s.channels.push_back (*c); });
  19501. }
  19502. else
  19503. ui.openFile (juce::File (project));
  19504. offline.dispatchPendingMessages();
  19505. int channel = -1;
  19506. for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
  19507. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::directwave)
  19508. channel = c;
  19509. if (channel < 0)
  19510. lines.add ("no DirectWave channel in " + project);
  19511. else
  19512. {
  19513. auto panel = lynx::makeChannelSettingsPanel (offline, channel);
  19514. juce::Component frame;
  19515. frame.setSize (panel->getWidth(), panel->getHeight());
  19516. frame.setOpaque (true);
  19517. frame.addAndMakeVisible (*panel);
  19518. panel->setTopLeftPosition (0, 0);
  19519. offline.dispatchPendingMessages();
  19520. juce::StringArray commands;
  19521. script.readLines (commands);
  19522. for (const auto& raw : commands)
  19523. {
  19524. const auto command = raw.trim();
  19525. if (command.isEmpty() || command.startsWith ("#"))
  19526. {
  19527. lines.add (command);
  19528. continue;
  19529. }
  19530. if (command.startsWith ("shot "))
  19531. {
  19532. frame.setSize (panel->getWidth(), panel->getHeight());
  19533. // (round 190jd: at the shot scale, --shot-scale / LYNX_SHOT_SCALE, with its suffix; scale 1 = the same pixels)
  19534. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  19535. const auto file = lynx::shot::file (juce::File (prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png"));
  19536. file.deleteFile();
  19537. juce::PNGImageFormat png;
  19538. if (auto out = file.createOutputStream())
  19539. png.writeImageToStream (image, *out);
  19540. lines.add (command + " -> " + file.getFileName());
  19541. continue;
  19542. }
  19543. if (command.startsWith ("savestate "))
  19544. {
  19545. const auto& st = offline.getSong().channels[(std::size_t) channel].pluginState;
  19546. juce::File (command.fromFirstOccurrenceOf (" ", false, false).trim()).replaceWithData (st.data(), st.size());
  19547. lines.add (command + " -> " + juce::String ((int) st.size()) + " bytes");
  19548. continue;
  19549. }
  19550. const auto result = lynx::directWaveEditorTest (*panel, command);
  19551. offline.dispatchPendingMessages();
  19552. lines.add (command + " -> " + result);
  19553. }
  19554. }
  19555. }
  19556. report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
  19557. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  19558. quit();
  19559. }
  19560. void runSlicexEditTest (const juce::File& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
  19561. {
  19562. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19563. juce::StringArray lines;
  19564. {
  19565. lynx::AudioEngine offline (false);
  19566. lynx::MainComponent ui (offline, false);
  19567. ui.setSize (1280, 720);
  19568. ui.openFile (project);
  19569. offline.dispatchPendingMessages();
  19570. int channel = -1;
  19571. for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
  19572. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  19573. channel = c;
  19574. if (channel < 0)
  19575. lines.add ("no Slicex channel in " + project.getFullPathName());
  19576. else
  19577. {
  19578. auto panel = lynx::makeChannelSettingsPanel (offline, channel);
  19579. juce::Component frame;
  19580. frame.setSize (panel->getWidth(), panel->getHeight());
  19581. frame.setOpaque (true);
  19582. frame.addAndMakeVisible (*panel);
  19583. panel->setTopLeftPosition (0, 0);
  19584. offline.dispatchPendingMessages();
  19585. juce::StringArray commands;
  19586. script.readLines (commands);
  19587. for (const auto& raw : commands)
  19588. {
  19589. const auto command = raw.trim();
  19590. if (command.isEmpty() || command.startsWith ("#"))
  19591. {
  19592. lines.add (command);
  19593. continue;
  19594. }
  19595. if (command.startsWith ("shot "))
  19596. {
  19597. frame.setSize (panel->getWidth(), panel->getHeight()); // (round 190hg: the display modes resize the editor)
  19598. // (round 190jd: at the shot scale, --shot-scale / LYNX_SHOT_SCALE, with its suffix; scale 1 = the same pixels)
  19599. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  19600. const auto file = lynx::shot::file (juce::File (prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png"));
  19601. file.deleteFile();
  19602. juce::PNGImageFormat png;
  19603. if (auto out = file.createOutputStream())
  19604. png.writeImageToStream (image, *out);
  19605. lines.add (command + " -> " + file.getFileName());
  19606. continue;
  19607. }
  19608. if (command.startsWith ("menushot ")) // round 190jd: the deck's Snap menu as a picture
  19609. {
  19610. const auto file = prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png";
  19611. saveMenus (juce::StringArray { "Slicex deck: Snap" }, std::vector<juce::PopupMenu> { lynx::slicexSnapMenuForSnapshot (*panel) }, file);
  19612. lines.add (command + " -> " + juce::File (file).getFileName());
  19613. continue;
  19614. }
  19615. const auto result = lynx::slicexEditorTest (*panel, command);
  19616. offline.dispatchPendingMessages();
  19617. lines.add (command + " -> " + result);
  19618. }
  19619. }
  19620. }
  19621. report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
  19622. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  19623. quit();
  19624. }
  19625. // --slicexkeytest (round 190ac): see the command line above
  19626. void runSlicexKeyTest (const juce::File& report)
  19627. {
  19628. engine = std::make_unique<lynx::AudioEngine>();
  19629. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  19630. struct StandIn final : juce::AudioIODevice
  19631. {
  19632. StandIn() : juce::AudioIODevice ("slicexkey", "test") {}
  19633. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  19634. juce::StringArray getInputChannelNames() override { return {}; }
  19635. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  19636. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  19637. int getDefaultBufferSize() override { return 512; }
  19638. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  19639. void close() override {}
  19640. bool isOpen() override { return true; }
  19641. void start (juce::AudioIODeviceCallback*) override {}
  19642. void stop() override {}
  19643. bool isPlaying() override { return true; }
  19644. juce::String getLastError() override { return {}; }
  19645. int getCurrentBufferSizeSamples() override { return 512; }
  19646. double getCurrentSampleRate() override { return 48000.0; }
  19647. int getCurrentBitDepth() override { return 32; }
  19648. juce::BigInteger getActiveOutputChannels() const override
  19649. {
  19650. juce::BigInteger b;
  19651. b.setRange (0, 2, true);
  19652. return b;
  19653. }
  19654. juce::BigInteger getActiveInputChannels() const override { return {}; }
  19655. int getOutputLatencyInSamples() override { return 0; }
  19656. int getInputLatencyInSamples() override { return 0; }
  19657. };
  19658. auto device = std::make_shared<StandIn>();
  19659. auto text = std::make_shared<juce::String>();
  19660. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  19661. // 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
  19662. // × region number), so the region a key played can be read from the output
  19663. constexpr int rate = 48000, regionFrames = rate / 4;
  19664. const auto wavFile = report.getSiblingFile ("slicexkey-deck.wav");
  19665. {
  19666. juce::MemoryOutputStream w;
  19667. auto chunk = [&w] (const char* id, const juce::MemoryBlock& body) {
  19668. w.write (id, 4);
  19669. w.writeInt ((int) body.getSize());
  19670. w.write (body.getData(), body.getSize());
  19671. };
  19672. juce::MemoryOutputStream fmt, data, cue;
  19673. fmt.writeShort (1);
  19674. fmt.writeShort (1);
  19675. fmt.writeInt (rate);
  19676. fmt.writeInt (rate * 2);
  19677. fmt.writeShort (2);
  19678. fmt.writeShort (16);
  19679. for (int i = 0; i < 4 * regionFrames; ++i)
  19680. data.writeShort ((short) std::lround (12000.0 * std::sin (juce::MathConstants<double>::twoPi * 200.0 * (double) (i / regionFrames + 1) * (double) i / rate)));
  19681. cue.writeInt (4);
  19682. for (int k = 0; k < 4; ++k)
  19683. {
  19684. cue.writeInt (k + 1);
  19685. cue.writeInt (k * regionFrames);
  19686. cue.write ("data", 4);
  19687. cue.writeInt (0);
  19688. cue.writeInt (0);
  19689. cue.writeInt (k * regionFrames);
  19690. }
  19691. juce::MemoryOutputStream riff;
  19692. riff.write ("WAVE", 4);
  19693. w.reset();
  19694. chunk ("fmt ", fmt.getMemoryBlock());
  19695. chunk ("data", data.getMemoryBlock());
  19696. chunk ("cue ", cue.getMemoryBlock());
  19697. riff.write (w.getData(), w.getDataSize());
  19698. juce::MemoryOutputStream file;
  19699. file.write ("RIFF", 4);
  19700. file.writeInt ((int) riff.getDataSize());
  19701. file.write (riff.getData(), riff.getDataSize());
  19702. wavFile.replaceWithData (file.getData(), file.getDataSize());
  19703. }
  19704. lynx::Song song;
  19705. song.bpm = 120.0;
  19706. song.mixer = lynx::Song::defaultMixer (2);
  19707. song.channels.resize (1);
  19708. auto& channel = song.channels[0];
  19709. channel.instrument = lynx::InstrumentKind::slicex;
  19710. channel.mixerTrack = 1;
  19711. channel.samplePath = wavFile.getFullPathName().toStdString();
  19712. {
  19713. auto state = lynx::slicex::fresh();
  19714. lynx::slicex::setDeckFile (state, 0, channel.samplePath, 4);
  19715. lynx::slicex::setDeckBeats (state, 0, 0.0, 2.0);
  19716. channel.pluginState = lynx::slicex::write (state);
  19717. }
  19718. song.patterns.emplace_back();
  19719. engine->setSong (song);
  19720. auto& callback = engine->deviceCallback();
  19721. callback.audioDeviceAboutToStart (device.get());
  19722. 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");
  19723. juce::Timer::callAfterDelay (2000, [this, device, step] {
  19724. if (engine == nullptr)
  19725. return;
  19726. auto& cb = engine->deviceCallback();
  19727. auto pump = [&cb] (int blocks) {
  19728. std::vector<float> l (512), r (512), out;
  19729. float* outs[] = { l.data(), r.data() };
  19730. juce::AudioIODeviceCallbackContext context;
  19731. for (int k = 0; k < blocks; ++k)
  19732. {
  19733. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  19734. out.insert (out.end(), l.begin(), l.end());
  19735. }
  19736. return out;
  19737. };
  19738. auto rms = [] (const std::vector<float>& x, int from, int count) {
  19739. double sum = 0.0;
  19740. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  19741. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  19742. return std::sqrt (sum / juce::jmax (1, count));
  19743. };
  19744. // the tone's frequency from its rising zero crossings over a stretch
  19745. auto hertz = [] (const std::vector<float>& x, int from, int count) {
  19746. int crossings = 0, first = -1, last = -1;
  19747. for (int i = from + 1; i < from + count && i < (int) x.size(); ++i)
  19748. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  19749. {
  19750. first = first < 0 ? i : first;
  19751. last = i;
  19752. ++crossings;
  19753. }
  19754. return crossings > 1 ? 48000.0 * (double) (crossings - 1) / (double) (last - first) : 0.0;
  19755. };
  19756. bool ok = true;
  19757. auto check = [&ok, step] (bool good, const juce::String& what) {
  19758. ok = ok && good;
  19759. step ((good ? "ok " : "FAIL ") + what);
  19760. };
  19761. const auto idle = pump (20);
  19762. engine->getMeters().takePeak (1, 0);
  19763. check (rms (idle, 0, (int) idle.size()) < 1.0e-6, "idle: rms " + juce::String (rms (idle, 0, (int) idle.size()), 9));
  19764. // 4 regions map to keys 60…63 (FL's automatic map); the editor's click: velocity 100 / 128
  19765. engine->sendLiveNote (0, 60, 0.78125f, true);
  19766. const auto first = pump (16); // 8192 frames = 171 ms, inside region 1 (250 ms)
  19767. const auto meter = engine->getMeters().takePeak (1, 0);
  19768. 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");
  19769. check (std::abs (hertz (first, 1024, 6000) - 200.0) < 4.0, "key 60 plays region 1 (200 Hz)");
  19770. check (meter > 0.01f, "mixer track 1 meter peak " + juce::String (meter, 6));
  19771. engine->sendLiveNote (0, 60, 0.0f, false);
  19772. const auto tail = pump (60);
  19773. 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));
  19774. engine->sendLiveNote (0, 62, 0.78125f, true);
  19775. const auto third = pump (16);
  19776. check (rms (third, 1024, 6000) > 0.01 && std::abs (hertz (third, 1024, 6000) - 600.0) < 8.0,
  19777. "key 62 plays region 3 (600 Hz): rms " + juce::String (rms (third, 1024, 6000), 6) + ", " + juce::String (hertz (third, 1024, 6000), 1) + " Hz");
  19778. engine->sendLiveNote (0, 62, 0.0f, false);
  19779. engine->sendLiveNote (0, 72, 0.78125f, true); // a key without a region
  19780. const auto none = pump (60);
  19781. 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));
  19782. engine->sendLiveNote (0, 72, 0.0f, false);
  19783. step (ok ? "result=OK" : "result=FAILED");
  19784. setApplicationReturnValue (ok ? 0 : 1);
  19785. quit();
  19786. });
  19787. }
  19788. // --renderaheadtest (round 190gq): see the command line above
  19789. void runRenderAheadTest (const juce::File& report, const juce::StringArray& projects, int block, double seconds)
  19790. {
  19791. struct StandIn final : juce::AudioIODevice
  19792. {
  19793. explicit StandIn (int b) : juce::AudioIODevice ("renderahead", "test"), block (b) {}
  19794. const int block;
  19795. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  19796. juce::StringArray getInputChannelNames() override { return {}; }
  19797. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  19798. juce::Array<int> getAvailableBufferSizes() override { return { block }; }
  19799. int getDefaultBufferSize() override { return block; }
  19800. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  19801. void close() override {}
  19802. bool isOpen() override { return true; }
  19803. void start (juce::AudioIODeviceCallback*) override {}
  19804. void stop() override {}
  19805. bool isPlaying() override { return true; }
  19806. juce::String getLastError() override { return {}; }
  19807. int getCurrentBufferSizeSamples() override { return block; }
  19808. double getCurrentSampleRate() override { return 48000.0; }
  19809. int getCurrentBitDepth() override { return 32; }
  19810. juce::BigInteger getActiveOutputChannels() const override
  19811. {
  19812. juce::BigInteger b;
  19813. b.setRange (0, 2, true);
  19814. return b;
  19815. }
  19816. juce::BigInteger getActiveInputChannels() const override { return {}; }
  19817. int getOutputLatencyInSamples() override { return 0; }
  19818. int getInputLatencyInSamples() override { return 0; }
  19819. };
  19820. struct Scenario
  19821. {
  19822. juce::String name;
  19823. juce::File file; // a project, or none: the showcase song
  19824. int mode = 0; // 0 Song mode from the start, 1 a loop region, 2 Pattern mode
  19825. };
  19826. auto scenarios = std::make_shared<std::vector<Scenario>>();
  19827. scenarios->push_back ({ "showcase, Song mode", {}, 0 });
  19828. scenarios->push_back ({ "showcase, a loop region wrapping mid-block", {}, 1 });
  19829. scenarios->push_back ({ "showcase, Pattern mode", {}, 2 });
  19830. for (const auto& p : projects)
  19831. scenarios->push_back ({ juce::File (p).getFileName(), juce::File (p), 0 });
  19832. auto text = std::make_shared<juce::String>();
  19833. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  19834. step ("render-ahead test: blocks of " + juce::String (block) + " at 48 kHz, " + juce::String (seconds, 1) + " s per run");
  19835. auto outputs = std::make_shared<std::vector<std::vector<float>>>();
  19836. auto ok = std::make_shared<bool> (true);
  19837. auto run = std::make_shared<std::function<void (std::size_t, int)>>();
  19838. // (round 190rf, LeakSanitizer: the step holds itself weakly, what is pending holds it: a strong self-capture kept the
  19839. // last engine's outputs for good)
  19840. *run = [this, scenarios, step, outputs, ok, weakRun = std::weak_ptr (run), block, seconds, report] (std::size_t index, int pass) {
  19841. const auto run = weakRun.lock();
  19842. if (run == nullptr)
  19843. return;
  19844. if (index >= scenarios->size())
  19845. {
  19846. lynx::renderAheadOption().store (true);
  19847. step (juce::String ("result=") + (*ok ? "OK" : "FAIL"));
  19848. setApplicationReturnValue (*ok ? 0 : 1);
  19849. engine.reset();
  19850. quit();
  19851. return;
  19852. }
  19853. const auto& sc = (*scenarios)[index];
  19854. lynx::renderAheadOption().store (pass == 1);
  19855. engine = std::make_unique<lynx::AudioEngine>();
  19856. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  19857. engine->setRenderAheadAlways (true); // (the showcase song is light: the app would leave it real-time)
  19858. juce::String error;
  19859. auto loaded = true;
  19860. if (sc.file == juce::File())
  19861. {
  19862. auto song = lynx::makeShowcaseSong (0);
  19863. if (sc.mode == 1)
  19864. {
  19865. song.loopStart = 4 * lynx::ppq * song.beatsPerBar + 37; // (not on a block boundary)
  19866. song.loopEnd = 6 * lynx::ppq * song.beatsPerBar + 211;
  19867. song.loopOff = false;
  19868. }
  19869. if (sc.mode == 2)
  19870. song.mode = lynx::PlayMode::pattern;
  19871. engine->setSong (std::move (song));
  19872. }
  19873. else if (sc.file.hasFileExtension ("flp"))
  19874. loaded = engine->importFlpFile (sc.file, error);
  19875. else if (auto song = lynx::ProjectFile::load (sc.file, error))
  19876. engine->setSong (std::move (*song));
  19877. else
  19878. loaded = false;
  19879. if (! loaded)
  19880. {
  19881. step ("FAIL " + sc.name + ": " + error);
  19882. *ok = false;
  19883. (*run) (index + 1, 0);
  19884. return;
  19885. }
  19886. auto device = std::make_shared<StandIn> (block);
  19887. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  19888. // the graph is (re)built on the message thread: the run starts once it has settled
  19889. juce::Timer::callAfterDelay (1500, [this, scenarios, step, outputs, ok, run, block, seconds, index, pass, device] {
  19890. if (engine == nullptr)
  19891. return;
  19892. const auto& sc = (*scenarios)[index];
  19893. auto& cb = engine->deviceCallback();
  19894. std::vector<float> l ((std::size_t) block), r ((std::size_t) block), out;
  19895. float* outs[] = { l.data(), r.data() };
  19896. juce::AudioIODeviceCallbackContext context;
  19897. engine->stop();
  19898. engine->seek (0.0);
  19899. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context); // (the seek, stopped)
  19900. engine->play();
  19901. const auto blocks = (int) (seconds * 48000.0 / block);
  19902. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  19903. for (int k = 0; k < blocks; ++k)
  19904. {
  19905. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
  19906. out.insert (out.end(), l.begin(), l.end());
  19907. out.insert (out.end(), r.begin(), r.end());
  19908. // (about the device's pace at the start of each second, so the render-ahead thread gets ahead)
  19909. if (k % (48000 / block) < 48000 / block / 2)
  19910. std::this_thread::sleep_for (std::chrono::microseconds ((int) (block * 1.0e6 / 48000.0 * 0.6)));
  19911. }
  19912. const auto ms = juce::Time::getMillisecondCounterHiRes() - t0;
  19913. engine->stop();
  19914. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
  19915. const auto* st = engine->renderAheadStats();
  19916. auto n = [] (const std::atomic<std::uint64_t>& v) { return (juce::int64) v.load(); };
  19917. juce::String line = sc.name + (pass == 1 ? ", render ahead on: " : ", render ahead off: ") + juce::String (ms / 1000.0, 1) + " s";
  19918. if (st != nullptr && pass == 1)
  19919. line << "; blocks " << n (st->blocks) << ", from the ring " << n (st->fromRing) << ", waited " << n (st->waited) << ", in the callback "
  19920. << n (st->inline_) << ", dropped " << n (st->flushes) << ", drained " << n (st->drains) << ", started " << n (st->engagements)
  19921. << ", boundary mismatches " << n (st->splitMismatches) << "; ahead " << st->aheadChannels.load() << " channels / "
  19922. << st->aheadTracks.load() << " inserts, boundary " << st->boundary.load() << ", window " << st->window.load();
  19923. step (" " + line);
  19924. if (pass == 0)
  19925. {
  19926. outputs->assign (1, std::move (out));
  19927. (*run) (index, 1);
  19928. return;
  19929. }
  19930. const auto& off = outputs->front();
  19931. std::size_t first = off.size() == out.size() ? off.size() : 0;
  19932. for (std::size_t s = 0; s < std::min (off.size(), out.size()); ++s)
  19933. if (std::memcmp (&off[s], &out[s], sizeof (float)) != 0)
  19934. {
  19935. first = s;
  19936. break;
  19937. }
  19938. const auto same = off.size() == out.size() && first == off.size();
  19939. const auto clean = st != nullptr && st->flushes.load() == 0 && st->splitMismatches.load() == 0 && st->engagements.load() >= 1
  19940. && st->fromRing.load() > st->blocks.load() / 4;
  19941. *ok = *ok && same && clean;
  19942. 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))
  19943. + (clean ? "" : ", render-ahead counters off (see above)"));
  19944. (*run) (index + 1, 0);
  19945. });
  19946. };
  19947. (*run) (0, 0);
  19948. }
  19949. void runClipLoopTest (const juce::File& report, const juce::File& wavFile)
  19950. {
  19951. engine = std::make_unique<lynx::AudioEngine>();
  19952. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  19953. struct StandIn final : juce::AudioIODevice
  19954. {
  19955. StandIn() : juce::AudioIODevice ("cliploop", "test") {}
  19956. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  19957. juce::StringArray getInputChannelNames() override { return {}; }
  19958. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  19959. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  19960. int getDefaultBufferSize() override { return 512; }
  19961. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  19962. void close() override {}
  19963. bool isOpen() override { return true; }
  19964. void start (juce::AudioIODeviceCallback*) override {}
  19965. void stop() override {}
  19966. bool isPlaying() override { return true; }
  19967. juce::String getLastError() override { return {}; }
  19968. int getCurrentBufferSizeSamples() override { return 512; }
  19969. double getCurrentSampleRate() override { return 48000.0; }
  19970. int getCurrentBitDepth() override { return 32; }
  19971. juce::BigInteger getActiveOutputChannels() const override
  19972. {
  19973. juce::BigInteger b;
  19974. b.setRange (0, 2, true);
  19975. return b;
  19976. }
  19977. juce::BigInteger getActiveInputChannels() const override { return {}; }
  19978. int getOutputLatencyInSamples() override { return 0; }
  19979. int getInputLatencyInSamples() override { return 0; }
  19980. };
  19981. auto device = std::make_shared<StandIn>();
  19982. auto text = std::make_shared<juce::String>();
  19983. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  19984. constexpr int bar = 96000, beat = bar / 4; // 120 BPM, 48 kHz
  19985. const auto ppq = (double) lynx::ppq;
  19986. lynx::Song song;
  19987. song.bpm = 120.0;
  19988. song.mixer = lynx::Song::defaultMixer (2);
  19989. song.channels.resize (1); // the synth of a new channel: deterministic
  19990. song.channels[0].mixerTrack = 1;
  19991. auto& pattern = song.patterns.emplace_back(); // 1 bar: C5 on beat 0, C6 on beat 2
  19992. for (auto [b, key] : { std::pair { 0, 60 }, std::pair { 2, 72 } })
  19993. {
  19994. lynx::Note n;
  19995. n.start = b * lynx::ppq;
  19996. n.length = lynx::ppq / 4;
  19997. n.key = key;
  19998. pattern.notes.push_back (n);
  19999. }
  20000. lynx::Clip clip;
  20001. clip.pattern = 0;
  20002. clip.length = 16 * lynx::ppq; // stretched to 4 bars
  20003. song.playlist.push_back (clip);
  20004. song.mode = lynx::PlayMode::song;
  20005. {
  20006. // the Windows GUI check's project: the same song with a 1-bar clip, to stretch with the mouse
  20007. auto gui = song;
  20008. gui.playlist[0].length = 4 * lynx::ppq;
  20009. juce::String error;
  20010. lynx::ProjectFile::save (gui, report.getSiblingFile ("cliploop-gui.lynx"), error);
  20011. }
  20012. engine->setSong (song);
  20013. auto& callback = engine->deviceCallback();
  20014. callback.audioDeviceAboutToStart (device.get());
  20015. step ("song=1-bar synth pattern, clip stretched to 4 bars, 120 BPM, 48 kHz, blocks of 512");
  20016. // the graph is (re)built on the message thread: the scenarios run once it has settled
  20017. juce::Timer::callAfterDelay (1500, [this, device, step, wavFile, ppq] {
  20018. if (engine == nullptr)
  20019. return;
  20020. auto& cb = engine->deviceCallback();
  20021. // plays `samples` from tick `from` through the device callback; `between` runs after each block (block index)
  20022. auto play = [this, &cb] (double from, int samples, const std::function<void (int)>& between = {}) {
  20023. engine->stop();
  20024. engine->seek (from);
  20025. std::vector<float> l (512), r (512), out;
  20026. float* outs[] = { l.data(), r.data() };
  20027. juce::AudioIODeviceCallbackContext context;
  20028. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context); // (the seek, stopped)
  20029. engine->play();
  20030. for (int k = 0; (int) out.size() < samples; ++k)
  20031. {
  20032. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  20033. out.insert (out.end(), l.begin(), l.end());
  20034. if (between)
  20035. between (k);
  20036. }
  20037. engine->stop();
  20038. for (int k = 0; k < 400; ++k) // the tails of the scenario die out
  20039. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  20040. out.resize ((std::size_t) samples);
  20041. return out;
  20042. };
  20043. auto rms = [] (const std::vector<float>& x, int from, int count) {
  20044. double sum = 0.0;
  20045. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  20046. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  20047. return std::sqrt (sum / juce::jmax (1, count));
  20048. };
  20049. auto diff = [] (const std::vector<float>& a, int aFrom, const std::vector<float>& b, int bFrom, int count) {
  20050. double m = 0.0;
  20051. for (int i = 0; i < count && aFrom + i < (int) a.size() && bFrom + i < (int) b.size(); ++i)
  20052. m = juce::jmax (m, (double) std::abs (a[(std::size_t) (aFrom + i)] - b[(std::size_t) (bFrom + i)]));
  20053. return m;
  20054. };
  20055. auto num = [] (double v) { return juce::String (v, 6); };
  20056. bool ok = true;
  20057. auto check = [&ok, step] (bool good, const juce::String& what) {
  20058. ok = ok && good;
  20059. step ((good ? "ok " : "FAIL ") + what);
  20060. };
  20061. lynx::setStretchedClipsLoop (true);
  20062. const auto a = play (0.0, 4 * bar);
  20063. const auto bar1 = rms (a, 0, bar);
  20064. check (bar1 > 0.01, "play from the start: bar 1 RMS " + num (bar1));
  20065. for (int k = 1; k < 4; ++k)
  20066. {
  20067. const auto rk = rms (a, k * bar, bar), d = diff (a, k * bar, a, 0, bar);
  20068. check (std::abs (rk / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  20069. "bar " + juce::String (k + 1) + " RMS " + num (rk) + " (x" + num (rk / bar1) + " of bar 1), max |bar - bar 1| " + juce::String (d, 9));
  20070. }
  20071. {
  20072. const auto x = play (10 * ppq, bar + bar / 2);
  20073. const auto d = juce::jmax (diff (x, 0, a, 2 * beat, bar / 2), diff (x, bar / 2, a, 0, bar));
  20074. check (rms (x, 0, bar / 2) > 0.01 && d < 1.0e-4,
  20075. "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));
  20076. }
  20077. {
  20078. // a seek while playing, after 6.99 beats, to bar 4 beat 3 (a ruler click)
  20079. const auto jumpBlock = 7 * beat / 512 - 1;
  20080. const auto x = play (0.0, 2 * bar, [this, jumpBlock, ppq] (int k) {
  20081. if (k == jumpBlock)
  20082. engine->seek (14 * ppq);
  20083. });
  20084. // (the best of 0-2 samples late: anything but 0 fails)
  20085. const auto at = (jumpBlock + 1) * 512;
  20086. int lag = 0;
  20087. auto d = 1.0e9;
  20088. for (int l = 0; l <= 2; ++l)
  20089. if (const auto dl = diff (x, at + l, a, 2 * beat, beat - 2); dl < d)
  20090. d = dl, lag = l;
  20091. d = lag == 0 ? d : 1.0;
  20092. const auto ratio = rms (x, at, beat) / rms (a, 2 * beat, beat);
  20093. check (std::abs (ratio - 1.0) < 1.0e-3 && d < 1.0e-4,
  20094. "jump mid-clip to bar 4 beat 3: RMS " + num (rms (x, at, beat)) + " (x" + num (ratio) + " of bar 1 beat 3), max diff "
  20095. + juce::String (d, 9) + " (" + juce::String (lag) + " sample(s) late)");
  20096. }
  20097. {
  20098. engine->editSong ([ppq] (lynx::Song& s) {
  20099. s.loopStart = (std::int64_t) (4 * ppq);
  20100. s.loopEnd = (std::int64_t) (12 * ppq);
  20101. }, false);
  20102. const auto x = play (0.0, 7 * bar);
  20103. double d = 0.0;
  20104. juce::String lags;
  20105. for (int k = 1; k < 7; ++k) // (the best of 0-2 samples late after a wrap, as after a jump)
  20106. {
  20107. auto best = 1.0e9;
  20108. int lag = 0;
  20109. for (int l = 0; l <= 2; ++l)
  20110. if (const auto dl = diff (x, k * bar + l, a, 0, bar - 2); dl < best)
  20111. best = dl, lag = l;
  20112. d = juce::jmax (d, lag == 0 ? best : 1.0); // a sample gained at a wrap fails (round 167q loopwrap)
  20113. lags << (k > 1 ? "," : "") << lag;
  20114. }
  20115. const auto r = rms (x, bar, 6 * bar);
  20116. check (std::abs (r / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  20117. "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)
  20118. + " (samples late, bars 2-7: " + lags + ")");
  20119. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  20120. }
  20121. {
  20122. // 100 wraps of a 1-bar loop region (bar 2): every pass on its sample, none gained (round 167q loopwrap: each
  20123. // wrap used to play one sample more)
  20124. engine->editSong ([ppq] (lynx::Song& s) {
  20125. s.loopStart = (std::int64_t) (4 * ppq);
  20126. s.loopEnd = (std::int64_t) (8 * ppq);
  20127. }, false);
  20128. const auto x = play (0.0, 101 * bar);
  20129. double d = 0.0;
  20130. int worst = 0;
  20131. for (int k = 1; k <= 100; ++k)
  20132. if (const auto dk = diff (x, k * bar, a, 0, bar); dk > d)
  20133. d = dk, worst = k + 1;
  20134. check (d < 1.0e-4, "loop region bar 2, 100 wraps: max diff of every pass vs bar 1 " + juce::String (d, 9)
  20135. + (d < 1.0e-4 ? juce::String() : " (worst: bar " + juce::String (worst) + ")"));
  20136. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  20137. }
  20138. lynx::setStretchedClipsLoop (false);
  20139. {
  20140. const auto x = play (0.0, 4 * bar);
  20141. const auto r = juce::jmax (rms (x, bar, bar), juce::jmax (rms (x, 2 * bar, bar), rms (x, 3 * bar, bar)));
  20142. 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));
  20143. }
  20144. lynx::setStretchedClipsLoop (true);
  20145. cb.audioDeviceStopped();
  20146. // the export: a WAV of the 4 bars, read back from the file
  20147. if (wavFile != juce::File())
  20148. {
  20149. for (const auto loops : { true, false })
  20150. {
  20151. lynx::setStretchedClipsLoop (loops);
  20152. const auto file = loops ? wavFile : wavFile.getSiblingFile (wavFile.getFileNameWithoutExtension() + "-off.wav");
  20153. file.deleteFile();
  20154. {
  20155. juce::WavAudioFormat wav;
  20156. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (file.createOutputStream().release(), 48000.0, 2, 32, {}, 0));
  20157. engine->stop();
  20158. engine->seek (0.0);
  20159. lynx::AudioEngine::RenderOptions o;
  20160. o.seconds = 8.0;
  20161. o.sampleRate = 48000.0;
  20162. o.output = writer.get();
  20163. engine->renderOffline (o);
  20164. }
  20165. juce::WavAudioFormat wav;
  20166. std::unique_ptr<juce::AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
  20167. std::vector<float> x;
  20168. if (reader != nullptr)
  20169. {
  20170. juce::AudioBuffer<float> buffer (2, (int) reader->lengthInSamples);
  20171. reader->read (&buffer, 0, (int) reader->lengthInSamples, 0, true, true);
  20172. x.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + buffer.getNumSamples());
  20173. }
  20174. const auto b1 = rms (x, 0, bar);
  20175. juce::String line = juce::String (loops ? "export" : "export, option off") + " (" + file.getFileName() + ", " + juce::String ((int) x.size()) + " samples): bar 1 RMS " + num (b1);
  20176. bool good = x.size() >= (std::size_t) 4 * bar && b1 > 0.01;
  20177. for (int k = 1; k < 4; ++k)
  20178. {
  20179. const auto rk = rms (x, k * bar, bar);
  20180. line << ", bar " << (k + 1) << " " << num (rk);
  20181. 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);
  20182. }
  20183. if (loops)
  20184. 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);
  20185. check (good, line);
  20186. }
  20187. lynx::setStretchedClipsLoop (true);
  20188. }
  20189. step (ok ? "result=OK" : "result=FAILED");
  20190. setApplicationReturnValue (ok ? 0 : 1);
  20191. quit();
  20192. });
  20193. }
  20194. // --rectest (round 163): see the command line above. Writes report lines step by step (a driver that ends the
  20195. // process leaves what was done).
  20196. void runRecordTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  20197. const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
  20198. {
  20199. engine = std::make_unique<lynx::AudioEngine>();
  20200. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  20201. savedDeviceState = engine->getDeviceManager().createStateXml();
  20202. auto text = std::make_shared<juce::String>();
  20203. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  20204. auto finish = [this, step] (int code) {
  20205. restoreSavedDeviceState();
  20206. setApplicationReturnValue (code);
  20207. quit();
  20208. };
  20209. auto& devices = engine->getDeviceManager();
  20210. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  20211. devices.setCurrentAudioDeviceType (deviceType, true);
  20212. {
  20213. auto setup = devices.getAudioDeviceSetup();
  20214. if (deviceName.isNotEmpty())
  20215. setup.outputDeviceName = deviceName;
  20216. if (bufferSize > 0)
  20217. setup.bufferSize = bufferSize;
  20218. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  20219. step ("device_error=" + error);
  20220. }
  20221. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  20222. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  20223. // takes go next to the report, not into the user's recordings folder
  20224. engine->setRecordingTarget (report.getSiblingFile (report.getFileNameWithoutExtension() + "-takes"), {});
  20225. auto* device = devices.getCurrentAudioDevice();
  20226. if (device == nullptr || engine->getInputChannelNames().empty())
  20227. {
  20228. step ("result=ERROR no device / no input");
  20229. finish (1);
  20230. return;
  20231. }
  20232. const auto rate = device->getCurrentSampleRate();
  20233. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples())
  20234. + " | driver latency in " + juce::String (device->getInputLatencyInSamples()) + " out " + juce::String (device->getOutputLatencyInSamples()));
  20235. // a click (the ping's pulse) on every beat at 120 bpm: beat k at sample k * rate / 2
  20236. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  20237. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  20238. {
  20239. lynx::takes::WavTakeWriter w;
  20240. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  20241. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  20242. std::vector<float> block (4096);
  20243. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  20244. {
  20245. std::fill (block.begin(), block.end(), 0.0f);
  20246. for (int k = 0; k < (int) block.size(); ++k)
  20247. {
  20248. const auto f = at + k;
  20249. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  20250. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  20251. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  20252. if (rel >= 0 && rel < 5)
  20253. block[(std::size_t) k] = 0.5f * shape[rel];
  20254. }
  20255. const float* d[] { block.data() };
  20256. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  20257. }
  20258. w.close();
  20259. }
  20260. lynx::Song song = lynx::Song::makeDefault();
  20261. song.bpm = 120.0;
  20262. song.mode = lynx::PlayMode::song;
  20263. song.playlist.clear();
  20264. lynx::ChannelDef c;
  20265. c.name = "Clicks";
  20266. c.instrument = lynx::InstrumentKind::audioClip;
  20267. c.samplePath = clickFile.getFullPathName().toStdString();
  20268. c.mixerTrack = 0;
  20269. c.volume = 1.0f;
  20270. song.channels.push_back (c);
  20271. lynx::Clip clip;
  20272. clip.kind = lynx::ClipKind::audio;
  20273. clip.channel = (int) song.channels.size() - 1;
  20274. clip.track = 0;
  20275. clip.start = 0;
  20276. clip.length = (std::int64_t) beats * lynx::ppq;
  20277. song.playlist.push_back (clip);
  20278. if (mode == 1) // loop recording, bars 2-4
  20279. {
  20280. song.loopStart = 4 * lynx::ppq;
  20281. song.loopEnd = 16 * lynx::ppq;
  20282. }
  20283. else if (mode == 2) // punch in/out, bars 3-4
  20284. {
  20285. song.loopStart = 8 * lynx::ppq;
  20286. song.loopEnd = 16 * lynx::ppq;
  20287. }
  20288. if (song.mixer.size() > 1)
  20289. {
  20290. song.mixer[1].name = "Loop In";
  20291. song.mixer[1].monitor = lynx::InputMonitor::off; // (the loopback must not hear itself)
  20292. song.mixer[1].recordSource = lynx::RecordSource::externalInput; // (round 190rj: FL's Post EQ records what the insert hears: nothing with the monitor off)
  20293. }
  20294. engine->setSong (std::move (song));
  20295. engine->setInsertInput (1, 0, false);
  20296. juce::ignoreUnused (pdcSamples);
  20297. // 1) the ping
  20298. if (const auto error = engine->startLatencyPing(); error.isNotEmpty())
  20299. step ("ping_error=" + error);
  20300. juce::Timer::callAfterDelay (3500, [this, step, finish, seconds, rate, report, mode] {
  20301. if (engine == nullptr)
  20302. return;
  20303. if (engine->isPinging())
  20304. engine->cancelLatencyPing();
  20305. const auto r = engine->finishLatencyPing();
  20306. step ("ping=" + juce::String (r.ok ? "ok" : "FAILED " + juce::String (r.problem)) + " samples " + juce::String (r.samples) + " spread " + juce::String (r.spread)
  20307. + " found " + juce::String (r.found) + "/" + juce::String (r.sent) + " peak " + juce::String (juce::Decibels::gainToDecibels (r.peak, -150.0f), 1) + " dB");
  20308. const auto l = engine->currentLatency();
  20309. step ("compensation=" + juce::String (l.total()) + " (round trip " + juce::String (l.roundTrip()) + ", manual " + juce::String (l.manual) + ", pdc " + juce::String (l.pdc) + ")");
  20310. // 2) record
  20311. engine->setInsertArmed (1, true);
  20312. auto o = engine->getRecordOptions();
  20313. o.recordAudio = true;
  20314. o.countInBars = 0;
  20315. o.waitForInput = false;
  20316. o.punchLoopRegion = mode == 2;
  20317. o.preRollBars = mode == 2 ? 1 : 0;
  20318. o.postRollBars = mode == 2 ? 1 : 0;
  20319. // (round 177c: LYNX_RECTEST_BLEND_OFF=1: Blend off; LYNX_RECTEST_LAST_PASS=1: "only the last pass plays")
  20320. o.mode = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_BLEND_OFF", {}) == "1" ? lynx::RecordMode::replace
  20321. : lynx::RecordMode::overdub;
  20322. o.lastLoopPassPlays = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_LAST_PASS", {}) == "1";
  20323. engine->setRecordOptions (o);
  20324. engine->stop();
  20325. engine->rewind();
  20326. engine->setRecording (true);
  20327. juce::Timer::callAfterDelay (300, [this, step, finish, seconds, rate, report, mode] {
  20328. if (engine == nullptr)
  20329. return;
  20330. engine->startPlayback(); // (as the Play button: pre-roll / punch)
  20331. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, step, finish, seconds, rate, report, mode] {
  20332. if (engine == nullptr)
  20333. return;
  20334. if (mode == 2)
  20335. step (juce::String ("stopped_by_post_roll=") + (engine->getTransport().playing.load() ? "no" : "yes"));
  20336. engine->stop();
  20337. juce::Timer::callAfterDelay (500, [this, step, finish, seconds, rate, report, mode] {
  20338. if (engine == nullptr)
  20339. return;
  20340. engine->setRecording (false);
  20341. const auto& s = engine->getSong();
  20342. const auto tps = 120.0 * lynx::ppq / (60.0 * rate);
  20343. int take = -1;
  20344. for (int ch = 0; ch < (int) s.channels.size(); ++ch)
  20345. if (s.channels[(std::size_t) ch].instrument == lynx::InstrumentKind::audioClip && s.channels[(std::size_t) ch].name != "Clicks")
  20346. take = ch;
  20347. if (take < 0)
  20348. {
  20349. step ("result=ERROR no take (" + engine->getLastRecordingError() + ")");
  20350. finish (1);
  20351. return;
  20352. }
  20353. std::vector<std::vector<float>> audio;
  20354. double takeRate = 0.0;
  20355. const auto& path = s.channels[(std::size_t) take].samplePath;
  20356. lynx::takes::readWav (path, audio, &takeRate);
  20357. const auto frames = audio.empty() ? (juce::int64) 0 : (juce::int64) audio[0].size();
  20358. step ("take=" + juce::String::fromUTF8 (path.c_str()) + " frames " + juce::String (frames) + " (" + juce::String ((double) frames / rate, 3)
  20359. + " s of " + juce::String (seconds, 1) + " s played) lost " + juce::String (engine->getLostRecordingFrames()));
  20360. // the clicks in the file (peaks above -12 dBFS, one per 1/8 s at most)
  20361. std::vector<juce::int64> peaks;
  20362. if (! audio.empty())
  20363. for (juce::int64 f = 1; f + 1 < frames; ++f)
  20364. {
  20365. const auto x = std::abs (audio[0][(std::size_t) f]);
  20366. if (x > 0.25f && x >= std::abs (audio[0][(std::size_t) f - 1]) && x > std::abs (audio[0][(std::size_t) f + 1])
  20367. && (peaks.empty() || f - peaks.back() > (juce::int64) (rate / 8)))
  20368. peaks.push_back (f);
  20369. }
  20370. // every clip of the take: each click inside it against the nearest beat
  20371. int clips = 0, checked = 0, muted = 0;
  20372. double worst = 0.0, sum = 0.0;
  20373. for (const auto& c : s.playlist)
  20374. {
  20375. if (c.kind != lynx::ClipKind::audio || c.channel != take)
  20376. continue;
  20377. ++clips;
  20378. muted += c.muted ? 1 : 0;
  20379. const auto skip = ((double) c.offset + (double) c.offsetFraction) / tps; // file samples before the clip start
  20380. for (const auto f : peaks)
  20381. {
  20382. const auto intoClip = (double) f - skip;
  20383. if (intoClip < 0.0 || intoClip * tps >= (double) c.length)
  20384. continue;
  20385. const auto songTick = (double) c.start + intoClip * tps - 2.0 * tps; // (the pulse's peak is its 3rd sample)
  20386. const auto beat = std::round (songTick / lynx::ppq) * lynx::ppq;
  20387. const auto error = (songTick - beat) / tps;
  20388. worst = std::max (worst, std::abs (error));
  20389. sum += error;
  20390. ++checked;
  20391. }
  20392. step ("clip track " + juce::String (c.track) + " start " + juce::String ((juce::int64) c.start) + " length " + juce::String ((juce::int64) c.length)
  20393. + " offset " + juce::String ((juce::int64) c.offset) + juce::String (c.offsetFraction >= 0.0f ? "+" : "") + juce::String (c.offsetFraction, 4)
  20394. + (c.muted ? " (muted lane)" : ""));
  20395. }
  20396. step ("clicks_in_file=" + juce::String ((int) peaks.size()) + " checked=" + juce::String (checked) + " clips=" + juce::String (clips)
  20397. + " muted_lanes=" + juce::String (muted));
  20398. step ("placement_error_samples=max " + juce::String (worst, 3) + " mean " + juce::String (checked > 0 ? sum / checked : 0.0, 3));
  20399. auto ok = checked > 0 && worst <= 1.0 && engine->getLostRecordingFrames() == 0;
  20400. if (mode == 2) // one clip, exactly the punch range, its 8 beats
  20401. {
  20402. const auto& sp = engine->getSong();
  20403. bool exact = false;
  20404. for (const auto& c : sp.playlist)
  20405. if (c.kind == lynx::ClipKind::audio && c.channel == take)
  20406. exact = c.start == sp.loopStart && c.start + c.length == sp.loopEnd;
  20407. step (juce::String ("punch_clip_matches_range=") + (exact ? "yes" : "no"));
  20408. ok = ok && clips == 1 && exact && checked == 8;
  20409. }
  20410. report.getSiblingFile (report.getFileNameWithoutExtension() + "-project.lynx").replaceWithText (lynx::ProjectFile::toJson (engine->getSong()));
  20411. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  20412. finish (ok ? 0 : 1);
  20413. });
  20414. });
  20415. });
  20416. });
  20417. }
  20418. // --hwinserttest (round 164d): see the command line above.
  20419. void runHwInsertTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  20420. const juce::String& inputName, int bufferSize, bool inPatcher = false, juce::File bounceFile = {})
  20421. {
  20422. engine = std::make_unique<lynx::AudioEngine>();
  20423. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  20424. savedDeviceState = engine->getDeviceManager().createStateXml();
  20425. auto text = std::make_shared<juce::String>();
  20426. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  20427. auto finish = [this] (int code) {
  20428. if (engine != nullptr)
  20429. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  20430. restoreSavedDeviceState();
  20431. setApplicationReturnValue (code);
  20432. quit();
  20433. };
  20434. auto& devices = engine->getDeviceManager();
  20435. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  20436. devices.setCurrentAudioDeviceType (deviceType, true);
  20437. {
  20438. auto setup = devices.getAudioDeviceSetup();
  20439. if (deviceName.isNotEmpty())
  20440. setup.outputDeviceName = deviceName;
  20441. if (bufferSize > 0)
  20442. setup.bufferSize = bufferSize;
  20443. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  20444. step ("device_error=" + error);
  20445. }
  20446. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  20447. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  20448. auto* device = devices.getCurrentAudioDevice();
  20449. if (device == nullptr || engine->getInputChannelNames().empty())
  20450. {
  20451. step ("result=ERROR no device / no input");
  20452. finish (1);
  20453. return;
  20454. }
  20455. const auto rate = device->getCurrentSampleRate();
  20456. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples()));
  20457. // the click track: the ping's pulse on every beat at 120 bpm
  20458. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  20459. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  20460. {
  20461. lynx::takes::WavTakeWriter w;
  20462. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  20463. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  20464. std::vector<float> block (4096);
  20465. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  20466. {
  20467. std::fill (block.begin(), block.end(), 0.0f);
  20468. for (int k = 0; k < (int) block.size(); ++k)
  20469. {
  20470. const auto f = at + k;
  20471. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  20472. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  20473. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  20474. if (rel >= 0 && rel < 5)
  20475. block[(std::size_t) k] = 0.5f * shape[rel];
  20476. }
  20477. const float* d[] { block.data() };
  20478. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  20479. }
  20480. w.close();
  20481. }
  20482. lynx::Song song = lynx::Song::makeDefault();
  20483. song.bpm = 120.0;
  20484. song.mode = lynx::PlayMode::song;
  20485. song.playlist.clear();
  20486. song.channels.clear();
  20487. for (int k = 0; k < 2; ++k)
  20488. {
  20489. lynx::ChannelDef c;
  20490. c.name = k == 0 ? "Wet" : "Dry";
  20491. c.instrument = lynx::InstrumentKind::audioClip;
  20492. c.samplePath = clickFile.getFullPathName().toStdString();
  20493. c.mixerTrack = k + 1;
  20494. c.volume = 1.0f;
  20495. song.channels.push_back (c);
  20496. lynx::Clip clip;
  20497. clip.kind = lynx::ClipKind::audio;
  20498. clip.channel = k;
  20499. clip.track = k;
  20500. clip.start = 0;
  20501. clip.length = (std::int64_t) beats * lynx::ppq;
  20502. song.playlist.push_back (clip);
  20503. }
  20504. song.mixer[0].outputChannel = lynx::outputNone; // (the cable carries the send only)
  20505. for (auto& fx : song.mixer[0].effects) // (no Master effects: the default limiter's PDC would hide nothing, but keep it plain)
  20506. fx.enabled = false;
  20507. song.mixer[1].pan = -1.0f;
  20508. song.mixer[2].pan = 1.0f;
  20509. auto hw = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  20510. hw.params[lynx::hwinsert::output] = lynx::hwinsert::channelValue (0);
  20511. hw.params[lynx::hwinsert::input] = lynx::hwinsert::channelValue (0);
  20512. hw.params[lynx::hwinsert::inputStereo] = 1.0f;
  20513. song.mixer[1].effects.clear();
  20514. lynx::AudioEngine::HardwareInsertRef ref { false, 1, 0, {} };
  20515. if (inPatcher) // (round 165c) From LYNX -> Hardware Insert -> To LYNX
  20516. {
  20517. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  20518. lynx::PatchNode node;
  20519. node.effect = hw;
  20520. slot.patcher.nodes = { node };
  20521. lynx::PatchWire in, out;
  20522. in.from = lynx::patchFromHost;
  20523. in.to = 0;
  20524. out.from = 0;
  20525. out.to = lynx::patchToHost;
  20526. slot.patcher.wires = { in, out };
  20527. song.mixer[1].effects.push_back (slot);
  20528. ref.nodes = { 0 };
  20529. }
  20530. else
  20531. song.mixer[1].effects.push_back (hw);
  20532. engine->setSong (std::move (song));
  20533. step (juce::String ("insert=") + (inPatcher ? "inside a Patcher on Insert 1" : "Insert 1 slot 1"));
  20534. const auto meter = [this, ref] (int output) {
  20535. const auto fx = engine->runningHardwareInsert (ref);
  20536. return fx != nullptr ? fx->controlOutput (output) : 0.0f;
  20537. };
  20538. // 1) the insert's ping (as its Ping button: a momentary value flipped)
  20539. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  20540. if (engine == nullptr)
  20541. return;
  20542. engine->pingHardwareInserts ({ ref });
  20543. juce::Timer::callAfterDelay (3500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  20544. if (engine == nullptr)
  20545. return;
  20546. // (round 165c) the engine makes a ping's result the slot's round trip with the device setup it belongs to; the
  20547. // new round trip rebuilds the insert (its latency), so the result is read from the slot
  20548. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  20549. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  20550. const auto setup = slot != nullptr ? lynx::hwinsert::measuredSetup (*slot) : std::string();
  20551. const auto state = meter (lynx::hwinsert::pingState);
  20552. const auto ok = samples > 0 && setup == engine->currentSetupKey();
  20553. step ("ping_round_trip=" + juce::String (samples) + " measured_setup=" + juce::String (setup) + (ok ? " (ok)" : " (FAILED)")
  20554. + " live_ping_state=" + juce::String (state, 3) + " status_flags=" + juce::String (juce::roundToInt (meter (lynx::hwinsert::status) * 16.0f)));
  20555. if (! ok)
  20556. {
  20557. step ("result=FAILED ping");
  20558. finish (1);
  20559. return;
  20560. }
  20561. // a stale setup is noticed: another setup key on the slot gives the notice, the real one none
  20562. step ("stale_now=" + juce::String ((int) engine->staleHardwareInserts().size()));
  20563. // 2) play, capturing the Master
  20564. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, samples, ref, inPatcher, bounceFile] {
  20565. if (engine == nullptr)
  20566. return;
  20567. step ("pdc_total=" + juce::String (engine->getLatencySamples()) + " (expected " + juce::String (samples) + ")");
  20568. // saved in the project: the slot comes back the same (routing, round trip), and its latency with it — also an
  20569. // odd round trip (12345 samples: the project keeps it to the sample)
  20570. if (! inPatcher)
  20571. {
  20572. auto odd = engine->getSong();
  20573. odd.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (12345);
  20574. juce::String error;
  20575. auto same = true;
  20576. for (const auto* song : { &engine->getSong(), (const lynx::Song*) &odd })
  20577. {
  20578. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (song == &odd ? "-odd.lynx" : ".lynx"));
  20579. const auto saved = lynx::ProjectFile::save (*song, file, error);
  20580. const auto loaded = saved ? lynx::ProjectFile::load (file, error) : std::nullopt;
  20581. same = same && loaded && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  20582. && loaded->mixer[1].effects[0].kind == lynx::EffectKind::hardwareInsert
  20583. && loaded->mixer[1].effects[0].params == song->mixer[1].effects[0].params
  20584. && lynx::makeEffect (loaded->mixer[1].effects[0])->latencySamples() == (song == &odd ? 12345 : samples);
  20585. }
  20586. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + ".lynx");
  20587. step (juce::String ("project_round_trip=") + (same ? "same" : "DIFFERENT " + error) + " (" + file.getFileName() + ")");
  20588. if (! same)
  20589. {
  20590. step ("result=FAILED project");
  20591. finish (1);
  20592. return;
  20593. }
  20594. }
  20595. auto left = std::make_shared<std::vector<float>>(), right = std::make_shared<std::vector<float>>();
  20596. engine->stop();
  20597. engine->rewind();
  20598. engine->getMeters().capture.setSource (0);
  20599. engine->play();
  20600. auto pulls = std::make_shared<int> ((int) (seconds * 5.0));
  20601. auto pull = std::make_shared<std::function<void()>>();
  20602. *pull = [this, report, step, finish, seconds, rate, samples, left, right, pulls, pull, ref, inPatcher, bounceFile] {
  20603. if (engine == nullptr)
  20604. return;
  20605. engine->getMeters().capture.pull (*left, *right);
  20606. if (*pulls == 10) // the insert's editor while it plays (next to the report)
  20607. for (const auto scale : { 1.0f, 1.5f })
  20608. {
  20609. auto editor = inPatcher ? lynx::makeNodeEffectEditor (
  20610. *engine, [ref] (lynx::Song& s) { return lynx::AudioEngine::locateHardwareInsert (s, ref); },
  20611. [this, ref] { return engine->runningHardwareInsert (ref); }, "Insert 1 (Patcher)", scale)
  20612. : lynx::makeNativeEffectEditor (*engine, 1, 0, scale, 0);
  20613. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  20614. {
  20615. juce::Graphics g (image);
  20616. g.fillAll (lynx::theme::panel);
  20617. editor->paintEntireComponent (g, false);
  20618. }
  20619. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (scale > 1.0f ? "-editor150.png" : "-editor.png"));
  20620. file.deleteFile();
  20621. juce::PNGImageFormat png;
  20622. if (auto stream = file.createOutputStream())
  20623. png.writeImageToStream (image, *stream);
  20624. }
  20625. if (--*pulls > 0)
  20626. {
  20627. juce::Timer::callAfterDelay (200, *pull);
  20628. return;
  20629. }
  20630. engine->stop();
  20631. const auto dropped = engine->getMeters().capture.droppedFrames();
  20632. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  20633. // the clicks of each side (peaks above -12 dBFS, one per 1/8 s at most)
  20634. auto peaksOf = [rate] (const std::vector<float>& x) {
  20635. std::vector<juce::int64> peaks;
  20636. for (std::size_t f = 1; f + 1 < x.size(); ++f)
  20637. 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])
  20638. && (peaks.empty() || (juce::int64) f - peaks.back() > (juce::int64) (rate / 8)))
  20639. peaks.push_back ((juce::int64) f);
  20640. return peaks;
  20641. };
  20642. const auto wet = peaksOf (*left), dry = peaksOf (*right);
  20643. int pairs = 0;
  20644. juce::int64 worst = 0;
  20645. double gainSum = 0.0, residual = 0.0, energy = 0.0;
  20646. for (const auto w : wet)
  20647. {
  20648. 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); });
  20649. if (best == dry.end() || std::abs (*best - w) > (juce::int64) (rate / 8))
  20650. continue;
  20651. ++pairs;
  20652. worst = std::max (worst, std::abs (*best - w));
  20653. gainSum += (*left)[(std::size_t) w] / (*right)[(std::size_t) *best];
  20654. }
  20655. const auto gain = pairs > 0 ? gainSum / pairs : 1.0;
  20656. // dry clicks with no wet click beside them (a dropout of the cable / device), listed
  20657. juce::String unmatched;
  20658. for (const auto d : dry)
  20659. if (std::none_of (wet.begin(), wet.end(), [d, rate] (juce::int64 w) { return std::abs (w - d) <= (juce::int64) (rate / 8); }))
  20660. unmatched << " " << (juce::int64) d << " (" << juce::String ((*left)[(std::size_t) d], 3) << ")";
  20661. if (unmatched.isNotEmpty())
  20662. step ("dry_clicks_without_wet=" + unmatched);
  20663. // the null test: left − gain · right around each click (both sides aligned → only the cable's colour remains)
  20664. for (const auto w : wet)
  20665. for (juce::int64 f = std::max<juce::int64> (0, w - 16); f < std::min<juce::int64> ((juce::int64) left->size(), w + 16); ++f)
  20666. {
  20667. const auto d = (double) (*left)[(std::size_t) f] - gain * (double) (*right)[(std::size_t) f];
  20668. residual += d * d;
  20669. energy += (double) (*left)[(std::size_t) f] * (*left)[(std::size_t) f];
  20670. }
  20671. const auto nullDb = energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, residual / energy)) : 0.0;
  20672. step ("captured=" + juce::String ((int) left->size()) + " frames dropped=" + juce::String (dropped) + " wet_clicks=" + juce::String ((int) wet.size())
  20673. + " dry_clicks=" + juce::String ((int) dry.size()) + " pairs=" + juce::String (pairs));
  20674. step ("alignment_error_samples=max " + juce::String ((int) worst) + " cable_gain=" + juce::String (gain, 4) + " null_residual_db=" + juce::String (nullDb, 1));
  20675. auto* dev = engine->getDeviceManager().getCurrentAudioDevice();
  20676. const auto xruns = dev != nullptr ? dev->getXRunCount() : -1;
  20677. step ("device_xruns=" + juce::String (xruns) + " (a dropout loses what was on the cable then: its clicks are excused)");
  20678. const auto excused = xruns > 0 ? 2 * xruns : 0;
  20679. const auto ok = pairs >= (int) (seconds * 2.0) - 2 - excused && worst == 0 && dropped == 0 && engine->getLatencySamples() == samples;
  20680. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  20681. // (round 165c) then the re-ping notice after a buffer size change
  20682. auto then = [this, ref, step, finish] (int code) {
  20683. if (code != 0)
  20684. finish (code);
  20685. else
  20686. runRepingCheck (ref, step, finish);
  20687. };
  20688. if (! ok)
  20689. {
  20690. finish (1);
  20691. return;
  20692. }
  20693. if (bounceFile == juce::File())
  20694. then (0);
  20695. else
  20696. runBounceCheck (bounceFile, step, then);
  20697. };
  20698. juce::Timer::callAfterDelay (200, *pull);
  20699. });
  20700. });
  20701. });
  20702. }
  20703. // --hwinserttest --bounce (round 165c): Export › "Render through the hardware in real time" of the test song next to
  20704. // the offline export of the same song. Through the loopback cable (gain 1) the return is the send delayed by the
  20705. // pinged round trip, so the real-time file must equal the offline one (which passes the dry signal at that delay)
  20706. // to float rounding, with the wet clicks (left) on the dry clicks' samples (right).
  20707. // --hwinserttest (round 165c): the buffer size changes (another round trip on the device): the engine notices the
  20708. // insert measured for the old setup (the app's "Ping now?" prompt), "Ping now" measures it again for the new one
  20709. void runRepingCheck (lynx::AudioEngine::HardwareInsertRef ref, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  20710. {
  20711. auto& devices = engine->getDeviceManager();
  20712. auto setup = devices.getAudioDeviceSetup();
  20713. const auto before = setup.bufferSize;
  20714. setup.bufferSize = before == 512 ? 256 : 512;
  20715. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  20716. step ("reping_device_error=" + error);
  20717. engine->takeHardwareInsertNotice(); // (whatever was pending before the change)
  20718. juce::Timer::callAfterDelay (1500, [this, ref, step, finish, before] {
  20719. if (engine == nullptr)
  20720. return;
  20721. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  20722. const auto block = device != nullptr ? device->getCurrentBufferSizeSamples() : 0;
  20723. const auto notice = engine->takeHardwareInsertNotice();
  20724. step ("reping_buffer=" + juce::String (before) + "->" + juce::String (block) + " notice=" + juce::String ((int) notice.size())
  20725. + " stale=" + juce::String ((int) engine->staleHardwareInserts().size()));
  20726. if (notice.size() != 1 || ! (notice[0] == ref))
  20727. {
  20728. step ("result_reping=FAILED (no notice)");
  20729. finish (1);
  20730. return;
  20731. }
  20732. engine->pingHardwareInserts (notice); // ("Ping now")
  20733. juce::Timer::callAfterDelay (3500, [this, ref, step, finish, block] {
  20734. if (engine == nullptr)
  20735. return;
  20736. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  20737. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  20738. const auto stale = (int) engine->staleHardwareInserts().size();
  20739. step ("reping_round_trip=" + juce::String (samples) + " pdc_total=" + juce::String (engine->getLatencySamples()) + " stale=" + juce::String (stale));
  20740. const auto ok = stale == 0 && samples > 0 && engine->getLatencySamples() == samples;
  20741. step (juce::String ("result_reping=") + (ok ? "OK" : "FAILED") + " (device block " + juce::String (block) + ")");
  20742. finish (ok ? 0 : 1);
  20743. });
  20744. });
  20745. }
  20746. void runBounceCheck (const juce::File& bounceFile, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  20747. {
  20748. // the Export window as the user sees it with the real-time option ticked (next to the report)
  20749. lynx::showExportDialog (*engine, bounceFile.getParentDirectory(), "bounce", 0);
  20750. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  20751. if (auto* w = juce::TopLevelWindow::getTopLevelWindow (k))
  20752. {
  20753. std::function<juce::ToggleButton* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ToggleButton* {
  20754. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Render through the hardware in real time"))
  20755. return t;
  20756. for (auto* child : c.getChildren())
  20757. if (auto* t = find (*child))
  20758. return t;
  20759. return nullptr;
  20760. };
  20761. if (auto* toggle = find (*w))
  20762. {
  20763. step (juce::String ("export_option_visible=") + (toggle->isVisible() ? "yes" : "NO"));
  20764. toggle->setToggleState (true, juce::sendNotificationSync); // (calls its onClick, as a click)
  20765. auto* c = dynamic_cast<juce::DocumentWindow*> (w) != nullptr ? static_cast<juce::DocumentWindow*> (w)->getContentComponent() : w;
  20766. if (c != nullptr)
  20767. {
  20768. const auto file = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-export.png");
  20769. file.deleteFile();
  20770. juce::FileOutputStream out (file);
  20771. juce::PNGImageFormat png;
  20772. if (out.openedOk())
  20773. png.writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  20774. }
  20775. delete w;
  20776. break;
  20777. }
  20778. }
  20779. lynx::exportopts::Options o;
  20780. o.format = lynx::exportopts::Format::wav;
  20781. o.wavBits = 32;
  20782. o.dither = lynx::exportopts::DitherMode::none;
  20783. o.tail = lynx::exportopts::TailMode::cut;
  20784. o.range = lynx::exportopts::Range::song;
  20785. o.trimPdc = true;
  20786. o.hqAllPlugins = false;
  20787. o.pluginWarmUp = false;
  20788. const auto offlineFile = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-offline.wav");
  20789. auto realtimeJob = std::make_shared<lynx::ExportJob> (*engine, o, bounceFile);
  20790. o.sampleRate = engine->getTransport().sampleRate.load();
  20791. auto offlineJob = std::make_shared<lynx::ExportJob> (engine->getSong(), o, offlineFile);
  20792. struct Shared
  20793. {
  20794. std::atomic<int> done { 0 };
  20795. bool okRealtime = false, okOffline = false;
  20796. juce::String errorRealtime, errorOffline;
  20797. double lastProgress = 0.0;
  20798. double started = juce::Time::getMillisecondCounterHiRes();
  20799. };
  20800. auto shared = std::make_shared<Shared>();
  20801. // (the jobs stay owned by the message thread's poll below: they are destroyed there)
  20802. juce::Thread::launch ([rt = realtimeJob.get(), off = offlineJob.get(), shared] {
  20803. shared->okRealtime = rt->run ([shared] (double p) { shared->lastProgress = p; return true; }, shared->errorRealtime);
  20804. shared->okOffline = off->run ({}, shared->errorOffline);
  20805. shared->done.store (1);
  20806. });
  20807. auto poll = std::make_shared<std::function<void()>>();
  20808. *poll = [this, poll, shared, realtimeJob, offlineJob, bounceFile, offlineFile, step, finish] {
  20809. if (shared->done.load() == 0)
  20810. {
  20811. juce::Timer::callAfterDelay (100, *poll);
  20812. return;
  20813. }
  20814. const auto seconds = (juce::Time::getMillisecondCounterHiRes() - shared->started) / 1000.0;
  20815. step ("bounce_realtime=" + juce::String (shared->okRealtime ? "ok" : "FAILED " + shared->errorRealtime) + " offline="
  20816. + juce::String (shared->okOffline ? "ok" : "FAILED " + shared->errorOffline) + " took=" + juce::String (seconds, 1) + " s (music "
  20817. + juce::String (realtimeJob->getMusicSeconds(), 1) + " s)" + (realtimeJob->getNotice().isNotEmpty() ? " notice=" + realtimeJob->getNotice() : juce::String()));
  20818. juce::AudioFormatManager formats;
  20819. formats.registerBasicFormats();
  20820. std::unique_ptr<juce::AudioFormatReader> a (formats.createReaderFor (bounceFile)), b (formats.createReaderFor (offlineFile));
  20821. if (! shared->okRealtime || ! shared->okOffline || a == nullptr || b == nullptr)
  20822. {
  20823. step ("result=FAILED bounce");
  20824. finish (1);
  20825. return;
  20826. }
  20827. const auto frames = (int) std::min (a->lengthInSamples, b->lengthInSamples);
  20828. juce::AudioBuffer<float> x (2, frames), y (2, frames);
  20829. a->read (&x, 0, frames, 0, true, true);
  20830. b->read (&y, 0, frames, 0, true, true);
  20831. double residual = 0.0, energy = 0.0, wetDry = 0.0;
  20832. for (int ch = 0; ch < 2; ++ch)
  20833. for (int i = 0; i < frames; ++i)
  20834. {
  20835. const double d = x.getSample (ch, i) - y.getSample (ch, i);
  20836. residual += d * d;
  20837. energy += (double) y.getSample (ch, i) * y.getSample (ch, i);
  20838. }
  20839. for (int i = 0; i < frames; ++i) // the wet side against the dry side of the real-time file
  20840. wetDry += std::pow ((double) x.getSample (0, i) - x.getSample (1, i), 2.0);
  20841. const auto db = [energy] (double r) { return energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, r / energy)) : 0.0; };
  20842. step ("bounce_frames=" + juce::String ((juce::int64) a->lengthInSamples) + " offline_frames=" + juce::String ((juce::int64) b->lengthInSamples)
  20843. + " rate=" + juce::String (a->sampleRate) + " bounce_vs_offline_db=" + juce::String (db (residual), 1)
  20844. + " wet_vs_dry_db=" + juce::String (db (2.0 * wetDry), 1) + " peak=" + juce::String (realtimeJob->getPeak(), 3));
  20845. const auto ok = std::abs (a->lengthInSamples - b->lengthInSamples) <= 1 && db (residual) < -100.0 && realtimeJob->getPeak() > 0.1f;
  20846. step (juce::String ("result_bounce=") + (ok ? "OK" : "FAILED"));
  20847. finish (ok ? 0 : 1);
  20848. };
  20849. juce::Timer::callAfterDelay (100, *poll);
  20850. }
  20851. // --rtstress --record: stops recording (the take becomes a clip of the song, as in the app), moves the take's WAV to
  20852. // `target` and describes it: length against the time played, channels, peak, the latencies the driver reported.
  20853. juce::String finishStressTake (const juce::File& target, double seconds)
  20854. {
  20855. juce::String text;
  20856. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  20857. text << " recording: input " << (device != nullptr ? device->getActiveInputChannels().countNumberOfSetBits() : 0) << " channel(s)";
  20858. if (device != nullptr)
  20859. text << ", input latency " << device->getInputLatencyInSamples() << " + output latency " << device->getOutputLatencyInSamples() << " samples";
  20860. engine->setRecording (false); // closes the take: a clip of the song
  20861. juce::File take;
  20862. for (const auto& c : engine->getSong().channels)
  20863. if (c.instrument == lynx::InstrumentKind::audioClip)
  20864. take = juce::File (juce::String::fromUTF8 (c.samplePath.c_str()));
  20865. if (! take.existsAsFile())
  20866. return text + "\n recording: no take (" + engine->getLastRecordingError() + ")\n";
  20867. target.deleteFile();
  20868. if (! take.moveFileTo (target))
  20869. take.copyFileTo (target);
  20870. juce::AudioFormatManager formats;
  20871. formats.registerBasicFormats();
  20872. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (target)); reader != nullptr)
  20873. {
  20874. juce::AudioBuffer<float> audio ((int) reader->numChannels, (int) reader->lengthInSamples);
  20875. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, true);
  20876. const auto peak = audio.getMagnitude (0, audio.getNumSamples());
  20877. const auto length = (double) reader->lengthInSamples / reader->sampleRate;
  20878. text << "\n recording: take " << juce::String (length, 3) << " s of " << juce::String (seconds, 0) << " s played, "
  20879. << (int) reader->numChannels << " ch @ " << (int) reader->sampleRate << " Hz, peak "
  20880. << juce::String (juce::Decibels::gainToDecibels (peak, -150.0f), 1) << " dBFS -> " << target.getFullPathName() << "\n";
  20881. }
  20882. else
  20883. text << "\n recording: take unreadable (" << target.getFullPathName() << ")\n";
  20884. return text;
  20885. }
  20886. // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
  20887. // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
  20888. void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
  20889. {
  20890. lynx::AudioEngine offline (false);
  20891. const juce::File input (inputPath);
  20892. juce::String error, report;
  20893. bool ok = false;
  20894. if (input.hasFileExtension ("flp;als;flm;songtmpl;band;blx;mod;xm;s3m;it;dawproject")) // (round 190ic: a GarageBand .band folder too; 190nw: a module; 190ri: a DAWproject)
  20895. ok = offline.importFlpFile (input, error);
  20896. else if (auto song = lynx::ProjectFile::load (input, error))
  20897. {
  20898. offline.setSong (std::move (*song));
  20899. ok = true;
  20900. }
  20901. int samplers = 0, samplersLoaded = 0;
  20902. if (ok)
  20903. {
  20904. for (const auto& c : offline.getSong().channels)
  20905. if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
  20906. {
  20907. ++samplers;
  20908. samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
  20909. }
  20910. const juce::File output (outputPath);
  20911. output.deleteFile();
  20912. juce::WavAudioFormat wav;
  20913. std::unique_ptr<juce::AudioFormatWriter> writer (
  20914. wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
  20915. if (writer == nullptr)
  20916. {
  20917. ok = false;
  20918. error = lynx::utf8 ("could not create ") + outputPath;
  20919. }
  20920. else
  20921. {
  20922. const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
  20923. report << "peak=" << peak << "\n";
  20924. ok = peak > 0.001f;
  20925. }
  20926. }
  20927. report << "samples=" << samplersLoaded << "/" << samplers << "\n"
  20928. << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  20929. juce::File (outputPath + ".txt").replaceWithText (report);
  20930. setApplicationReturnValue (ok ? 0 : 1);
  20931. quit();
  20932. }
  20933. // LYNX.exe --export-flp project.(lynx|flp|als) output.(flp|zip) [--substitute] (round 171e): File › Export › FL Studio
  20934. // project without the window (option A unless --substitute; the renders next to a .flp in "<name> audio"); the
  20935. // report goes to output.txt
  20936. void runAlsExport (const juce::String& inputPath, const juce::String& folderPath, bool live11, bool reference)
  20937. {
  20938. juce::String error;
  20939. juce::StringArray notes;
  20940. juce::File als;
  20941. {
  20942. lynx::AudioEngine loader (false);
  20943. const juce::File input (inputPath);
  20944. bool ok = false;
  20945. // --scan: the targeted plugin scan an open runs first (child processes), so the set's plugins load
  20946. if (juce::JUCEApplication::getCommandLineParameterArray().contains ("--scan") && input.hasFileExtension ("flp;als;flm;songtmpl"))
  20947. {
  20948. juce::MemoryBlock data;
  20949. if (input.loadFileAsData (data))
  20950. {
  20951. const std::vector<std::uint8_t> bytes (static_cast<const std::uint8_t*> (data.getData()),
  20952. static_cast<const std::uint8_t*> (data.getData()) + data.getSize());
  20953. try
  20954. {
  20955. const auto uses = input.hasFileExtension ("als") ? lynx::alsForeignPlugins (bytes)
  20956. : lynx::flpForeignPlugins (flp::parseProject ({ bytes.data(), bytes.size() }));
  20957. loader.getPluginHost().scanFiles (loader.getPluginHost().filesToScanFor (uses), {});
  20958. }
  20959. catch (const std::exception&)
  20960. {
  20961. }
  20962. }
  20963. }
  20964. if (input.hasFileExtension ("flp;als;flm;songtmpl;band;blx;mod;xm;s3m;it"))
  20965. ok = loader.importFlpFile (input, error);
  20966. else if (auto song = lynx::ProjectFile::load (input, error))
  20967. {
  20968. loader.setSong (std::move (*song));
  20969. ok = true;
  20970. }
  20971. if (ok)
  20972. {
  20973. loader.capturePluginStates();
  20974. const juce::File folder (folderPath);
  20975. folder.createDirectory();
  20976. als = lynx::writeAlsProject (loader.getSong(), &loader.getPluginHost(), live11 ? lynx::AlsVersion::live11 : lynx::AlsVersion::live12, ! reference, folder,
  20977. input.getFileNameWithoutExtension(), notes, error);
  20978. }
  20979. }
  20980. juce::String report;
  20981. report << (als != juce::File() ? "ok " + als.getFullPathName() : "error=" + error) << "\n" << notes.joinIntoString ("\n") << "\n";
  20982. juce::File (folderPath).getChildFile ("export-als.txt").replaceWithText (report);
  20983. setApplicationReturnValue (als != juce::File() ? 0 : 1);
  20984. quit();
  20985. }
  20986. // --versionsshot <prefix> (round 190ap): everything the round adds, offscreen (no window on the desktop):
  20987. // -versions.png / -versions-unsaved.png the Versions panel (a project with versions, backups and labels; a new one)
  20988. // -menu-file.png / -menu-file-pluginsoff.png the File menu, and as it is while the plugins are off
  20989. // -pluginsoff-window.png / -pluginsoff-mixer.png a project opened without its third-party plugins (the tags)
  20990. // -pluginsoff-panel.png / -pluginsoff-panel-one.png the list, all off, then after "Switch on" for one
  20991. // -export-default.png / -export.png the Export window as it opens, and with the additions in use
  20992. bool runLinkShot (const juce::String& prefix)
  20993. {
  20994. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20995. juce::StringArray report;
  20996. bool allOk = true;
  20997. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  20998. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  20999. allOk = allOk && ok;
  21000. };
  21001. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  21002. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  21003. };
  21004. using lynx::AutomationTarget;
  21005. using lynx::AutomationTargetKind;
  21006. using lynx::MidiLink;
  21007. lynx::AudioEngine engine (false);
  21008. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 },
  21009. insert { AutomationTargetKind::mixerVolume, 1 };
  21010. // ---- the window as it opens on a control with no link (FL's defaults)
  21011. {
  21012. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  21013. shoot (*panel, "remote-default");
  21014. check ("default_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  21015. // Auto detect: the controller that sends next fills the fields
  21016. engine.injectControllerForTest (74, 2, 100, 5);
  21017. lynx::remoteControlPanelPoll (*panel);
  21018. check ("auto_detect", lynx::remoteControlPanelState (*panel).startsWith ("5|3|74|"), lynx::remoteControlPanelState (*panel));
  21019. // a formula preset, smoothing; Accept writes the link
  21020. lynx::remoteControlPanelSetController (*panel, -1, 1, 7);
  21021. lynx::remoteControlPanelSetFormula (*panel, "Tension(Input,10)");
  21022. lynx::remoteControlPanelSetSmoothing (*panel, true, 469);
  21023. shoot (*panel, "remote-formula-smoothing");
  21024. lynx::remoteControlPanelPress (*panel, 2);
  21025. const auto& links = engine.getSong().midiLinks;
  21026. check ("accept_writes_link", links.size() == 1 && links[0].cc == 7 && links[0].channel == 0 && links[0].port == -1
  21027. && links[0].formula == "Tension(Input,10)" && links[0].smooth && links[0].target == volume);
  21028. }
  21029. // ---- a broken formula: the message, the red text
  21030. {
  21031. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  21032. lynx::remoteControlPanelSetFormula (*panel, "Min(Input*2,");
  21033. shoot (*panel, "remote-formula-error");
  21034. check ("formula_error_shown", ! lynx::remoteControlPanelState (*panel).contains ("Compiled ok."), lynx::remoteControlPanelState (*panel));
  21035. }
  21036. // ---- the engine: formula, port, conflicts, omni
  21037. {
  21038. engine.editSong ([&] (lynx::Song& s) {
  21039. s.midiLinks.clear();
  21040. MidiLink inverted { 20, 0, volume };
  21041. inverted.formula = "1-Input";
  21042. MidiLink ported { 21, 0, pan };
  21043. ported.port = 3;
  21044. s.midiLinks = { inverted, ported };
  21045. });
  21046. engine.injectControllerForTest (20, 0, 127);
  21047. check ("formula_inverts", std::abs (engine.currentTargetValue (volume)) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  21048. engine.injectControllerForTest (20, 0, 0);
  21049. check ("formula_inverts_back", std::abs (engine.currentTargetValue (volume) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  21050. const auto panBefore = engine.currentTargetValue (pan);
  21051. engine.injectControllerForTest (21, 0, 127); // no port: not this link's device
  21052. check ("port_must_match", std::abs (engine.currentTargetValue (pan) - panBefore) < 0.001f);
  21053. engine.injectControllerForTest (21, 0, 127, 3);
  21054. check ("port_matches", std::abs (engine.currentTargetValue (pan) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (pan)));
  21055. // the window on a control whose controller another control uses: Remove conflicts in red; Accept removes it
  21056. auto panel = lynx::makeRemoteControlPanel (engine, { insert }, false);
  21057. lynx::remoteControlPanelSetController (*panel, -1, 1, 20);
  21058. shoot (*panel, "remote-conflict");
  21059. check ("conflict_counted", lynx::remoteControlPanelState (*panel).contains ("|1|"), lynx::remoteControlPanelState (*panel));
  21060. lynx::remoteControlPanelPress (*panel, 2);
  21061. const auto& links = engine.getSong().midiLinks;
  21062. check ("conflict_removed", links.size() == 2
  21063. && std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; })
  21064. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == insert && l.cc == 20; }));
  21065. engine.undo();
  21066. check ("accept_is_one_undo_step", engine.getSong().midiLinks.size() == 2 && engine.getSong().midiLinks[0].target == volume);
  21067. }
  21068. // ---- an existing link opened again: "Link 1" / "New link"
  21069. {
  21070. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  21071. shoot (*panel, "remote-existing-link");
  21072. check ("existing_link_loaded", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|20|1-Input|"), lynx::remoteControlPanelState (*panel));
  21073. // Reset, then Accept: a link without a controller is removed
  21074. lynx::remoteControlPanelPress (*panel, 0);
  21075. check ("reset_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  21076. lynx::remoteControlPanelPress (*panel, 2);
  21077. const auto& links = engine.getSong().midiLinks;
  21078. check ("reset_accept_unlinks", std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; }));
  21079. }
  21080. // ---- several controls ("Link to controllers..."): Accept and Skip step through them
  21081. {
  21082. auto panel = lynx::makeRemoteControlPanel (engine, { volume, pan, insert }, false, [] {});
  21083. shoot (*panel, "remote-multilink");
  21084. const auto parameter = [&panel] { return juce::StringArray::fromTokens (lynx::remoteControlPanelState (*panel), "|", "")[6]; };
  21085. const auto first = parameter();
  21086. check ("multilink_caption_and_skip", first.startsWith ("1/3") && first.contains (lynx::tr ("Channel volume"))
  21087. && lynx::remoteControlPanelState (*panel).contains ("S|omni"),
  21088. lynx::remoteControlPanelState (*panel));
  21089. lynx::remoteControlPanelSetController (*panel, -1, 1, 30);
  21090. lynx::remoteControlPanelPress (*panel, 2); // Accept: volume linked, on to pan
  21091. const auto second = parameter();
  21092. lynx::remoteControlPanelPress (*panel, 1); // Skip: pan untouched, on to the insert
  21093. const auto third = parameter();
  21094. const auto beforeLast = lynx::remoteControlPanelFinished (*panel);
  21095. lynx::remoteControlPanelPress (*panel, 1); // Skip on the last one: done
  21096. const auto closed = ! beforeLast && lynx::remoteControlPanelFinished (*panel);
  21097. const auto& links = engine.getSong().midiLinks;
  21098. check ("multilink_steps", first != second && second != third && closed
  21099. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume && l.cc == 30; }),
  21100. first + " > " + second + " > " + third);
  21101. }
  21102. // ---- Global link settings
  21103. {
  21104. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  21105. shoot (*panel, "global-default");
  21106. lynx::remoteControlPanelSetController (*panel, 2, 1, 11);
  21107. lynx::remoteControlPanelSetFormula (*panel, "Input*0.5");
  21108. lynx::remoteControlPanelPress (*panel, 2);
  21109. const auto global = engine.globalLinkOf (volume);
  21110. check ("global_link_written", global && global->cc == 11 && global->port == 2 && global->formula == "Input*0.5");
  21111. const auto text = engine.getMidiPrefs().toText();
  21112. const auto back = lynx::prefs::MidiPrefs::fromText (text);
  21113. check ("global_link_settings_round_trip", back.globalLinks == engine.getMidiPrefs().globalLinks && text.find ("linkset=2|0|469|Input*0.5") != std::string::npos);
  21114. auto again = lynx::makeRemoteControlPanel (engine, { volume }, true);
  21115. shoot (*again, "global-existing-link");
  21116. engine.setGlobalLink (volume, std::nullopt);
  21117. check ("global_link_removed", ! engine.globalLinkOf (volume));
  21118. }
  21119. // ---- the project file: links with settings come back; a project of an older version loads the same
  21120. {
  21121. lynx::Song song = engine.getSong();
  21122. MidiLink plain { 7, -1, volume };
  21123. MidiLink rich { 74, 2, pan };
  21124. rich.port = 4;
  21125. rich.formula = "Min(Input*1.1,0.5)+Max(Input*1.1,0.6)-0.6";
  21126. rich.smooth = true;
  21127. rich.smoothing = -300;
  21128. rich.omni = true;
  21129. song.midiLinks = { plain, rich };
  21130. juce::String error;
  21131. const auto json = lynx::ProjectFile::toJson (song);
  21132. const auto back = lynx::ProjectFile::fromJson (json, error);
  21133. check ("project_round_trip", back && back->midiLinks == song.midiLinks, error);
  21134. // without settings the file holds only the list older versions wrote
  21135. song.midiLinks = { plain };
  21136. const auto plainJson = lynx::ProjectFile::toJson (song);
  21137. check ("plain_links_write_the_old_form", ! plainJson.contains ("midiLinkSettings") && plainJson.contains ("midiLinks"));
  21138. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  21139. check ("old_project_loads_the_same", plainBack && plainBack->midiLinks.size() == 1 && plainBack->midiLinks[0] == plain
  21140. && ! plainBack->midiLinks[0].hasSettings());
  21141. // what an older version does with a new file: it reads "midiLinks" alone, so the links stay (plain)
  21142. auto parsed = juce::JSON::parse (json);
  21143. if (auto* o = parsed.getDynamicObject())
  21144. o->removeProperty ("midiLinkSettings");
  21145. const auto stripped = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  21146. check ("older_version_keeps_the_links", stripped && stripped->midiLinks.size() == 2 && stripped->midiLinks[1].cc == 74
  21147. && ! stripped->midiLinks[1].hasSettings());
  21148. }
  21149. // ---- round 190cs: FL's live answers (live check 190cq) and the note / button link modes
  21150. {
  21151. const auto state = [] (juce::Component& p) { return lynx::remoteControlPanelState (p); };
  21152. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  21153. // the layout FL shows: no assignment list without a link, no Skip outside Multilink, no internal
  21154. // controller group without a controller in the project; the parameter caption in FL's words
  21155. auto fresh = lynx::makeRemoteControlPanel (engine, { volume }, false);
  21156. shoot (*fresh, "cs-remote-default");
  21157. check ("cs_layout_without_link", state (*fresh).contains ("|" + lynx::tr ("Channel volume") + "|") && state (*fresh).contains ("|shown=POC|"), state (*fresh));
  21158. // Omni: enabled on a mixer track's volume (FL: "Insert 1 - Volume"), greyed on the tempo
  21159. auto onInsert = lynx::makeRemoteControlPanel (engine, { insert }, false);
  21160. auto onTempo = lynx::makeRemoteControlPanel (engine, { AutomationTarget { AutomationTargetKind::tempo, 0 } }, false);
  21161. shoot (*onInsert, "cs-remote-omni-insert");
  21162. check ("cs_omni_mixer_track", state (*onInsert).contains ("|omni=on|") && state (*onTempo).contains ("|omni=off|"),
  21163. state (*onInsert) + " / " + state (*onTempo));
  21164. // the formula compiles on Enter only; FL's messages and colours
  21165. lynx::remoteControlPanelSetFormula (*fresh, "1-Input^2", false);
  21166. check ("cs_no_compile_while_typing", state (*fresh).contains ("|" + lynx::tr ("(default 1:1 mapping)") + "|"), state (*fresh));
  21167. lynx::remoteControlPanelSetFormula (*fresh, "-Input^2");
  21168. shoot (*fresh, "cs-remote-compiled");
  21169. check ("cs_compiled_on_enter", state (*fresh).contains ("|" + lynx::tr ("Compiled ok.") + "|"), state (*fresh));
  21170. const std::pair<const char*, const char*> errors[] { { "Input*", "Syntax error: function or operand" },
  21171. { "foo(Input)", "Invalid identifier: foo" },
  21172. { "Sin(Input", "Unequal brackets" },
  21173. { "Input 2", "input two space limited" } };
  21174. for (const auto& [text, expected] : errors)
  21175. {
  21176. lynx::remoteControlPanelSetFormula (*fresh, text);
  21177. check ("cs_fl_error_text", state (*fresh).contains (expected), state (*fresh));
  21178. }
  21179. lynx::remoteControlPanelSetFormula (*fresh, "foo(Input)");
  21180. shoot (*fresh, "cs-remote-error");
  21181. // Accept with that formula: the link is made, the formula is not kept (FL reopens it as "Input")
  21182. lynx::remoteControlPanelSetController (*fresh, -1, 1, 7);
  21183. lynx::remoteControlPanelPress (*fresh, 2);
  21184. check ("cs_bad_formula_accept_is_input", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == 7
  21185. && engine.getSong().midiLinks[0].formula.empty());
  21186. auto reopened = lynx::makeRemoteControlPanel (engine, { volume }, false);
  21187. shoot (*reopened, "cs-remote-reopened");
  21188. check ("cs_reopened_shows_input_and_link_list", state (*reopened).startsWith ("-1|1|7|Input|" + lynx::tr ("(default 1:1 mapping)") + "|")
  21189. && state (*reopened).contains ("|shown=PAOC|"),
  21190. state (*reopened));
  21191. // the internal controller group appears with a controller in the project, with "Record automation"
  21192. engine.editSong ([] (lynx::Song& s) {
  21193. lynx::EffectSlot peak;
  21194. peak.kind = lynx::EffectKind::peakController;
  21195. s.mixer[0].effects.push_back (peak);
  21196. });
  21197. auto withController = lynx::makeRemoteControlPanel (engine, { volume }, false);
  21198. lynx::remoteControlPanelSetInternal (*withController, 1, true);
  21199. shoot (*withController, "cs-remote-internal");
  21200. check ("cs_internal_group_shown", state (*withController).contains ("|shown=PAIOC|") && state (*withController).startsWith ("-1|1|-1|"),
  21201. state (*withController));
  21202. lynx::remoteControlPanelPress (*withController, 2);
  21203. const auto& autos = engine.getSong().automations;
  21204. check ("cs_record_automation_kept", std::any_of (autos.begin(), autos.end(), [&] (const lynx::Automation& a) {
  21205. return a.isLive() && a.target == volume && a.recordLive;
  21206. }));
  21207. engine.editSong ([] (lynx::Song& s) {
  21208. s.mixer[0].effects.pop_back();
  21209. s.automations.clear();
  21210. s.midiLinks.clear();
  21211. });
  21212. // the global window: no parameter list, Omni, Remove conflicts or Skip; Mode is there
  21213. auto globalPanel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  21214. shoot (*globalPanel, "cs-global-default");
  21215. check ("cs_global_layout", state (*globalPanel).contains ("|shown=|"), state (*globalPanel));
  21216. // a key link in each Mode: note 60 = FL's controller number 256 + 60
  21217. const auto key = lynx::linkNoteBase + 60;
  21218. auto modePanel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  21219. lynx::remoteControlPanelSetController (*modePanel, -1, 1, key);
  21220. lynx::remoteControlPanelSetMode (*modePanel, 2);
  21221. shoot (*modePanel, "cs-remote-note-latch");
  21222. lynx::remoteControlPanelPress (*modePanel, 2);
  21223. check ("cs_note_link_written", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == key
  21224. && engine.getSong().midiLinks[0].mode == 2);
  21225. const auto play = [&engine, key, volume] (int velocity) {
  21226. engine.injectControllerForTest (key, 0, velocity);
  21227. return engine.currentTargetValue (volume);
  21228. };
  21229. const auto setMode = [&engine] (int mode) {
  21230. engine.editSong ([mode] (lynx::Song& s) { s.midiLinks[0].mode = mode; });
  21231. engine.editSong ([] (lynx::Song& s) { s.setTargetValue ({ AutomationTargetKind::channelVolume, 0 }, 0.25f); });
  21232. };
  21233. setMode (2); // Latch: press switches, release does nothing
  21234. const auto l1 = play (100), l1off = play (0), l2 = play (90), l2off = play (0);
  21235. check ("cs_mode_latch", std::abs (l1 - 1.0f) < 1e-4f && std::abs (l1off - 1.0f) < 1e-4f && l2 < 1e-4f && l2off < 1e-4f,
  21236. juce::String (l1) + " " + juce::String (l1off) + " " + juce::String (l2) + " " + juce::String (l2off));
  21237. setMode (1); // Hold: the velocity while held, back to 0 on release
  21238. const auto h1 = play (100), h1off = play (0);
  21239. check ("cs_mode_hold", std::abs (h1 - 100.0f / 127.0f) < 1e-4f && h1off < 1e-4f, juce::String (h1) + " " + juce::String (h1off));
  21240. setMode (0); // Default: as Hold for a key
  21241. const auto d1 = play (64), d1off = play (0);
  21242. check ("cs_mode_default", std::abs (d1 - 64.0f / 127.0f) < 1e-4f && d1off < 1e-4f, juce::String (d1) + " " + juce::String (d1off));
  21243. setMode (3); // Inc: each press adds 1/128
  21244. const auto i1 = play (100), i1off = play (0), i2 = play (20);
  21245. check ("cs_mode_inc", std::abs (i1 - (0.25f + 1.0f / 128.0f)) < 1e-4f && std::abs (i1off - i1) < 1e-6f
  21246. && std::abs (i2 - (0.25f + 2.0f / 128.0f)) < 1e-4f,
  21247. juce::String (i1) + " " + juce::String (i2));
  21248. setMode (4); // Stay: the velocity, kept after the release
  21249. const auto s1 = play (100), s1off = play (0);
  21250. 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));
  21251. // the project file keeps the key link and its mode; an older reader skips it
  21252. lynx::Song song = engine.getSong();
  21253. song.midiLinks[0].mode = 2;
  21254. MidiLink cc7 { 7, 0, pan };
  21255. cc7.mode = 4;
  21256. song.midiLinks.insert (song.midiLinks.begin(), cc7);
  21257. juce::String error;
  21258. const auto json = lynx::ProjectFile::toJson (song);
  21259. const auto back = lynx::ProjectFile::fromJson (json, error);
  21260. check ("cs_note_link_round_trip", back && back->midiLinks == song.midiLinks && json.contains ("midiNoteLinks"), error);
  21261. auto parsed = juce::JSON::parse (json);
  21262. if (auto* o = parsed.getDynamicObject())
  21263. {
  21264. o->removeProperty ("midiNoteLinks");
  21265. o->removeProperty ("midiLinkSettings");
  21266. }
  21267. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  21268. check ("cs_older_reader_keeps_cc_links_only", older && older->midiLinks.size() == 1 && older->midiLinks[0].cc == 7);
  21269. // "Record automation" of an internal-controller link, saved only when on
  21270. lynx::Automation live;
  21271. live.target = volume;
  21272. live.source.track = 0;
  21273. live.recordLive = true;
  21274. song.automations = { live };
  21275. const auto withLive = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  21276. live.recordLive = false;
  21277. song.automations = { live };
  21278. check ("cs_record_automation_round_trip", withLive && withLive->automations.size() == 1 && withLive->automations[0].recordLive
  21279. && ! lynx::ProjectFile::toJson (song).contains ("recordLive"));
  21280. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  21281. }
  21282. // ---- menus: the control menu, the formula presets, the controller list, the Multilink items
  21283. {
  21284. juce::PopupMenu control;
  21285. lynx::addAutomationItem (control, engine, volume, true);
  21286. engine.setMultilink (true);
  21287. engine.noteTweaked (volume);
  21288. engine.noteTweaked (pan);
  21289. juce::PopupMenu multilink;
  21290. lynx::addMultilinkControlsItems (multilink, engine);
  21291. check ("multilink_queue", engine.multilinkTargets().size() == 2);
  21292. engine.setMultilink (false);
  21293. saveMenus (juce::StringArray { "Control menu", "Formula presets", "Multilink" },
  21294. std::vector<juce::PopupMenu> { control, lynx::remoteControlFormulaMenu ([] (const juce::String&) {}), multilink },
  21295. prefix + "-menus.png");
  21296. saveMenus (juce::StringArray { "Ctrl menu" }, std::vector<juce::PopupMenu> { lynx::remoteControlControllerMenu ([] (int) {}) },
  21297. prefix + "-ctrl-menu.png");
  21298. // the Mode list as its box pops it up (round 190cs)
  21299. juce::PopupMenu modes;
  21300. for (const char* m : { "Default", "Hold", "Latch", "Inc", "Stay" })
  21301. modes.addItem (lynx::tr (m), true, juce::String (m) == "Default", [] {});
  21302. saveMenus (juce::StringArray { "Mode" }, std::vector<juce::PopupMenu> { modes }, prefix + "-mode-menu.png");
  21303. }
  21304. // ---- Settings > MIDI: the input's Port box, the link list with a link's settings
  21305. {
  21306. engine.editSong ([&] (lynx::Song& s) {
  21307. MidiLink l { 74, 2, pan };
  21308. l.port = 4;
  21309. l.formula = "1-Input";
  21310. l.smooth = true;
  21311. s.midiLinks = { MidiLink { 7, 0, volume }, l };
  21312. });
  21313. auto page = lynx::makeMidiPage (engine, {}, false);
  21314. page->setSize (760, 900);
  21315. shoot (*page, "settings-midi");
  21316. }
  21317. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  21318. return allOk;
  21319. }
  21320. // A stand-in hosted plugin for the shot route: three parameters, its state = their values
  21321. struct FlCtlShotPlugin final : juce::AudioPluginInstance
  21322. {
  21323. FlCtlShotPlugin()
  21324. {
  21325. for (const char* n : { "Cutoff", "Resonance", "Drive" })
  21326. addHostedParameter (std::make_unique<juce::AudioParameterFloat> (juce::ParameterID (n, 1), n, 0.0f, 1.0f, 0.5f));
  21327. }
  21328. const juce::String getName() const override { return "Shot plugin"; }
  21329. void prepareToPlay (double, int) override {}
  21330. void releaseResources() override {}
  21331. void processBlock (juce::AudioBuffer<float>&, juce::MidiBuffer&) override {}
  21332. double getTailLengthSeconds() const override { return 0.0; }
  21333. bool acceptsMidi() const override { return false; }
  21334. bool producesMidi() const override { return false; }
  21335. juce::AudioProcessorEditor* createEditor() override { return nullptr; }
  21336. bool hasEditor() const override { return false; }
  21337. int getNumPrograms() override { return 1; }
  21338. int getCurrentProgram() override { return 0; }
  21339. void setCurrentProgram (int) override {}
  21340. const juce::String getProgramName (int) override { return {}; }
  21341. void changeProgramName (int, const juce::String&) override {}
  21342. void getStateInformation (juce::MemoryBlock& b) override
  21343. {
  21344. for (auto* p : getParameters())
  21345. {
  21346. const float v = static_cast<juce::AudioParameterFloat*> (p)->get();
  21347. b.append (&v, sizeof (float));
  21348. }
  21349. }
  21350. void setStateInformation (const void* data, int size) override
  21351. {
  21352. const auto& list = getParameters();
  21353. for (int i = 0; i < list.size() && (i + 1) * (int) sizeof (float) <= size; ++i)
  21354. *static_cast<juce::AudioParameterFloat*> (list[i]) = static_cast<const float*> (data)[i];
  21355. }
  21356. void fillInPluginDescription (juce::PluginDescription& d) const override
  21357. {
  21358. d.name = getName();
  21359. d.pluginFormatName = "Shot";
  21360. d.fileOrIdentifier = "shot";
  21361. }
  21362. };
  21363. static juce::File writeShotSample (const juce::File& file, double hz)
  21364. {
  21365. juce::AudioBuffer<float> buffer (1, 22050);
  21366. for (int i = 0; i < buffer.getNumSamples(); ++i)
  21367. buffer.setSample (0, i, (float) (std::sin (juce::MathConstants<double>::twoPi * hz * i / 44100.0) * std::exp (-i / 6000.0)));
  21368. file.deleteFile();
  21369. juce::WavAudioFormat wav;
  21370. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  21371. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  21372. return file;
  21373. }
  21374. static bool clickMenuItem (const juce::PopupMenu& menu, const juce::String& text)
  21375. {
  21376. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  21377. if (it.getItem().text == text && it.getItem().isEnabled && it.getItem().action != nullptr)
  21378. {
  21379. it.getItem().action();
  21380. return true;
  21381. }
  21382. return false;
  21383. }
  21384. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen — the page as FL's shot (dock188a) shows it,
  21385. // the legacy effects, a small window, a zoomed waveform — and its laws turned as a user would; prefix-checks.txt
  21386. bool runSamplerPageShot (const juce::String& prefix)
  21387. {
  21388. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21389. juce::StringArray report;
  21390. bool allOk = true;
  21391. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  21392. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  21393. allOk = allOk && ok;
  21394. };
  21395. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  21396. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  21397. };
  21398. lynx::AudioEngine engine (false);
  21399. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("sampler-samples");
  21400. folder.createDirectory();
  21401. // an 808-like kick, 1 s (FL's shot: "Basic 808 Kick.wav")
  21402. const auto kick = folder.getChildFile ("Basic 808 Kick.wav");
  21403. {
  21404. juce::AudioBuffer<float> buffer (1, 44100);
  21405. double phase = 0.0;
  21406. for (int i = 0; i < buffer.getNumSamples(); ++i)
  21407. {
  21408. const auto t = i / 44100.0;
  21409. phase += juce::MathConstants<double>::twoPi * (48.0 + 90.0 * std::exp (-t * 30.0)) / 44100.0;
  21410. buffer.setSample (0, i, (float) (0.9 * std::sin (phase) * std::exp (-t * 3.2)));
  21411. }
  21412. kick.deleteFile();
  21413. juce::WavAudioFormat wav;
  21414. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (kick.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  21415. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  21416. }
  21417. engine.editSong ([&] (lynx::Song& s) {
  21418. if (s.channels.empty())
  21419. s.channels.resize (1);
  21420. lynx::audioclips::loadSampleInto (s.channels[0], kick.getFullPathName().toStdString(), "808 Kick");
  21421. // FL's shot: Resample and Load regions on, Use loop points on, declicking "Out only (no bleeding)"
  21422. s.channels[0].sampler.resampleOnLoad = true;
  21423. });
  21424. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  21425. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  21426. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  21427. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  21428. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  21429. shoot (*frame, "sampler-page");
  21430. report.add ("page size " + juce::String (frame->getWidth()) + "x" + juce::String (frame->getHeight()));
  21431. // ---- the laws, turned on the page
  21432. auto& f = *frame;
  21433. lynx::samplerPageTurn (f, "pingPong", 1.0);
  21434. check ("ping_pong", sampler().precompute.pingPong);
  21435. lynx::samplerPageTurn (f, "pingPong", 0.0);
  21436. lynx::samplerPageTurn (f, "loopStart", 5000.0);
  21437. check ("loop_start", sampler().loopStart == 5000 && sampler().loopEnd == 5001, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  21438. lynx::samplerPageTurn (f, "loopEnd", 15000.0);
  21439. check ("loop_end", sampler().loopStart == 5000 && sampler().loopEnd == 15000);
  21440. lynx::samplerPageTurn (f, "loopStart", 20000.0, true); // Shift: the loop moves
  21441. check ("loop_shift_moves", sampler().loopStart == 20000 && sampler().loopEnd == 30000, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  21442. check ("keep_on_disk_greyed_with_loop", lynx::samplerPageQuery (f, "keepOnDisk") == "0");
  21443. lynx::samplerPageTurn (f, "useLoops", 0.0);
  21444. check ("keep_on_disk_back", lynx::samplerPageQuery (f, "keepOnDisk") == "1" && ! sampler().useLoopPoints);
  21445. check ("not_cut_yet", ! lynx::channelCutsItself (engine.getSong().channels[0]));
  21446. lynx::samplerPageTurn (f, "useLoops", 1.0);
  21447. check ("use_loops_cuts_itself", sampler().useLoopPoints && lynx::channelCutsItself (engine.getSong().channels[0]));
  21448. engine.editSong ([] (lynx::Song& s) {
  21449. lynx::setChannelCutsItself (s.channels[0], 0, false);
  21450. s.channels[0].sampler.useLoopPoints = false;
  21451. });
  21452. lynx::samplerPageTurn (f, "crossfade", 300.0); // (Use loop points off: the crossfade switches it on)
  21453. check ("crossfade_switches_loops_on", sampler().precompute.crossfade == 300 && sampler().useLoopPoints);
  21454. lynx::samplerPageTurn (f, "crossfade", 0.0);
  21455. lynx::samplerPageTurn (f, "pitch", 300.0); // (Resample: FL switches to Auto)
  21456. check ("pitch_resample_to_auto", sampler().keepPitch && sampler().flStretchMode == 5 && sampler().flStretchPitch == 300
  21457. && lynx::samplerPageQuery (f, "mode") == lynx::tr ("General"),
  21458. lynx::samplerPageQuery (f, "mode") + " " + juce::String (sampler().pitch));
  21459. lynx::samplerPageTurn (f, "pitch", 0.0);
  21460. lynx::samplerPageTurn (f, "mode", 1.0); // Resample
  21461. check ("mode_resample", ! sampler().keepPitch && std::abs (sampler().pitch) < 1.0e-4f);
  21462. lynx::samplerPageTurn (f, "time", 4.0);
  21463. lynx::samplerPageTurn (f, "mul", 10000.0);
  21464. check ("time_mul", std::abs (sampler().stretchBeats - 8.0f) < 1.0e-3f && sampler().stretchMul == 10000, juce::String (sampler().stretchBeats));
  21465. lynx::samplerPageTurn (f, "mul", 0.0);
  21466. lynx::samplerPageTurn (f, "time", 0.0);
  21467. lynx::samplerPageTurn (f, "length", 0.5);
  21468. lynx::samplerPageTurn (f, "smpStart", 0.5);
  21469. check ("smp_start_keeps_length", std::abs (sampler().regionStart - 0.5f) < 1.0e-3f && std::abs (sampler().regionEnd - 0.75f) < 1.0e-3f,
  21470. juce::String (sampler().regionStart) + "-" + juce::String (sampler().regionEnd));
  21471. lynx::samplerPageTurn (f, "smpStart", 0.0);
  21472. lynx::samplerPageTurn (f, "length", 1.0);
  21473. lynx::samplerPageTurn (f, "declick", 4.0);
  21474. check ("declick_mode", sampler().declickMode == 4);
  21475. lynx::samplerPageTurn (f, "declick", 0.0);
  21476. // ---- the .lynx keeps what the page set
  21477. {
  21478. lynx::samplerPageTurn (f, "mul", -5000.0);
  21479. lynx::samplerPageTurn (f, "keepOnDisk", 1.0);
  21480. juce::String error;
  21481. const auto json = lynx::ProjectFile::toJson (engine.getSong(), false);
  21482. const auto back = lynx::ProjectFile::fromJson (json, error);
  21483. check ("lynx_round_trip", back.has_value() && back->channels[0].sampler == engine.getSong().channels[0].sampler, error);
  21484. lynx::samplerPageTurn (f, "mul", 0.0);
  21485. lynx::samplerPageTurn (f, "keepOnDisk", 0.0);
  21486. }
  21487. // ---- shots: FL's state again (loop points from the file: none), the legacy panel, a zoom, a small window
  21488. engine.editSong ([] (lynx::Song& s) {
  21489. auto& ch = s.channels[0];
  21490. ch.sampler.loopStart = ch.sampler.loopEnd = -1;
  21491. ch.sampler.useLoopPoints = true;
  21492. ch.sampler.precompute = {};
  21493. });
  21494. lynx::samplerPageTurn (f, "show", 0.0); // (no control: the page shows the channel again)
  21495. frame->createComponentSnapshot (frame->getLocalBounds());
  21496. shoot (*frame, "sampler-page-fl-state");
  21497. lynx::samplerPageTurn (f, "legacy", 1.0);
  21498. check ("legacy_panel", lynx::samplerPageQuery (f, "legacy") == "1");
  21499. shoot (*frame, "sampler-page-legacy");
  21500. lynx::samplerPageTurn (f, "legacy", 0.0);
  21501. lynx::samplerPageTurn (f, "zoom", 0.25);
  21502. check ("zoom_scroll", lynx::samplerPageQuery (f, "scroll") == "0.250", lynx::samplerPageQuery (f, "scroll"));
  21503. shoot (*frame, "sampler-page-zoom");
  21504. lynx::samplerPageTurn (f, "zoom", 1.0);
  21505. frame->setSize (520, 470);
  21506. frame->createComponentSnapshot (frame->getLocalBounds());
  21507. shoot (*frame, "sampler-page-small");
  21508. report.add (juce::String ("result=") + (allOk ? "OK" : "FAIL"));
  21509. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  21510. return allOk;
  21511. }
  21512. bool runFlCtlShot (const juce::String& prefix)
  21513. {
  21514. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21515. juce::StringArray report;
  21516. bool allOk = true;
  21517. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  21518. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  21519. allOk = allOk && ok;
  21520. };
  21521. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  21522. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  21523. };
  21524. using lynx::AutomationTarget;
  21525. using lynx::AutomationTargetKind;
  21526. lynx::AudioEngine engine (false);
  21527. engine.editSong ([] (lynx::Song& s) {
  21528. if (s.channels.size() < 3)
  21529. s.channels.resize (3);
  21530. if (s.patterns.empty())
  21531. s.patterns.resize (1);
  21532. s.currentPattern = 0;
  21533. });
  21534. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 };
  21535. // ---- FL's multilink menu: on with two queued controls, off with the last tweaked parameters
  21536. {
  21537. engine.setMultilink (true);
  21538. engine.noteTweaked (volume);
  21539. engine.noteTweaked (pan);
  21540. auto on = lynx::multilinkButtonMenu (engine);
  21541. juce::PopupMenu::MenuItemIterator first (on);
  21542. first.next();
  21543. check ("ml_caption_on", first.getItem().isSectionHeader && first.getItem().text == lynx::tr ("{0} parameters selected", { "2" }), first.getItem().text);
  21544. // Init pattern: the values at the pattern's start; ends multilink
  21545. const auto v0 = engine.currentTargetValue (volume);
  21546. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initPattern, engine.multilinkTargets(), 0);
  21547. const auto& lanes = engine.getSong().patterns[0].events;
  21548. check ("ml_init_pattern", lanes.size() == 2 && ! lanes[0].events.empty() && lanes[0].events[0].tick == 0
  21549. && std::abs (lanes[0].events[0].value - v0) < 1.0e-6f && ! engine.isMultilinkOn());
  21550. // Randomize keeps multilink on; Humanize moves at most an eighth
  21551. engine.setMultilink (true);
  21552. engine.noteTweaked (volume);
  21553. engine.noteTweaked (pan);
  21554. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::randomize, engine.multilinkTargets(), 1234);
  21555. check ("ml_randomize_keeps_queue", engine.isMultilinkOn() && engine.multilinkTargets().size() == 2);
  21556. const auto before = engine.currentTargetValue (volume);
  21557. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::humanize, engine.multilinkTargets(), 99);
  21558. check ("ml_humanize_small", std::abs (engine.currentTargetValue (volume) - before) <= 0.1251f && engine.isMultilinkOn(),
  21559. juce::String (before) + " -> " + juce::String (engine.currentTargetValue (volume)));
  21560. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initSong, engine.multilinkTargets(), 0);
  21561. check ("ml_init_song", engine.getSong().findInitialValue (volume) >= 0 && ! engine.isMultilinkOn());
  21562. // off: the last two tweaked parameters, no Cancel
  21563. auto off = lynx::multilinkButtonMenu (engine);
  21564. bool hasCancel = false;
  21565. for (juce::PopupMenu::MenuItemIterator it (off); it.next();)
  21566. hasCancel = hasCancel || it.getItem().text == lynx::tr ("Cancel");
  21567. juce::PopupMenu::MenuItemIterator offFirst (off);
  21568. offFirst.next();
  21569. check ("ml_off_caption", offFirst.getItem().text == lynx::tr ("Last 2 tweaked parameters") && ! hasCancel, offFirst.getItem().text);
  21570. // LYNX's own one-step items stay, after FL's items below a line (greyed while multilink is off)
  21571. juce::String last;
  21572. bool lineBefore = false, prevLine = false;
  21573. for (juce::PopupMenu::MenuItemIterator it (on); it.next();)
  21574. {
  21575. if (it.getItem().text == lynx::tr ("Link to controller"))
  21576. lineBefore = prevLine;
  21577. prevLine = it.getItem().isSeparator;
  21578. last = it.getItem().text;
  21579. }
  21580. check ("ml_lynx_items_after_fl", lineBefore && last == lynx::tr ("Override global links"), last);
  21581. saveMenus (juce::StringArray { "Multilink on (2 queued)", "Multilink off" }, std::vector<juce::PopupMenu> { on, off },
  21582. prefix + "-multilink-menu.png");
  21583. }
  21584. // ---- the plugin menu's spare state and Parameters > Link all parameters...
  21585. {
  21586. FlCtlShotPlugin plugin;
  21587. juce::PopupMenu menu;
  21588. lynx::addPluginWrapperItems (menu, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  21589. saveMenus (juce::StringArray { "Plugin menu: spare state and parameters" }, std::vector<juce::PopupMenu> { menu }, prefix + "-plugin-menu.png");
  21590. const auto targets = lynx::allPluginParameterTargets (plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  21591. check ("link_all_parameters", targets.size() == 3 && targets[2].param == 2 && targets[2].index == 1);
  21592. auto* cutoff = static_cast<juce::AudioParameterFloat*> (plugin.getParameters()[0]);
  21593. *cutoff = 0.2f;
  21594. check ("spare_store", clickMenuItem (menu, lynx::tr ("Store in spare state")));
  21595. *cutoff = 0.9f;
  21596. juce::PopupMenu again;
  21597. lynx::addPluginWrapperItems (again, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  21598. check ("spare_flip", clickMenuItem (again, lynx::tr ("Flip with spare state")) && std::abs (cutoff->get() - 0.2f) < 1.0e-6f, juce::String (cutoff->get()));
  21599. 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()));
  21600. lynx::sparestate::shared().forget (&plugin);
  21601. }
  21602. // ---- the sampler's File row: Load (history menu, wheel), Locate, Remove
  21603. {
  21604. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flctl-samples");
  21605. folder.createDirectory();
  21606. const auto a = writeShotSample (folder.getChildFile ("Kick 1.wav"), 60.0), b = writeShotSample (folder.getChildFile ("Snare 2.wav"), 200.0),
  21607. c = writeShotSample (folder.getChildFile ("Hat 3.wav"), 900.0);
  21608. lynx::samplehistory::list().clear();
  21609. engine.editSong ([&] (lynx::Song& s) {
  21610. for (const auto& f : { c, b, a }) // (each load goes into the history, newest first)
  21611. lynx::audioclips::loadSampleInto (s.channels[1], f.getFullPathName().toStdString(), f.getFileNameWithoutExtension().toStdString());
  21612. });
  21613. check ("history_order", lynx::samplehistory::list().size() == 3 && lynx::samplehistory::list().front() == a.getFullPathName().toStdString());
  21614. juce::File located;
  21615. lynx::locateInBrowserHandler() = [&located] (const juce::File& f) { located = f; };
  21616. auto frame = lynx::makeChannelFrame (engine, 1, 0);
  21617. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 820);
  21618. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  21619. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  21620. shoot (*frame, "sampler-file-row");
  21621. const auto history = lynx::samplerHistoryMenu (*frame);
  21622. check ("history_menu", history.has_value() && history->getNumItems() == 4); // (caption + three samples)
  21623. if (history)
  21624. saveMenus (juce::StringArray { "Load: Sample history" }, std::vector<juce::PopupMenu> { *history }, prefix + "-sample-history.png");
  21625. lynx::samplerFileRowPress (*frame, 0); // wheel down: the next (older) sample
  21626. check ("wheel_down", engine.getSong().channels[1].samplePath == b.getFullPathName().toStdString(), juce::String (engine.getSong().channels[1].samplePath));
  21627. lynx::samplerFileRowPress (*frame, 1); // wheel up: back
  21628. check ("wheel_up", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  21629. lynx::samplerFileRowPress (*frame, 2);
  21630. check ("locate", located == a, located.getFullPathName());
  21631. lynx::samplerFileRowPress (*frame, 3);
  21632. check ("remove", engine.getSong().channels[1].samplePath.empty());
  21633. engine.undo();
  21634. check ("remove_undo", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  21635. lynx::locateInBrowserHandler() = nullptr;
  21636. }
  21637. // ---- a sampler running FL's voice: FL's Envelope / instrument page with the tensions, the predelay and presets
  21638. {
  21639. engine.editSong ([] (lynx::Song& s) {
  21640. auto& ch = s.channels[2];
  21641. ch.instrument = lynx::InstrumentKind::sampler;
  21642. ch.name = "FL sampler";
  21643. const auto snap = lynx::flvp::defaultSnapshot();
  21644. ch.sampler.flChannel.assign (90, 0);
  21645. std::memcpy (ch.sampler.flChannel.data(), snap.data(), 85 * 4);
  21646. std::memcpy (&ch.sampler.flChannel[85], snap.data() + 0x15c, 4);
  21647. std::memcpy (&ch.sampler.flChannel[86], snap.data() + 0x160, 4);
  21648. std::memcpy (&ch.sampler.flChannel[87], snap.data() + 0x168, 4);
  21649. ch.sampler.flChannel[88] = 96;
  21650. ch.sampler.flChannel[89] = 0;
  21651. auto& vol = ch.sampler.flChannel; // the volume envelope on, bent
  21652. vol[17 + 1] = -1;
  21653. vol[17 + 2] = 4000; // predelay
  21654. vol[17 + 14] = -70; // attack tension
  21655. vol[17 + 15] = 60; // decay tension
  21656. vol[17 + 16] = -40; // release tension
  21657. });
  21658. auto frame = lynx::makeChannelFrame (engine, 2, 1);
  21659. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 560);
  21660. shoot (*frame, "sampler-fl-envelope");
  21661. check ("fl_page_shown", lynx::flVoicePresetsMenu (*frame).has_value());
  21662. lynx::flVoicePresetFolder().deleteRecursively();
  21663. check ("preset_save", lynx::flVoiceSavePreset (*frame, "Bent volume")
  21664. && lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV").getSize() == 68);
  21665. if (const auto menu = lynx::flVoicePresetsMenu (*frame))
  21666. saveMenus (juce::StringArray { "Channel envelope presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-envelope-presets.png");
  21667. // the preset into the pitch target: its record becomes the saved one
  21668. lynx::showFlVoiceTarget (*frame, lynx::flvoice::pitch);
  21669. const auto loaded = lynx::flVoiceLoadPreset (*frame, lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV"));
  21670. const auto& fl = engine.getSong().channels[2].sampler.flChannel;
  21671. check ("preset_load", loaded && fl.size() == 90 && fl[68 + 2] == 4000 && fl[68 + 14] == -70 && fl[68 + 16] == -40 && fl[88] == 96);
  21672. engine.undo();
  21673. check ("preset_load_undo", engine.getSong().channels[2].sampler.flChannel[68 + 14] != -70);
  21674. }
  21675. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  21676. return allOk;
  21677. }
  21678. // --flplshot (round 190dx): see the dispatch above
  21679. bool runHdrShot190ft (const juce::String& prefix)
  21680. {
  21681. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21682. juce::StringArray report;
  21683. bool allOk = true;
  21684. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  21685. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  21686. allOk = allOk && ok;
  21687. };
  21688. const auto list = [] (const std::vector<int>& v) {
  21689. juce::StringArray out;
  21690. for (auto i : v)
  21691. out.add (juce::String (i));
  21692. return out.joinIntoString (",");
  21693. };
  21694. lynx::AudioEngine engine (false);
  21695. lynx::MainComponent ui (engine, false);
  21696. ui.setSize (1600, 900);
  21697. {
  21698. auto song = lynx::Song::makeDefault();
  21699. song.playlist.clear();
  21700. for (int t = 0; t < 6; ++t)
  21701. {
  21702. if ((int) song.playlistTracks.size() <= t)
  21703. song.playlistTracks.resize ((std::size_t) t + 1);
  21704. song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
  21705. for (int k = 0; k < 2; ++k)
  21706. {
  21707. lynx::Clip c;
  21708. c.kind = lynx::ClipKind::pattern;
  21709. c.pattern = 0;
  21710. c.track = t;
  21711. c.start = (std::int64_t) (k * 4 + t % 3) * lynx::ppq;
  21712. c.length = 2 * lynx::ppq;
  21713. song.playlist.push_back (c);
  21714. }
  21715. }
  21716. if (song.mixer.size() < 4)
  21717. song.mixer.resize (4);
  21718. song.playlistTracks[2].mode = lynx::PlaylistTrackMode::audio; // an audio track linked to mixer track 3
  21719. song.playlistTracks[2].mixerTrack = 3;
  21720. song.playlistTracks[2].name = "Vox";
  21721. engine.setSong (std::move (song));
  21722. }
  21723. engine.dispatchPendingMessages();
  21724. ui.selectTabForSnapshot (2);
  21725. engine.dispatchPendingMessages();
  21726. auto& pl = ui.getPlaylistForSnapshot();
  21727. pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
  21728. auto source = juce::Desktop::getInstance().getMainMouseSource();
  21729. const auto now = juce::Time::getCurrentTime();
  21730. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  21731. const int ctrl = juce::ModifierKeys::commandModifier; // (FL's Ctrl: Cmd on a Mac)
  21732. const int shift = juce::ModifierKeys::shiftModifier;
  21733. const int alt = juce::ModifierKeys::altModifier;
  21734. const auto event = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  21735. 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);
  21736. };
  21737. // a press (and release) at p with the modifiers; `to`: a drag there before the release
  21738. const auto press = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}, int clicks = 1) {
  21739. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  21740. c.mouseMove (event (c, p, mods, p, 1, false));
  21741. c.mouseDown (event (c, p, down, p, clicks, false));
  21742. if (to)
  21743. c.mouseDrag (event (c, *to, down, p, clicks, true));
  21744. c.mouseUp (event (c, to ? *to : p, mods, p, clicks, to.has_value()));
  21745. };
  21746. const auto headerPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getY() + juce::jmin (10, r.getHeight() / 3)); };
  21747. const auto bandPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getBottom() - 2); };
  21748. const auto clipsOn = [&] (const std::vector<int>& tracks) {
  21749. std::vector<int> out;
  21750. const auto& song = engine.getSong();
  21751. for (int i = 0; i < (int) song.playlist.size(); ++i)
  21752. if (std::find (tracks.begin(), tracks.end(), song.playlist[(std::size_t) i].track) != tracks.end())
  21753. out.push_back (i);
  21754. return out;
  21755. };
  21756. const auto sortedClips = [&] { auto v = pl.getSelectedClips(); std::sort (v.begin(), v.end()); return v; };
  21757. const auto headerShot = [&] (const juce::String& name, int rows) {
  21758. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  21759. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 760), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  21760. };
  21761. // ---- 1. selection (AUTracksPanelMouseDown / FUN_012e83e0)
  21762. press (pl, headerPoint (1), {});
  21763. check ("click_selects_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
  21764. pl.selectClipsForSnapshot ({});
  21765. // LYNX extra (issue #163): Ctrl+click adds / removes one track, its clips follow
  21766. press (pl, headerPoint (3), ctrl);
  21767. check ("ctrl_click_adds_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3 } && sortedClips() == clipsOn ({ 3 }),
  21768. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  21769. press (pl, headerPoint (5), ctrl);
  21770. press (pl, headerPoint (1), ctrl);
  21771. check ("ctrl_click_removes_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 3, 5 } && sortedClips() == clipsOn ({ 3, 5 }),
  21772. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  21773. // FL's own toggle: Ctrl+Shift+click (its clips are added)
  21774. press (pl, headerPoint (1), ctrl | shift);
  21775. check ("ctrl_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
  21776. check ("ctrl_shift_click_adds_clips", sortedClips() == clipsOn ({ 1, 3, 5 }), list (sortedClips()));
  21777. press (pl, headerPoint (3), ctrl | shift);
  21778. check ("ctrl_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 5 }, list (pl.selectedTracksForSnapshot()));
  21779. press (pl, headerPoint (3), ctrl | shift);
  21780. check ("ctrl_shift_click_adds_again", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
  21781. pl.selectClipsForSnapshot ({});
  21782. headerShot ("-ctrl-multiselect.png", 6);
  21783. press (pl, headerPoint (0), ctrl, headerPoint (2));
  21784. check ("ctrl_drag_range_with_clips", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2 } && sortedClips() == clipsOn ({ 0, 1, 2 }),
  21785. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  21786. press (pl, headerPoint (1), shift); // LYNX's own Shift+click range (from the last clicked track, 0)
  21787. check ("lynx_shift_range_kept", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
  21788. {
  21789. int linked = -1;
  21790. auto old = pl.onLinkedMixerTrack;
  21791. pl.onLinkedMixerTrack = [&linked] (int insert) { linked = insert; };
  21792. press (pl, headerPoint (2), {});
  21793. check ("audio_track_click_links_mixer_track", linked == 3, juce::String (linked));
  21794. pl.onLinkedMixerTrack = old;
  21795. }
  21796. // ---- 2. the resize band (FUN_00ea93a0, AUTracksPanelMouseMove)
  21797. const auto heightOf = [&] (int t) { return pl.trackRowForSnapshot (t).getHeight(); };
  21798. const auto& tracks = [&]() -> const std::vector<lynx::PlaylistTrack>& { return engine.getSong().playlistTracks; };
  21799. press (pl, headerPoint (4), {}); // (track 4 alone selected)
  21800. {
  21801. const auto start = bandPoint (4);
  21802. press (pl, start, {}, start + juce::Point<int> (0, 41));
  21803. 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)
  21804. headerShot ("-resized.png", 6);
  21805. const auto again = bandPoint (4);
  21806. press (pl, again, {}, again + juce::Point<int> (0, -100)); // (above the row's top, but less than 32 px)
  21807. check ("drag_stops_at_16", heightOf (4) == 16, juce::String (heightOf (4)));
  21808. press (pl, bandPoint (4), alt);
  21809. check ("alt_click_resets", tracks()[4].height == 0 && tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (heightOf (4)));
  21810. press (pl, bandPoint (4), {}, {}, 2); // the second press of a double click
  21811. check ("double_click_locks_small", tracks()[4].lockedHeight == 1 && heightOf (4) == 16, juce::String (tracks()[4].lockedHeight));
  21812. press (pl, bandPoint (4), {});
  21813. check ("click_on_locked_band_unlocks", tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (tracks()[4].lockedHeight));
  21814. const auto top = pl.trackRowForSnapshot (4).getY();
  21815. const auto b = bandPoint (4);
  21816. press (pl, b, {}, juce::Point<int> (b.x, top - 40));
  21817. check ("drag_past_the_top_groups", tracks()[4].grouped && tracks()[4].height == 0, juce::String ((int) tracks()[4].grouped));
  21818. const auto b2 = bandPoint (4);
  21819. press (pl, b2, {}, juce::Point<int> (b2.x, pl.trackRowForSnapshot (4).getY() - 40));
  21820. check ("again_ungroups", ! tracks()[4].grouped, juce::String ((int) tracks()[4].grouped));
  21821. }
  21822. {
  21823. // every selected track: the same height, from the first one's top to the mouse
  21824. press (pl, headerPoint (1), {});
  21825. press (pl, headerPoint (2), ctrl | shift);
  21826. press (pl, headerPoint (3), ctrl | shift);
  21827. const auto top = pl.trackRowForSnapshot (1).getY();
  21828. const auto b = bandPoint (2);
  21829. press (pl, b, {}, juce::Point<int> (b.x, top + 2 * 50));
  21830. check ("selected_tracks_share_the_height", tracks()[1].height == 50 && tracks()[2].height == 50 && tracks()[3].height == 50,
  21831. juce::String (tracks()[1].height) + "," + juce::String (tracks()[2].height) + "," + juce::String (tracks()[3].height));
  21832. headerShot ("-selected-resized.png", 6);
  21833. }
  21834. // ---- 3. saved: .lynx round trip and the .flp size factor
  21835. {
  21836. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[5].height = 300; s.playlistTracks[0].lockedHeight = 60; });
  21837. const auto json = lynx::ProjectFile::toJson (engine.getSong());
  21838. juce::String error;
  21839. const auto back = lynx::ProjectFile::fromJson (json, error);
  21840. check ("lynx_round_trip", back && back->playlistTracks.size() > 5 && back->playlistTracks[5].height == 300 && back->playlistTracks[1].height == 50
  21841. && back->playlistTracks[0].lockedHeight == 60, error);
  21842. lynx::flpexport::Options options;
  21843. lynx::flpexport::Report flpReport;
  21844. const auto project = flp::parseProject (lynx::flpexport::exportFlp (engine.getSong(), options, flpReport));
  21845. float size5 = -1.0f, size1 = -1.0f;
  21846. for (const auto& arrangement : project.arrangements)
  21847. for (const auto& t : arrangement.tracks)
  21848. {
  21849. if (t.index == 5) size5 = t.heightScale;
  21850. if (t.index == 1) size1 = t.heightScale;
  21851. }
  21852. 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,
  21853. juce::String (size5) + " " + juce::String (size1));
  21854. }
  21855. // ---- 4. the mixer strips (round 170b's FL rules): Ctrl+click alone, Ctrl+Shift+click adds / removes
  21856. {
  21857. ui.selectTabForSnapshot (3);
  21858. engine.editSong ([] (lynx::Song& s) { if (s.mixer.size() < 9) s.mixer.resize (9); });
  21859. engine.dispatchPendingMessages();
  21860. auto& mixer = ui.getMixerForSnapshot();
  21861. mixer.setSize (1400, 640);
  21862. auto& strips = mixer.getStripsForSnapshot();
  21863. strips.setSize (juce::jmax (strips.getWidth(), 1300), juce::jmax (strips.getHeight(), 560));
  21864. const auto at = [&] (int t) { return juce::Point<int> (strips.stripLeft (t) + 8, strips.getHeight() / 2 + 40); };
  21865. press (strips, at (2), {});
  21866. check ("mixer_click_alone", strips.getSelection() == std::vector<int> { 2 }, list (strips.getSelection()));
  21867. // LYNX extra (issue #163): Ctrl+click adds / removes one insert
  21868. press (strips, at (4), ctrl);
  21869. press (strips, at (6), ctrl);
  21870. check ("mixer_ctrl_click_adds_lynx", strips.getSelection() == std::vector<int> { 2, 4, 6 }, list (strips.getSelection()));
  21871. press (strips, at (4), ctrl);
  21872. check ("mixer_ctrl_click_removes_lynx", strips.getSelection() == std::vector<int> { 2, 6 }, list (strips.getSelection()));
  21873. // FL: Ctrl+Shift+click adds / removes too
  21874. press (strips, at (5), ctrl | shift);
  21875. check ("mixer_ctrl_shift_click_adds", strips.getSelection() == std::vector<int> { 2, 5, 6 }, list (strips.getSelection()));
  21876. savePng (mixer.createComponentSnapshot ({ 0, 0, juce::jmin (mixer.getWidth(), 900), mixer.getHeight() }), prefix + "-mixer-ctrl-multiselect.png");
  21877. // FL: Ctrl+drag across the strips = the range from the press, alone
  21878. press (strips, at (3), ctrl, at (4));
  21879. check ("mixer_ctrl_drag_range", strips.getSelection() == std::vector<int> { 3, 4 }, list (strips.getSelection()));
  21880. }
  21881. // ---- 5. round 190gw (live check 190gu B1): FL's default row, the left lock strip, the right selection strip
  21882. {
  21883. ui.selectTabForSnapshot (2);
  21884. auto song = lynx::Song::makeDefault();
  21885. song.playlist.clear();
  21886. song.playlistTracks.assign (6, {});
  21887. for (int t = 0; t < 6; ++t)
  21888. song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
  21889. engine.setSong (std::move (song));
  21890. engine.dispatchPendingMessages();
  21891. pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
  21892. check ("gw_default_row_48", heightOf (0) == 48 && heightOf (5) == 48, juce::String (heightOf (0)));
  21893. const auto rowMid = [&] (int t) { const auto r = pl.trackRowForSnapshot (t); return r.getY() + r.getHeight() / 2 - 4; };
  21894. const auto stripX = pl.headerWidthForSnapshot() - 4;
  21895. // the left strip (x < 10): the row flips to the smallest size and back; nothing selects
  21896. press (pl, { 2, rowMid (2) }, {});
  21897. check ("gw_left_strip_smallest", heightOf (2) == 16 && tracks()[2].lockedHeight == 1, juce::String (heightOf (2)));
  21898. press (pl, { 2, rowMid (2) }, {});
  21899. check ("gw_left_strip_back", heightOf (2) == 48 && tracks()[2].lockedHeight == -1, juce::String (heightOf (2)));
  21900. // the right strip: click = alone, Shift+click toggles, right-click toggles with no menu
  21901. press (pl, { stripX, rowMid (0) }, {});
  21902. check ("gw_strip_click_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 0 }, list (pl.selectedTracksForSnapshot()));
  21903. press (pl, { stripX, rowMid (1) }, shift);
  21904. check ("gw_strip_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
  21905. headerShot ("-gw-strip-two-selected.png", 6);
  21906. press (pl, { stripX, rowMid (0) }, shift);
  21907. check ("gw_strip_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
  21908. {
  21909. const juce::Point<int> p { stripX, rowMid (4) };
  21910. const juce::ModifierKeys right (juce::ModifierKeys::rightButtonModifier);
  21911. pl.mouseDown (event (pl, p, right, p, 1, false));
  21912. pl.mouseUp (event (pl, p, {}, p, 1, false));
  21913. }
  21914. check ("gw_strip_right_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 4 }, list (pl.selectedTracksForSnapshot()));
  21915. // a drag down the strip: the tracks crossed join (FUN_012e8740)
  21916. press (pl, { stripX, rowMid (0) }, {}, juce::Point<int> (stripX, rowMid (4)));
  21917. check ("gw_strip_drag_range", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2, 3, 4 }, list (pl.selectedTracksForSnapshot()));
  21918. headerShot ("-gw-strip-range.png", 6);
  21919. // a double click: the track alone <-> every track
  21920. press (pl, { stripX, rowMid (2) }, {});
  21921. press (pl, { stripX, rowMid (2) }, {}, {}, 2);
  21922. check ("gw_strip_double_click_all", (int) pl.selectedTracksForSnapshot().size() == pl.numTracksForSnapshot(), list (pl.selectedTracksForSnapshot()));
  21923. press (pl, { stripX, rowMid (1) }, {});
  21924. // .lynx: the new default row is saved; a project from before (no key) keeps LYNX's old 38 px row
  21925. juce::String error;
  21926. const auto json = lynx::ProjectFile::toJson (engine.getSong());
  21927. const auto back = lynx::ProjectFile::fromJson (json, error);
  21928. check ("gw_lynx_row_saved", back && back->playlistRowHeight == 48, error);
  21929. auto parsed = juce::JSON::parse (json);
  21930. if (auto* o = parsed.getDynamicObject())
  21931. o->removeProperty ("playlistRowHeight");
  21932. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  21933. check ("gw_old_lynx_keeps_38", old && old->playlistRowHeight == 38, error);
  21934. engine.setSong (*old);
  21935. engine.dispatchPendingMessages();
  21936. check ("gw_old_lynx_rows_38", heightOf (0) == 38, juce::String (heightOf (0)));
  21937. // an automation clip with two target links (Crossfade with) comes back with its links and formulas
  21938. auto linked = lynx::Song::makeDefault();
  21939. linked.channels.resize (2);
  21940. lynx::Automation a;
  21941. a.links = { { { lynx::AutomationTargetKind::channelAdjust, 0, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeOutFormula },
  21942. { { lynx::AutomationTargetKind::channelAdjust, 1, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeInFormula } };
  21943. a.target = a.links[0].target;
  21944. a.points = { { 0, 1.0f, 0.0f }, { 384, 0.0f, 0.0f } };
  21945. linked.automations.push_back (a);
  21946. const auto linkedBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (linked), error);
  21947. check ("gw_lynx_links_round_trip", linkedBack && linkedBack->automations.size() == linked.automations.size()
  21948. && linkedBack->automations.back().links == a.links && linkedBack->automations.back().target == a.target, error);
  21949. // Sampler › Open in new Fruity Slicer / Slicex channel: named after the sample, " #n" when taken
  21950. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190gw").getChildFile ("Basic 808 Clap.wav");
  21951. wav.getParentDirectory().createDirectory();
  21952. {
  21953. juce::AudioBuffer<float> b (1, 4410);
  21954. for (int i = 0; i < b.getNumSamples(); ++i)
  21955. b.setSample (0, i, 0.5f * std::sin ((float) i * 0.2f) * (1.0f - (float) i / (float) b.getNumSamples()));
  21956. wav.deleteFile();
  21957. juce::WavAudioFormat format;
  21958. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream());
  21959. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  21960. {
  21961. out.release();
  21962. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  21963. writer->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  21964. }
  21965. }
  21966. engine.editSong ([] (lynx::Song& s) {
  21967. s.channels.resize (1);
  21968. s.channels[0] = {};
  21969. s.channels[0].name = "Basic 808 Clap";
  21970. });
  21971. engine.dispatchPendingMessages();
  21972. if (lynx::openInNewChannelHandler())
  21973. {
  21974. lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::fruityslicer);
  21975. lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::slicex);
  21976. }
  21977. engine.dispatchPendingMessages();
  21978. const auto& ch = engine.getSong().channels;
  21979. 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"
  21980. && ch[1].instrument == lynx::InstrumentKind::fruityslicer && ch[2].instrument == lynx::InstrumentKind::slicex,
  21981. ch.size() >= 3 ? juce::String::fromUTF8 (ch[1].name.c_str()) + " | " + juce::String::fromUTF8 (ch[2].name.c_str()) : juce::String ((int) ch.size()));
  21982. wav.getParentDirectory().deleteRecursively();
  21983. // the mixer's two boxes (live check 190gu B4): "Insert multiple..." asks "Number of tracks to add" (1),
  21984. // "Add multiple..." "Enter the number of mixer tracks to add" (10)
  21985. for (const auto adding : { false, true })
  21986. {
  21987. auto box = lynx::MixerStrips::makeInsertMultipleBox (adding);
  21988. const auto text = box->getTextEditorContents ("count");
  21989. check (adding ? "gw_add_multiple_box" : "gw_insert_multiple_box", text == (adding ? "10" : "1"), text);
  21990. if (box->getWidth() > 0 && box->getHeight() > 0)
  21991. savePng (box->createComponentSnapshot (box->getLocalBounds()), prefix + (adding ? "-gw-add-multiple-box.png" : "-gw-insert-multiple-box.png"));
  21992. }
  21993. }
  21994. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  21995. return allOk;
  21996. }
  21997. #include "FoldersShot190jf.inc" // round 190jf (slice B17)
  21998. // --userfixshot190ib (round 190ib): see the dispatch above
  21999. bool runUserFixShot190ib (const juce::String& prefix)
  22000. {
  22001. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22002. juce::StringArray report;
  22003. bool allOk = true;
  22004. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  22005. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  22006. allOk = allOk && ok;
  22007. };
  22008. lynx::AudioEngine engine (false);
  22009. lynx::MainComponent ui (engine, false);
  22010. ui.setSize (1600, 900);
  22011. engine.dispatchPendingMessages();
  22012. // ---- #182: a real JUCE popup menu inside a host component, keys sent to its window as the keyboard would
  22013. juce::Component host;
  22014. host.setSize (560, 900);
  22015. const auto typeInto = [&host] (const juce::String& text) {
  22016. auto* menuWindow = host.getNumChildComponents() > 0 ? host.getChildComponent (host.getNumChildComponents() - 1) : nullptr;
  22017. for (auto c : text)
  22018. if (menuWindow != nullptr)
  22019. menuWindow->keyPressed (juce::KeyPress ((int) juce::CharacterFunctions::toLowerCase (c), 0, c));
  22020. return menuWindow != nullptr;
  22021. };
  22022. const auto shotMenu = [&host, &prefix] (const juce::String& name) {
  22023. savePng (host.createComponentSnapshot (host.getLocalBounds()), prefix + name);
  22024. };
  22025. {
  22026. auto& pl = ui.getPlaylistForSnapshot();
  22027. pl.editMenu().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
  22028. check ("menu_shown", host.getNumChildComponents() > 0, juce::String (host.getNumChildComponents()));
  22029. shotMenu ("-menu-0.png");
  22030. typeInto ("d");
  22031. shotMenu ("-menu-d.png"); // the first item starting with D
  22032. typeInto ("d");
  22033. shotMenu ("-menu-dd.png"); // D again: the next one
  22034. juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100); // (a pause: a new prefix)
  22035. typeInto ("drop a");
  22036. shotMenu ("-menu-drop-a.png"); // "Drop audio on track headers"
  22037. juce::PopupMenu::dismissAllActiveMenus();
  22038. }
  22039. {
  22040. auto& pr = ui.getPianoRollForSnapshot();
  22041. pr.moreMenuForSnapshot().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
  22042. juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100);
  22043. typeInto ("preview");
  22044. shotMenu ("-pianoroll-preview.png"); // #183's item, reached by typing its name
  22045. juce::PopupMenu::dismissAllActiveMenus();
  22046. check ("preview_while_playing_off_by_default", ! lynx::PianoRollComponent::previewWhilePlaying);
  22047. }
  22048. // ---- #181: Ctrl+, (Cmd+, on macOS) through the main window's key handling opens Settings, again closes it
  22049. const auto ctrlComma = juce::KeyPress (',', juce::ModifierKeys::commandModifier, ',');
  22050. check ("settings_closed_first", lynx::shownSettingsPage() < 0);
  22051. ui.keyPressed (ctrlComma);
  22052. check ("ctrl_comma_opens_settings", lynx::shownSettingsPage() == (int) lynx::SettingsPage::general, juce::String (lynx::shownSettingsPage()));
  22053. ui.keyPressed (ctrlComma);
  22054. check ("ctrl_comma_again_closes_it", lynx::shownSettingsPage() < 0, juce::String (lynx::shownSettingsPage()));
  22055. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  22056. return allOk;
  22057. }
  22058. // --issuesshot190ht (round 190ht): see the dispatch above
  22059. bool runIssuesShot190ht (const juce::String& prefix)
  22060. {
  22061. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22062. juce::StringArray report;
  22063. bool allOk = true;
  22064. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  22065. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  22066. allOk = allOk && ok;
  22067. };
  22068. using namespace lynx;
  22069. AudioEngine engine (false);
  22070. MainComponent ui (engine, false);
  22071. ui.setSize (1600, 900);
  22072. const auto bar = (std::int64_t) 4 * ppq;
  22073. {
  22074. // Kick (1 bar), Bass (2 bars, a long note across its second bar), Lead (1 bar), Pad (1 bar): blocks in rows
  22075. auto song = Song::makeDefault();
  22076. song.playlist.clear();
  22077. song.patterns.clear();
  22078. const auto pattern = [&song] (const char* name, std::uint32_t colour, int channel, std::int64_t length) {
  22079. auto& p = song.patterns.emplace_back();
  22080. p.name = name;
  22081. p.colour = colour;
  22082. for (int step : { 0, 4, 8, 12 })
  22083. p.toggleStep (channel, step);
  22084. p.lengthTicks = length;
  22085. return (int) song.patterns.size() - 1;
  22086. };
  22087. pattern ("Kick", 0xFFD85A3C, 0, bar);
  22088. const auto bass = pattern ("Bass", 0xFF3C8DD8, 1, 0);
  22089. Note longNote;
  22090. longNote.channel = 1;
  22091. longNote.start = 6 * ppq;
  22092. longNote.length = 2 * ppq;
  22093. song.patterns[(std::size_t) bass].notes.push_back (longNote);
  22094. song.patterns[(std::size_t) bass].sortNotes();
  22095. pattern ("Lead", 0xFF8A5CD8, 2, bar);
  22096. pattern ("Pad", 0xFF5CB85C, 3, bar);
  22097. song.patternBlocksOn = true;
  22098. for (int b = 0; b < 8; ++b)
  22099. patternblocks::place (song, 0, b * bar);
  22100. patternblocks::place (song, 1, 0);
  22101. patternblocks::place (song, 1, 4 * bar);
  22102. for (int b = 2; b < 6; ++b)
  22103. patternblocks::place (song, 2, b * bar);
  22104. patternblocks::place (song, 3, 0);
  22105. engine.setSong (std::move (song));
  22106. }
  22107. engine.dispatchPendingMessages();
  22108. ui.selectTabForSnapshot (2);
  22109. engine.dispatchPendingMessages();
  22110. auto& pl = ui.getPlaylistForSnapshot();
  22111. pl.setSize (juce::jmax (pl.getWidth(), 1000), juce::jmax (pl.getHeight(), 640));
  22112. pl.setViewForSnapshot (90.0, 0, 0); // (bar 1 at the left edge)
  22113. pl.setBlocksHeight (6 + 5 * 18 + 6);
  22114. engine.dispatchPendingMessages();
  22115. const auto& song = [&]() -> const Song& { return engine.getSong(); };
  22116. auto* blocks = pl.getBlocksViewForSnapshot();
  22117. check ("blocks_view", blocks != nullptr && blocks->isVisible());
  22118. if (blocks == nullptr)
  22119. {
  22120. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=FAIL\n");
  22121. return false;
  22122. }
  22123. const auto shotBlocks = [&] (const juce::String& name) {
  22124. engine.dispatchPendingMessages();
  22125. const auto area = blocks->getBoundsInParent().withWidth (juce::jmin (pl.getWidth(), 900)).expanded (0, 2).getIntersection (pl.getLocalBounds());
  22126. savePng (pl.createComponentSnapshot (area), prefix + name);
  22127. };
  22128. auto source = juce::Desktop::getInstance().getMainMouseSource();
  22129. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
  22130. juce::Point<float> pressedAt;
  22131. const auto bEvent = [&] (int row, std::int64_t tick, juce::ModifierKeys mods, int clicks = 1) {
  22132. const auto at = blocks->pointForSnapshot (row, tick).toFloat();
  22133. const auto now = juce::Time::getCurrentTime();
  22134. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, clicks, at != pressedAt);
  22135. };
  22136. const auto bPress = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  22137. pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
  22138. blocks->mouseDown (bEvent (row, tick, mods));
  22139. };
  22140. const auto bDrag = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (bEvent (row, tick, mods)); };
  22141. const auto bRelease = [&] (int row, std::int64_t tick, juce::ModifierKeys mods = {}) {
  22142. blocks->mouseUp (bEvent (row, tick, mods));
  22143. engine.dispatchPendingMessages();
  22144. };
  22145. const auto blockOf = [&] (int row, std::int64_t start) -> const PatternBlock* {
  22146. const auto i = patternblocks::indexOf (song(), { row, start });
  22147. return i < 0 ? nullptr : &song().blocks[(std::size_t) i];
  22148. };
  22149. const auto mutedAt = [&] (int row, std::int64_t start) { const auto* x = blockOf (row, start); return x != nullptr && x->muted; };
  22150. const auto playingAt = [&] (int row, std::int64_t start) { const auto* x = blockOf (row, start); return x != nullptr && ! x->muted; };
  22151. const auto mutedCount = [&] {
  22152. int n = 0;
  22153. for (const auto& b : song().blocks)
  22154. n += b.muted ? 1 : 0;
  22155. return n;
  22156. };
  22157. shotBlocks ("-blocks-before.png");
  22158. // ---- #127 Mute: a click mutes the block, a drag down across rows mutes the blocks it crosses (any row)
  22159. pl.setToolForSnapshot (EditTool::mute);
  22160. bPress (0, 2 * bar + 40, left);
  22161. bRelease (0, 2 * bar + 40);
  22162. check ("mute_click", blockOf (0, 2 * bar) != nullptr && mutedAt (0, 2 * bar) && mutedCount() == 1);
  22163. bPress (0, 4 * bar + 40, left);
  22164. bDrag (1, 4 * bar + 60, left);
  22165. bDrag (2, 4 * bar + 80, left);
  22166. bRelease (2, 4 * bar + 80);
  22167. check ("mute_drag_across_rows", mutedAt (0, 4 * bar) && blockOf (1, 4 * bar) != nullptr && mutedAt (1, 4 * bar)
  22168. && mutedAt (2, 4 * bar) && playingAt (3, 0) && mutedCount() == 4,
  22169. juce::String (mutedCount()));
  22170. shotBlocks ("-blocks-mute.png");
  22171. // a sweep that starts on a muted block unmutes
  22172. bPress (0, 2 * bar + 40, left);
  22173. bDrag (0, 3 * bar + 40, left);
  22174. bRelease (0, 3 * bar + 40);
  22175. check ("mute_sweep_from_muted_unmutes", playingAt (0, 2 * bar) && playingAt (0, 3 * bar) && mutedCount() == 3,
  22176. juce::String (mutedCount()));
  22177. // the right button erases, as with every tool but Select / Slice / Zoom
  22178. bPress (3, 40, right);
  22179. bRelease (3, 40);
  22180. check ("mute_right_click_erases", blockOf (3, 0) == nullptr);
  22181. engine.undo();
  22182. engine.dispatchPendingMessages();
  22183. check ("undo_erase", blockOf (3, 0) != nullptr);
  22184. // the muted blocks play nothing: their clips in the playback copy are muted
  22185. {
  22186. auto copy = song();
  22187. patternblocks::expandSong (copy);
  22188. int mutedClips = 0;
  22189. for (const auto& c : copy.playlist)
  22190. mutedClips += c.muted ? 1 : 0;
  22191. check ("muted_blocks_play_muted_clips", mutedClips == 3, juce::String (mutedClips));
  22192. juce::String error;
  22193. const auto back = ProjectFile::fromJson (ProjectFile::toJson (song()), error);
  22194. check ("muted_blocks_saved", back && back->blocks == song().blocks, error);
  22195. }
  22196. // ---- #127 Select: a box over rows 0-2, bars 5-6 selects every block it meets; Pencil moves them together
  22197. pl.setToolForSnapshot (EditTool::lasso);
  22198. bPress (0, 4 * bar + 40, left);
  22199. bDrag (2, 5 * bar + 40, left);
  22200. shotBlocks ("-blocks-select-box.png");
  22201. bRelease (2, 5 * bar + 40);
  22202. const auto selection = blocks->selectionForSnapshot();
  22203. check ("select_box_any_row", selection.size() == 5 && patternblocks::contains (selection, { 0, 4 * bar }) && patternblocks::contains (selection, { 1, 4 * bar })
  22204. && patternblocks::contains (selection, { 2, 5 * bar }),
  22205. juce::String ((int) selection.size()));
  22206. pl.setToolForSnapshot (EditTool::pencil);
  22207. // (Kick's bars 7 and 8 are in the way of a 2-bar move: move the group by 1 bar after clearing them)
  22208. engine.editSong ([bar] (Song& s) { patternblocks::eraseRange (s, 0, 6 * bar, 8 * bar); });
  22209. engine.dispatchPendingMessages();
  22210. bPress (1, 4 * bar + 40, left);
  22211. bDrag (1, 6 * bar + 40, left);
  22212. bRelease (1, 6 * bar + 40);
  22213. check ("pencil_moves_the_selection", blockOf (1, 6 * bar) != nullptr && blockOf (0, 6 * bar) != nullptr && blockOf (0, 7 * bar) != nullptr
  22214. && blockOf (2, 6 * bar) != nullptr && blockOf (2, 7 * bar) != nullptr && blockOf (1, 4 * bar) == nullptr
  22215. && blocks->selectionForSnapshot().size() == 5);
  22216. shotBlocks ("-blocks-select-moved.png");
  22217. // a press on a block outside the selection moves that block alone and drops the selection
  22218. bPress (3, 40, left);
  22219. bDrag (3, bar + 40, left);
  22220. bRelease (3, bar + 40);
  22221. check ("pencil_unselected_block_alone", blockOf (3, bar) != nullptr && blockOf (0, 6 * bar) != nullptr && blocks->selectionForSnapshot().empty());
  22222. // the right button selects too (FL 10: either button)
  22223. pl.setToolForSnapshot (EditTool::lasso);
  22224. bPress (3, bar + 40, right);
  22225. bRelease (3, bar + 40);
  22226. check ("select_click_right_button", blocks->selectionForSnapshot().size() == 1 && blockOf (3, bar) != nullptr);
  22227. // ---- #127 Slice: a click on Bass's first block at bar 2 beat 4 cuts the pattern; a new pattern takes the rest
  22228. pl.setToolForSnapshot (EditTool::knife);
  22229. const auto patternsBefore = song().patterns.size();
  22230. const juce::ModifierKeys freeLeft (juce::ModifierKeys::leftButtonModifier | juce::ModifierKeys::altModifier); // (Alt: no snap)
  22231. bPress (1, bar + 3 * ppq, freeLeft);
  22232. bDrag (2, bar + 3 * ppq, freeLeft); // (a vertical drag: the row under the mouse when released is cut)
  22233. bRelease (1, bar + 3 * ppq);
  22234. check ("slice_adds_a_pattern", song().patterns.size() == patternsBefore + 1 && song().patterns[2].name == "Bass #2",
  22235. juce::String ((int) song().patterns.size()));
  22236. check ("slice_trims_the_long_note", song().patterns[1].notes.back().start == 6 * ppq && song().patterns[1].notes.back().length >= ppq
  22237. && song().patterns[1].notes.back().length < ppq + ppq / 4 && song().patterns[2].notes.empty(),
  22238. juce::String (song().patterns[1].notes.back().length));
  22239. check ("slice_new_blocks_where_bass_ends", blockOf (2, 2 * bar) != nullptr && blockOf (2, 8 * bar) != nullptr);
  22240. shotBlocks ("-blocks-slice.png");
  22241. engine.undo();
  22242. engine.dispatchPendingMessages();
  22243. check ("undo_slice", song().patterns.size() == patternsBefore && song().patterns[2].name == "Lead");
  22244. // ---- #127 Zoom: a drag zooms to the range, a click goes back
  22245. pl.setToolForSnapshot (EditTool::zoom);
  22246. const auto zoomBefore = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  22247. bPress (0, 2 * bar, left);
  22248. bDrag (0, 4 * bar, left);
  22249. bRelease (0, 4 * bar);
  22250. const auto zoomed = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  22251. check ("zoom_drag_zooms_in", zoomed > zoomBefore * 1.5, juce::String (zoomed) + " vs " + juce::String (zoomBefore));
  22252. pressedAt = blocks->pointForSnapshot (0, 3 * bar).toFloat();
  22253. blocks->mouseDown (bEvent (0, 3 * bar, right));
  22254. blocks->mouseUp (bEvent (0, 3 * bar, {}));
  22255. const auto back = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  22256. check ("zoom_click_goes_back", std::abs (back - zoomBefore) < 0.5, juce::String (back));
  22257. // hints name each tool's gesture
  22258. pl.setToolForSnapshot (EditTool::mute);
  22259. check ("hint_mute", blocks->hintAt (blocks->pointForSnapshot (0, 40)).text.contains ("mutes"));
  22260. pl.setToolForSnapshot (EditTool::pencil);
  22261. // ---- #154: linked tracks, then the insert effects list on their headers
  22262. engine.editSong ([bar] (Song& s) {
  22263. s.patternBlocksOn = false;
  22264. s.blocks.clear();
  22265. s.playlist.clear();
  22266. ChannelDef vox;
  22267. vox.name = "Lead vocal";
  22268. vox.instrument = InstrumentKind::audioClip;
  22269. vox.samplePath = "/shots/Lead vocal.wav";
  22270. vox.mixerTrack = 12;
  22271. s.channels.push_back (vox);
  22272. const auto voxChannel = (int) s.channels.size() - 1;
  22273. s.mixer[12].name = "Vox chain";
  22274. for (auto k : { EffectKind::parametricEq, EffectKind::compressor, EffectKind::delay, EffectKind::reverb })
  22275. s.mixer[12].effects.push_back (makeEffectSlot (k));
  22276. s.mixer[12].effects[2].enabled = false;
  22277. s.channels[0].mixerTrack = 3;
  22278. s.mixer[3].name = "Kick";
  22279. s.mixer[3].effects.push_back (makeEffectSlot (EffectKind::compressor));
  22280. const auto clip = [&s, bar] (int track, ClipKind kind, int source, int at, int bars) {
  22281. Clip c;
  22282. c.kind = kind;
  22283. c.track = track;
  22284. c.start = at * bar;
  22285. c.length = bars * bar;
  22286. (kind == ClipKind::pattern ? c.pattern : c.channel) = source;
  22287. s.playlist.push_back (c);
  22288. };
  22289. clip (0, ClipKind::pattern, 0, 0, 4);
  22290. clip (1, ClipKind::audio, voxChannel, 0, 8);
  22291. s.playlistTracks.resize (4);
  22292. s.playlistTracks[1].height = 70;
  22293. });
  22294. engine.dispatchPendingMessages();
  22295. // (rollup 0.1.30: since round 190ib, switching the link on asks first when it moves inserts or routes channels;
  22296. // this run accepts, as the user clicking "Link")
  22297. PlaylistComponent::answerLinkConfirmation = [] (const autolink::Report&) { return true; };
  22298. // (round 190qk: the inserts column is on by default now; this route starts with it off, as before, and puts it back)
  22299. const auto insertsWere = std::exchange (PlaylistComponent::showTrackInserts, false);
  22300. pl.runAction ("playlist.linkTracks");
  22301. PlaylistComponent::answerLinkConfirmation = nullptr;
  22302. engine.dispatchPendingMessages();
  22303. // (rollup 0.1.30: round 190ib links Playlist track N to insert N, moving the inserts there: the Vox chain and
  22304. // the Kick follow their tracks, so the checks read the inserts the tracks are linked to)
  22305. const auto vox = song().playlistTracks.size() > 1 ? song().playlistTracks[1].mixerTrack : -1;
  22306. const auto kick = song().playlistTracks.size() > 0 ? song().playlistTracks[0].mixerTrack : -1;
  22307. check ("linked", song().linkTracksToMixer && vox > 0 && song().mixer[(std::size_t) vox].name == "Vox chain" && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth,
  22308. juce::String (pl.headerWidthForSnapshot()));
  22309. check ("inserts_off", ! PlaylistComponent::showTrackInserts && pl.insertsListForSnapshot (1).isEmpty());
  22310. const auto shotRows = [&] (const juce::String& name, int rows) {
  22311. engine.dispatchPendingMessages();
  22312. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  22313. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 820), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  22314. };
  22315. shotRows ("-inserts-off.png", 3);
  22316. pl.runAction ("playlist.trackInserts");
  22317. engine.dispatchPendingMessages();
  22318. check ("inserts_on_widens_linked_headers", PlaylistComponent::showTrackInserts
  22319. && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth + PlaylistComponent::insertsColumnWidth,
  22320. juce::String (pl.headerWidthForSnapshot()));
  22321. const auto list = [&] (int t) { return pl.insertsListForSnapshot (t); };
  22322. check ("list_on_linked_tracks_only", ! list (0).isEmpty() && ! list (1).isEmpty() && list (2).isEmpty(),
  22323. list (0).toString() + " / " + list (1).toString());
  22324. shotRows ("-inserts-on.png", 3);
  22325. // a row's hint names the effect
  22326. const auto rowPoint = [&] (int t, int row, bool dot) {
  22327. const auto r = list (t);
  22328. return juce::Point<int> (dot ? r.getX() + 5 : r.getX() + 40, r.getY() + row * 13 + 6);
  22329. };
  22330. const auto hintOf = [&] (juce::Point<int> p) { return pl.hintAt (p); };
  22331. check ("hint_names_the_effect", hintOf (rowPoint (1, 1, false)).value == quickpick::slotName (engine, song().mixer[(std::size_t) vox].effects[1]),
  22332. hintOf (rowPoint (1, 1, false)).value);
  22333. check ("hint_add_row", hintOf (rowPoint (0, 1, false)).text.contains ("add an effect"));
  22334. const auto now = juce::Time::getCurrentTime();
  22335. const int ctrl = juce::ModifierKeys::commandModifier;
  22336. const auto event = [&] (juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  22337. 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);
  22338. };
  22339. const auto press = [&] (juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}) {
  22340. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  22341. pl.mouseMove (event (p, mods, p, 1, false));
  22342. pl.mouseDown (event (p, down, p, 1, false));
  22343. if (to)
  22344. {
  22345. pl.mouseDrag (event ((p + *to) / 2, down, p, 1, true));
  22346. pl.mouseDrag (event (*to, down, p, 1, true));
  22347. }
  22348. pl.mouseUp (event (to ? *to : p, mods, p, 1, to.has_value()));
  22349. engine.dispatchPendingMessages();
  22350. };
  22351. const auto kinds = [&] (int insert) {
  22352. juce::StringArray k;
  22353. for (const auto& fx : song().mixer[(std::size_t) insert].effects)
  22354. k.add (juce::String ((int) fx.kind) + (fx.enabled ? "" : "-"));
  22355. return k.joinIntoString (",");
  22356. };
  22357. const auto eq = juce::String ((int) EffectKind::parametricEq), comp = juce::String ((int) EffectKind::compressor),
  22358. delay = juce::String ((int) EffectKind::delay), verb = juce::String ((int) EffectKind::reverb);
  22359. // the dot bypasses / un-bypasses, as the Mixer slot's LED (one undo step each)
  22360. press (rowPoint (1, 0, true), {});
  22361. check ("dot_bypasses", ! song().mixer[(std::size_t) vox].effects[0].enabled);
  22362. press (rowPoint (1, 2, true), {});
  22363. check ("dot_switches_on", song().mixer[(std::size_t) vox].effects[2].enabled);
  22364. engine.undo();
  22365. engine.dispatchPendingMessages();
  22366. check ("undo_dot", ! song().mixer[(std::size_t) vox].effects[2].enabled && ! song().mixer[(std::size_t) vox].effects[0].enabled);
  22367. press (rowPoint (1, 0, true), {});
  22368. shotRows ("-inserts-bypass.png", 3);
  22369. // drag the reverb (row 4) above the EQ: the chain order changes, as the Device View's drag
  22370. const auto before = kinds (vox);
  22371. press (rowPoint (1, 3, false), {}, rowPoint (1, 0, false) - juce::Point<int> (0, 4));
  22372. check ("drag_reorders", kinds (vox) == verb + "," + eq + "," + comp + "," + delay + "-", before + " -> " + kinds (vox));
  22373. // Ctrl + drag copies (the compressor, under the delay)
  22374. press (rowPoint (1, 2, false), juce::ModifierKeys (ctrl), rowPoint (1, 4, false) - juce::Point<int> (0, 4));
  22375. check ("ctrl_drag_copies", kinds (vox) == verb + "," + eq + "," + comp + "," + delay + "-," + comp, kinds (vox));
  22376. // onto another linked track's list: it moves to that insert (the Kick's)
  22377. press (rowPoint (1, 1, false), {}, rowPoint (0, 0, false));
  22378. check ("drag_to_another_track_moves", kinds (kick) == comp + "," + eq && kinds (vox) == verb + "," + comp + "," + delay + "-," + comp,
  22379. kinds (kick) + " | " + kinds (vox));
  22380. // the wheel scrolls a list longer than its track (Kick's 4 effects + "add" in a 3-row header)
  22381. engine.editSong ([kick] (Song& s) {
  22382. s.mixer[(std::size_t) kick].effects.push_back (makeEffectSlot (EffectKind::delay));
  22383. s.mixer[(std::size_t) kick].effects.push_back (makeEffectSlot (EffectKind::reverb));
  22384. });
  22385. engine.dispatchPendingMessages();
  22386. const auto firstName = hintOf (rowPoint (0, 0, false)).value;
  22387. const auto rowsShown = list (0).getHeight() / 13;
  22388. pl.mouseWheelMove (event (rowPoint (0, 0, false), {}, rowPoint (0, 0, false), 0, false), juce::MouseWheelDetails { 0.0f, -0.5f, false, false, false });
  22389. const auto afterWheel = hintOf (rowPoint (0, 0, false));
  22390. check ("wheel_scrolls_a_long_list", rowsShown < 5 && afterWheel.value != firstName
  22391. && afterWheel.value == quickpick::slotName (engine, song().mixer[(std::size_t) kick].effects[1]),
  22392. juce::String (rowsShown) + " rows, " + firstName + " -> " + afterWheel.value);
  22393. shotRows ("-inserts-edited.png", 3);
  22394. // a view option: not saved with the project
  22395. check ("option_not_in_project", ! ProjectFile::toJson (song()).contains ("trackInserts"));
  22396. // off again: the linked headers' own width
  22397. pl.runAction ("playlist.trackInserts");
  22398. engine.dispatchPendingMessages();
  22399. check ("inserts_off_again", ! PlaylistComponent::showTrackInserts && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth);
  22400. PlaylistComponent::showTrackInserts = insertsWere;
  22401. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  22402. return allOk;
  22403. }
  22404. #include "WorkflowShot190iu.inc" // round 190iu
  22405. #include "PlaylistShot190jq.inc" // round 190jq
  22406. #include "IssuesShot190jz.inc" // round 190jz
  22407. #include "AudioEdit190stShot.inc" // round 190st
  22408. #include "DrumSynth190syCheck.inc" // round 190sy: the Kick / Snare / Clap / Hat editors and docked rack windows
  22409. #include "IssuesShot190lw.inc" // round 190lw
  22410. #include "IssuesShot190mq.inc" // round 190mq
  22411. #include "Focus218Shot190ng.inc" // round 190ng (issue #218)
  22412. #include "Mixer221Shot190ng.inc" // round 190ng (issue #221)
  22413. #include "MixerQolShot190qh.inc" // round 190qh (research190qa R5, Mixer QoL)
  22414. #include "Slots260Shot190qf.inc" // round 190qf (PR #260)
  22415. #include "IssuesShot190ng.inc" // round 190ng (issues #215, #217, #219, #220, #222)
  22416. #include "TrackClipsShot190ne.inc" // round 190ne
  22417. #include "TrackStatesShot190op.inc" // round 190op
  22418. #include "AutoModesShot190pa.inc" // round 190pa
  22419. #include "Tracks190peShot.inc" // round 190pe
  22420. #include "HeaderGearShot248.inc" // rollup 0.1.31 step 7 (PRs #248 / #256)
  22421. #include "PerTabShot259.inc" // round 190pw (PR #259)
  22422. #include "HotfixUi190qp.inc" // hotfix 0.1.31.1 (round 190qp)
  22423. #include "Hotfix190ra.inc" // hotfix 0.1.31.2 (round 190ra)
  22424. #include "TrackerShot190nw.inc" // round 190nw
  22425. #include "IssuesShot190nq.inc" // round 190nq (issues #193, #225-#230)
  22426. #include "Research190onShot.inc" // round 190on (research190oe P2, P8, P10)
  22427. #include "IssuesShot190ns.inc" // round 190ns (issues #231-#235)
  22428. #include "Rollup031S3Shot.inc" // rollup 0.1.31 step 3 (round 190ny)
  22429. #include "Tabs2Test190nz.inc" // round 190nz (issue #232 stage 2)
  22430. #include "IssuesShot190od.inc" // round 190od (issues #236-#242)
  22431. #include "Design190ojShot.inc" // round 190oj (design review of every view)
  22432. #include "Design190ooShot.inc" // round 190oo (design review 2: the owner's options and the round's fixes)
  22433. #include "Extras190qkShot.inc" // round 190qk (the LYNX extras on by default)
  22434. #include "Extras190roShot.inc" // round 190ro (LYNX extras review 2)
  22435. #include "PlaylistView190soShot.inc" // round 190so (0.1.33 block A3, the Playlist view group)
  22436. #include "Custom190ssShot.inc" // round 190ss (0.1.33 block C, the customisation group)
  22437. #include "Q5fix190rsShot.inc" // round 190rs (0.1.32 stage Q5 fixes)
  22438. #include "Optionsux190qx.inc" // round 190qx (the owner's "make the options easy")
  22439. #include "SettingsShots190qx.inc" // round 190qx (Settings pages before / after)
  22440. #include "Polish190qwShot.inc" // round 190qw (design polish pass, the Soft look)
  22441. #include "IssuesShot190oq.inc" // round 190oq (issues #243-#252)
  22442. #include "IssuesShot190qb.inc" // round 190qb (follow-ups of issues #206, #215)
  22443. #include "Picker190qiShot.inc" // round 190qi (TOP-NEXT R6): picker and Browser quality of life
  22444. #include "PickerPaintBench190qi.inc" // round 190qi: the plugin lists' and the Browser's paint gate
  22445. #include "IssuesShot190qo.inc" // round 190qo (issues #239, #215, #251, #270)
  22446. #include "RackAuto190owShot.inc" // round 190ow (PAT-7 rest, DE-123: the automation clip rows at work)
  22447. #include "DetailsShot190kn.inc" // round 190kn
  22448. #include "SmartTipShot190ok.inc" // round 190ok (D1)
  22449. #include "SimpleDuckShot190ot.inc" // round 190ot (research190oe P5)
  22450. #include "Discord190quShot.inc" // round 190qu (Discord #general 11-24)
  22451. #include "Repeats190pmShot.inc" // round 190pm (research190oe P19, P23)
  22452. #include "DetailsShot190ld.inc" // round 190ld
  22453. #include "DetailsShot190lr.inc" // round 190lr
  22454. #include "DetailsShot190lx.inc" // round 190lx
  22455. #include "DetailsShot190mf.inc" // round 190mf
  22456. #include "DetailsShot190mk.inc" // round 190mk
  22457. #include "DetailsShot190mp.inc" // round 190mp
  22458. #include "HWheel254Test.inc" // round 190ou: issue #254, the horizontal wheel
  22459. #include "Feel190qeTest.inc" // round 190qe (TOP-NEXT R1): edge scroll, view stack, glide, keep labels
  22460. #include "MultiEditor255Test.inc" // round 190ou: issue #255, several plugin editors in use
  22461. #include "Issue258Test.inc" // round 190pv: issue #258, a cloned channel's own automation
  22462. #include "Hotfix190qpTest.inc" // round 190qp: imported automation heard and shown (issue #253)
  22463. #include "Sweep190re.inc" // round 190re: the 0.1.32 regression sweep (open, layouts, panels, reload, undo)
  22464. #include "Hotfix190qpWf.inc" // round 190qp: 0.1.31.1 hotfix (track clips open their notes; Export... with folders in the name)
  22465. #include "Issue282Check.inc" // round 190qs: issue #282, FL's trial mark and the Patcher generator in Export to FL Studio
  22466. #include "ToolbarShot190qg.inc" // round 190qg: the toolbar never hides anything silently (walk, pictures)
  22467. #include "Issues190qrCheck.inc" // round 190qr: issues #274-#281 (markers, rack meter, zoom, extras)
  22468. #include "NoFl190rhCheck.inc" // round 190rh: the FL natives without FL Studio
  22469. #include "Downgrade0132_190tfCheck.inc" // round 190tf (rollup 0.1.33): Save a copy for LYNX SHARE 0.1.32
  22470. #include "TrialMark190qtCheck.inc" // round 190qt: a project from an FL trial save goes back to FL as one (option A)
  22471. #include "Community190riCheck.inc" // round 190ri: the 0.1.32 community batch
  22472. #include "FlParity190tcCheck.inc" // round 190tc: FL parity block D part 1 (notes of no length, Shift+5 rows, ghosts, target links, slot names)
  22473. #include "Perf190rnCheck.inc" // round 190rn: the undo history's memory cap
  22474. #include "Perf190sbCheck.inc" // round 190sb: FL's plugin database kept between starts
  22475. #include "CacheCheck190tgCheck.inc" // round 190tg: the disk caches' integrity check
  22476. #include "StoppedBench190sp.inc" // round 190sp: the device callback while stopped, for instruction-count compares
  22477. #include "Undo190spCheck.inc" // round 190sp: the undo history shares the song's big containers (core/CowVector.h)
  22478. #include "MenuWindows190skCheck.inc" // round 190sk: the File menu's "..." items open their windows (DAWproject export did nothing)
  22479. #include "Issues330skCheck.inc" // round 190sk: audio2000's Linux issues #330-#342
  22480. #include "Yannik190sqCheck.inc" // round 190sq: yannik's issues #346, #251 follow-up, #347
  22481. #include "Batch334svCheck.inc" // round 190sv: #334 drops into plugin editors (XDND relay), #290 touchpad pinch, #304 command markers
  22482. #include "Rea190taCheck.inc" // round 190ta: the 0.1.33 REA gap-hunt's small FL-exact fixes
  22483. #include "Details190tdCheck.inc" // round 190td: undo names per layout (D2), Esc clears the selection first (D1), items 73-78
  22484. #include "Round190tiCheck.inc" // round 190ti: Slicex's pitch automation paths, the Playlist's Add key marker
  22485. #include "Round190tkCheck.inc" // round 190tk: FL's automation timing for imported FL projects
  22486. #include "Round190tmCheck.inc" // round 190tm: Reload re-reads the file, the Playlist ▾ Time markers, Song mode key markers, muted clips
  22487. #include "Round190toCheck.inc" // round 190to: FL's per-insert effects switch, the Master's / Current column's icons, Extra large
  22488. #include "SmallBugs190srCheck.inc" // round 190sr: #350, #349, QUEUE 0.1.33 items 42 / 43
  22489. #include "QuickWins190srCheck.inc" // round 190sr: the quick wins (#318 ...)
  22490. #include "Batch292Check190sw.inc" // round 190sw: #292 routing cables, #322 macOS's menu bar, #289 the hardware outputs export
  22491. #include "Round190teCheck.inc" // round 190te: #356 latency-compensated transport (LYNX extra), item 58 XDND finished accepted, item 82 Time markers Delete
  22492. #include "Backlog190rcCheck.inc" // round 190rc: #288 native presets, #287 MIDI drop, #283 #285 #286, PR #284, Discord 11-24
  22493. #include "Bugs190rvCheck.inc" // round 190rv: 0.1.32 open bug issues (#317 header LED, #319 pin)
  22494. #include "Q6Check190sa.inc" // round 190sa: 0.1.32 Q6 (files) + the Simple layout's sound drop
  22495. #include "KeySheetCheck190sj.inc" // round 190sj: issue #327, every key of the F1 shortcut sheet runs its action
  22496. #include "Details190tbCheck.inc" // round 190tb: 0.1.33 details pass (hint readouts, FL's pointers and arrows)
  22497. #include "Children190thCheck.inc" // round 190th: issue #359, what a plugin's child processes get from LYNX (Shrub's hang)
  22498. #include "Notes190tjCheck.inc" // round 190tj: issue #358, the Notes window
  22499. #include "Uhe190sjTest.inc" // round 190sj: issues #329 / #255, u-he editors opened, closed and removed (--uhe190sjtest)
  22500. #include "Issue325Check190sg.inc" // round 190sg: issue #325, a sample dropped on an audio clip replaces its channel's sample (FL)
  22501. #include "Qa190rbCheck.inc" // round 190rb: the 0.1.32 quality round's crash / memory fixes, checked
  22502. #include "Stab190rpCheck.inc" // round 190rp: 0.1.32 Q4 stability (recovery box, device lost, recovery round trip, sample 0)
  22503. #include "Iox190rmCheck.inc" // round 190rm: the 0.1.32 import / export sweep (--convert190rm)
  22504. #include "Issues190rtShot.inc" // round 190rt: issues #309 / #310 / #311 (--issues190rtshot, --issues190rttest)
  22505. #include "DetailsShot190mr.inc" // round 190mr
  22506. #include "DetailsShot190mv.inc" // round 190mv
  22507. #include "DetailsShot190my.inc" // round 190my
  22508. #include "DetailsShot190oa.inc" // round 190oa
  22509. #include "DetailsSweep190tb.inc" // round 190tb
  22510. #include "RackShot190nc.inc" // round 190nc
  22511. #include "OnboardShot190np.inc" // round 190np
  22512. #include "Demo190pgCheck.inc" // round 190pg
  22513. #include "Demo190plCheck.inc" // round 190pl
  22514. #include "Demo190qxCheck.inc" // round 190qx
  22515. #include "AutoLinks190ovCheck.inc" // round 190ov (FL automation clips linked to several controls)
  22516. // --trackautoshot190gz (round 190gz): see the dispatch above
  22517. bool runTrackAutoShot190gz (const juce::String& prefix)
  22518. {
  22519. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22520. juce::StringArray report;
  22521. bool allOk = true;
  22522. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  22523. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  22524. allOk = allOk && ok;
  22525. };
  22526. lynx::AudioEngine engine (false);
  22527. lynx::MainComponent ui (engine, false);
  22528. ui.setSize (1600, 900);
  22529. {
  22530. // a small song in FL's shape: Kick and Synth patterns, a drum loop, a vocal on its prepared insert, a mixed beat
  22531. using namespace lynx;
  22532. auto song = Song::makeDefault();
  22533. song.playlist.clear();
  22534. song.patterns.clear();
  22535. for (auto& c : song.channels)
  22536. c.mixerTrack = 0; // (FL's new channels play on the Master)
  22537. song.channels[4].mixerTrack = 9; // the Synth on a bus the user made
  22538. song.mixer[9].name = "Synth bus";
  22539. const auto audio = [&song] (const char* name, int mixer) {
  22540. ChannelDef c;
  22541. c.name = name;
  22542. c.instrument = InstrumentKind::audioClip;
  22543. c.samplePath = std::string ("/shots/") + name + ".wav";
  22544. c.mixerTrack = mixer;
  22545. song.channels.push_back (c);
  22546. return (int) song.channels.size() - 1;
  22547. };
  22548. const auto loop = audio ("Drum loop", 0);
  22549. const auto vox = audio ("Lead vocal", 12);
  22550. song.mixer[12].name = "Vox chain";
  22551. song.mixer[12].colour = 0xFF3C8DD8;
  22552. song.mixer[12].effects.push_back (makeEffectSlot (EffectKind::parametricEq));
  22553. const auto pattern = [&song] (const char* name, std::vector<int> channels, std::uint32_t colour) {
  22554. auto& p = song.patterns.emplace_back();
  22555. p.name = name;
  22556. p.colour = colour;
  22557. for (const auto c : channels)
  22558. for (int step : { 0, 4, 8, 12 })
  22559. p.toggleStep (c, step);
  22560. return (int) song.patterns.size() - 1;
  22561. };
  22562. const auto kick = pattern ("Kick", { 0 }, 0xFFD85A3C);
  22563. const auto lead = pattern ("Lead", { 4 }, 0xFF8A5CD8);
  22564. const auto beat = pattern ("Beat", { 1, 2, 3 }, 0xFF5CB85C);
  22565. const auto clip = [&song] (int track, ClipKind kind, int source, int bar, int bars) {
  22566. Clip c;
  22567. c.kind = kind;
  22568. c.track = track;
  22569. c.start = (std::int64_t) bar * 4 * ppq;
  22570. c.length = (std::int64_t) bars * 4 * ppq;
  22571. (kind == ClipKind::pattern ? c.pattern : c.channel) = source;
  22572. song.playlist.push_back (c);
  22573. };
  22574. for (int bar = 0; bar < 8; bar += 2)
  22575. {
  22576. clip (0, ClipKind::pattern, kick, bar, 2);
  22577. clip (2, ClipKind::pattern, beat, bar, 2);
  22578. }
  22579. clip (1, ClipKind::audio, loop, 0, 8);
  22580. clip (3, ClipKind::pattern, lead, 2, 4);
  22581. clip (4, ClipKind::audio, vox, 4, 4);
  22582. clip (6, ClipKind::pattern, kick, 4, 2); // (round 190ib: Track 7 only repeats Track 1's Kick)
  22583. song.playlistTracks.resize (8);
  22584. engine.setSong (std::move (song));
  22585. }
  22586. engine.dispatchPendingMessages();
  22587. ui.selectTabForSnapshot (2);
  22588. engine.dispatchPendingMessages();
  22589. auto& pl = ui.getPlaylistForSnapshot();
  22590. pl.setSize (juce::jmax (pl.getWidth(), 1000), juce::jmax (pl.getHeight(), 640));
  22591. pl.setViewForSnapshot (120.0, 1, 0);
  22592. const auto shotRows = [&] (const juce::String& name, int rows) {
  22593. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  22594. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 820), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  22595. };
  22596. const auto& song = [&]() -> const lynx::Song& { return engine.getSong(); };
  22597. const auto mode = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mode : lynx::PlaylistTrackMode::unassigned; };
  22598. const auto mixerOf = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mixerTrack : -1; };
  22599. // ---- 1. FL's default: tracks and inserts apart, FL's narrow headers
  22600. check ("off_by_default", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow(),
  22601. juce::String (pl.headerWidthForSnapshot()));
  22602. shotRows ("-off.png", 7);
  22603. // ---- 2. the switch (Playlist › Edit, Track mode, Settings › Project): it lists what it changes and asks (round
  22604. // 190ib: inserts move, channels are routed), then it is one undo step
  22605. lynx::autolink::Report plan;
  22606. bool asked = false;
  22607. lynx::PlaylistComponent::answerLinkConfirmation = [&] (const lynx::autolink::Report& r) {
  22608. plan = r;
  22609. asked = true;
  22610. return true;
  22611. };
  22612. {
  22613. const auto text = lynx::PlaylistComponent::describeLinkPlan (song(), lynx::autolink::planOn (song()));
  22614. juce::AlertWindow box (lynx::tr ("Link Playlist tracks to mixer tracks"), text, juce::MessageBoxIconType::QuestionIcon);
  22615. box.addButton (lynx::tr ("Link"), 1);
  22616. box.addButton (lynx::tr ("Cancel"), 0);
  22617. box.sendLookAndFeelChange();
  22618. savePng (lynx::shot::snapshot (box), prefix + "-confirm.png");
  22619. }
  22620. pl.runAction ("playlist.linkTracks");
  22621. engine.dispatchPendingMessages();
  22622. const auto moved = [&plan] (int from, int to) {
  22623. return std::any_of (plan.changes.begin(), plan.changes.end(), [=] (const lynx::autolink::Change& c) {
  22624. return c.kind == lynx::autolink::Change::Kind::moveInsert && c.from == from && c.to == to;
  22625. });
  22626. };
  22627. check ("asked_first_with_the_moves", asked && moved (9, 4) && moved (12, 5) && plan.repeats.size() == 1 && ! plan.changesSound(),
  22628. juce::String ((int) plan.changes.size()));
  22629. check ("switch_on", song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth,
  22630. juce::String (pl.headerWidthForSnapshot()));
  22631. check ("kick_instrument_track_insert_1", mode (0) == lynx::PlaylistTrackMode::instrument && mixerOf (0) == 1 && song().channels[0].mixerTrack == 1,
  22632. juce::String (mixerOf (0)));
  22633. check ("loop_audio_track_insert_2", mode (1) == lynx::PlaylistTrackMode::audio && mixerOf (1) == 2 && song().mixer[2].name == "Drum loop",
  22634. juce::String (mixerOf (1)));
  22635. // (round 190ib: Track N = insert N for every track with content of its own)
  22636. check ("beat_track_insert_3", mode (2) == lynx::PlaylistTrackMode::audio && mixerOf (2) == 3 && song().channels[1].mixerTrack == 3
  22637. && song().channels[2].mixerTrack == 3 && song().channels[3].mixerTrack == 3,
  22638. juce::String (mixerOf (2)));
  22639. check ("synth_bus_moves_to_insert_4", mode (3) == lynx::PlaylistTrackMode::instrument && song().channels[4].mixerTrack == 4
  22640. && song().mixer[4].name == "Synth bus" && song().playlistTracks[3].name == "Synth bus",
  22641. juce::String (song().channels[4].mixerTrack));
  22642. check ("vocal_chain_moves_to_insert_5", mode (4) == lynx::PlaylistTrackMode::audio && mixerOf (4) == 5 && song().mixer[5].effects.size() == 1
  22643. && song().mixer[5].name == "Vox chain",
  22644. juce::String (mixerOf (4)));
  22645. check ("empty_and_repeat_tracks_stay", mode (5) == lynx::PlaylistTrackMode::unassigned && mode (6) == lynx::PlaylistTrackMode::unassigned
  22646. && lynx::autolink::repeatedTracks (song())[6] == 0);
  22647. shotRows ("-on.png", 7);
  22648. // one undo step: Undo brings FL's tracks back, Redo the links
  22649. engine.undo();
  22650. engine.dispatchPendingMessages();
  22651. check ("undo_switch_on", ! song().linkTracksToMixer && mode (0) == lynx::PlaylistTrackMode::unassigned && mode (1) == lynx::PlaylistTrackMode::unassigned
  22652. && song().channels[0].mixerTrack == 0 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow());
  22653. engine.redo();
  22654. engine.dispatchPendingMessages();
  22655. check ("redo_switch_on", song().linkTracksToMixer && mixerOf (1) == 2 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth);
  22656. auto source = juce::Desktop::getInstance().getMainMouseSource();
  22657. const auto now = juce::Time::getCurrentTime();
  22658. const int ctrl = juce::ModifierKeys::commandModifier;
  22659. const auto event = [&] (juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  22660. 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);
  22661. };
  22662. const auto press = [&] (juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}) {
  22663. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  22664. pl.mouseMove (event (p, mods, p, 1, false));
  22665. pl.mouseDown (event (p, down, p, 1, false));
  22666. if (to)
  22667. pl.mouseDrag (event (*to, down, p, 1, true));
  22668. pl.mouseUp (event (to ? *to : p, mods, p, 1, to.has_value()));
  22669. engine.flushLevels();
  22670. engine.dispatchPendingMessages();
  22671. };
  22672. const auto doubleClick = [&] (juce::Point<int> p) {
  22673. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  22674. pl.mouseDown (event (p, down, p, 2, false));
  22675. pl.mouseDoubleClick (event (p, down, p, 2, false));
  22676. pl.mouseUp (event (p, {}, p, 2, false));
  22677. engine.flushLevels();
  22678. engine.dispatchPendingMessages();
  22679. };
  22680. // the controls are found where they are drawn: M right of the plate, S left of it, the volume bar and the pan knob
  22681. // under them (the same geometry the header paints with)
  22682. const auto row = [&] (int t) { return pl.trackRowForSnapshot (t); };
  22683. const int w = pl.headerWidthForSnapshot();
  22684. const auto mAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 13 - 9, r.getY() + 11); }; // (meter column 9 px)
  22685. const auto sAt = [&] (int t) { return mAt (t) - juce::Point<int> (20, 0); };
  22686. const auto volumeAt = [&] (int t, float fraction) {
  22687. const auto r = row (t);
  22688. const auto left = 8, width = w - 9 - 2 - 32;
  22689. return juce::Point<int> (left + juce::roundToInt (fraction * (float) width), r.getY() + 26);
  22690. };
  22691. const auto panAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 9 - 6 - 7, r.getY() + 26); };
  22692. const auto& insert2 = [&]() -> const lynx::MixerTrack& { return song().mixer[2]; };
  22693. // ---- 3. the linked headers' controls act on the track's mixer track
  22694. press (mAt (1), {});
  22695. check ("m_mutes_the_insert", insert2().muted, juce::String ((int) insert2().muted));
  22696. press (mAt (1), {});
  22697. check ("m_again_unmutes", ! insert2().muted);
  22698. press (sAt (1), {});
  22699. check ("s_solos_the_insert", insert2().solo);
  22700. press (sAt (1), {});
  22701. press (volumeAt (1, 0.25f), {});
  22702. check ("volume_click_sets_the_level", std::abs (insert2().volume - 0.25f) < 0.03f, juce::String (insert2().volume, 3));
  22703. press (volumeAt (1, 0.25f), {}, volumeAt (1, 0.5f));
  22704. check ("volume_drag", std::abs (insert2().volume - 0.5f) < 0.03f, juce::String (insert2().volume, 3));
  22705. doubleClick (volumeAt (1, 0.5f));
  22706. check ("volume_double_click_0_db", insert2().volume == lynx::unityFader, juce::String (insert2().volume, 3));
  22707. press (panAt (1), {}, panAt (1) - juce::Point<int> (0, 40));
  22708. check ("pan_drag_up", std::abs (insert2().pan - 0.5f) < 0.02f, juce::String (insert2().pan, 3));
  22709. shotRows ("-controls.png", 7);
  22710. doubleClick (panAt (1));
  22711. check ("pan_double_click_centre", insert2().pan == 0.0f, juce::String (insert2().pan, 3));
  22712. // an instrument track's header acts on its channel's insert (Synth: insert 4 since round 190ib)
  22713. press (volumeAt (3, 0.4f), {});
  22714. check ("instrument_track_volume_on_its_insert", std::abs (song().mixer[4].volume - 0.4f) < 0.03f, juce::String (song().mixer[4].volume, 3));
  22715. engine.editSong ([] (lynx::Song& s) { s.mixer[4].volume = lynx::unityFader; });
  22716. // FL's track mute and solo stay on the Playlist track: Ctrl+click on M solos it, a muted track lights M and the
  22717. // first click unmutes it
  22718. press (mAt (1), ctrl);
  22719. check ("ctrl_m_solos_the_playlist_track", song().isTrackMuted (0) && ! song().isTrackMuted (1) && ! insert2().solo);
  22720. press (mAt (1), ctrl);
  22721. engine.editSong ([] (lynx::Song& s) {
  22722. for (auto& t : s.playlistTracks)
  22723. t.muted = false;
  22724. s.playlistTracks[1].muted = true;
  22725. });
  22726. press (mAt (1), {});
  22727. check ("m_unmutes_a_muted_playlist_track_first", ! song().isTrackMuted (1) && ! insert2().muted);
  22728. // a track that only repeats another keeps FL's LED (Track 7, Track 1's Kick): a click mutes the Playlist track
  22729. press (juce::Point<int> (w - 9 - 11, row (6).getCentreY()), {});
  22730. check ("unlinked_led_is_fl", song().isTrackMuted (6));
  22731. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[6].muted = false; });
  22732. // round 190ib: a linked track and its insert keep one name, whichever is renamed
  22733. engine.editSong ([] (lynx::Song& s) { s.mixer[3].name = "Drums"; });
  22734. check ("insert_rename_renames_the_track", song().playlistTracks[2].name == "Drums");
  22735. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[2].name = "Beat"; });
  22736. check ("track_rename_renames_the_insert", song().mixer[3].name == "Beat");
  22737. // ---- 4. new content follows: a sample on empty Track 6 makes it an audio track (insert 6)
  22738. engine.editSong ([] (lynx::Song& s) {
  22739. lynx::ChannelDef c;
  22740. c.name = "Guitar";
  22741. c.instrument = lynx::InstrumentKind::audioClip;
  22742. c.samplePath = "/shots/Guitar.wav";
  22743. s.channels.push_back (c);
  22744. lynx::Clip clip;
  22745. clip.kind = lynx::ClipKind::audio;
  22746. clip.channel = (int) s.channels.size() - 1;
  22747. clip.track = 5;
  22748. clip.start = 4 * 4 * lynx::ppq;
  22749. clip.length = 4 * 4 * lynx::ppq;
  22750. s.playlist.push_back (clip);
  22751. });
  22752. check ("new_sample_links_its_track", mode (5) == lynx::PlaylistTrackMode::audio && mixerOf (5) == 6 && song().channels.back().mixerTrack == 6,
  22753. juce::String (mixerOf (5)));
  22754. engine.undo();
  22755. check ("undo_takes_the_clip_and_the_link", mode (5) == lynx::PlaylistTrackMode::unassigned && song().channels.back().name != "Guitar");
  22756. // ---- 5. row heights (round 190ft): short rows keep M / S; from 34 px the volume and pan; tall rows the input
  22757. const auto heights = [&] (std::vector<std::pair<int, int>> rows) {
  22758. engine.editSong ([rows] (lynx::Song& s) {
  22759. for (const auto& [t, h] : rows)
  22760. s.playlistTracks[(std::size_t) t].height = h;
  22761. });
  22762. engine.dispatchPendingMessages();
  22763. };
  22764. heights ({ { 0, 16 }, { 1, 24 }, { 4, 80 } });
  22765. shotRows ("-heights.png", 7);
  22766. {
  22767. const auto r = row (1);
  22768. const auto before = insert2().volume;
  22769. press (juce::Point<int> (20, r.getY() + 12), {}); // (no volume bar on a 24 px row: the press selects)
  22770. check ("short_row_has_no_volume_bar", insert2().volume == before && pl.selectedTracksForSnapshot() == std::vector<int> { 1 });
  22771. press (juce::Point<int> (w - 22, r.getY() + 12), {});
  22772. check ("short_row_m_still_works", insert2().muted);
  22773. press (juce::Point<int> (w - 22, r.getY() + 12), {});
  22774. }
  22775. heights ({ { 0, 0 }, { 1, 0 }, { 4, 0 } });
  22776. // ---- 6. saved: .lynx keeps the switch; the links themselves are FL track modes
  22777. {
  22778. juce::String error;
  22779. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song()), error);
  22780. check ("lynx_round_trip", back && back->linkTracksToMixer && back->playlistTracks.size() > 4 && back->playlistTracks[1].mixerTrack == 2
  22781. && back->playlistTracks[0].mode == lynx::PlaylistTrackMode::instrument, error);
  22782. auto plain = song();
  22783. plain.linkTracksToMixer = false;
  22784. const auto json = lynx::ProjectFile::toJson (plain);
  22785. check ("off_not_saved", ! json.contains ("linkTracksToMixer"));
  22786. }
  22787. // ---- 7. off: FL's headers again (the links stay)
  22788. lynx::PlaylistComponent::answerLinkConfirmation = nullptr;
  22789. pl.runAction ("playlist.linkTracks");
  22790. engine.dispatchPendingMessages();
  22791. check ("switch_off_fl_headers", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow()
  22792. && mode (1) == lynx::PlaylistTrackMode::audio);
  22793. shotRows ("-off-after.png", 7);
  22794. // ---- 8. Settings › Project's switches
  22795. {
  22796. auto panel = lynx::makeSettingsPanel (engine, lynx::SettingsPage::project);
  22797. panel->setSize (760, 720);
  22798. savePng (lynx::shot::snapshot (*panel), prefix + "-settings-project.png");
  22799. }
  22800. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  22801. return allOk;
  22802. }
  22803. bool runFlPlShot (const juce::String& prefix)
  22804. {
  22805. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22806. juce::StringArray report;
  22807. bool allOk = true;
  22808. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  22809. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  22810. allOk = allOk && ok;
  22811. };
  22812. const auto plain = [] (juce::String t) {
  22813. // (without the shortcut column and the mnemonic: the mark, or the " (K)" a translation without the letter gets)
  22814. t = t.upToFirstOccurrenceOf ("\t", false, false);
  22815. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  22816. t = t.substring (0, at);
  22817. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  22818. };
  22819. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  22820. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  22821. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  22822. return it.getItem().subMenu.get();
  22823. return nullptr;
  22824. };
  22825. const auto texts = [&plain] (const juce::PopupMenu& menu, int count) {
  22826. juce::StringArray out;
  22827. for (juce::PopupMenu::MenuItemIterator it (menu); it.next() && out.size() < count;)
  22828. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  22829. return out;
  22830. };
  22831. const auto modelTexts = [] (const std::vector<lynx::fltrackmenus::Entry>& model) {
  22832. juce::StringArray out;
  22833. for (const auto& e : model)
  22834. if (e.kind != lynx::fltrackmenus::Entry::Kind::list)
  22835. out.add (e.kind == lynx::fltrackmenus::Entry::Kind::separator ? juce::String ("-")
  22836. : e.kind == lynx::fltrackmenus::Entry::Kind::caption ? "[" + lynx::tr (e.text) + "]"
  22837. : lynx::tr (e.text));
  22838. return out;
  22839. };
  22840. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  22841. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  22842. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  22843. {
  22844. it.getItem().action();
  22845. return true;
  22846. }
  22847. return false;
  22848. };
  22849. lynx::AudioEngine engine (false);
  22850. lynx::MainComponent ui (engine, false);
  22851. ui.setSize (1600, 900);
  22852. int vox = -1;
  22853. {
  22854. auto song = lynx::Song::makeDefault();
  22855. song.channels.push_back ({});
  22856. song.channels.back().name = "Vox";
  22857. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  22858. song.channels.back().volume = 0.6f;
  22859. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  22860. vox = (int) song.channels.size() - 1;
  22861. lynx::Clip c;
  22862. c.kind = lynx::ClipKind::audio;
  22863. c.channel = vox;
  22864. c.track = 3;
  22865. c.start = 4 * lynx::ppq;
  22866. c.length = 2 * lynx::ppq;
  22867. song.playlist.push_back (c);
  22868. engine.setSong (std::move (song));
  22869. }
  22870. engine.dispatchPendingMessages();
  22871. auto& playlist = ui.getPlaylistForSnapshot();
  22872. // ---- 1. the audio clip menu: Preview first, Automate › Panning / Volume
  22873. {
  22874. const auto menu = playlist.getClipMenuForSnapshot (0);
  22875. juce::PopupMenu::MenuItemIterator it (menu);
  22876. it.next(); // (the "Audio clip" title band)
  22877. it.next();
  22878. check ("clip_menu_preview_first", plain (it.getItem().text) == lynx::tr ("Preview"), it.getItem().text);
  22879. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  22880. check ("clip_menu_automate", automate != nullptr && texts (*automate, 9) == modelTexts (lynx::fltrackmenus::automate()),
  22881. automate != nullptr ? texts (*automate, 9).joinIntoString ("|") : juce::String ("missing"));
  22882. saveMenus (juce::StringArray { "Audio clip menu", "Automate" }, std::vector<juce::PopupMenu> { menu, automate != nullptr ? *automate : juce::PopupMenu() },
  22883. prefix + "-clip-menu.png");
  22884. const auto before = engine.getSong().automations.size();
  22885. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  22886. const auto& song = engine.getSong();
  22887. // (round 190dz: the Levels adjustment's volume multiplier, neutral = 0.5 of its 0…200 % travel)
  22888. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  22889. && song.automations.back().target.param == lynx::leveladjust::volume
  22890. && song.automations.back().target.index == vox && song.automations.back().points.size() == 2
  22891. && song.automations.back().points[1].tick == 2 * lynx::ppq && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  22892. const auto* clip = ok ? &song.playlist.back() : nullptr;
  22893. check ("automate_volume_clip", ok && clip->kind == lynx::ClipKind::automation && clip->track == 3 && clip->start == 4 * lynx::ppq
  22894. && clip->length == 2 * lynx::ppq,
  22895. ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  22896. engine.undo();
  22897. check ("automate_undo", engine.getSong().automations.size() == before);
  22898. // Preview: the clip's own audio (FL plays it through its channel); LYNX renders it for the preview output
  22899. const auto rendered = engine.renderClipAudio (0);
  22900. check ("preview_renders_the_clip", ! rendered.left.empty(), juce::String ((int) rendered.left.size()) + " frames");
  22901. }
  22902. // ---- 2. the Playlist's "+": its menu, a right click's audio track, the corner
  22903. {
  22904. const auto menu = playlist.getAddTrackMenuForSnapshot();
  22905. check ("add_menu_head", texts (menu, 5) == modelTexts (lynx::fltrackmenus::addTrack()), texts (menu, 5).joinIntoString ("|"));
  22906. saveMenus (juce::StringArray { "Playlist +" }, std::vector<juce::PopupMenu> { menu }, prefix + "-add-track-menu.png");
  22907. ui.selectTabForSnapshot (2);
  22908. engine.dispatchPendingMessages();
  22909. auto* button = playlist.getAddTrackButtonForSnapshot();
  22910. check ("add_button_in_corner", button != nullptr && button->isVisible() && button->getX() == 7 && button->getWidth() == 21 && button->getHeight() == 18
  22911. && button->getBottom() <= lynx::PlaylistComponent::headerHeight);
  22912. savePng (playlist.createComponentSnapshot (juce::Rectangle<int> (0, 0, juce::jmin (560, playlist.getWidth()), juce::jmin (260, playlist.getHeight()))),
  22913. prefix + "-playlist-corner.png");
  22914. const auto track = playlist.addAudioTrackNow();
  22915. const auto& song = engine.getSong();
  22916. check ("add_audio_track", track == 0 && song.playlistTracks.size() > 0 && song.playlistTracks[0].mode == lynx::PlaylistTrackMode::audio
  22917. && song.playlistTracks[0].mixerTrack > 0,
  22918. juce::String (track));
  22919. engine.undo();
  22920. }
  22921. // ---- 3. Track mode › Instrument track ›
  22922. {
  22923. const auto menu = playlist.getTrackMenuForSnapshot (5);
  22924. const auto* modes = findSub (menu, lynx::tr ("Track mode"));
  22925. const auto* instrument = modes != nullptr ? findSub (*modes, lynx::tr ("Instrument track")) : nullptr;
  22926. check ("instrument_track_head", instrument != nullptr && texts (*instrument, 4) == modelTexts (lynx::fltrackmenus::instrumentTrack()),
  22927. instrument != nullptr ? texts (*instrument, 4).joinIntoString ("|") : juce::String ("missing"));
  22928. const auto* existing = instrument != nullptr ? findSub (*instrument, lynx::tr ("Use existing channel")) : nullptr;
  22929. check ("use_existing_lists_generators", existing != nullptr && existing->getNumItems() == 5, existing != nullptr ? juce::String (existing->getNumItems()) : juce::String());
  22930. std::vector<juce::PopupMenu> menus { modes != nullptr ? *modes : juce::PopupMenu(), instrument != nullptr ? *instrument : juce::PopupMenu(),
  22931. existing != nullptr ? *existing : juce::PopupMenu() };
  22932. saveMenus (juce::StringArray { "Track mode", "Instrument track", "Use existing channel" }, menus, prefix + "-instrument-track-menu.png");
  22933. lynx::ChannelDef synth;
  22934. synth.name = "Lead";
  22935. synth.instrument = lynx::InstrumentKind::synth;
  22936. const auto channels = engine.getSong().channels.size();
  22937. int made = -1;
  22938. engine.editSong ([&] (lynx::Song& s) { made = lynx::trackmodes::addInstrumentTrack (s, synth, 5); });
  22939. check ("instrument_track_new_channel", made == (int) channels && engine.getSong().playlistTracks.size() > 5
  22940. && engine.getSong().playlistTracks[5].channel == made);
  22941. engine.undo();
  22942. }
  22943. // ---- 4. the Channel rack menu: Assign to new instrument track / Unassign
  22944. {
  22945. auto& rack = ui.getRackForSnapshot();
  22946. const auto menu = rack.getChannelMenuForSnapshot (1);
  22947. saveMenus (juce::StringArray { "Channel menu" }, std::vector<juce::PopupMenu> { menu }, prefix + "-channel-menu.png");
  22948. check ("assign_runs", click (menu, lynx::tr ("Assign to new instrument track")));
  22949. const auto tracks = lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1);
  22950. check ("assign_first_free_track", tracks == std::vector<int> { 0 }, juce::String (tracks.empty() ? -1 : tracks.front()));
  22951. const auto again = rack.getChannelMenuForSnapshot (1);
  22952. check ("unassign_offered", click (again, lynx::tr ("Unassign from instrument track")) && lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1).empty());
  22953. bool greyed = false;
  22954. const auto voxMenu = rack.getChannelMenuForSnapshot (vox);
  22955. for (juce::PopupMenu::MenuItemIterator it (voxMenu); it.next();)
  22956. if (plain (it.getItem().text) == plain (lynx::tr ("Assign to new instrument track")))
  22957. greyed = ! it.getItem().isEnabled;
  22958. check ("assign_greyed_for_audio_clip_channel", greyed);
  22959. }
  22960. // ---- 5. Tools › One-click audio recording
  22961. std::fprintf (stderr, "flplshot: tools\n");
  22962. {
  22963. const auto names = ui.getMenuNamesForSnapshot();
  22964. const auto tools = ui.getMenuForSnapshot (names.indexOf (lynx::tr ("Tools")));
  22965. const auto* oneClick = findSub (tools, lynx::tr ("One-click audio recording"));
  22966. check ("one_click_submenu", oneClick != nullptr && texts (*oneClick, 3) == modelTexts (lynx::fltrackmenus::oneClickRecording()),
  22967. oneClick != nullptr ? texts (*oneClick, 3).joinIntoString ("|") : juce::String ("missing"));
  22968. saveMenus (juce::StringArray { "Tools", "One-click audio recording" }, std::vector<juce::PopupMenu> { tools, oneClick != nullptr ? *oneClick : juce::PopupMenu() },
  22969. prefix + "-tools-one-click.png");
  22970. const auto plan = lynx::oneclick::plan (engine.getSong(), {}, 2, lynx::oneclick::Into::playlist);
  22971. check ("one_click_plan", plan.insert == 2 && plan.armInsert && plan.askInput && plan.songMode);
  22972. }
  22973. // ---- 6. Mixer › Disk recording › Latency compensation
  22974. {
  22975. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  22976. const auto menu = strips.buildMenu (1);
  22977. const auto* disk = findSub (menu, lynx::tr ("Disk recording"));
  22978. int after = -1, at = -1, i = 0;
  22979. bool ticked = false;
  22980. if (disk != nullptr)
  22981. for (juce::PopupMenu::MenuItemIterator it (*disk); it.next(); ++i)
  22982. {
  22983. if (plain (it.getItem().text) == plain (lynx::tr ("Auto-create audio clip (the rendered files go on the Playlist)")))
  22984. after = i;
  22985. if (plain (it.getItem().text) == plain (lynx::tr ("Line up recordings with the audio latency")))
  22986. {
  22987. at = i;
  22988. ticked = it.getItem().isTicked;
  22989. }
  22990. }
  22991. check ("latency_comp_item", disk != nullptr && after >= 0 && at == after + 1 && ticked && engine.getRecordOptions().latencyCompensation,
  22992. juce::String (after) + " " + juce::String (at));
  22993. saveMenus (juce::StringArray { "Disk recording" }, std::vector<juce::PopupMenu> { disk != nullptr ? *disk : juce::PopupMenu() },
  22994. prefix + "-disk-recording.png");
  22995. check ("latency_comp_toggles", disk != nullptr && click (*disk, lynx::tr ("Line up recordings with the audio latency")) && ! engine.getRecordOptions().latencyCompensation);
  22996. }
  22997. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  22998. return allOk;
  22999. }
  23000. // --flclipshot (round 190dz): see the dispatch above
  23001. // a menu as JUCE lays it out with explicit column breaks (PopupMenu::addColumnBreak): the columns side by side on
  23002. // one menu background; custom items (the title band) are painted by their own component
  23003. static juce::Image columnMenuImage (const juce::PopupMenu& menu)
  23004. {
  23005. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  23006. const auto border = lf.getPopupMenuBorderSize();
  23007. struct Row
  23008. {
  23009. const juce::PopupMenu::Item* item;
  23010. int height;
  23011. };
  23012. std::vector<std::vector<Row>> columns (1);
  23013. std::vector<int> widths (1, 160);
  23014. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23015. {
  23016. const auto& item = it.getItem();
  23017. int w = 0, h = 0;
  23018. if (item.customComponent != nullptr)
  23019. item.customComponent->getIdealSize (w, h);
  23020. else
  23021. {
  23022. lf.getIdealPopupMenuItemSize (item.text.upToFirstOccurrenceOf ("\t", false, false), item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  23023. if (item.isSectionHeader)
  23024. h += h / 2; // as JUCE does
  23025. if (item.text.containsChar ('\t'))
  23026. w += 90;
  23027. }
  23028. columns.back().push_back ({ &item, h });
  23029. widths.back() = juce::jmax (widths.back(), w + 10);
  23030. if (item.shouldBreakAfter)
  23031. {
  23032. columns.emplace_back();
  23033. widths.push_back (160);
  23034. }
  23035. }
  23036. int width = 0, height = 0;
  23037. for (std::size_t c = 0; c < columns.size(); ++c)
  23038. {
  23039. width += widths[c];
  23040. int h = 2 * border;
  23041. for (const auto& row : columns[c])
  23042. h += row.height;
  23043. height = juce::jmax (height, h);
  23044. }
  23045. auto image = lynx::shot::canvas (width, height);
  23046. juce::Graphics g (image);
  23047. lynx::shot::logical (g);
  23048. lf.drawPopupMenuBackground (g, width, height);
  23049. int x = 0;
  23050. for (std::size_t c = 0; c < columns.size(); ++c)
  23051. {
  23052. int y = border;
  23053. for (const auto& row : columns[c])
  23054. {
  23055. const auto& item = *row.item;
  23056. const juce::Rectangle<int> r (x, y, widths[c], row.height);
  23057. if (item.customComponent != nullptr)
  23058. {
  23059. juce::Graphics::ScopedSaveState state (g);
  23060. g.setOrigin (r.getPosition());
  23061. item.customComponent->setSize (r.getWidth(), r.getHeight());
  23062. item.customComponent->paintEntireComponent (g, false);
  23063. }
  23064. else if (item.isSectionHeader)
  23065. lf.drawPopupMenuSectionHeader (g, r, item.text);
  23066. else
  23067. {
  23068. juce::Graphics::ScopedSaveState state (g);
  23069. g.setOrigin (r.getPosition());
  23070. lf.drawPopupMenuItem (g, r.withPosition (0, 0), item.isSeparator, item.isEnabled, false, item.isTicked, item.subMenu != nullptr,
  23071. item.text.upToFirstOccurrenceOf ("\t", false, false), item.text.fromFirstOccurrenceOf ("\t", false, false),
  23072. item.image.get(), nullptr);
  23073. }
  23074. y += row.height;
  23075. }
  23076. x += widths[c];
  23077. if (c + 1 < columns.size()) // (JUCE's column separator)
  23078. {
  23079. g.setColour (lf.findColour (juce::PopupMenu::textColourId).withAlpha (0.15f));
  23080. g.fillRect (x - 1, border, 1, height - 2 * border);
  23081. }
  23082. }
  23083. return image;
  23084. }
  23085. // --genpresetshot (round 190fs): see the dispatch above
  23086. bool runGenPresetShot (const juce::String& prefix)
  23087. {
  23088. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23089. juce::StringArray report;
  23090. bool allOk = true;
  23091. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  23092. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  23093. allOk = allOk && ok;
  23094. };
  23095. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  23096. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  23097. };
  23098. const auto plain = [] (juce::String t) { return t.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&"); };
  23099. const auto texts = [&plain] (const juce::PopupMenu& menu) {
  23100. juce::StringArray out;
  23101. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23102. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  23103. return out;
  23104. };
  23105. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  23106. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23107. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  23108. {
  23109. it.getItem().action();
  23110. return true;
  23111. }
  23112. return false;
  23113. };
  23114. const auto sameSound = [] (const lynx::ChannelDef& a, const lynx::ChannelDef& b) { return lynx::genpresets::sameSound (a, b); };
  23115. lynx::AudioEngine engine (false);
  23116. const auto& fl = lynx::flStudioAccess();
  23117. auto dx = lynx::natives::makeChannel (lynx::InstrumentKind::dx10, fl);
  23118. auto osc = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, fl);
  23119. check ("channels_made", dx.has_value() && osc.has_value());
  23120. if (! dx || ! osc)
  23121. {
  23122. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  23123. return false;
  23124. }
  23125. engine.editSong ([&] (lynx::Song& s) {
  23126. s.channels.clear();
  23127. s.channels.push_back (*dx);
  23128. s.channels.back().mixerTrack = 1;
  23129. s.channels.push_back (*osc);
  23130. s.channels.back().mixerTrack = 2;
  23131. lynx::ChannelDef synth;
  23132. synth.instrument = lynx::InstrumentKind::synth;
  23133. synth.name = "Synth";
  23134. synth.mixerTrack = 3;
  23135. s.channels.push_back (synth);
  23136. });
  23137. const auto channel = [&engine] (int i) { return engine.getSong().channels[(std::size_t) i]; };
  23138. // ---- 1. Fruity DX10: the preset box before and after "Save preset..."
  23139. {
  23140. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  23141. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  23142. auto menu = lynx::channelPresetMenu (*frame);
  23143. check ("dx10_menu", menu.has_value());
  23144. const auto before = menu ? texts (*menu) : juce::StringArray();
  23145. check ("dx10_menu_has_save", before.contains (lynx::tr ("Save preset...")) && before.contains (lynx::tr ("Show the presets folder"))
  23146. && ! before.contains ("[" + lynx::tr ("Your presets") + "]"), before.joinIntoString ("|"));
  23147. if (menu)
  23148. saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu-before.png");
  23149. // a sound of its own: the bank's 4th preset, then a knob moved (a sound no factory preset has)
  23150. const auto mine = [&] {
  23151. auto c = channel (0);
  23152. if (auto b = lynx::banks::withPreset (c, 3))
  23153. c = *b;
  23154. if (! c.pluginState.empty())
  23155. c.pluginState[c.pluginState.size() / 2] ^= 0x5a;
  23156. return c;
  23157. }();
  23158. engine.editSong ([&] (lynx::Song& s) { s.channels[0] = mine; });
  23159. check ("dx10_saved", lynx::channelPresetSave (*frame, "My FM Bell"));
  23160. const auto file = lynx::genpresetui::folderFor (lynx::InstrumentKind::dx10).getChildFile ("My FM Bell.lynxpreset");
  23161. check ("dx10_file", file.existsAsFile() && lynx::genpresetui::isPresetFile (file), file.getFullPathName());
  23162. check ("dx10_box_shows_it", lynx::channelPresetName (*frame) == "My FM Bell", lynx::channelPresetName (*frame));
  23163. menu = lynx::channelPresetMenu (*frame);
  23164. const auto after = menu ? texts (*menu) : juce::StringArray();
  23165. check ("dx10_menu_your_presets", after.contains ("[" + lynx::tr ("Your presets") + "]") && after.contains ("My FM Bell")
  23166. && after.contains (lynx::tr ("Delete preset \"{0}\"", { "My FM Bell" })), after.joinIntoString ("|"));
  23167. if (menu)
  23168. saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu.png");
  23169. shoot (*frame, "dx10-window");
  23170. // another sound, then the user's preset from the menu: the saved sound back, one undo step, project changed
  23171. if (auto other = lynx::banks::withPreset (channel (0), 0))
  23172. engine.editSong ([&] (lynx::Song& s) { s.channels[0] = *other; });
  23173. check ("dx10_other_sound", ! sameSound (channel (0), mine));
  23174. engine.markSaved();
  23175. menu = lynx::channelPresetMenu (*frame);
  23176. check ("dx10_load_click", menu.has_value() && click (*menu, "My FM Bell"));
  23177. check ("dx10_loaded_identical", sameSound (channel (0), mine) && channel (0).pluginState == mine.pluginState);
  23178. check ("dx10_loaded_name_and_insert", channel (0).name == "My FM Bell" && channel (0).mixerTrack == 1,
  23179. juce::String::fromUTF8 (channel (0).name.c_str()));
  23180. check ("dx10_project_changed", engine.isModified());
  23181. engine.undo();
  23182. check ("dx10_one_undo_step", ! sameSound (channel (0), mine));
  23183. engine.redo();
  23184. check ("dx10_redo", sameSound (channel (0), mine));
  23185. // the Browser: a new channel with the preset's generator, sound and name
  23186. juce::String error;
  23187. const auto count = engine.getSong().channels.size();
  23188. check ("browser_new_channel", lynx::genpresetui::addChannel (engine, file, error) && engine.getSong().channels.size() == count + 1, error);
  23189. const auto added = engine.getSong().channels.back();
  23190. check ("browser_channel_sound", added.instrument == lynx::InstrumentKind::dx10 && sameSound (added, mine) && added.name == "My FM Bell");
  23191. engine.undo();
  23192. check ("browser_channel_undo", engine.getSong().channels.size() == count);
  23193. }
  23194. // ---- 2. 3x Osc: save, the menu, delete
  23195. {
  23196. auto frame = lynx::makeChannelFrame (engine, 1, 0);
  23197. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  23198. check ("3xosc_saved", lynx::channelPresetSave (*frame, "Wide Saw Lead") && lynx::channelPresetSave (*frame, "Sub Bass"));
  23199. auto menu = lynx::channelPresetMenu (*frame);
  23200. const auto items = menu ? texts (*menu) : juce::StringArray();
  23201. check ("3xosc_menu", items.contains ("Wide Saw Lead") && items.contains ("Sub Bass") && items.contains (lynx::tr ("Save preset...")),
  23202. items.joinIntoString ("|"));
  23203. if (menu)
  23204. saveMenus (juce::StringArray { "3x Osc presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-3xosc-menu.png");
  23205. shoot (*frame, "3xosc-window");
  23206. check ("3xosc_delete", menu.has_value() && click (*menu, lynx::tr ("Delete preset \"{0}\"", { "Sub Bass" })));
  23207. check ("3xosc_deleted", lynx::genpresetui::userPresets (lynx::InstrumentKind::threeosc).size() == 1
  23208. && ! lynx::genpresetui::folderFor (lynx::InstrumentKind::threeosc).getChildFile ("Sub Bass.lynxpreset").exists());
  23209. menu = lynx::channelPresetMenu (*frame);
  23210. const auto left = menu ? texts (*menu) : juce::StringArray();
  23211. check ("3xosc_menu_after_delete", left.contains ("Wide Saw Lead") && ! left.contains ("Sub Bass"), left.joinIntoString ("|"));
  23212. }
  23213. // ---- 3. LYNX's synth: its "Presets..." box
  23214. {
  23215. engine.editSong ([] (lynx::Song& s) { s.channels[2].synth.cutoff = 777.0f; });
  23216. auto frame = lynx::makeChannelFrame (engine, 2, 0);
  23217. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  23218. check ("synth_saved", lynx::channelPresetSave (*frame, "Dark Pad"));
  23219. const auto menu = lynx::channelPresetMenu (*frame);
  23220. const auto items = menu ? texts (*menu) : juce::StringArray();
  23221. check ("synth_menu", items.contains ("Dark Pad") && items.contains (lynx::tr ("Save preset...")) && items.contains (lynx::tr ("Show the presets folder")),
  23222. items.joinIntoString ("|"));
  23223. if (menu)
  23224. saveMenus (juce::StringArray { "Synth presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-synth-menu.png");
  23225. const auto saved = lynx::genpresetui::read (lynx::genpresetui::folderFor (lynx::InstrumentKind::synth).getChildFile ("Dark Pad.lynxpreset"));
  23226. check ("synth_file", saved.has_value() && saved->sound.synth.cutoff == 777.0f);
  23227. }
  23228. // ---- 4. the name box (the hosted plugins' and the effects' "Save preset" box)
  23229. {
  23230. auto box = lynx::genpresetui::makeNameBox ("My FM Bell");
  23231. box->setSize (juce::jmax (360, box->getWidth()), juce::jmax (150, box->getHeight()));
  23232. shoot (*box, "save-name-box");
  23233. check ("name_box", box->getTextEditorContents ("name") == "My FM Bell");
  23234. }
  23235. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  23236. return allOk;
  23237. }
  23238. // --flfixshot (round 190ey): see the dispatch above
  23239. bool runFlFixShot (const juce::String& prefix)
  23240. {
  23241. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23242. juce::StringArray report;
  23243. bool allOk = true;
  23244. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  23245. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  23246. allOk = allOk && ok;
  23247. };
  23248. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  23249. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  23250. };
  23251. const auto plain = [] (juce::String t) {
  23252. t = t.upToFirstOccurrenceOf ("\t", false, false);
  23253. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  23254. t = t.substring (0, at);
  23255. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  23256. };
  23257. const auto texts = [&plain] (const juce::PopupMenu& menu) {
  23258. juce::StringArray out;
  23259. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23260. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  23261. return out;
  23262. };
  23263. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  23264. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23265. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  23266. return it.getItem().subMenu.get();
  23267. return nullptr;
  23268. };
  23269. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  23270. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23271. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  23272. {
  23273. it.getItem().action();
  23274. return true;
  23275. }
  23276. return false;
  23277. };
  23278. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flfix-samples");
  23279. folder.createDirectory();
  23280. const auto writeWav = [] (const juce::File& file, double rate, int frames, double hz) {
  23281. juce::AudioBuffer<float> buffer (1, frames);
  23282. for (int i = 0; i < frames; ++i)
  23283. buffer.setSample (0, i, (float) (0.8 * std::sin (juce::MathConstants<double>::twoPi * hz * i / rate) * std::exp (-i / (rate * 0.12))));
  23284. file.deleteFile();
  23285. juce::WavAudioFormat wav;
  23286. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), rate, 1, 16, {}, 0)))
  23287. out->writeFromAudioSampleBuffer (buffer, 0, frames);
  23288. return file;
  23289. };
  23290. // ---- 1. the Sampler page (SMP-1 / 4 / 5 / 7, CTL-4)
  23291. {
  23292. lynx::AudioEngine engine (false);
  23293. const auto clap = writeWav (folder.getChildFile ("Basic 808 Clap.wav"), 44100.0, 11600, 180.0);
  23294. const auto loop48 = writeWav (folder.getChildFile ("Loop 48k.wav"), 48000.0, 48000, 220.0);
  23295. engine.editSong ([&] (lynx::Song& s) {
  23296. if (s.channels.empty())
  23297. s.channels.resize (1);
  23298. lynx::audioclips::loadSampleInto (s.channels[0], clap.getFullPathName().toStdString(), "808 Clap");
  23299. });
  23300. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  23301. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  23302. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  23303. frame->createComponentSnapshot (frame->getLocalBounds());
  23304. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  23305. auto& f = *frame;
  23306. lynx::samplerPageTurn (f, "show", 0.0);
  23307. const auto rate = engine.getTransport().sampleRate.load();
  23308. check ("resample_greyed_at_project_rate", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 44100.0) < 0.5 ? "0" : "1"), juce::String (rate));
  23309. check ("load_regions_greyed_without_regions", lynx::samplerPageQuery (f, "loadRegions") == "0");
  23310. check ("load_markers_greyed_without_markers", lynx::samplerPageQuery (f, "loadMarkers") == "0");
  23311. check ("bit_depth_16", lynx::samplerPageQuery (f, "corner") == "16", lynx::samplerPageQuery (f, "corner"));
  23312. check ("wave_hint_summary", lynx::samplerPageQuery (f, "waveHint").startsWith ("44100Hz, 16Bit int mono, 0:263"), lynx::samplerPageQuery (f, "waveHint"));
  23313. shoot (f, "sampler-44k");
  23314. // SMP-5: MUL's text
  23315. lynx::samplerPageTurn (f, "mul", 800.0);
  23316. check ("mul_text", lynx::samplerPageQuery (f, "mulText") == "105.70%", lynx::samplerPageQuery (f, "mulText"));
  23317. lynx::samplerPageTurn (f, "mul", 0.0);
  23318. // SMP-4: CROSSFADE on a loopless sample: Use loop points on, the loop = the whole sample, the box reads 32
  23319. engine.editSong ([] (lynx::Song& s) { s.channels[0].sampler.useLoopPoints = false; });
  23320. lynx::samplerPageTurn (f, "crossfade", 120.0);
  23321. check ("crossfade_loops_whole_sample", sampler().useLoopPoints && sampler().loopStart == 0 && sampler().loopEnd == 11599,
  23322. juce::String (sampler().loopStart) + ".." + juce::String (sampler().loopEnd));
  23323. check ("bit_depth_32_precomputed", lynx::samplerPageQuery (f, "corner") == "32", lynx::samplerPageQuery (f, "corner"));
  23324. frame->createComponentSnapshot (frame->getLocalBounds());
  23325. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  23326. shoot (f, "sampler-crossfade-red-loop");
  23327. lynx::samplerPageTurn (f, "crossfade", 0.0);
  23328. // SMP-3: a loop set with END alone, drawn red (FL: 0..276)
  23329. engine.editSong ([] (lynx::Song& s) {
  23330. s.channels[0].sampler.loopStart = 0;
  23331. s.channels[0].sampler.loopEnd = 2400;
  23332. });
  23333. lynx::samplerPageTurn (f, "show", 0.0);
  23334. shoot (f, "sampler-end-loop-red");
  23335. // round 190gw (live check 190gu B3): the waveform menu's Spectrum view / Multichannel waveform view, on a stereo
  23336. // clap-like noise burst (left and right differ) with no loop, as FL's shot
  23337. {
  23338. const auto noisy = folder.getChildFile ("Noise Clap.wav");
  23339. juce::AudioBuffer<float> b (2, 44100);
  23340. juce::Random random (190);
  23341. for (int i = 0; i < b.getNumSamples(); ++i)
  23342. for (int c = 0; c < 2; ++c)
  23343. b.setSample (c, i, (float) ((random.nextFloat() * 2.0f - 1.0f) * 0.9 * std::exp (-i / (44100.0 * (c == 0 ? 0.10 : 0.18)))
  23344. * (i > 1500 * c ? 1.0 : 0.15)));
  23345. noisy.deleteFile();
  23346. juce::WavAudioFormat wav;
  23347. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (noisy.createOutputStream().release(), 44100.0, 2, 16, {}, 0)))
  23348. out->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  23349. const auto before = engine.getSong().channels[0];
  23350. engine.editSong ([&] (lynx::Song& s) {
  23351. s.channels[0].samplePath = noisy.getFullPathName().toStdString();
  23352. s.channels[0].sampler.loopStart = s.channels[0].sampler.loopEnd = -1;
  23353. s.channels[0].sampler.useLoopPoints = false;
  23354. });
  23355. lynx::samplerPageTurn (f, "show", 0.0);
  23356. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
  23357. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  23358. lynx::samplerpage::waveViews().spectrum = true;
  23359. lynx::samplerPageTurn (f, "show", 0.0);
  23360. shoot (f, "sampler-spectrum-view");
  23361. lynx::samplerpage::waveViews() = { false, true };
  23362. lynx::samplerPageTurn (f, "show", 0.0);
  23363. shoot (f, "sampler-multichannel-view");
  23364. lynx::samplerpage::waveViews() = {};
  23365. engine.editSong ([&before] (lynx::Song& s) { s.channels[0] = before; });
  23366. lynx::samplerPageTurn (f, "show", 0.0);
  23367. frame->createComponentSnapshot (frame->getLocalBounds());
  23368. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  23369. }
  23370. // SMP-7: the waveform menu
  23371. const auto waveMenu = lynx::samplerWaveMenu (f);
  23372. juce::StringArray expected { lynx::tr ("Reload"), lynx::tr ("Save as..."), lynx::tr ("Locate file"), lynx::tr ("Copy audio to clipboard"),
  23373. lynx::tr ("Paste audio from clipboard"), "-", lynx::tr ("Edit in audio editor"),
  23374. lynx::tr ("Edit in pitch corrector"), lynx::tr ("Edit in time warper"), "-", // (round 190gw)
  23375. lynx::tr ("Open in new sampler channel"), lynx::tr ("Open in new Fruity Granulizer channel"),
  23376. lynx::tr ("Open in new Fruity Slicer channel"), lynx::tr ("Open in new Slicex channel"), "-", // (round 190gk)
  23377. lynx::tr ("Detect tempo") };
  23378. if (lynx::fileProperties) // (round 190gk: Windows only)
  23379. expected.add (lynx::tr ("Get properties"));
  23380. expected.addArray (juce::StringArray { "-", lynx::tr ("Spectrum view"), lynx::tr ("Multichannel waveform view") }); // (round 190gw)
  23381. check ("wave_menu_items", waveMenu.has_value() && texts (*waveMenu) == expected, waveMenu.has_value() ? texts (*waveMenu).joinIntoString ("|") : juce::String ("none"));
  23382. if (waveMenu.has_value())
  23383. saveMenus (juce::StringArray { "Sampler waveform" }, std::vector<juce::PopupMenu> { *waveMenu }, prefix + "-wave-menu.png");
  23384. check ("copy_audio_to_clipboard", waveMenu.has_value() && click (*waveMenu, lynx::tr ("Copy audio to clipboard"))
  23385. && lynx::audioclipboard::editor().frames() == 11600);
  23386. // SMP-1: a 48 kHz sample in this project: Resample enabled
  23387. lynx::samplerPageTurn (f, "show", 0.0);
  23388. engine.editSong ([&] (lynx::Song& s) { s.channels[0].samplePath = loop48.getFullPathName().toStdString(); });
  23389. lynx::samplerPageTurn (f, "show", 0.0);
  23390. check ("resample_enabled_48k", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 48000.0) < 0.5 ? "0" : "1"), juce::String (rate));
  23391. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
  23392. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  23393. shoot (f, "sampler-48k");
  23394. // CTL-4: Remove sample renames the channel "Sampler"
  23395. lynx::samplerFileRowPress (f, 3);
  23396. check ("remove_sample_renames", engine.getSong().channels[0].name == "Sampler" && engine.getSong().channels[0].samplePath.empty(),
  23397. juce::String::fromUTF8 (engine.getSong().channels[0].name.c_str()));
  23398. lynx::samplerPageTurn (f, "show", 0.0);
  23399. check ("no_sample_content_greyed", lynx::samplerPageQuery (f, "keepOnDisk") == "0" && lynx::samplerPageQuery (f, "resample") == "0");
  23400. shoot (f, "sampler-removed");
  23401. }
  23402. // ---- 2. the Multilink button's menu with multilink off (CTL-1)
  23403. lynx::AudioEngine engine (false);
  23404. lynx::MainComponent ui (engine, false);
  23405. ui.setSize (1600, 900);
  23406. {
  23407. using lynx::AutomationTarget;
  23408. using lynx::AutomationTargetKind;
  23409. engine.editSong ([] (lynx::Song& s) {
  23410. if (s.channels.empty())
  23411. s.channels.resize (1);
  23412. s.channels[0].name = "808 Kick";
  23413. });
  23414. engine.setMultilink (false);
  23415. engine.noteTweaked ({ AutomationTargetKind::channelVolume, 0 });
  23416. engine.noteTweaked ({ AutomationTargetKind::channelPan, 0 });
  23417. const auto menu = ui.getMultilinkMenuForSnapshot();
  23418. juce::PopupMenu::MenuItemIterator first (menu);
  23419. first.next();
  23420. const auto caption = first.getItem().text;
  23421. bool columnBreak = false, lynxLines = false;
  23422. juce::String rightCaption;
  23423. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23424. {
  23425. if (columnBreak && rightCaption.isEmpty() && it.getItem().isSectionHeader)
  23426. rightCaption = it.getItem().text;
  23427. columnBreak = columnBreak || it.getItem().shouldBreakAfter;
  23428. lynxLines = lynxLines || it.getItem().text == lynx::tr ("Link to controller");
  23429. }
  23430. check ("ml_off_left_column_named", first.getItem().isSectionHeader && caption == lynx::describeAutomationTarget (engine, { AutomationTargetKind::channelPan, 0 }), caption);
  23431. check ("ml_off_two_columns", columnBreak && rightCaption == lynx::tr ("Last 2 tweaked parameters"), rightCaption);
  23432. check ("ml_off_no_lynx_greyed_lines", ! lynxLines);
  23433. savePng (columnMenuImage (menu), prefix + "-multilink-off-menu.png");
  23434. }
  23435. // ---- 3. the Playlist (PL-1 / 2 / 3 / 6 / 7 / 8)
  23436. auto& playlist = ui.getPlaylistForSnapshot();
  23437. {
  23438. auto song = lynx::Song::makeDefault();
  23439. lynx::ChannelDef bass;
  23440. bass.name = "Amount Too - Bass";
  23441. bass.instrument = lynx::InstrumentKind::audioClip;
  23442. bass.samplePath = writeWav (folder.getChildFile ("bass.wav"), 44100.0, 88200, 82.0).getFullPathName().toStdString();
  23443. bass.misc.levels.volume = 1.468f;
  23444. song.channels.push_back (bass);
  23445. lynx::Clip c;
  23446. c.kind = lynx::ClipKind::audio;
  23447. c.channel = (int) song.channels.size() - 1;
  23448. c.track = 3;
  23449. c.start = 4 * lynx::ppq;
  23450. c.length = 2 * lynx::ppq;
  23451. song.playlist.push_back (c);
  23452. engine.setSong (std::move (song));
  23453. }
  23454. engine.dispatchPendingMessages();
  23455. const auto clipIndex = (int) engine.getSong().playlist.size() - 1;
  23456. {
  23457. const auto menu = playlist.getClipMenuForSnapshot (clipIndex);
  23458. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  23459. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  23460. const auto& song = engine.getSong();
  23461. const auto made = (int) song.automations.size() - 1;
  23462. check ("automate_makes_current_clip", made >= 0 && playlist.brush.kind == lynx::ClipKind::automation && playlist.brush.index == made,
  23463. juce::String (playlist.brush.index));
  23464. // (PL-2: Levels VOL 147 %, FL's clip plays unity)
  23465. check ("automate_volume_unity", made >= 0 && song.automations.back().points[0].value == 0.5f
  23466. && lynx::lasttweak::valueText (song, song.automations.back().target, song.automations.back().points[0].value) == "100% 0.0dB 1.00");
  23467. const auto again = playlist.getClipMenuForSnapshot (clipIndex);
  23468. const auto* automate2 = findSub (again, lynx::tr ("Automate"));
  23469. check ("automate_second_is_2", automate2 != nullptr && click (*automate2, lynx::tr ("Volume"))
  23470. && juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()).endsWith (" #2"),
  23471. juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()));
  23472. // PL-7: Fade in / out curve
  23473. const auto* fadeIn = findSub (menu, lynx::tr ("Fade in curve"));
  23474. const auto* fadeOut = findSub (menu, lynx::tr ("Fade out curve"));
  23475. const juce::StringArray curve { lynx::tr ("Reset"), lynx::tr ("Normalize"), lynx::tr ("Normalize selection as a group"), lynx::tr ("Create crossfade"),
  23476. lynx::tr ("Manual"), "[" + lynx::tr ("Declicker") + "]", lynx::tr ("Automatic"), lynx::tr ("Disabled"), lynx::tr ("Enabled"),
  23477. "[" + lynx::tr ("Curve shape") + "]", lynx::tr ("Smooth curve"), lynx::tr ("Single curve") };
  23478. check ("fade_curve_submenus", fadeIn != nullptr && fadeOut != nullptr && texts (*fadeIn) == curve && texts (*fadeOut) == curve,
  23479. fadeIn != nullptr ? texts (*fadeIn).joinIntoString ("|") : juce::String ("missing"));
  23480. if (fadeOut != nullptr)
  23481. saveMenus (juce::StringArray { "Audio clip menu", "Fade out curve" }, std::vector<juce::PopupMenu> { menu, *fadeOut }, prefix + "-fade-curve-menu.png");
  23482. // PL-8: Detect tempo is one item now
  23483. bool detectItem = false;
  23484. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23485. if (plain (it.getItem().text) == plain (lynx::tr ("Detect tempo")))
  23486. detectItem = it.getItem().subMenu == nullptr && it.getItem().action != nullptr;
  23487. check ("detect_tempo_item", detectItem);
  23488. // PL-3: Preview through the channel; transport start ends it
  23489. check ("preview_through_channel", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  23490. engine.play();
  23491. check ("preview_stops_on_transport", ! engine.isClipPreviewing());
  23492. engine.stop();
  23493. check ("preview_again_then_stop", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  23494. engine.stop();
  23495. check ("preview_stops_on_stop", ! engine.isClipPreviewing());
  23496. }
  23497. // PL-8: the dialog
  23498. {
  23499. lynx::ui::TempoDetectionRequest r;
  23500. r.name = "Amount Too - Bass";
  23501. // (a drum-like loop at 117.5 BPM, 100 beats as in FL's dialog: clicks on every beat)
  23502. {
  23503. auto beats = std::make_shared<lynx::SampleData>();
  23504. beats->sampleRate = 44100.0;
  23505. const auto period = 44100.0 * 60.0 / 117.5;
  23506. beats->left.assign ((std::size_t) std::llround (period * 100.0), 0.0f);
  23507. for (int b = 0; b < 100; ++b)
  23508. for (int i = 0; i < 2000; ++i)
  23509. if (const auto at = (std::size_t) std::llround (b * period) + (std::size_t) i; at < beats->left.size())
  23510. beats->left[at] = (float) (0.9 * std::sin (i * 0.09) * std::exp (-i / 400.0));
  23511. r.sample = beats;
  23512. }
  23513. r.projectBpm = 100.0;
  23514. double applied = -1.0;
  23515. r.apply = [&applied] (double beats) { applied = beats; };
  23516. auto panel = lynx::ui::makeTempoDetectionPanel (r);
  23517. panel->setSize (panel->getWidth(), panel->getHeight());
  23518. shoot (*panel, "tempo-detection");
  23519. report.add ("tempo dialog title: " + lynx::ui::tempoDetectionTitle (r.name));
  23520. const auto project = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 3);
  23521. const auto seconds = (double) r.sample->frames() / r.sample->sampleRate; // (100 beats at 117.5 BPM)
  23522. check ("tempo_project_button", std::abs (applied - seconds * 100.0 / 60.0) < 1.0e-6, project + " -> " + juce::String (applied));
  23523. const auto none = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 2);
  23524. check ("tempo_no_tempo_button", applied == 0.0, none);
  23525. }
  23526. // ---- 4. issue #152's question (ISS152-1): FL's message with "Remember my choice"
  23527. {
  23528. auto box = lynx::makeFlMessageDialog ({ lynx::tr ("External input"),
  23529. 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?"),
  23530. { lynx::tr ("Yes"), lynx::tr ("No") }, true });
  23531. shoot (*box, "external-input-question");
  23532. bool listed = false;
  23533. for (const auto& m : lynx::messages::all())
  23534. listed = listed || juce::String (m.id) == "RecAutoSwitchExternalInput";
  23535. check ("external_input_in_manage_messages", listed);
  23536. }
  23537. // ---- 5. round 190gk: FL's Start in the render window; the Sampler's "Open in new Fruity Slicer / Slicex channel";
  23538. // a Gross Beat slot picked by MIDI becomes its parameter
  23539. {
  23540. lynx::AudioEngine engine (false);
  23541. auto panel = lynx::makeClipRenderPanel (engine);
  23542. panel->setSize (panel->getWidth() > 0 ? panel->getWidth() : 640, panel->getHeight() > 0 ? panel->getHeight() : 480);
  23543. juce::String button;
  23544. for (auto* c : panel->getChildren())
  23545. if (auto* b = dynamic_cast<juce::TextButton*> (c); b != nullptr && b->isVisible() && b->getTooltip() == lynx::tr ("Start rendering"))
  23546. button = b->getButtonText();
  23547. check ("render_button_start", button == lynx::trc ("@render button: Start") && button == "Start", button);
  23548. shoot (*panel, "fltails190gk-render-start");
  23549. const auto clap = writeWav (folder.getChildFile ("Slice me.wav"), 44100.0, 44100, 140.0);
  23550. engine.editSong ([] (lynx::Song& s) {
  23551. s.channels.resize (2);
  23552. s.channels[0] = {};
  23553. s.channels[0].instrument = lynx::InstrumentKind::fruityslicer;
  23554. s.channels[0].name = "Fruity Slicer";
  23555. s.channels[1] = {};
  23556. s.channels[1].instrument = lynx::InstrumentKind::slicex;
  23557. s.channels[1].name = "Slicex";
  23558. });
  23559. const auto locate = [] (int index) {
  23560. return [index] (lynx::Song& s) -> lynx::ChannelDef* { return index < (int) s.channels.size() ? &s.channels[(std::size_t) index] : nullptr; };
  23561. };
  23562. lynx::loadSampleWhenOpened (0, clap.getFullPathName());
  23563. auto slicer = lynx::makeFruitySlicerEditor (engine, locate (0), 0);
  23564. const auto& fs = engine.getSong().channels[0];
  23565. check ("open_in_new_fruity_slicer", fs.samplePath == clap.getFullPathName().toStdString() && ! fs.pluginState.empty(), juce::String (fs.samplePath));
  23566. lynx::loadSlicexSampleWhenOpened (1, clap.getFullPathName());
  23567. auto slicex = lynx::makeSlicexEditor (engine, locate (1), 1);
  23568. const auto& sx = engine.getSong().channels[1];
  23569. check ("open_in_new_slicex", sx.samplePath == clap.getFullPathName().toStdString() && ! sx.pluginState.empty(), juce::String (sx.samplePath));
  23570. auto again = lynx::makeSlicexEditor (engine, locate (1), 1); // (the request is used once)
  23571. check ("open_in_new_used_once", engine.getSong().channels[1].samplePath == sx.samplePath);
  23572. // Gross Beat on insert 1: two notes on its MIDI input, one block, the engine's timer step
  23573. engine.editSong ([] (lynx::Song& s) {
  23574. if (s.mixer.size() < 2)
  23575. s.mixer.resize (2);
  23576. s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::grossBeat) };
  23577. });
  23578. engine.dispatchPendingMessages();
  23579. auto fx = engine.getEffect (1, 0);
  23580. check ("gb_running", fx != nullptr);
  23581. if (fx != nullptr)
  23582. {
  23583. std::vector<float> l (512, 0.1f), r (512, 0.1f);
  23584. fx->prepare (44100.0);
  23585. fx->setSongPosition (0.0);
  23586. fx->midiNote (60 + 9, 100, 0);
  23587. fx->midiNote (24 + 3, 100, 0);
  23588. fx->process (l.data(), r.data(), 512, engine.getSong().mixer[1].effects[0].params, 120.0);
  23589. engine.pumpGrossBeatPicks();
  23590. const auto& p = engine.getSong().mixer[1].effects[0].params;
  23591. check ("gb_midi_pick_sets_parameters", lynx::grossbeat::rawFromParam (0, p[0]) == 9 && lynx::grossbeat::rawFromParam (1, p[1]) == 3,
  23592. juce::String (lynx::grossbeat::rawFromParam (0, p[0])) + " " + juce::String (lynx::grossbeat::rawFromParam (1, p[1])));
  23593. }
  23594. }
  23595. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  23596. return allOk;
  23597. }
  23598. // --grooveshot190fm (round 190fm): see the dispatch above
  23599. bool runGrooveShot190fm (const juce::String& prefix)
  23600. {
  23601. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23602. juce::StringArray report;
  23603. bool allOk = true;
  23604. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  23605. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  23606. allOk = allOk && ok;
  23607. };
  23608. const auto plain = [] (juce::String t) {
  23609. t = t.upToFirstOccurrenceOf ("\t", false, false);
  23610. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  23611. };
  23612. const auto sub = [&plain] (const juce::PopupMenu& menu, const juce::String& start) -> const juce::PopupMenu* {
  23613. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23614. if (it.getItem().subMenu != nullptr && plain (it.getItem().text).startsWith (start))
  23615. return it.getItem().subMenu.get();
  23616. return nullptr;
  23617. };
  23618. const auto item = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  23619. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23620. if (plain (it.getItem().text) == text)
  23621. return &it.getItem();
  23622. return nullptr;
  23623. };
  23624. lynx::AudioEngine engine (false);
  23625. lynx::MainComponent ui (engine, false);
  23626. ui.setSize (1600, 900);
  23627. std::uint32_t classic = 0;
  23628. {
  23629. auto song = lynx::Song::makeDefault();
  23630. song.mode = lynx::PlayMode::song;
  23631. song.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
  23632. song.playlist.push_back ({ 0, 1, 4 * lynx::ppq, 4 * lynx::ppq, 0 });
  23633. for (const auto& e : lynx::groove::factoryBank())
  23634. if (juce::String (e.folder) == "Classic swing" && e.groove.base == lynx::GrooveBase::sixteenth
  23635. && (e.groove.name == "Swing 16ths 54 %" || e.groove.name == "Swing 16ths 58 %" || e.groove.name == "Swing 16ths 62 %"
  23636. || e.groove.name == "Swing 16ths 71 %"))
  23637. {
  23638. const auto id = lynx::groove::add (song.grooves, e.groove);
  23639. if (e.groove.name == "Swing 16ths 58 %")
  23640. classic = id;
  23641. }
  23642. song.playlist[0].groove = classic;
  23643. engine.setSong (std::move (song));
  23644. }
  23645. engine.dispatchPendingMessages();
  23646. auto& playlist = ui.getPlaylistForSnapshot();
  23647. const auto menu = playlist.getClipMenuForSnapshot (0);
  23648. const auto* chooser = sub (menu, lynx::tr ("Groove"));
  23649. check ("groove_chooser_in_clip_menu", chooser != nullptr);
  23650. const auto* add = chooser != nullptr ? sub (*chooser, lynx::tr ("Add a groove")) : nullptr;
  23651. const auto* folder = add != nullptr ? sub (*add, lynx::tr ("Classic swing")) : nullptr;
  23652. check ("classic_swing_folder", folder != nullptr && folder->getNumItems() == 27, folder != nullptr ? juce::String (folder->getNumItems()) : juce::String ("missing"));
  23653. const auto* commit = item (menu, lynx::tr ("Commit groove"));
  23654. check ("commit_enabled_with_a_groove", commit != nullptr && commit->isEnabled);
  23655. check ("extract_present", item (menu, lynx::tr ("Extract groove")) != nullptr);
  23656. {
  23657. juce::StringArray names { "Pattern clip menu" };
  23658. std::vector<juce::PopupMenu> menus { menu };
  23659. if (chooser != nullptr)
  23660. {
  23661. names.add ("Groove");
  23662. menus.push_back (*chooser);
  23663. }
  23664. if (add != nullptr)
  23665. {
  23666. names.add ("Add a groove");
  23667. menus.push_back (*add);
  23668. }
  23669. if (folder != nullptr)
  23670. {
  23671. names.add ("Classic swing");
  23672. menus.push_back (*folder);
  23673. }
  23674. saveMenus (names, menus, prefix + "-playlist-clip-menu.png");
  23675. }
  23676. // the second clip (no groove): Commit is off; choosing a groove from the menu sets it
  23677. {
  23678. const auto other = playlist.getClipMenuForSnapshot (1);
  23679. const auto* c2 = item (other, lynx::tr ("Commit groove"));
  23680. check ("commit_disabled_without_a_groove", c2 != nullptr && ! c2->isEnabled);
  23681. const auto* ch2 = sub (other, lynx::tr ("Groove"));
  23682. const auto* pick = ch2 != nullptr ? item (*ch2, "Swing 16ths 71 %") : nullptr;
  23683. if (pick != nullptr && pick->action != nullptr)
  23684. pick->action();
  23685. const auto& song = engine.getSong();
  23686. check ("chooser_sets_the_clip_groove", song.playlist.size() == 2 && lynx::groove::ofClip (song, song.playlist[1]) != nullptr
  23687. && lynx::groove::ofClip (song, song.playlist[1])->name == "Swing 16ths 71 %");
  23688. }
  23689. // the pool with the classic grooves
  23690. {
  23691. auto pool = lynx::makeGroovePool (engine);
  23692. pool->setSize (900, lynx::groovePoolHeight (engine));
  23693. savePng (pool->createComponentSnapshot (pool->getLocalBounds()), prefix + "-pool.png");
  23694. }
  23695. // .lynx: a Playlist clip's groove comes back; a project without one writes nothing new
  23696. {
  23697. juce::String error;
  23698. const auto& song = engine.getSong();
  23699. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  23700. check ("lynx_round_trip", back && back->playlist.size() == 2 && back->playlist[0].groove == song.playlist[0].groove
  23701. && back->playlist[1].groove == song.playlist[1].groove && back->grooves == song.grooves,
  23702. error);
  23703. auto old = lynx::Song::makeDefault();
  23704. old.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
  23705. const auto json = lynx::ProjectFile::toJson (old, false);
  23706. const auto reloaded = lynx::ProjectFile::fromJson (json, error);
  23707. check ("old_project_unchanged", reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json && reloaded->playlist[0].groove == 0);
  23708. }
  23709. // Commit from the menu: the clip's pattern (shared with the second clip) is copied, the groove is off
  23710. {
  23711. const auto patterns = engine.getSong().patterns.size();
  23712. const auto again = playlist.getClipMenuForSnapshot (0);
  23713. if (const auto* c = item (again, lynx::tr ("Commit groove")); c != nullptr && c->action != nullptr)
  23714. c->action();
  23715. const auto& song = engine.getSong();
  23716. check ("commit_runs", song.playlist[0].groove == 0 && song.patterns.size() == patterns + 1 && song.playlist[0].pattern == (int) patterns);
  23717. }
  23718. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n" + (allOk ? "ALL OK" : "SOME FAILED") + "\n");
  23719. return allOk;
  23720. }
  23721. bool runFlClipShot (const juce::String& prefix)
  23722. {
  23723. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23724. juce::StringArray report;
  23725. bool allOk = true;
  23726. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  23727. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  23728. allOk = allOk && ok;
  23729. };
  23730. const auto plain = [] (juce::String t) {
  23731. t = t.upToFirstOccurrenceOf ("\t", false, false);
  23732. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  23733. t = t.substring (0, at);
  23734. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  23735. };
  23736. const auto find = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  23737. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23738. if (plain (it.getItem().text) == plain (text))
  23739. return &it.getItem();
  23740. return nullptr;
  23741. };
  23742. const auto click = [&find] (const juce::PopupMenu& menu, const juce::String& text) {
  23743. const auto* item = find (menu, text);
  23744. if (item == nullptr || ! item->isEnabled || item->action == nullptr)
  23745. return false;
  23746. item->action();
  23747. return true;
  23748. };
  23749. lynx::AudioEngine engine (false);
  23750. lynx::MainComponent ui (engine, false);
  23751. ui.setSize (1600, 900);
  23752. int vox = -1;
  23753. {
  23754. auto song = lynx::Song::makeDefault();
  23755. song.channels.push_back ({});
  23756. song.channels.back().name = "Vox";
  23757. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  23758. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  23759. vox = (int) song.channels.size() - 1;
  23760. lynx::Clip c;
  23761. c.kind = lynx::ClipKind::audio;
  23762. c.channel = vox;
  23763. c.track = 3;
  23764. c.start = 4 * lynx::ppq;
  23765. c.length = 2 * lynx::ppq;
  23766. c.fadeIn = lynx::ppq / 4;
  23767. song.playlist.push_back (c);
  23768. engine.setSong (std::move (song));
  23769. }
  23770. engine.dispatchPendingMessages();
  23771. auto& playlist = ui.getPlaylistForSnapshot();
  23772. // ---- 1. the audio clip menu: FL's order, sections and columns, then LYNX's own items
  23773. {
  23774. const auto menu = playlist.getClipMenuForSnapshot (0);
  23775. juce::StringArray got, want;
  23776. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23777. {
  23778. const auto& item = it.getItem();
  23779. // (round 190kx's loop items, whose labels carry the clip's own key / tempo, are not in the fixed list)
  23780. if (! item.isSeparator && ! item.isSectionHeader
  23781. && (plain (item.text).startsWith (lynx::tr ("Follow the project key")) || plain (item.text).startsWith (lynx::tr ("Loop key"))
  23782. || plain (item.text).startsWith (lynx::tr ("Fit to the project tempo ({0}, from {1} BPM)").upToFirstOccurrenceOf (" (", false, false))))
  23783. continue;
  23784. got.add (item.customComponent != nullptr ? "[" + lynx::tr ("Audio clip") + "]"
  23785. : item.isSeparator ? juce::String ("-")
  23786. : item.isSectionHeader ? "[" + plain (item.text) + "]"
  23787. : plain (item.text));
  23788. }
  23789. for (const auto& e : lynx::flclipmenu::shown (true, false))
  23790. if (e.kind != lynx::flclipmenu::Entry::Kind::columnBreak)
  23791. want.add (e.kind == lynx::flclipmenu::Entry::Kind::separator ? juce::String ("-")
  23792. : e.kind == lynx::flclipmenu::Entry::Kind::header ? "[" + lynx::tr (e.text.c_str()) + "]"
  23793. : lynx::tr (e.text.c_str()));
  23794. // (rollup step 8: the separators round 190kx's key items bring into the LYNX extras column go with them)
  23795. for (int k = got.indexOf ("[" + lynx::tr ("LYNX extras") + "]") + 1; k > 0 && k < got.size();)
  23796. if (got[k] == "-")
  23797. got.remove (k);
  23798. else
  23799. ++k;
  23800. want.add ("[" + lynx::tr ("LYNX extras") + "]"); // (round 190gi; round 190jv: in a third column)
  23801. for (const auto& x : lynx::flclipmenu::lynxExtras())
  23802. want.add (lynx::tr (x.c_str()));
  23803. check ("clip_menu_fl_order", got == want, got.joinIntoString ("|"));
  23804. // FL's two columns (Chop | Sample), then LYNX's own items in a third (round 190jv)
  23805. juce::StringArray breaks;
  23806. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23807. if (it.getItem().shouldBreakAfter)
  23808. breaks.add (it.getItem().isSectionHeader || it.getItem().customComponent != nullptr ? "?" : plain (it.getItem().text));
  23809. check ("clip_menu_two_columns", breaks.size() == 2 && breaks[0] == lynx::tr ("Chop") && breaks[1] == lynx::tr ("Fade out curve"),
  23810. breaks.joinIntoString ("|"));
  23811. const auto* crossfade = find (menu, lynx::tr ("Crossfade with"));
  23812. check ("crossfade_with_greyed", crossfade != nullptr && ! crossfade->isEnabled);
  23813. const auto* region = find (menu, lynx::tr ("Select region"));
  23814. const auto* full = region != nullptr && region->subMenu != nullptr ? find (*region->subMenu, lynx::tr ("Full")) : nullptr;
  23815. check ("select_region_full_ticked", full != nullptr && full->isTicked);
  23816. const auto* chop = find (menu, lynx::tr ("Chop"));
  23817. check ("chop_time_based", chop != nullptr && chop->subMenu != nullptr && find (*chop->subMenu, lynx::tr ("Chop in 32nd beats")) != nullptr
  23818. && find (*chop->subMenu, lynx::tr ("Chop to grid")) != nullptr);
  23819. savePng (columnMenuImage (menu), prefix + "-clip-menu.png");
  23820. std::fprintf (stderr, "flclipshot: menu saved\n");
  23821. // Muted is a check; Reset fades clears the fades; Select all similar clips selects
  23822. check ("muted_toggles", click (menu, lynx::tr ("Muted")) && engine.getSong().playlist[0].muted);
  23823. const auto again = playlist.getClipMenuForSnapshot (0);
  23824. const auto* muted = find (again, lynx::tr ("Muted"));
  23825. check ("muted_ticked", muted != nullptr && muted->isTicked);
  23826. check ("reset_fades", click (again, lynx::tr ("Reset fades")) && engine.getSong().playlist[0].fadeIn == 0);
  23827. engine.undo();
  23828. engine.undo();
  23829. engine.dispatchPendingMessages();
  23830. std::fprintf (stderr, "flclipshot: automate\n");
  23831. // Automate › Volume / Panning: the clip channel's Levels adjustment (FL's channel parameters 0x11 / 0x10)
  23832. const auto fresh = playlist.getClipMenuForSnapshot (0);
  23833. const auto* automate = find (fresh, lynx::tr ("Automate"));
  23834. const auto before = engine.getSong().automations.size();
  23835. check ("automate_volume_runs", automate != nullptr && automate->subMenu != nullptr && click (*automate->subMenu, lynx::tr ("Volume")));
  23836. const auto& song = engine.getSong();
  23837. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  23838. && song.automations.back().target.param == lynx::leveladjust::volume && song.automations.back().target.index == vox
  23839. && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  23840. check ("automate_volume_is_level_adjust", ok, ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  23841. engine.undo();
  23842. engine.dispatchPendingMessages();
  23843. }
  23844. std::fprintf (stderr, "flclipshot: overlap\n");
  23845. // ---- 2. a second channel's clip overlapping: Crossfade with lists it and makes FL's crossfade clip (round 190gw)
  23846. {
  23847. engine.editSong ([vox] (lynx::Song& s) {
  23848. auto copy = s.playlist[0]; // (another audio clip channel's clip, at the same time)
  23849. s.channels.push_back (s.channels[(std::size_t) vox]);
  23850. s.channels.back().name = "Vox 2";
  23851. copy.channel = (int) s.channels.size() - 1;
  23852. copy.track = 4;
  23853. s.playlist.push_back (copy);
  23854. });
  23855. engine.dispatchPendingMessages();
  23856. const auto overlapped = playlist.getClipMenuForSnapshot (0);
  23857. const auto* with = find (overlapped, lynx::tr ("Crossfade with"));
  23858. check ("crossfade_with_lists_the_overlap", with != nullptr && with->isEnabled && with->subMenu != nullptr && find (*with->subMenu, "Vox 2") != nullptr);
  23859. const auto made = with != nullptr && with->subMenu != nullptr && click (*with->subMenu, "Vox 2");
  23860. engine.dispatchPendingMessages();
  23861. const auto& xsong = engine.getSong();
  23862. const auto xok = made && ! xsong.automations.empty() && xsong.automations.back().links.size() == 2
  23863. && juce::String::fromUTF8 (xsong.automations.back().name.c_str()).endsWith (" to Vox 2 crossfade");
  23864. check ("crossfade_with_makes_the_clip", xok, xok ? juce::String::fromUTF8 (xsong.automations.back().name.c_str()) : juce::String());
  23865. if (made)
  23866. engine.undo();
  23867. engine.undo();
  23868. engine.dispatchPendingMessages();
  23869. }
  23870. std::fprintf (stderr, "flclipshot: misc\n");
  23871. // ---- 3. the channel's Misc tab: Levels adjustment = the offsets (pan 0, volume 100 %, Mod X / Y 0 %)
  23872. {
  23873. engine.editSong ([vox] (lynx::Song& s) {
  23874. s.channels[(std::size_t) vox].misc.levels.volume = 0.5f;
  23875. s.channels[(std::size_t) vox].misc.levels.pan = -0.25f;
  23876. });
  23877. engine.dispatchPendingMessages();
  23878. auto frame = lynx::makeChannelFrame (engine, vox, -1);
  23879. frame->setSize (juce::jmax (frame->getWidth(), 800), juce::jmax (frame->getHeight(), 420));
  23880. savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-misc-levels.png");
  23881. auto synthFrame = lynx::makeChannelFrame (engine, 0, -1);
  23882. synthFrame->setSize (juce::jmax (synthFrame->getWidth(), 800), juce::jmax (synthFrame->getHeight(), 420));
  23883. savePng (synthFrame->createComponentSnapshot (synthFrame->getLocalBounds()), prefix + "-misc-levels-ch1.png");
  23884. std::fprintf (stderr, "flclipshot: round trip\n");
  23885. // the .lynx round trip of the adjustment and of an automation of it; an old project writes nothing new
  23886. juce::String error;
  23887. auto song = engine.getSong();
  23888. lynx::Automation a;
  23889. a.target = { lynx::AutomationTargetKind::channelAdjust, vox, 0, lynx::leveladjust::volume };
  23890. a.points = { { 0, 0.25f, 0.0f } };
  23891. song.automations.push_back (a);
  23892. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  23893. check ("lynx_round_trip", back && back->channels[(std::size_t) vox].misc.levels == song.channels[(std::size_t) vox].misc.levels
  23894. && back->automations.back().target == a.target,
  23895. error);
  23896. auto old = lynx::Song::makeDefault();
  23897. const auto json = lynx::ProjectFile::toJson (old, false);
  23898. const auto reloaded = lynx::ProjectFile::fromJson (json, error);
  23899. check ("old_project_unchanged", ! json.contains ("\"levels\"") && reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json
  23900. && std::all_of (reloaded->channels.begin(), reloaded->channels.end(),
  23901. [] (const lynx::ChannelDef& c) { return c.misc.levels.neutral(); }));
  23902. }
  23903. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  23904. return allOk;
  23905. }
  23906. // --bandlab190jrshot <prefix> (round 190jr; B15, BUILD-LIST 13 / 14): a synthetic BandLab project (.blx: the revision
  23907. // JSON, a MIDI file, a WAV) opened through the real import, shown in the Simple layout; its looped regions and their
  23908. // loop handles; a loop dragged longer; the automation view with and without points and its parameter menu; the clip
  23909. // menu's loop items; the Extract stems form (Standard and 6 stems). Pictures at the --shot-scale asked for.
  23910. void runBandlab190jrShot (const juce::String& prefix)
  23911. {
  23912. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23913. lynx::AudioEngine offline (false);
  23914. lynx::MainComponent ui (offline, false);
  23915. ui.setSize (1600, 900);
  23916. const auto note = [] (const juce::String& what) { std::fprintf (stderr, "bandlab190jrshot: %s\n", what.toRawUTF8()); };
  23917. const auto writeImage = [&prefix, &note] (const juce::Image& image, const char* name) {
  23918. note (name);
  23919. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  23920. file.deleteFile();
  23921. juce::FileOutputStream out (file);
  23922. juce::PNGImageFormat().writeImageToStream (image, out);
  23923. };
  23924. juce::String report;
  23925. const auto check = [&report, &note] (const juce::String& what, bool ok) {
  23926. note ((ok ? "ok " : "FAIL ") + what);
  23927. report << (ok ? "ok " : "FAIL ") << what << "\n";
  23928. };
  23929. // ---- 1. the project: a revision with a looped piano region, a voice take and a drum machine
  23930. const auto folder = juce::File (prefix + "-blx");
  23931. folder.deleteRecursively();
  23932. folder.getChildFile ("Audio").createDirectory();
  23933. folder.getChildFile ("MIDI").createDirectory();
  23934. {
  23935. // a 4-beat MIDI part (100 BPM: 2.4 s) and a drum beat, 480 ticks per quarter
  23936. const auto midi = [] (const std::vector<std::array<int, 4>>& notes) {
  23937. juce::MidiMessageSequence seq;
  23938. for (const auto& n : notes)
  23939. {
  23940. seq.addEvent (juce::MidiMessage::noteOn (1, n[2], (juce::uint8) n[3]), n[0]);
  23941. seq.addEvent (juce::MidiMessage::noteOff (1, n[2]), n[0] + n[1]);
  23942. }
  23943. seq.updateMatchedPairs();
  23944. juce::MidiFile file;
  23945. file.setTicksPerQuarterNote (480);
  23946. file.addTrack (seq);
  23947. juce::MemoryOutputStream out;
  23948. file.writeTo (out);
  23949. return out.getMemoryBlock();
  23950. };
  23951. const auto keysBlock = midi ({ { 0, 480, 62, 100 }, { 0, 480, 65, 90 }, { 0, 480, 69, 90 }, { 480, 240, 64, 80 },
  23952. { 960, 480, 60, 100 }, { 960, 480, 64, 90 }, { 1440, 480, 67, 90 } });
  23953. folder.getChildFile ("MIDI/s-keys.mid").replaceWithData (keysBlock.getData(), keysBlock.getSize());
  23954. const auto beat = midi ({ { 0, 120, 36, 120 }, { 480, 120, 38, 110 }, { 960, 120, 36, 120 }, { 1440, 120, 38, 110 }, { 240, 60, 42, 80 },
  23955. { 720, 60, 42, 80 }, { 1200, 60, 42, 80 }, { 1680, 60, 42, 80 } });
  23956. folder.getChildFile ("MIDI/s-beat.mid").replaceWithData (beat.getData(), beat.getSize());
  23957. // a 4.8 s "voice" (a sine with a slow swell), 44.1 kHz
  23958. juce::AudioBuffer<float> wave (1, 44100 * 48 / 10);
  23959. for (int i = 0; i < wave.getNumSamples(); ++i)
  23960. wave.setSample (0, i, 0.4f * std::sin ((float) i * 0.0627f) * (0.5f + 0.5f * std::sin ((float) i * 0.00012f)));
  23961. juce::WavAudioFormat wav;
  23962. const auto out = folder.getChildFile ("Audio/s-vox.wav");
  23963. if (auto stream = out.createOutputStream())
  23964. if (std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (stream.get(), 44100.0, 1, 16, {}, 0)); writer != nullptr)
  23965. {
  23966. stream.release();
  23967. writer->writeFromAudioSampleBuffer (wave, 0, wave.getNumSamples());
  23968. }
  23969. folder.getChildFile ("Scratch Song.blx").replaceWithText (R"({ "revision": {
  23970. "key": "D min", "volume": 1, "song": { "name": "Scratch Song" },
  23971. "metronome": { "bpm": 100, "signature": { "notesCount": 4, "noteValue": 4 } },
  23972. "auxChannels": [ { "id": "aux1", "preset": "sharedReverb", "returnLevel": 1 } ],
  23973. "samples": [ { "id": "s-keys", "isMidi": true, "duration": 2.4 }, { "id": "s-vox", "isMidi": false, "duration": 4.8 }, { "id": "s-beat", "isMidi": true } ],
  23974. "tracks": [
  23975. { "id": "t1", "order": 0, "name": "Keys", "type": "instrument", "soundbank": "studio-grand", "volume": 0.9, "colorName": "Red",
  23976. "regions": [ { "id": "r1", "sampleId": "s-keys", "name": "Chords", "startPosition": 0, "endPosition": 9.6, "loopLength": 2.4 } ] },
  23977. { "id": "t2", "order": 1, "name": "Vocal", "type": "voice", "volume": 1, "pan": -0.2, "colorName": "Blue",
  23978. "effects": [ { "slug": "compressor", "params": { "attack": 0.003, "ratio": 3, "release": 0.12, "threshold": -18 } },
  23979. { "slug": "threeBandEq", "params": { "lowGain": -2, "midGain": 1, "highGain": 3, "midFreq": 2500 } },
  23980. { "slug": "chorusPedal", "params": {} } ],
  23981. "auxSends": [ { "id": "aux1", "sendLevel": 0.3 } ],
  23982. "automation": { "volume": [ { "position": 0, "value": 0.2 }, { "position": 8, "value": 1 }, { "position": 16, "value": 0.7 } ] },
  23983. "regions": [ { "id": "r2", "sampleId": "s-vox", "name": "Take 1", "startPosition": 2.4, "endPosition": 7.2, "fadeIn": 0.2, "fadeOut": 0.5 } ] },
  23984. { "id": "t3", "order": 2, "name": "Drum Machine", "type": "drum-machine", "volume": 1, "colorName": "Violet",
  23985. "regions": [ { "id": "r3", "sampleId": "s-beat", "name": "Beat", "startPosition": 0, "endPosition": 4.8, "loopLength": 2.4 } ] }
  23986. ] } })");
  23987. }
  23988. juce::String error;
  23989. const auto blx = folder.getChildFile ("Scratch Song.blx");
  23990. const auto imported = offline.importFlpFile (blx, error);
  23991. check ("the .blx opens through the import (" + error + ")", imported);
  23992. offline.dispatchPendingMessages();
  23993. const auto& song = offline.getSong();
  23994. check ("three Simple tracks: Keys (instrument), Vocal (audio), Drum Machine (drums)",
  23995. lynx::simpletracks::kindOf (song, 0) == lynx::simpletracks::Kind::instrument && lynx::simpletracks::kindOf (song, 1) == lynx::simpletracks::Kind::audio
  23996. && lynx::simpletracks::kindOf (song, 2) == lynx::simpletracks::Kind::drums);
  23997. check ("tempo 100, key D minor", std::abs (song.bpm - 100.0) < 1e-6 && lynx::projectkey::get (song).has_value());
  23998. int keysClips = 0, beatClips = 0, voxClips = 0;
  23999. for (const auto& c : song.playlist)
  24000. {
  24001. keysClips += c.track == 0;
  24002. voxClips += c.track == 1 && c.kind == lynx::ClipKind::audio;
  24003. beatClips += c.track == 2;
  24004. }
  24005. check ("the looped Keys region: 4 passes; the beat: 2; the take: 1 audio clip", keysClips == 4 && beatClips == 2 && voxClips == 1);
  24006. const auto voxInsert = lynx::simpletracks::insertOf (song, 1);
  24007. check ("the vocal's compressor, EQ and chorus on its insert",
  24008. voxInsert > 0 && song.mixer[(std::size_t) voxInsert].effects.size() == 3);
  24009. check ("the vocal's volume automation: a lane under its track", ! song.playlistTracks[1].lanes.empty());
  24010. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  24011. offline.dispatchPendingMessages();
  24012. ui.selectTabForSnapshot (2);
  24013. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  24014. simple->hideChooser();
  24015. auto& playlist = ui.getPlaylistForSnapshot();
  24016. playlist.setViewForSnapshot (96.0, 0, 0);
  24017. offline.dispatchPendingMessages();
  24018. writeImage (lynx::shot::snapshot (ui), "blx-simple");
  24019. writeImage (lynx::shot::snapshot (playlist), "loop-handles");
  24020. // ---- 2. a loop dragged longer: the take repeated to bar 9 (as the handle's drag does it)
  24021. {
  24022. int take = -1;
  24023. for (int i = 0; i < (int) song.playlist.size(); ++i)
  24024. if (song.playlist[(std::size_t) i].track == 1 && song.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  24025. take = i;
  24026. const auto end = (std::int64_t) lynx::ppq * 4 * 8;
  24027. offline.editSong ([take, end] (lynx::Song& s) { lynx::regionloop::loopTo (s, take, end); });
  24028. offline.dispatchPendingMessages();
  24029. 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]));
  24030. check ("the take loops to bar 9 in passes of its length", run.passes() >= 3 && run.end == end);
  24031. writeImage (lynx::shot::snapshot (playlist), "loop-dragged");
  24032. auto menu = playlist.getClipMenuForSnapshot (run.clips.empty() ? take : run.clips.back());
  24033. bool hasLoop = false;
  24034. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  24035. hasLoop = hasLoop || it.getItem().text == lynx::tr ("Unloop");
  24036. check ("the Simple clip menu has Loop until next / Unloop", hasLoop);
  24037. saveMenus (juce::StringArray { "Clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu.png");
  24038. }
  24039. // ---- 3. the automation view: the vocal's lane on its row, the others' dashed line at their level
  24040. playlist.setSimpleAutomation (true);
  24041. offline.dispatchPendingMessages();
  24042. writeImage (lynx::shot::snapshot (playlist), "automation-view");
  24043. check ("the view changes nothing in the song", offline.getSong().playlistTracks[0].lanes.empty());
  24044. playlist.setSimpleAutoTargetForSnapshot (1, { lynx::AutomationTargetKind::effectParam, voxInsert, 0, 0 }); // the compressor's threshold
  24045. writeImage (lynx::shot::snapshot (playlist), "automation-param");
  24046. playlist.setSimpleAutoTargetForSnapshot (1, { lynx::AutomationTargetKind::mixerVolume, voxInsert, 0, 0 });
  24047. saveMenus (juce::StringArray { "Volume" }, std::vector<juce::PopupMenu> { playlist.getSimpleAutoMenuForSnapshot (1) }, prefix + "-automation-menu.png");
  24048. playlist.setSimpleAutomation (false);
  24049. offline.dispatchPendingMessages();
  24050. // ---- 4. the Extract stems form
  24051. {
  24052. auto panel = lynx::makeStemOptionsPanel (lynx::stemsplit::Options {}, [] (lynx::stemsplit::Options) {});
  24053. writeImage (lynx::shot::paint (*panel, lynx::theme::colour::bg2), "stem-options");
  24054. lynx::stemsplit::Options six;
  24055. six.model = lynx::stemsplit::Model::sixStems;
  24056. six.stems = { true, true, false, true, true, true };
  24057. auto panel6 = lynx::makeStemOptionsPanel (six, [] (lynx::stemsplit::Options) {});
  24058. writeImage (lynx::shot::paint (*panel6, lynx::theme::colour::bg2), "stem-options-six");
  24059. }
  24060. juce::File (lynx::shot::fileName (prefix + "-report.txt")).replaceWithText (report);
  24061. }
  24062. // --bandlabshot <prefix> (round 190ch): the Lyrics / Notes panel (Pattern and Simple layouts, and on its own), the
  24063. // Reference match window measured on a real render and a real file, "Start from", and Clean voice, off-screen; and
  24064. // <prefix>-report.txt with what each route did (ok / FAIL lines)
  24065. void runBandlabShot (const juce::String& prefix)
  24066. {
  24067. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24068. lynx::AudioEngine offline (false);
  24069. lynx::MainComponent ui (offline, false);
  24070. ui.setSize (1600, 900);
  24071. // (each step is named on stderr as it starts: a run that stops says where)
  24072. const auto note = [] (const juce::String& what) { std::fprintf (stderr, "bandlabshot: %s\n", what.toRawUTF8()); };
  24073. const auto shoot = [&prefix, &note] (juce::Component& c, const char* name) {
  24074. note (name);
  24075. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  24076. };
  24077. juce::String report;
  24078. const auto check = [&report, &note] (const juce::String& what, bool ok) {
  24079. note ((ok ? "ok " : "FAIL ") + what);
  24080. report << (ok ? "ok " : "FAIL ") << what << "\n";
  24081. };
  24082. const auto bar = (double) lynx::ppq * 4.0;
  24083. // ---- 1. Lyrics / Notes: the project's Comments
  24084. {
  24085. auto song = lynx::makeShowcaseSong (0);
  24086. song.info.title = "Night Drive";
  24087. 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"
  24088. "I keep driving through the night\n\n[Chorus]\nNight drive, night drive\nNothing but the white line\n\n"
  24089. "Notes: double the chorus vocal, try the second verse an octave down.";
  24090. lynx::Marker chorus;
  24091. chorus.tick = (std::int64_t) (12.0 * bar);
  24092. chorus.name = "Chorus";
  24093. song.addMarker (chorus);
  24094. offline.setSong (std::move (song));
  24095. }
  24096. note ("song set");
  24097. offline.dispatchPendingMessages();
  24098. ui.selectTabForSnapshot (2);
  24099. note ("show lyrics");
  24100. ui.showLyrics (false);
  24101. note ("lyrics shown");
  24102. if (auto* panel = ui.getLyricsPanelForSnapshot())
  24103. {
  24104. panel->showForSnapshot ({}, 6.5 * bar); // the playhead inside bar 7: that line is the one playing
  24105. shoot (ui, "lyrics-pattern");
  24106. shoot (*panel, "lyrics-panel");
  24107. const auto markersBefore = offline.getSong().markers().size();
  24108. panel->setCaretLineForSnapshot (6); // "I keep driving through the night"
  24109. panel->markAtPlayheadForSnapshot (10.0 * bar + 2.0 * lynx::ppq);
  24110. offline.dispatchPendingMessages();
  24111. ui.commitSongNotes();
  24112. const auto& s = offline.getSong();
  24113. check ("Marker at playhead stamps the line [11.3] and adds one marker",
  24114. juce::String::fromUTF8 (s.info.comments.c_str()).contains ("[11.3] I keep driving") && s.markers().size() == markersBefore + 1);
  24115. // (no audio device here: the seek is the request the audio thread takes at its next block)
  24116. const auto& seek = offline.getTransport().seekRequest;
  24117. check ("clicking the stamped line moves the playhead to bar 7", panel->jumpToLineForSnapshot (4) && std::abs (seek.load() - 6.0 * bar) < 1.0);
  24118. check ("clicking [Chorus] (no position) goes to the marker of that name, bar 13",
  24119. panel->jumpToLineForSnapshot (8) && std::abs (seek.load() - 12.0 * bar) < 1.0);
  24120. check ("a line without a position does not jump", ! panel->jumpToLineForSnapshot (9));
  24121. panel->showForSnapshot ("night", 10.5 * bar);
  24122. shoot (*panel, "lyrics-search");
  24123. // the text travels in the project file, and old readers see it as the Comments they always had
  24124. juce::String error;
  24125. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  24126. const auto back = lynx::ProjectFile::fromJson (json, error);
  24127. check ("lyrics round-trip through .lynx (the Comments field)", back.has_value() && back->info.comments == offline.getSong().info.comments);
  24128. const auto text = lynx::lyrics::exportText (offline.getSong(), lynx::lyrics::Stamps::times);
  24129. juce::File (prefix + "-lyrics-export.txt").replaceWithText (juce::String::fromUTF8 (text.c_str()));
  24130. check ("export as text with times", text.find ("[0:") != std::string::npos);
  24131. panel->showForSnapshot ({}, 6.5 * bar);
  24132. }
  24133. else
  24134. check ("the docked Lyrics panel exists", false);
  24135. {
  24136. const auto names = ui.getMenuNamesForSnapshot();
  24137. const auto view = names.indexOf (lynx::tr ("View"));
  24138. saveMenus (juce::StringArray { lynx::tr ("View") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (juce::jmax (0, view)) }, prefix + "-menu-view.png");
  24139. }
  24140. ui.showDesktopForSnapshot (false);
  24141. check ("the panel stays docked beside the Playlist in the default desktop", ui.isLyricsShowing());
  24142. shoot (ui, "lyrics-desktop");
  24143. // ---- the Simple layout: the Lyrics button in its title tools, the chooser's "Start from" link
  24144. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  24145. offline.dispatchPendingMessages();
  24146. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  24147. auto* simple = ui.getSimpleWorkflowForSnapshot();
  24148. check ("the Simple workflow exists", simple != nullptr);
  24149. if (simple != nullptr)
  24150. {
  24151. simple->hideChooser();
  24152. if (! ui.isLyricsShowing())
  24153. ui.showLyrics (false);
  24154. shoot (ui, "lyrics-simple");
  24155. ui.hideLyrics();
  24156. check ("closing the panel keeps the text", juce::String::fromUTF8 (offline.getSong().info.comments.c_str()).contains ("Night drive, night drive"));
  24157. // ---- 4. Clean voice: on a voice track, from the track's menu
  24158. lynx::simpletracks::Result voice;
  24159. offline.editSongStructural ([&voice] (lynx::Song& s) {
  24160. lynx::simpletracks::Request q;
  24161. q.kind = lynx::simpletracks::Kind::voice;
  24162. q.name = "Lead vocal";
  24163. voice = lynx::simpletracks::addTrack (s, q);
  24164. });
  24165. offline.dispatchPendingMessages();
  24166. check ("a voice track was added", voice.insert > 0);
  24167. if (voice.insert > 0)
  24168. {
  24169. auto menu = ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (voice.track);
  24170. juce::StringArray names { "Track" };
  24171. std::vector<juce::PopupMenu> menus { menu };
  24172. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  24173. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Clean voice"))
  24174. {
  24175. names.add (lynx::tr ("Clean voice"));
  24176. menus.push_back (*it.getItem().subMenu);
  24177. }
  24178. check ("the Simple track menu has Clean voice", menus.size() == 2);
  24179. saveMenus (names, menus, prefix + "-cleanvoice-menu.png");
  24180. const auto before = offline.getSong().mixer[(std::size_t) voice.insert].effects.size();
  24181. check ("Clean voice applies", lynx::ui::applyCleanVoice (offline, voice.insert, false));
  24182. offline.dispatchPendingMessages();
  24183. const auto& fx = offline.getSong().mixer[(std::size_t) voice.insert].effects;
  24184. check ("four slots in front of the track's effects", fx.size() == before + 4 && lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4
  24185. && fx[0].kind == lynx::EffectKind::facetEq);
  24186. check ("with noise reduction: five, none doubled", lynx::ui::applyCleanVoice (offline, voice.insert, true)
  24187. && offline.getSong().mixer[(std::size_t) voice.insert].effects.size() == before + 5);
  24188. offline.dispatchPendingMessages();
  24189. juce::String error;
  24190. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  24191. check ("the chain round-trips through .lynx and is still found", back.has_value() && lynx::cleanvoice::slotsOf (*back, voice.insert).size() == 5
  24192. && back->mixer[(std::size_t) voice.insert].effects == offline.getSong().mixer[(std::size_t) voice.insert].effects);
  24193. saveMenus (juce::StringArray { lynx::tr ("Clean voice") }, std::vector<juce::PopupMenu> { lynx::ui::cleanVoiceMenu (offline, voice.insert) },
  24194. prefix + "-cleanvoice-menu-on.png");
  24195. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  24196. offline.dispatchPendingMessages();
  24197. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  24198. ui.selectMixerTrackForSnapshot (voice.insert);
  24199. shoot (ui, "cleanvoice-mixer");
  24200. offline.undo(); // the second chain
  24201. offline.dispatchPendingMessages();
  24202. check ("undo brings the first chain back", lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4);
  24203. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  24204. offline.dispatchPendingMessages();
  24205. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  24206. simple = ui.getSimpleWorkflowForSnapshot();
  24207. }
  24208. }
  24209. // ---- 2. Reference match: the song's Master render against a file (pink noise with more top, at about -14 LUFS)
  24210. {
  24211. const auto file = juce::File (prefix + "-reference.wav");
  24212. file.deleteFile();
  24213. const auto rate = 44100.0;
  24214. const auto frames = (int) (20.0 * rate);
  24215. juce::AudioBuffer<float> audio (2, frames);
  24216. juce::Random random (190);
  24217. for (int ch = 0; ch < 2; ++ch)
  24218. {
  24219. double b0 = 0, b1 = 0, b2 = 0, hp = 0;
  24220. for (int i = 0; i < frames; ++i)
  24221. {
  24222. const auto w = (double) random.nextFloat() * 2.0 - 1.0;
  24223. b0 = 0.99765 * b0 + w * 0.0990460;
  24224. b1 = 0.96300 * b1 + w * 0.2965164;
  24225. b2 = 0.57000 * b2 + w * 1.0526913;
  24226. const auto pink = (b0 + b1 + b2 + w * 0.1848) * 0.071; // (about -14 LUFS: a streaming master)
  24227. hp += 0.25 * (pink - hp); // a little more top than pink noise has
  24228. audio.setSample (ch, i, (float) (pink + 0.35 * (pink - hp)));
  24229. }
  24230. }
  24231. if (auto out = file.createOutputStream())
  24232. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 24, {}, 0)))
  24233. {
  24234. out.release();
  24235. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  24236. }
  24237. note ("measure reference");
  24238. const auto reference = lynx::ReferenceMatchPanel::measureFile (offline, file);
  24239. note ("measure song");
  24240. const auto song = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), false);
  24241. check ("the reference file was measured", reference.valid);
  24242. check ("the song's Master render was measured", song.valid);
  24243. lynx::ReferenceMatchPanel panel (offline, {});
  24244. panel.setSize (lynx::ReferenceMatchPanel::defaultWidth, lynx::ReferenceMatchPanel::defaultHeight);
  24245. panel.showForSnapshot ("Reference.wav", song, reference, nullptr);
  24246. shoot (panel, "refmatch-measured");
  24247. const auto masterBefore = offline.getSong().mixer[0].effects.size();
  24248. check ("Match adds its two slots at the end of the Master", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  24249. offline.dispatchPendingMessages();
  24250. const auto first = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  24251. panel.showForSnapshot ("Reference.wav", song, reference, &first);
  24252. panel.refresh();
  24253. shoot (panel, "refmatch-matched");
  24254. report << " first Match: " << juce::String (first.lufs, 2) << " LUFS, " << juce::String (first.truePeakDb, 2) << " dBTP, EQ output "
  24255. << juce::String (lynx::facet::outputDb (offline.getSong().mixer[0].effects[masterBefore].params[(std::size_t) lynx::facet::outputParam]), 2) << " dB\n";
  24256. // a result more than 0.5 LU from the reference (a limiter that has to hold peaks back): Match again takes
  24257. // what is missing, as the window's note says
  24258. auto after = first;
  24259. const auto secondPass = std::abs (first.lufs - reference.lufs) > 0.5;
  24260. if (secondPass)
  24261. {
  24262. check ("Match again replaces the two slots (level corrected)", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  24263. offline.dispatchPendingMessages();
  24264. after = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  24265. panel.showForSnapshot ("Reference.wav", song, reference, &after);
  24266. panel.refresh();
  24267. shoot (panel, "refmatch-matched-again");
  24268. }
  24269. report << " " << (secondPass ? "a second Match was needed for the level" : "one Match was enough for the level") << "\n";
  24270. const auto& s = panel.suggestionForSnapshot();
  24271. report << " song " << juce::String (song.lufs, 2) << " LUFS, " << juce::String (song.truePeakDb, 2) << " dBTP, width " << juce::String (song.widthPercent(), 1)
  24272. << " % | reference " << juce::String (reference.lufs, 2) << " LUFS, " << juce::String (reference.truePeakDb, 2) << " dBTP, width "
  24273. << juce::String (reference.widthPercent(), 1) << " % | after " << juce::String (after.lufs, 2) << " LUFS, " << juce::String (after.truePeakDb, 2)
  24274. << " dBTP\n next suggestion: gain " << juce::String (s.gainDb, 2) << " dB, EQ fit error " << juce::String (s.fitErrorDb, 2) << " dB\n";
  24275. double before = 0.0, now = 0.0;
  24276. int counted = 0;
  24277. {
  24278. // tone only (each curve around its own mean), over the bands both hold
  24279. double ms = 0, mr = 0, ma = 0;
  24280. const auto used = juce::jmin (song.usedBands, reference.usedBands);
  24281. for (int k = 0; k < used; ++k)
  24282. ms += song.spectrumDb[(std::size_t) k], mr += reference.spectrumDb[(std::size_t) k], ma += after.spectrumDb[(std::size_t) k];
  24283. for (int k = 2; k < used; ++k, ++counted)
  24284. {
  24285. before += std::abs ((song.spectrumDb[(std::size_t) k] - ms / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  24286. now += std::abs ((after.spectrumDb[(std::size_t) k] - ma / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  24287. }
  24288. }
  24289. report << " mean tone difference to the reference: " << juce::String (before / juce::jmax (1, counted), 2) << " dB before, "
  24290. << juce::String (now / juce::jmax (1, counted), 2) << " dB after one Match (each band moves 6 dB at most)\n";
  24291. check ("after Match the tone is closer to the reference", after.valid && now < before);
  24292. check ("after Match the loudness is within 1 LU of the reference", std::abs (after.lufs - reference.lufs) < 1.0);
  24293. 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);
  24294. juce::String error;
  24295. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  24296. check ("the match round-trips through .lynx as two ordinary Master slots", back.has_value() && lynx::refmatch::present (*back)
  24297. && back->mixer[0].effects == offline.getSong().mixer[0].effects);
  24298. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  24299. offline.dispatchPendingMessages();
  24300. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  24301. ui.selectMixerTrackForSnapshot (0);
  24302. shoot (ui, "refmatch-mixer");
  24303. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  24304. offline.dispatchPendingMessages();
  24305. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  24306. simple = ui.getSimpleWorkflowForSnapshot();
  24307. if (simple != nullptr)
  24308. {
  24309. simple->hideChooser();
  24310. simple->showFinish();
  24311. shoot (ui, "finish-dock"); // "Match a reference track..." under the saving buttons
  24312. simple->hideFinish();
  24313. }
  24314. file.deleteFile();
  24315. }
  24316. // ---- 3. Start from: the chooser's link, the list, and opening an entry
  24317. if (simple != nullptr)
  24318. {
  24319. simple->showChooser();
  24320. shoot (ui, "chooser");
  24321. simple->hideChooser();
  24322. auto* panel = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot());
  24323. check ("the Start from list opens", panel != nullptr && simple->isStartFromShowing());
  24324. if (panel != nullptr)
  24325. {
  24326. shoot (ui, "startfrom");
  24327. auto list = lynx::startfrom::entries();
  24328. check ("it lists the demo song and the templates shipped", list.size() >= 3 && list[0].kind == lynx::startfrom::Entry::Kind::demo
  24329. && (int) list.size() == panel->entryCountForSnapshot());
  24330. for (auto& e : list)
  24331. report << " " << e.name << " | " << juce::String (e.bpm, 0) << " BPM, " << e.channels << " channels, " << e.bars << " bars"
  24332. << (e.playable ? ", preview" : "") << "\n";
  24333. if (const auto demo = lynx::startfrom::songOf (list[0]))
  24334. {
  24335. const auto wav = juce::File (prefix + "-preview.wav");
  24336. const auto ok = lynx::startfrom::renderPreview (*demo, wav);
  24337. check ("the demo's preview renders (" + juce::String (wav.getSize() / 1024) + " kB)", ok && wav.getSize() > 100000);
  24338. wav.deleteFile();
  24339. }
  24340. panel->selectForSnapshot (juce::jmin (2, panel->entryCountForSnapshot() - 1));
  24341. shoot (ui, "startfrom-selected");
  24342. offline.markSaved(); // (a project with changes asks first: Save / Don't save / Cancel)
  24343. const auto opened = panel->openForSnapshot (0);
  24344. offline.dispatchPendingMessages();
  24345. check ("opening the demo starts a new project from it and closes the list",
  24346. opened && ! simple->isStartFromShowing() && offline.getSong().info.comments.empty() && ! offline.getSong().channels.empty());
  24347. shoot (ui, "startfrom-opened");
  24348. }
  24349. }
  24350. juce::File (prefix + "-report.txt").replaceWithText (report);
  24351. }
  24352. void runVersionsShot (const juce::String& prefix)
  24353. {
  24354. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24355. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  24356. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  24357. };
  24358. // ---- the Versions panel, on files in a temporary folder
  24359. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  24360. .getChildFile ("lynx-versionsshot-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  24361. const juce::ScopeGuard cleanUp { [&root] { root.deleteRecursively(); } };
  24362. const auto project = root.getChildFile ("Night Drive"), backup = root.getChildFile ("Backup");
  24363. project.createDirectory();
  24364. backup.createDirectory();
  24365. const auto now = juce::Time::getCurrentTime();
  24366. const auto put = [&now] (const juce::File& folder, const juce::String& name, const char* kind, int kilobytes, double hoursAgo) {
  24367. const auto time = now - juce::RelativeTime::hours (hoursAgo);
  24368. const auto file = folder.getChildFile (kind == nullptr ? name + ".lynx" : name + " (" + kind + " on " + time.formatted ("%Y-%m-%d at %Hh%M") + ").lynx");
  24369. juce::MemoryBlock data ((size_t) kilobytes * 1024, true);
  24370. file.replaceWithData (data.getData(), data.getSize());
  24371. file.setLastModificationTime (time);
  24372. };
  24373. put (project, "Night Drive", nullptr, 412, 26.0 * 24.0);
  24374. put (project, "Night Drive_2", nullptr, 688, 9.0 * 24.0);
  24375. put (project, "Night Drive_3", nullptr, 731, 2.0 * 24.0);
  24376. put (project, "Night Drive_4", nullptr, 905, 1.6);
  24377. put (backup, "Night Drive_4", "autosaved", 907, 0.07);
  24378. put (backup, "Night Drive_4", "autosaved", 906, 0.4);
  24379. put (backup, "Night Drive_4", "overwritten", 890, 1.6);
  24380. put (backup, "Night Drive_4", "autosaved", 884, 3.2);
  24381. put (backup, "Night Drive_3", "overwritten", 720, 2.0 * 24.0);
  24382. put (backup, "Night Drive_2", "autosaved", 690, 8.0 * 24.0);
  24383. const lynx::VersionsContext context { project.getChildFile ("Night Drive_4.lynx"), "Night Drive_4", backup, ".lynx" };
  24384. {
  24385. const auto entries = lynx::versionEntries (context);
  24386. const auto label = [&] (const juce::String& startsWith, const char* text) {
  24387. for (const auto& e : entries)
  24388. if (juce::String::fromUTF8 (e.name.c_str()).startsWith (startsWith))
  24389. {
  24390. lynx::setVersionLabel (context, e, text);
  24391. return;
  24392. }
  24393. };
  24394. label ("Night Drive_2", "first full arrangement");
  24395. label ("Night Drive_3", "sent to the singer");
  24396. label ("Night Drive_4 (autosaved", "new bass line");
  24397. }
  24398. {
  24399. lynx::VersionsActions actions;
  24400. actions.context = [context] { return context; };
  24401. auto panel = lynx::makeVersionsPanel (actions);
  24402. shoot (*panel, "versions");
  24403. lynx::VersionsActions fresh;
  24404. fresh.context = [backup] { return lynx::VersionsContext { juce::File(), "Untitled", backup, ".lynx" }; };
  24405. auto empty = lynx::makeVersionsPanel (fresh);
  24406. shoot (*empty, "versions-unsaved");
  24407. }
  24408. // ---- the window
  24409. lynx::AudioEngine offline (false);
  24410. lynx::MainComponent ui (offline, false);
  24411. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  24412. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  24413. const auto saveFileMenu = [&] (const char* name) {
  24414. const auto index = juce::jmax (0, ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("File")));
  24415. saveMenus (juce::StringArray { lynx::tr ("File") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-" + name + ".png");
  24416. };
  24417. saveFileMenu ("menu-file");
  24418. // ---- a project opened without its third-party plugins (the plugins are not installed: nothing foreign runs)
  24419. {
  24420. const auto ref = [] (const char* id, const char* name) {
  24421. lynx::PluginRef r;
  24422. r.id = id;
  24423. r.name = name;
  24424. r.state = "c2V0dGluZ3M=";
  24425. return r;
  24426. };
  24427. auto song = lynx::Song::makeDefault();
  24428. while (song.channels.size() < 4)
  24429. song.channels.push_back (song.channels.front());
  24430. while (song.mixer.size() < 5)
  24431. song.mixer.push_back (song.mixer.back());
  24432. const char* names[] = { "Lead", "Pad" };
  24433. for (int c = 0; c < 2; ++c)
  24434. {
  24435. auto& channel = song.channels[(std::size_t) (c + 2)];
  24436. channel.instrument = lynx::InstrumentKind::plugin;
  24437. channel.plugin = ref ("VST3-ShotSynth-11111111-aaaaaaaa", "Shot Synth");
  24438. channel.name = names[c];
  24439. channel.mixerTrack = c + 1;
  24440. }
  24441. lynx::EffectSlot fx;
  24442. fx.kind = lynx::EffectKind::plugin;
  24443. fx.plugin = ref ("VST3-ShotVerb-22222222-bbbbbbbb", "Shot Verb");
  24444. song.mixer[1].effects.push_back (fx);
  24445. fx.plugin = ref ("VST3-ShotComp-33333333-cccccccc", "Shot Comp");
  24446. song.mixer[2].effects.push_back (fx);
  24447. song.mixer[0].effects.push_back (fx);
  24448. offline.setSongWithPluginsOff (std::move (song));
  24449. ui.showDesktopForSnapshot (false);
  24450. shoot (ui, "pluginsoff-window");
  24451. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  24452. shoot (ui, "pluginsoff-mixer"); // (the rack's and the mixer's "off" tags together)
  24453. saveFileMenu ("menu-file-pluginsoff");
  24454. auto panel = lynx::makePluginsOffPanel (offline);
  24455. shoot (*panel, "pluginsoff-panel");
  24456. offline.switchPluginOn ("VST3-ShotVerb-22222222-bbbbbbbb"); // (not installed: "Did not load")
  24457. auto after = lynx::makePluginsOffPanel (offline);
  24458. shoot (*after, "pluginsoff-panel-one");
  24459. }
  24460. // ---- the Export window: as it opens, and with a preset chosen, sections on and a last export to repeat
  24461. {
  24462. auto song = lynx::Song::makeDefault();
  24463. const auto bar = song.barTicks();
  24464. song.mode = lynx::PlayMode::song;
  24465. song.playlist.clear();
  24466. lynx::Clip clip;
  24467. clip.length = 32 * bar;
  24468. song.playlist.push_back (clip);
  24469. const char* sections[] = { "Intro", "Verse", "Chorus", "Outro" };
  24470. for (int i = 0; i < 4; ++i)
  24471. {
  24472. lynx::Marker m;
  24473. m.tick = i * 8 * bar;
  24474. m.name = sections[i];
  24475. song.addMarker (m);
  24476. }
  24477. offline.setSong (std::move (song)); // (also ends the plugins-off mode)
  24478. auto plain = lynx::makeExportPanel (offline, 0);
  24479. shoot (*plain, "export-default");
  24480. auto additions = lynx::makeExportPanelWithAdditions (offline);
  24481. shoot (*additions, "export");
  24482. }
  24483. }
  24484. // Round 190ox (modulators stage 2): the Modulators window with one modulator of each kind (the LFO in Assign mode),
  24485. // a native effect editor and the LYNX Synth page with modulation rings, the parameter menu's "Modulate with"
  24486. // submenu; checks in prefix-checks.txt. --shot-scale 1.5 --shot-suffix @150 for the 150 % pictures.
  24487. void runModShot190ox (const juce::String& prefix)
  24488. {
  24489. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24490. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  24491. juce::String checks;
  24492. int failures = 0;
  24493. 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")); };
  24494. const auto check = [&] (const juce::String& what, bool ok) {
  24495. checks << (ok ? "ok " : "FAIL ") << what << "\n";
  24496. failures += ok ? 0 : 1;
  24497. flush();
  24498. };
  24499. lynx::AudioEngine offline (false);
  24500. lynx::modring::setEngine (&offline);
  24501. const auto settle = [&] {
  24502. for (int k = 0; k < 3; ++k)
  24503. offline.dispatchPendingMessages();
  24504. };
  24505. const auto write = [&prefix, &settle] (juce::Component& c, const juce::String& name) {
  24506. settle();
  24507. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  24508. };
  24509. using namespace lynx;
  24510. offline.editSong ([] (Song& s) {
  24511. if (s.channels.size() < 2)
  24512. s.channels.resize (2);
  24513. s.channels[0].name = "Kick";
  24514. s.channels[0].instrument = InstrumentKind::sampler;
  24515. s.channels[0].mixerTrack = 1;
  24516. s.channels[1].name = "Keys";
  24517. s.channels[1].instrument = InstrumentKind::synth;
  24518. s.channels[1].mixerTrack = 2;
  24519. if (s.mixer.size() < 4)
  24520. s.mixer.resize (4);
  24521. s.mixer[1].name = "Kick";
  24522. s.mixer[2].name = "Keys";
  24523. s.mixer[2].effects.clear();
  24524. s.mixer[2].effects.push_back (makeEffectSlot (EffectKind::filter));
  24525. s.mixer[2].effects.push_back (makeEffectSlot (EffectKind::delay));
  24526. const AutomationTarget cutoff { AutomationTargetKind::effectParam, 2, 0, 1 }, res { AutomationTargetKind::effectParam, 2, 0, 2 }; // (the Filter's Cutoff, Reso.)
  24527. const AutomationTarget synthCutoff { AutomationTargetKind::channelParam, 1, 0, synthparam::target (synthparam::cutoff) };
  24528. const AutomationTarget synthRes { AutomationTargetKind::channelParam, 1, 0, synthparam::target (synthparam::resonance) };
  24529. s.modulators.clear();
  24530. auto add = [&s] (ModKind kind, const char* name, AutomationTarget host, std::vector<ModRoute> routes) {
  24531. auto m = Modulator::make (kind);
  24532. m.name = name;
  24533. m.host = host;
  24534. m.routes = std::move (routes);
  24535. s.modulators.push_back (m);
  24536. return (int) s.modulators.size() - 1;
  24537. };
  24538. const AutomationTarget onKick { AutomationTargetKind::mixerVolume, 1, 0, 0 }, onKeys { AutomationTargetKind::channelVolume, 1, 0, 0 };
  24539. add (ModKind::lfo, "LFO 1", { AutomationTargetKind::mixerVolume, 2, 0, 0 }, { { cutoff, 0.3f }, { synthCutoff, 0.2f } });
  24540. s.modulators.back().shape = ModShape::triangle;
  24541. add (ModKind::follower, "Follower 1", onKick, { { cutoff, -0.4f } });
  24542. s.modulators.back().input = { AutomationTargetKind::mixerVolume, 1, 0, 0 };
  24543. add (ModKind::envelope, "Envelope 1", onKeys, { { synthRes, 0.35f } });
  24544. add (ModKind::steps, "Steps 1", { AutomationTargetKind::mixerVolume, 2, 0, 0 }, { { res, 0.25f } });
  24545. add (ModKind::random, "Random 1", onKeys, { { synthCutoff, -0.15f } });
  24546. s.modulators.back().smooth = 0.5f;
  24547. add (ModKind::macro, "Macro 1", onKeys, { { synthRes, 0.2f }, { { AutomationTargetKind::effectParam, 2, 1, 0 }, 0.3f } });
  24548. s.modulators.back().macro = 0.4f;
  24549. add (ModKind::keytrack, "Keytrack 1", onKeys, { { synthCutoff, 0.1f } });
  24550. add (ModKind::velocity, "Velocity 1", onKeys, {});
  24551. }, false);
  24552. settle();
  24553. modring::setArmed (0);
  24554. // the Modulators window's panel, tall enough for every row
  24555. {
  24556. auto panel = makeModulatorsPanel (offline);
  24557. panel->setSize (900, 1500);
  24558. settle();
  24559. write (*panel, "modulators");
  24560. }
  24561. modring::setArmed (0); // (the panel ends Assign mode when it goes)
  24562. // a native editor's knobs with their rings (the filter's cutoff: LFO 1 armed, Follower 1)
  24563. {
  24564. modring::Ring ring;
  24565. check ("ring on the filter's cutoff: 2 routes, the armed one first",
  24566. modring::ringFor ({ AutomationTargetKind::effectParam, 2, 0, 1 }, ring) && ring.count == 2 && ring.armedRoute == 0);
  24567. if (auto editor = makeNativeEffectEditor (offline, 2, 0))
  24568. write (*editor, "filter-rings");
  24569. if (auto editor = makeNativeEffectEditor (offline, 2, 1))
  24570. write (*editor, "delay-rings");
  24571. modring::setArmed (-1);
  24572. if (auto editor = makeNativeEffectEditor (offline, 2, 0))
  24573. write (*editor, "filter-rings-unarmed");
  24574. }
  24575. // the LYNX Synth page: its tagged knobs show rings
  24576. {
  24577. auto page = makeChannelSettingsPanel (offline, 1);
  24578. page->setSize (juce::jmax (page->getWidth(), 760), juce::jmax (page->getHeight(), 520));
  24579. write (*page, "synth-rings");
  24580. }
  24581. // the parameter menu: the Modulate with submenu of a knob (the routed ones ticked, a new one of each kind)
  24582. {
  24583. juce::PopupMenu menu;
  24584. addAutomationItem (menu, offline, { AutomationTargetKind::effectParam, 2, 0, 1 }, true);
  24585. juce::PopupMenu modulate;
  24586. juce::StringArray rows;
  24587. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  24588. if (it.getItem().subMenu != nullptr && it.getItem().text == tr ("Modulate with"))
  24589. modulate = *it.getItem().subMenu;
  24590. for (juce::PopupMenu::MenuItemIterator it (modulate); it.next();)
  24591. rows.add (it.getItem().text);
  24592. check ("Modulate with: the routed ones and a new one of each kind (" + rows.joinIntoString (" | ") + ")",
  24593. rows.size() >= 8 + 8 + 1 && rows.contains (tr ("New {0}", { tr ("Envelope follower") })));
  24594. saveMenus (juce::StringArray { "Parameter menu", "Modulate with" }, std::vector<juce::PopupMenu> { menu, modulate },
  24595. prefix + "-menu.png");
  24596. }
  24597. modring::setEngine (nullptr);
  24598. flush();
  24599. }
  24600. void runGapShot190og (const juce::String& prefix)
  24601. {
  24602. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24603. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  24604. juce::String checks;
  24605. int failures = 0;
  24606. 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")); };
  24607. const auto check = [&] (const juce::String& what, bool ok) {
  24608. checks << (ok ? "ok " : "FAIL ") << what << "\n";
  24609. failures += ok ? 0 : 1;
  24610. flush();
  24611. };
  24612. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  24613. const auto menuRows = [] (const juce::PopupMenu& menu) {
  24614. juce::StringArray rows;
  24615. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  24616. rows.add (it.getItem().isSeparator ? juce::String ("--") : (it.getItem().isEnabled ? "" : "(off) ") + it.getItem().text.replace ("\t", " | "));
  24617. return rows;
  24618. };
  24619. const auto itemOf = [] (const juce::PopupMenu& menu, const juce::String& start) -> const juce::PopupMenu::Item* {
  24620. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  24621. if (! it.getItem().isSeparator && it.getItem().text.startsWith (start))
  24622. return &it.getItem();
  24623. return nullptr;
  24624. };
  24625. lynx::AudioEngine offline (false);
  24626. lynx::MainComponent ui (offline, false);
  24627. ui.setSize (1600, 900);
  24628. const auto settle = [&] {
  24629. for (int k = 0; k < 3; ++k)
  24630. offline.dispatchPendingMessages();
  24631. };
  24632. const auto write = [&prefix, &settle] (juce::Component& c, const juce::String& name) {
  24633. settle();
  24634. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  24635. };
  24636. const auto area = [&prefix, &settle] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) {
  24637. settle();
  24638. savePng (lynx::shot::snapshot (c).getClippedImage ((r.toFloat() * lynx::shot::scale()).toNearestInt()), prefix + "-" + name + ".png");
  24639. };
  24640. ui.setVisible (true);
  24641. lynx::DetailView::shownSetting = true;
  24642. lynx::DetailView::devicesPage = true;
  24643. ui.setClipLaunchWorkflow (true);
  24644. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  24645. const auto bar = 4 * lynx::ppq;
  24646. offline.editSong ([bar] (lynx::Song& s) {
  24647. if (s.channels.size() < 1)
  24648. s.channels.resize (1);
  24649. s.channels[0].name = "Keys";
  24650. s.channels[0].instrument = lynx::InstrumentKind::synth;
  24651. s.channels[0].mixerTrack = 2;
  24652. if (s.mixer.size() < 4)
  24653. s.mixer.resize (4);
  24654. s.mixer[2].name = "Keys";
  24655. s.mixer[2].effects.clear();
  24656. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  24657. s.mixer[2].effects.push_back (lynx::makeEffectSlot (kind));
  24658. while (s.patterns.size() < 1)
  24659. s.patterns.emplace_back();
  24660. auto& p = s.patterns[0];
  24661. p.name = "Chords";
  24662. p.notes.clear();
  24663. // a one-bar loop with a rising line; a note crossing the loop's end and one after it (Duplicate Loop / Crop)
  24664. const int keys[] { 60, 64, 67, 72, 71, 67, 64, 62 };
  24665. for (int i = 0; i < 8; ++i)
  24666. {
  24667. lynx::Note n;
  24668. n.channel = 0;
  24669. n.key = keys[i];
  24670. n.start = i * (bar / 8);
  24671. n.length = bar / 8 - 60;
  24672. n.velocity = (float) (40 + i * 10) / 127.0f;
  24673. p.notes.push_back (n);
  24674. }
  24675. lynx::Note tail;
  24676. tail.channel = 0;
  24677. tail.key = 55;
  24678. tail.start = bar + lynx::ppq;
  24679. tail.length = lynx::ppq;
  24680. p.notes.push_back (tail);
  24681. p.lengthTicks = 2 * bar;
  24682. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  24683. s.playlistTracks[1].name = "Keys";
  24684. lynx::Clip clip;
  24685. clip.pattern = 0;
  24686. clip.length = bar;
  24687. lynx::launcher::setClip (s, 1, 0, clip);
  24688. if (auto* c = const_cast<lynx::Clip*> (lynx::launcher::clipAt (*s.clipGrid, 1, 0)))
  24689. c->offset = 0, c->length = bar; // (a one-bar loop over the two-bar pattern)
  24690. }, false);
  24691. settle();
  24692. ui.resized();
  24693. auto* detail = ui.getDetailViewForSnapshot();
  24694. auto* grid = ui.getClipGridForSnapshot();
  24695. if (detail == nullptr || grid == nullptr)
  24696. {
  24697. check ("the Clip-launch layout has its detail view and grid", false);
  24698. return;
  24699. }
  24700. const auto editMenu = [&ui] {
  24701. const auto names = ui.getMenuNamesForSnapshot();
  24702. return ui.getMenuForSnapshot (juce::jmax (0, names.indexOf (lynx::tr ("Edit"))));
  24703. };
  24704. const auto fxNames = [&offline] {
  24705. juce::StringArray names;
  24706. for (const auto& fx : offline.getSong().mixer[2].effects)
  24707. names.add (juce::String ((int) fx.kind));
  24708. return names.joinIntoString (",");
  24709. };
  24710. // --- deviceview-0012: the Edit menu's Live block on the Device View ---------------------------------------------
  24711. detail->showSelection (1, 0);
  24712. detail->setPage (lynx::DetailView::Page::devices);
  24713. settle();
  24714. detail->selectCardForCheck (2); // (card 0 the instrument, 1 the EQ, 2 the Compressor)
  24715. settle();
  24716. write (ui, "01-devices-window");
  24717. write (*detail, "01b-devices");
  24718. {
  24719. const auto menu = editMenu();
  24720. saveMenus (juce::StringArray { lynx::tr ("Edit") }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-edit-menu-device.png");
  24721. line ("Edit menu: " + menuRows (menu).joinIntoString (" // "));
  24722. const auto* cut = itemOf (menu, lynx::tr ("Cut") + "\t");
  24723. const auto* paste = itemOf (menu, lynx::tr ("Paste") + "\t");
  24724. check ("Edit menu (Clip-launch): Live's Cut | Ctrl+X, Copy, Paste, Duplicate, Delete | Del after Undo / Redo",
  24725. cut != nullptr && cut->text.endsWith ("Ctrl+X") && itemOf (menu, lynx::tr ("Copy") + "\tCtrl+C") != nullptr
  24726. && paste != nullptr && itemOf (menu, lynx::tr ("Duplicate") + "\tCtrl+D") != nullptr && itemOf (menu, lynx::tr ("Delete") + "\tDel") != nullptr
  24727. && menuRows (menu).indexOf ("--") < menuRows (menu).indexOf (lynx::tr ("Cut") + " | Ctrl+X"));
  24728. check ("a selected device: Cut / Copy / Duplicate / Delete on, Paste off with nothing copied", cut != nullptr && cut->isEnabled && paste != nullptr && ! paste->isEnabled);
  24729. }
  24730. const auto invoke = [&] (const juce::String& start) {
  24731. const auto menu = editMenu();
  24732. if (const auto* item = itemOf (menu, start); item != nullptr && item->isEnabled && item->action != nullptr)
  24733. {
  24734. item->action();
  24735. settle();
  24736. return true;
  24737. }
  24738. return false;
  24739. };
  24740. line ("effects before: " + fxNames());
  24741. check ("Edit > Copy on the Compressor", invoke (lynx::tr ("Copy") + "\t"));
  24742. detail->selectCardForCheck (3); // the Delay
  24743. settle();
  24744. check ("Edit > Paste with the Delay selected: in front of it (Live: \"Pasted devices are inserted in front of the selected device\")",
  24745. invoke (lynx::tr ("Paste") + "\t") && fxNames() == juce::String ((int) lynx::EffectKind::eq) + "," + juce::String ((int) lynx::EffectKind::compressor) + ","
  24746. + juce::String ((int) lynx::EffectKind::compressor) + "," + juce::String ((int) lynx::EffectKind::delay));
  24747. line ("effects after Paste: " + fxNames());
  24748. write (*detail, "03-devices-after-paste");
  24749. check ("Edit > Duplicate", invoke (lynx::tr ("Duplicate") + "\t") && offline.getSong().mixer[2].effects.size() == 5);
  24750. check ("Edit > Delete", invoke (lynx::tr ("Delete") + "\t") && offline.getSong().mixer[2].effects.size() == 4);
  24751. detail->selectCardForCheck (2); // (Delete left nothing selected)
  24752. settle();
  24753. check ("Edit > Cut", invoke (lynx::tr ("Cut") + "\t") && offline.getSong().mixer[2].effects.size() == 3);
  24754. line ("effects after Duplicate, Delete, Cut: " + fxNames());
  24755. // the Pattern layout keeps FL's Edit menu
  24756. ui.setClipLaunchWorkflow (false);
  24757. settle();
  24758. check ("the Pattern layout's Edit menu has no Live block", itemOf (editMenu(), lynx::tr ("Cut") + "\t") == nullptr);
  24759. ui.setClipLaunchWorkflow (true);
  24760. settle();
  24761. ui.resized();
  24762. // --- detail-019: the Clip panel's Duplicate (Loop) button ------------------------------------------------------
  24763. detail->showSelection (1, 0);
  24764. detail->setPage (lynx::DetailView::Page::clip);
  24765. detail->setClipTab (false);
  24766. lynx::DetailView::devicesPage = false;
  24767. detail->clipSectionsForSnapshot (true, true, true, 0);
  24768. settle();
  24769. ui.resized();
  24770. write (ui, "04-clip-window");
  24771. write (*detail, "04b-clip-detail");
  24772. const auto clipNow = [&offline] () -> lynx::Clip {
  24773. const auto& g = offline.getSong().clipGrid;
  24774. const auto* c = g ? lynx::launcher::clipAt (*g, 1, 0) : nullptr;
  24775. return c != nullptr ? *c : lynx::Clip();
  24776. };
  24777. const auto noteCount = [&offline] { return (int) offline.getSong().patterns[0].notes.size(); };
  24778. // (the grid keeps a MIDI clip as long as its pattern: the loop is the pattern's two bars, all 9 notes inside it)
  24779. const auto loopBefore = clipNow().length;
  24780. int inLoop = 0;
  24781. for (const auto& n : offline.getSong().patterns[0].notes)
  24782. inLoop += n.start >= clipNow().offset && n.start < clipNow().offset + loopBefore ? 1 : 0;
  24783. const auto lastBefore = offline.getSong().patterns[0].notes.back().start;
  24784. line ("before: loop " + juce::String (clipNow().offset) + " + " + juce::String (loopBefore) + ", " + juce::String (noteCount()) + " notes, "
  24785. + juce::String (inLoop) + " in the loop");
  24786. check ("the clip is a MIDI clip with 9 notes in its pattern", loopBefore > 0 && noteCount() == 9);
  24787. check ("the Duplicate button pressed", detail->duplicateLoopForCheck());
  24788. settle();
  24789. line ("after Duplicate Loop: loop " + juce::String (clipNow().offset) + " + " + juce::String (clipNow().length) + ", " + juce::String (noteCount()) + " notes, last at "
  24790. + juce::String (offline.getSong().patterns[0].notes.back().start));
  24791. check ("Duplicate Loop: the loop twice as long, the notes in it copied one loop later",
  24792. clipNow().length == 2 * loopBefore && noteCount() == 9 + inLoop && offline.getSong().patterns[0].notes.back().start == lastBefore + loopBefore);
  24793. write (*detail, "05-clip-after-duplicate-loop");
  24794. check ("one undo step brings the one-bar loop back", [&] { ui.runActionForSnapshot ("edit.undo"); settle(); return clipNow().length == loopBefore && noteCount() == 9; }());
  24795. // --- detail-047: the Velocity lane's Randomize footer ---------------------------------------------------------
  24796. auto& roll = ui.getPianoRollForSnapshot();
  24797. roll.setLaneForSnapshot (lynx::PianoRollComponent::laneVelocity);
  24798. settle();
  24799. ui.resized();
  24800. settle();
  24801. const auto footer = roll.liveRandomizeBoundsForCheck();
  24802. line ("roll " + roll.getBounds().toString() + ", footer " + juce::String (roll.liveFooterHeight()) + " px, Randomize " + footer.toString());
  24803. check ("the docked roll (Live look) shows Live's Velocity footer with Randomize", roll.liveFooterHeight() == lynx::PianoRollComponent::liveFooterBar && ! footer.isEmpty());
  24804. write (ui, "06-velocity-footer-window");
  24805. if (roll.getParentComponent() != nullptr)
  24806. area (roll, roll.getLocalBounds().removeFromBottom (90), "06b-velocity-footer");
  24807. {
  24808. std::vector<float> before;
  24809. for (const auto& n : offline.getSong().patterns[0].notes)
  24810. before.push_back (n.velocity);
  24811. lynx::PianoRollComponent::liveRandomizeAmount = 20;
  24812. roll.liveRandomizeVelocity();
  24813. settle();
  24814. int moved = 0, within = 0;
  24815. const auto& notes = offline.getSong().patterns[0].notes;
  24816. for (std::size_t i = 0; i < notes.size() && i < before.size(); ++i)
  24817. {
  24818. const auto d = std::abs (juce::roundToInt (notes[i].velocity * 127.0f) - juce::roundToInt (before[i] * 127.0f));
  24819. moved += d > 0 ? 1 : 0;
  24820. within += d <= 20 ? 1 : 0;
  24821. }
  24822. line ("Randomize (amount 20, nothing selected): " + juce::String (moved) + " of " + juce::String ((int) notes.size()) + " notes moved");
  24823. check ("Randomize with nothing selected moves the notes' velocities by at most the amount", moved > 0 && within == (int) notes.size());
  24824. lynx::PianoRollComponent::liveRandomizeAmount = 100;
  24825. write (ui, "07-velocity-after-randomize");
  24826. }
  24827. // --- detail-020: Crop Clip in the clip's menu and on Ctrl+Shift+J ---------------------------------------------
  24828. {
  24829. const auto menu = lynx::clipGridSlotMenu (*grid, 1, 0);
  24830. saveMenus (juce::StringArray { "Clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-08-clip-menu.png");
  24831. line ("clip menu: " + menuRows (menu).joinIntoString (" // "));
  24832. const auto rows = menuRows (menu);
  24833. const auto crop = rows.indexOf (lynx::tr ("Crop Clip") + " | Ctrl+Shift+J");
  24834. check ("the clip menu (Live look) has Crop Clip | Ctrl+Shift+J in its own group before the colours",
  24835. crop > 0 && rows[crop - 1] == "--" && rows[crop + 1] == "--" && rows.indexOf (lynx::tr ("Deactivate Clip") + " | 0") < crop);
  24836. }
  24837. offline.editSong ([bar] (lynx::Song& s) {
  24838. if (auto* c = s.clipGrid ? const_cast<lynx::Clip*> (lynx::launcher::clipAt (*s.clipGrid, 1, 0)) : nullptr)
  24839. c->offset = bar / 2, c->length = bar / 2; // the loop on the second half bar
  24840. });
  24841. settle();
  24842. lynx::selectClipGridSlotForSnapshot (*grid, 1, 0);
  24843. const auto keyed = lynx::clipGridKeyForSnapshot (*grid, juce::KeyPress ('j', juce::ModifierKeys::commandModifier | juce::ModifierKeys::shiftModifier, 0));
  24844. settle();
  24845. juce::String kept;
  24846. for (const auto& n : offline.getSong().patterns[0].notes)
  24847. kept << n.start << ":" << n.key << " ";
  24848. line ("after Ctrl+Shift+J: loop " + juce::String (clipNow().offset) + " + " + juce::String (clipNow().length) + ", notes " + kept);
  24849. check ("Ctrl+Shift+J crops the clip: the half bar's 4 notes kept, moved to the start; the loop starts at 0",
  24850. keyed && noteCount() == 4 && offline.getSong().patterns[0].notes.front().start == 0 && clipNow().offset == 0 && clipNow().length == bar / 2);
  24851. write (*detail, "09-clip-after-crop");
  24852. // --- mapping-0028: Key Map Mode on the transport switches -------------------------------------------------------
  24853. {
  24854. using namespace lynx::remotemap;
  24855. offline.editSong ([] (lynx::Song& s) {
  24856. assignKey (s, Target::of (lynx::RemoteAction::overdub), 'O');
  24857. assignKey (s, Target::of (lynx::RemoteAction::loopSwitch), 'L');
  24858. assignKey (s, Target::of (lynx::RemoteAction::punchIn), 'I');
  24859. assignKey (s, Target::of (lynx::RemoteAction::punchOut), 'U');
  24860. });
  24861. settle();
  24862. for (const auto mode : { Mode::key, Mode::midi })
  24863. {
  24864. ui.setMapMode (mode);
  24865. settle();
  24866. if (auto* overlay = ui.mapOverlayForSnapshot())
  24867. {
  24868. overlay->refresh();
  24869. const auto& spots = overlay->spots();
  24870. 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; }); };
  24871. line (juce::String (mode == Mode::key ? "key" : "midi") + " map: " + juce::String ((int) spots.size()) + " spots; overdub " + juce::String (count (lynx::RemoteAction::overdub))
  24872. + ", loop " + juce::String (count (lynx::RemoteAction::loopSwitch)) + ", punch in " + juce::String (count (lynx::RemoteAction::punchIn)) + ", punch out "
  24873. + juce::String (count (lynx::RemoteAction::punchOut)));
  24874. check (juce::String (mode == Mode::key ? "Key" : "MIDI") + " Map Mode: Arrangement Overdub, Loop, Punch-In and Punch-Out are mappable in the Control Bar",
  24875. count (lynx::RemoteAction::overdub) == 1 && count (lynx::RemoteAction::loopSwitch) == 1 && count (lynx::RemoteAction::punchIn) == 1
  24876. && count (lynx::RemoteAction::punchOut) == 1);
  24877. }
  24878. write (ui, mode == Mode::key ? "10-keymap" : "11-midimap");
  24879. if (mode == Mode::key)
  24880. area (ui, ui.getLocalBounds().removeFromTop (60), "10b-keymap-controlbar");
  24881. if (mode == Mode::key)
  24882. if (auto* browser = ui.mappingBrowserForSnapshot())
  24883. write (*browser, "12-key-mappings-browser");
  24884. }
  24885. ui.setMapMode (Mode::off);
  24886. settle();
  24887. // the mapped keys switch them, and the mappings survive a save
  24888. const auto options = [&offline] { return offline.getRecordOptions(); };
  24889. const auto blend = options().mode;
  24890. const auto loopBefore = offline.getSong().loopPlays();
  24891. const auto inBefore = options().punchLoopRegion && options().punchIn;
  24892. const auto press = [&] (int key) {
  24893. for (const auto& f : keyFires (offline.getSong(), key, true))
  24894. ui.fireRemote (f);
  24895. settle();
  24896. };
  24897. press ('O');
  24898. press ('L');
  24899. press ('I');
  24900. check ("the mapped keys switch Overdub, Loop and Punch-In", options().mode != blend && offline.getSong().loopPlays() != loopBefore
  24901. && (options().punchLoopRegion && options().punchIn) != inBefore);
  24902. juce::String error;
  24903. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  24904. int kept4 = 0;
  24905. if (back)
  24906. for (const auto& m : back->remoteMappings)
  24907. kept4 += m.action == lynx::RemoteAction::overdub || m.action == lynx::RemoteAction::loopSwitch || m.action == lynx::RemoteAction::punchIn
  24908. || m.action == lynx::RemoteAction::punchOut ? 1 : 0;
  24909. check ("the four mappings are saved with the project and read back", kept4 == 4);
  24910. }
  24911. flush();
  24912. }
  24913. void runUndoShot190mz (const juce::String& prefix)
  24914. {
  24915. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24916. juce::String report;
  24917. int failures = 0;
  24918. const auto check = [&] (const juce::String& name, bool ok) {
  24919. report << (ok ? "OK " : "FAIL ") << name << "\n";
  24920. failures += ok ? 0 : 1;
  24921. };
  24922. {
  24923. lynx::AudioEngine engine (false);
  24924. lynx::MainComponent ui (engine, false);
  24925. ui.setSize (1600, 900);
  24926. engine.dispatchPendingMessages();
  24927. // FL 2026's default: Ctrl+Z steps back
  24928. check ("alternate undo mode is on by default (FL 2026)", ui.getAlternateUndo());
  24929. const auto editMenuText = [&ui] {
  24930. const auto names = ui.getMenuNamesForSnapshot();
  24931. juce::StringArray rows;
  24932. const auto menu = ui.getMenuForSnapshot (juce::jmax (0, names.indexOf (lynx::tr ("Edit"))));
  24933. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  24934. {
  24935. if (it.getItem().isSeparator)
  24936. break;
  24937. rows.add ((it.getItem().isEnabled ? "" : "(off) ") + it.getItem().text.replace ("\t", " | "));
  24938. }
  24939. return rows;
  24940. };
  24941. const auto saveEditMenu = [&ui, &prefix] (const juce::String& name) {
  24942. const auto names = ui.getMenuNamesForSnapshot();
  24943. const auto index = juce::jmax (0, names.indexOf (lynx::tr ("Edit")));
  24944. saveMenus (juce::StringArray { names[index] }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-menu-" + name + ".png");
  24945. };
  24946. const auto key = [&ui, &engine] (const char* action) {
  24947. ui.runActionForSnapshot (action);
  24948. engine.dispatchPendingMessages();
  24949. };
  24950. const auto bpm = [&engine] { return engine.getSong().bpm; };
  24951. const auto start = bpm();
  24952. const auto swing0 = engine.getSong().swing;
  24953. // round 190td (item 72): the step's name in the layout shown (FL's in Pattern, Live's in Clip-launch)
  24954. const auto nameOf = [] (lynx::undonames::Action action, const char* lynxName) {
  24955. lynx::ChangeLabel label;
  24956. label.text = lynxName;
  24957. label.action = action;
  24958. return lynx::ui::undoStepName (label, false);
  24959. };
  24960. const auto log = [&] (const juce::String& state) {
  24961. report << " " << state << ": bpm " << bpm() << ", level " << engine.getHistoryPosition() + 1 << "/" << engine.getHistorySize()
  24962. << ", Edit menu: " << editMenuText().joinIntoString (" // ") << "\n";
  24963. };
  24964. log ("fresh");
  24965. saveEditMenu ("pattern-0-fresh");
  24966. engine.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  24967. engine.editSong ([] (lynx::Song& s) { s.swing = s.swing == 0.25f ? 0.5f : 0.25f; });
  24968. engine.editSong ([] (lynx::Song& s) { s.bpm = 103.0; });
  24969. engine.dispatchPendingMessages();
  24970. log ("three edits");
  24971. saveEditMenu ("pattern-1-three-edits");
  24972. check ("menu names the step: Undo Tempo | Ctrl+Z, no Redo item (FL)",
  24973. editMenuText()[0].startsWith (lynx::tr ("Undo {0}", { nameOf (lynx::undonames::Action::tempo, "Tempo") })) && editMenuText()[0].contains ("Ctrl+Z")
  24974. && ! editMenuText()[1].startsWith (lynx::tr ("Redo {0}", { nameOf (lynx::undonames::Action::tempo, "Tempo") })));
  24975. // the reporter's case (issue #214): Ctrl+Z pressed again keeps going back
  24976. key ("edit.undo");
  24977. log ("Ctrl+Z");
  24978. saveEditMenu ("pattern-2-alt-ctrl-z");
  24979. check ("alternate: menu shows Undo Swing | Ctrl+Z and Redo Tempo | Ctrl+Alt+Z (FL)",
  24980. editMenuText()[0].startsWith (lynx::tr ("Undo {0}", { nameOf (lynx::undonames::Action::swing, "Swing") })) && editMenuText()[0].endsWith ("Ctrl+Z")
  24981. && editMenuText()[1].startsWith (lynx::tr ("Redo {0}", { nameOf (lynx::undonames::Action::tempo, "Tempo") })) && editMenuText()[1].endsWith ("Ctrl+Alt+Z"));
  24982. key ("edit.undo");
  24983. log ("Ctrl+Z x2");
  24984. check ("alternate: Ctrl+Z twice goes two steps back (swing undone, bpm 101)", bpm() == 101.0 && engine.getSong().swing == swing0);
  24985. key ("edit.undo");
  24986. key ("edit.undo"); // (nothing left: nothing happens, no redo)
  24987. log ("Ctrl+Z x4");
  24988. check ("alternate: Ctrl+Z walks to the start and stops there", bpm() == start && ! engine.canUndo() && engine.canRedo());
  24989. saveEditMenu ("pattern-3-alt-at-start");
  24990. key ("edit.redo");
  24991. check ("alternate: Ctrl+Y / Ctrl+Shift+Z redo one step", bpm() == 101.0);
  24992. key ("edit.redo");
  24993. key ("edit.redo");
  24994. check ("alternate: redo back to the newest state", bpm() == 103.0 && ! engine.canRedo());
  24995. key ("edit.undo");
  24996. key ("edit.undoBackwards");
  24997. check ("alternate: Ctrl+Alt+Z redoes what was undone (FL swaps the two keys)", bpm() == 103.0 && ! engine.canRedo());
  24998. // FL's other mode: Ctrl+Z undoes, then redoes (the toggle the issue describes); Ctrl+Alt+Z walks back
  24999. ui.setAlternateUndoForSnapshot (false);
  25000. key ("edit.undo");
  25001. log ("default mode, Ctrl+Z");
  25002. saveEditMenu ("pattern-4-toggle-ctrl-z");
  25003. check ("toggle mode: menu shows Undo Swing | Ctrl+Alt+Z and Redo Tempo | Ctrl+Z (FL)",
  25004. editMenuText()[0].startsWith (lynx::tr ("Undo {0}", { nameOf (lynx::undonames::Action::swing, "Swing") })) && editMenuText()[0].endsWith ("Ctrl+Alt+Z")
  25005. && editMenuText()[1].startsWith (lynx::tr ("Redo {0}", { nameOf (lynx::undonames::Action::tempo, "Tempo") })) && editMenuText()[1].endsWith ("Ctrl+Z"));
  25006. key ("edit.undo");
  25007. log ("default mode, Ctrl+Z x2");
  25008. check ("toggle mode: Ctrl+Z again redoes the step", bpm() == 103.0 && ! engine.canRedo());
  25009. key ("edit.undoBackwards");
  25010. key ("edit.undoBackwards");
  25011. check ("toggle mode: Ctrl+Alt+Z walks back", bpm() == 101.0 && engine.getSong().swing == swing0);
  25012. key ("edit.undo");
  25013. check ("toggle mode: Ctrl+Z after walking back redoes one step (FL: position - 1)", engine.getSong().swing != swing0 && bpm() == 101.0);
  25014. key ("edit.redo");
  25015. check ("toggle mode: Ctrl+Y / Ctrl+Shift+Z redo", bpm() == 103.0 && ! engine.canRedo());
  25016. // Clip-launch and Simple: Live's form (both items, "Nothing to redo", redo on Ctrl+Y)
  25017. ui.setAlternateUndoForSnapshot (true);
  25018. for (const auto style : { lynx::layoutstyle::Style::clipLaunch, lynx::layoutstyle::Style::simple })
  25019. {
  25020. const juce::String name = style == lynx::layoutstyle::Style::simple ? "simple" : "cliplaunch";
  25021. ui.setLayoutStyle (style);
  25022. engine.dispatchPendingMessages();
  25023. log (name);
  25024. saveEditMenu (name + "-1-newest");
  25025. check (name + ": Undo Tempo | Ctrl+Z, Nothing to redo | Ctrl+Y",
  25026. editMenuText()[0].startsWith (lynx::tr ("Undo {0}", { nameOf (lynx::undonames::Action::tempo, "Tempo") })) && editMenuText()[0].endsWith ("Ctrl+Z")
  25027. && editMenuText()[1].startsWith ("(off) " + lynx::tr ("Nothing to redo")) && editMenuText()[1].endsWith ("Ctrl+Y"));
  25028. key ("edit.undo");
  25029. key ("edit.undo");
  25030. log (name + ", Ctrl+Z x2");
  25031. saveEditMenu (name + "-2-ctrl-z-x2");
  25032. check (name + ": Ctrl+Z twice goes two steps back", bpm() == 101.0 && engine.getSong().swing == swing0);
  25033. key ("edit.redo");
  25034. key ("edit.redo");
  25035. check (name + ": Ctrl+Y redoes both", bpm() == 103.0 && ! engine.canRedo());
  25036. }
  25037. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  25038. engine.dispatchPendingMessages();
  25039. }
  25040. report << (failures == 0 ? "ALL OK\n" : juce::String (failures) + " FAILED\n");
  25041. juce::File (prefix + "-checks.txt").replaceWithText (report);
  25042. }
  25043. void runGamepadShot (const juce::String& prefix)
  25044. {
  25045. juce::String report;
  25046. int failures = 0;
  25047. {
  25048. lynx::AudioEngine engine (false);
  25049. auto hints = lynx::makeGamepadHints();
  25050. savePng (lynx::shot::snapshot (*hints), prefix + "-hints.png");
  25051. auto prefs = engine.getMidiPrefs();
  25052. prefs.gamepad = true;
  25053. engine.setMidiPrefs (prefs, false);
  25054. auto page = lynx::makeMidiPage (engine, {}, false);
  25055. page->setSize (760, 1400);
  25056. savePng (lynx::shot::snapshot (*page), prefix + "-settings.png");
  25057. // the poller with fake states: what the handler gets
  25058. using namespace lynx::gamepad;
  25059. std::vector<std::string> got;
  25060. lynx::GamepadInput input ([&got] (const Changes& c, const State&, double dt) {
  25061. for (int i = 0; i < c.pressedCount; ++i)
  25062. got.push_back (std::string ("press ") + buttonName (c.pressed[(std::size_t) i]));
  25063. for (int i = 0; i < c.releasedCount; ++i)
  25064. got.push_back (std::string ("release ") + buttonName (c.released[(std::size_t) i]));
  25065. for (int i = 0; i < c.controllerCount; ++i)
  25066. got.push_back ("cc " + std::to_string (c.controller[(std::size_t) i]) + "=" + std::to_string (c.value[(std::size_t) i]));
  25067. if (c.connectedChanged)
  25068. got.push_back ("connected changed");
  25069. got.push_back ("dt " + std::to_string ((int) std::lround (dt * 1000)));
  25070. });
  25071. State pad;
  25072. pad.connected = true;
  25073. input.inject (pad, 1.0 / 60.0);
  25074. pad.buttons = mask (Button::a);
  25075. pad.rightTrigger = 255;
  25076. input.inject (pad, 1.0 / 60.0);
  25077. pad.buttons = 0;
  25078. input.inject (pad, 1.0 / 60.0);
  25079. const std::vector<std::string> expected { "connected changed", "dt 17", "press A", "cc 102=127", "cc 21=127", "dt 17",
  25080. "release A", "cc 102=0", "dt 17" };
  25081. for (const auto& line : got)
  25082. report << line << "\n";
  25083. if (got != expected)
  25084. {
  25085. ++failures;
  25086. report << "FAILED: the poller's changes differ from the expected ones\n";
  25087. }
  25088. report << "xinput " << (input.available() ? "loaded" : "not available") << "\n";
  25089. }
  25090. report << (failures == 0 ? "gamepad OK" : "gamepad FAILED") << "\n";
  25091. juce::File (prefix + "-gamepad.txt").replaceWithText (report);
  25092. setApplicationReturnValue (failures == 0 ? 0 : 1);
  25093. quit();
  25094. }
  25095. void runBundleExport (const juce::String& inputPath, const juce::String& folderPath, bool zip, bool mixdown, const juce::String& shotPrefix)
  25096. {
  25097. juce::String error;
  25098. bool ok = false;
  25099. lynx::otherapps::Result result;
  25100. {
  25101. lynx::AudioEngine loader (false);
  25102. const juce::File input (inputPath);
  25103. if (input.hasFileExtension ("flp;als"))
  25104. ok = loader.importFlpFile (input, error);
  25105. else if (auto song = lynx::ProjectFile::load (input, error))
  25106. {
  25107. loader.setSong (std::move (*song));
  25108. ok = true;
  25109. }
  25110. if (ok)
  25111. {
  25112. loader.capturePluginStates();
  25113. lynx::otherapps::Context context;
  25114. context.host = &loader.getPluginHost();
  25115. context.flOptions = lynx::flstudio::optionsFor (context.host, lynx::flpexport::LynxOnly::renderAudio, loader.getSong());
  25116. context.render = [] (const lynx::Song& s, const lynx::exportopts::Options& o, const juce::File& file,
  25117. const std::function<bool (double)>& progress, juce::String& err) {
  25118. lynx::ExportJob job (s, o, file);
  25119. return job.run (progress, err);
  25120. };
  25121. context.onMessageThread = [] (std::function<void()> f) { f(); };
  25122. lynx::exportbundle::Options options;
  25123. options.zip = zip;
  25124. options.mixdown = mixdown;
  25125. const auto name = input.getFileNameWithoutExtension();
  25126. const auto shot = [&shotPrefix] (juce::Component& c, const juce::String& suffix) {
  25127. if (shotPrefix.isNotEmpty())
  25128. savePng (lynx::shot::snapshot (c), shotPrefix + suffix);
  25129. };
  25130. if (auto panel = lynx::makeOtherAppsExportPanel (loader, name))
  25131. shot (*panel, "-panel.png");
  25132. ok = lynx::otherapps::write (loader.getSong(), name, options, juce::File (folderPath), context, result);
  25133. if (auto report = lynx::makeOtherAppsReportPanel (result.folder, result.written, result.failed))
  25134. shot (*report, "-report.png");
  25135. }
  25136. }
  25137. juce::String report;
  25138. report << (ok ? "ok " + result.folder.getFullPathName() : "error=" + error) << "\n";
  25139. for (const auto& w : result.written)
  25140. report << "written " << w << "\n";
  25141. for (const auto& f : result.failed)
  25142. report << "failed " << f << "\n";
  25143. juce::File (folderPath).getChildFile ("export-bundle.txt").replaceWithText (report);
  25144. setApplicationReturnValue (ok && result.failed.isEmpty() ? 0 : 1);
  25145. quit();
  25146. }
  25147. void runFlExport (const juce::String& inputPath, const juce::String& outputPath, bool substitute)
  25148. {
  25149. juce::String error;
  25150. bool ok = false;
  25151. lynx::flstudio::Written written;
  25152. {
  25153. lynx::AudioEngine loader (false);
  25154. const juce::File input (inputPath);
  25155. // a Live set opens through the same import as an .flp (as File › Open does, and --export-als accepts an .flp)
  25156. if (input.hasFileExtension ("flp;als;flm;songtmpl;band;blx;mod;xm;s3m;it;dawproject")) // (round 190ri: every format File › Open imports)
  25157. ok = loader.importFlpFile (input, error);
  25158. else if (auto song = lynx::ProjectFile::load (input, error))
  25159. {
  25160. loader.setSong (std::move (*song));
  25161. ok = true;
  25162. }
  25163. if (ok)
  25164. {
  25165. const juce::File output (outputPath);
  25166. const auto zip = output.hasFileExtension ("zip");
  25167. const auto mode = substitute ? lynx::flpexport::LynxOnly::substitute : lynx::flpexport::LynxOnly::renderAudio;
  25168. loader.capturePluginStates();
  25169. auto options = lynx::flstudio::optionsFor (&loader.getPluginHost(), mode, loader.getSong());
  25170. // --flp-ppq N: the file's PPQ (tests; default: 96 when the notes and clips fit it)
  25171. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--flp-ppq"))
  25172. options.ppq = juce::jlimit (0, 960, args[args.indexOf ("--flp-ppq") + 1].getIntValue());
  25173. const auto renderDir = zip ? juce::File::getSpecialLocation (juce::File::tempDirectory).getNonexistentChildFile ("LYNX FL export", {}, false)
  25174. : output.getSiblingFile (output.getFileNameWithoutExtension() + " audio");
  25175. ok = lynx::flstudio::exportProject (loader.getSong(), options, output, zip, renderDir, 44100.0,
  25176. [] (const lynx::Song& s, const lynx::ExportSettings& settings, const juce::File& wav,
  25177. const std::function<bool (double)>& progress, juce::String& err) {
  25178. lynx::ExportJob job (s, settings, wav);
  25179. return job.run (progress, err);
  25180. },
  25181. {}, written, error);
  25182. if (zip)
  25183. renderDir.deleteRecursively();
  25184. }
  25185. }
  25186. juce::String report;
  25187. report << (ok ? "ok" : "error=" + error) << "\n"
  25188. << "exact=" << (int) written.report.exact.size() << " rendered=" << (int) written.report.rendered.size()
  25189. << " substituted=" << (int) written.report.substituted.size() << " dropped=" << (int) written.report.dropped.size()
  25190. << " samples=" << written.samples << "\n\n"
  25191. << lynx::flstudio::reportText (written) << "\n";
  25192. juce::File (outputPath + ".txt").replaceWithText (report);
  25193. setApplicationReturnValue (ok ? 0 : 1);
  25194. quit();
  25195. }
  25196. // LYNX.exe --export project.(flp|als|lynx) output.(wav|flac|ogg|mp3|aif|aiff|m4a|aac) [--pattern] [--insert N] [--rate N]
  25197. // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail. .aif / .aiff: 24-bit AIFF;
  25198. // .m4a: AAC at 192 kbps through the system's encoder (engine/AacEncoder.h; .aac writes the same MPEG-4 file under the
  25199. // name .m4a). M4A is not available on Linux: the export stops with that message.
  25200. void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
  25201. {
  25202. juce::String error, report;
  25203. bool ok = false;
  25204. const auto started = juce::Time::getMillisecondCounterHiRes();
  25205. lynx::loadtrace::begin (inputPath.toStdString()); // phase times (round 112): report lines + load.log
  25206. {
  25207. lynx::AudioEngine loader (false);
  25208. const juce::File input (inputPath);
  25209. // --find-plugins: first the targeted scan opening the project in the app runs (its plugins not known yet)
  25210. if (input.hasFileExtension ("flp") && juce::JUCEApplication::getCommandLineParameters().contains ("--find-plugins"))
  25211. {
  25212. juce::MemoryBlock data;
  25213. if (input.loadFileAsData (data))
  25214. try
  25215. {
  25216. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  25217. auto& host = loader.getPluginHost();
  25218. const auto listed = std::chrono::steady_clock::now();
  25219. const auto files = host.filesToScanFor (uses);
  25220. lynx::loadtrace::add ("plugin_scan_list", lynx::loadtrace::msSince (listed));
  25221. report << "scanned=" << files.joinIntoString (";") << "\n";
  25222. const auto scanned = std::chrono::steady_clock::now();
  25223. host.scanFiles (files, {});
  25224. lynx::loadtrace::add ("plugin_scan", lynx::loadtrace::msSince (scanned), files.size());
  25225. }
  25226. catch (const flp::Error&)
  25227. {
  25228. }
  25229. }
  25230. if (input.hasFileExtension ("flp;als;mod;xm;s3m;it")) // a Live set opens through the same import (round 182b); a module too (190nw)
  25231. ok = loader.importFlpFile (input, error);
  25232. else if (auto song = lynx::ProjectFile::load (input, error))
  25233. {
  25234. loader.setSong (std::move (*song));
  25235. ok = true;
  25236. }
  25237. // M4A without a system AAC encoder (Linux): said before anything is rendered
  25238. if (ok && juce::File (outputPath).hasFileExtension ("m4a;aac") && ! lynx::aac::available())
  25239. {
  25240. ok = false;
  25241. error = juce::String::fromUTF8 (lynx::aac::unavailableReason().c_str());
  25242. }
  25243. if (ok)
  25244. {
  25245. // (an .aac name gets the MPEG-4 file it holds: .m4a)
  25246. const juce::File output (juce::File (outputPath).hasFileExtension ("aac") ? juce::File (outputPath).withFileExtension ("m4a") : juce::File (outputPath));
  25247. lynx::ExportSettings settings;
  25248. settings.wholeSong = ! patternOnly;
  25249. settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
  25250. : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
  25251. : lynx::ExportSettings::Format::wav24;
  25252. // --insert N: only that insert's output (what "Render to audio" records)
  25253. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
  25254. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
  25255. loader.editSong ([] (lynx::Song& s) {
  25256. for (auto& t : s.mixer)
  25257. t.effects.clear();
  25258. }, false);
  25259. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
  25260. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
  25261. loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
  25262. const auto loaded = juce::Time::getMillisecondCounterHiRes();
  25263. // .mp3: the Export window's MP3 (320 kbps); everything else as before
  25264. auto options = settings.toOptions();
  25265. // --save-tempo: FL's "Tempo information" (acid chunk) on (round 167l: compare with FL's AcidBox render; --export)
  25266. if (juce::JUCEApplication::getCommandLineParameters().contains ("--save-tempo"))
  25267. options.saveTempo = true;
  25268. // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
  25269. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
  25270. options.pluginWarmUp = false;
  25271. // --rate N: render at another sample rate (round 157b: samples resampled as at a 48 kHz device)
  25272. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--rate"))
  25273. if (const auto rate = args[args.indexOf ("--rate") + 1].getDoubleValue(); rate >= 8000.0 && rate <= 384000.0)
  25274. options.sampleRate = rate;
  25275. if (output.hasFileExtension ("mp3"))
  25276. {
  25277. options.format = lynx::exportopts::Format::mp3;
  25278. options.mp3Kbps = 320;
  25279. }
  25280. else if (output.hasFileExtension ("aif;aiff")) // (as the .wav: 24 bits, no dither)
  25281. {
  25282. options.format = lynx::exportopts::Format::aiff;
  25283. options.aiffBits = 24;
  25284. }
  25285. else if (output.hasFileExtension ("m4a"))
  25286. {
  25287. options.format = lynx::exportopts::Format::aac;
  25288. options.aacKbps = 192;
  25289. }
  25290. lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), options, output);
  25291. job.setExtraData (true);
  25292. const auto prepared = juce::Time::getMillisecondCounterHiRes();
  25293. lynx::loadtrace::end();
  25294. int lastPercent = -1;
  25295. ok = job.run ([&lastPercent] (double p) {
  25296. lastPercent = (int) (p * 100.0);
  25297. return true;
  25298. }, error);
  25299. auto joined = [] (const std::map<std::string, int>& items) {
  25300. juce::StringArray names;
  25301. for (const auto& [name, count] : items)
  25302. names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
  25303. return names.joinIntoString (", ");
  25304. };
  25305. const auto& importReport = loader.getImportReport();
  25306. report << "converted=" << joined (importReport.converted) << "\n"
  25307. << "approximated=" << joined (importReport.approximated) << "\n"
  25308. << "unsupported=" << joined (importReport.unsupported) << "\n"
  25309. << "not_reproduced=" << joined (importReport.notReproduced) << "\n" // (round qafix190kq)
  25310. << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
  25311. << "partial_effects=" << joined (importReport.partialEffects) << "\n"
  25312. << "missing_samples=" << importReport.missingSamples << "\n";
  25313. // third-party plugins: how each was found, or what plays in its place (diagnostics for level differences)
  25314. for (const auto& line : loader.getMatchedPlugins())
  25315. report << "plugin_found=" << line << "\n";
  25316. for (const auto& m : loader.getMissingPluginDetails())
  25317. report << "plugin_missing=" << juce::String::fromUTF8 (m.name.c_str()) << " -> "
  25318. << juce::String::fromUTF8 (m.replacement.c_str()).replace ("{0}", juce::String::fromUTF8 (m.replacementArg.c_str())) << "\n";
  25319. {
  25320. const auto& song = loader.getSong();
  25321. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  25322. {
  25323. const auto& track = song.mixer[t];
  25324. if (track.effects.empty() && track.sends.empty())
  25325. continue;
  25326. report << "insert " << (int) t << " vol=" << juce::String (track.volume / lynx::unityFader, 3)
  25327. << (track.muted ? " muted" : "") << (track.toMaster ? "" : " noMaster");
  25328. for (const auto& s : track.sends)
  25329. report << " send>" << s.target << "@" << juce::String (s.level, 3);
  25330. report << " |";
  25331. for (const auto& fx : track.effects)
  25332. report << " [" << (fx.kind == lynx::EffectKind::plugin ? juce::String::fromUTF8 (fx.plugin.name.c_str())
  25333. : juce::String::fromUTF8 (lynx::effectInfo (fx.kind).name))
  25334. << (fx.isSubstitute() ? " (substitute)" : "") << (fx.enabled ? "" : " off")
  25335. << (fx.mix < 0.999f ? " mix=" + juce::String (fx.mix, 2) : juce::String()) << "]";
  25336. report << "\n";
  25337. }
  25338. }
  25339. report << juce::String (lynx::loadtrace::reportLines());
  25340. lynx::PluginHost::settingsFolder().getChildFile ("load.log").replaceWithText (juce::String (lynx::loadtrace::table()));
  25341. report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
  25342. << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
  25343. << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
  25344. << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
  25345. << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
  25346. << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
  25347. << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
  25348. << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
  25349. << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
  25350. << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
  25351. << "song_seconds=" << job.getMusicSeconds() << "\n"
  25352. << "peak=" << job.getPeak() << "\n"
  25353. << "final_progress=" << lastPercent << "\n"
  25354. << "bytes=" << output.getSize() << "\n"
  25355. << "file=" << output.getFullPathName() << "\n";
  25356. // round qafix190kq (QA-9): a silent render failed with an empty message. Say why: a project with nothing to
  25357. // play (Live's lesson sets "Playing Software Instruments" / "Recording Audio" hold no clip at all), or a
  25358. // render that stays below -60 dBFS
  25359. if (ok && job.getPeak() <= 0.001f)
  25360. {
  25361. ok = false;
  25362. error = juce::String::fromUTF8 (lynx::exportsilence::reason (loader.getSong(), patternOnly).c_str());
  25363. }
  25364. }
  25365. }
  25366. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  25367. juce::File (outputPath + ".txt").replaceWithText (report);
  25368. setApplicationReturnValue (ok ? 0 : 1);
  25369. quit();
  25370. }
  25371. // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
  25372. // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
  25373. // --editorcpu: one editor after another; each phase runs 2 s to settle and 8 s measured
  25374. struct EditorCpuRun final : juce::Timer
  25375. {
  25376. struct Case { lynx::EffectKind kind; const char* name; int type; bool demo; }; // type 0 native, 1 display-first, 2 Facet EQ
  25377. std::vector<Case> cases;
  25378. std::size_t at = 0;
  25379. int phase = 0;
  25380. double t0 = 0.0, c0 = 0.0;
  25381. juce::String report;
  25382. juce::File out;
  25383. std::unique_ptr<lynx::AudioEngine> engine;
  25384. std::unique_ptr<juce::DocumentWindow> window;
  25385. std::function<void()> done;
  25386. void start()
  25387. {
  25388. engine = std::make_unique<lynx::AudioEngine> (false);
  25389. report << "editor\tmode\tcpu % of one core\n";
  25390. open();
  25391. startTimer (250);
  25392. }
  25393. void open()
  25394. {
  25395. window.reset();
  25396. if (at >= cases.size()) { out.replaceWithText (report); stopTimer(); if (done) done(); return; }
  25397. const auto& c = cases[at];
  25398. lynx::Song song;
  25399. song.mixer.resize (2);
  25400. song.mixer[0].name = "Master";
  25401. song.mixer[1].name = "Insert 1";
  25402. song.mixer[1].effects.push_back (lynx::makeEffectSlot (c.kind));
  25403. engine->setSong (std::move (song));
  25404. engine->dispatchPendingMessages();
  25405. lynx::setNativeEditorDemo (c.demo);
  25406. auto editor = c.type == 1 ? lynx::makeProEditor (*engine, 1, 0, c.demo) : c.type == 2 ? lynx::makeFacetEqEditor (*engine, 1, 0, c.demo)
  25407. : lynx::makeNativeEffectEditor (*engine, 1, 0, 1.0f, 0);
  25408. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX editor CPU - ") + c.name, lynx::theme::colour::bg1, 0);
  25409. window->setUsingNativeTitleBar (true);
  25410. window->setContentOwned (editor.release(), true);
  25411. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  25412. window->setTopLeftPosition (area.getRight() - window->getWidth() - 8, area.getBottom() - window->getHeight() - 8);
  25413. window->setVisible (true);
  25414. phase = 0;
  25415. t0 = juce::Time::getMillisecondCounterHiRes();
  25416. }
  25417. void timerCallback() override
  25418. {
  25419. const auto now = juce::Time::getMillisecondCounterHiRes();
  25420. if (phase == 0 && now - t0 > 2000.0) { phase = 1; t0 = now; c0 = lynx::processCpuSeconds(); return; }
  25421. if (phase == 1 && now - t0 > 8000.0)
  25422. {
  25423. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  25424. const auto& c = cases[at];
  25425. report << c.name << "\t" << (c.demo ? "animating" : "idle") << "\t" << juce::String (cpu, 2) << "\n";
  25426. ++at;
  25427. open();
  25428. }
  25429. }
  25430. };
  25431. std::unique_ptr<EditorCpuRun> editorCpu;
  25432. void runEditorCpu (const juce::String& path)
  25433. {
  25434. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25435. editorCpu = std::make_unique<EditorCpuRun>();
  25436. editorCpu->out = juce::File (path);
  25437. using K = lynx::EffectKind;
  25438. for (const auto demo : { false, true })
  25439. for (const auto& c : std::vector<EditorCpuRun::Case> { { K::facetEq, "Facet EQ", 2, demo }, { K::crestCompressor, "Crest Compressor", 1, demo },
  25440. { K::apexLimiter, "Apex Limiter", 1, demo }, { K::prismMultiband, "Prism Multiband", 1, demo },
  25441. { K::epochVerb, "Epoch Verb", 0, demo }, { K::glowLeveler, "Glow Leveler", 0, demo },
  25442. { K::fruityLimiter, "Fruity Limiter", 0, demo }, { K::lynxTune, "LYNX Tune", 0, demo } })
  25443. editorCpu->cases.push_back (c);
  25444. editorCpu->done = [this] { juce::MessageManager::callAsync ([this] { editorCpu.reset(); quit(); }); };
  25445. editorCpu->start();
  25446. }
  25447. struct ParityShow
  25448. {
  25449. std::unique_ptr<lynx::AudioEngine> engine;
  25450. std::unique_ptr<juce::Component> editor;
  25451. std::unique_ptr<juce::DocumentWindow> window;
  25452. ~ParityShow() { window.reset(); editor.reset(); engine.reset(); }
  25453. };
  25454. std::shared_ptr<ParityShow> parityShow;
  25455. juce::File selfTestTemp; // --selftest: its own temp folder (round 190mo), deleted when the run ends
  25456. bool parityShotFailed = false; // --parityshot: the effect name matched no built-in effect
  25457. void runParityShot (const juce::String& path, const juce::String& effectName, const juce::String& paramsFile)
  25458. {
  25459. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25460. int kindIndex = -1;
  25461. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  25462. if (juce::String::fromUTF8 (lynx::effectInfo ((lynx::EffectKind) k).name).equalsIgnoreCase (effectName))
  25463. kindIndex = k;
  25464. if (kindIndex < 0)
  25465. {
  25466. // round tp172b7: say so and fail (a silent exit 0 hid a split effect name in a launch script)
  25467. std::fprintf (stderr, "unknown effect: %s\n", effectName.toRawUTF8());
  25468. std::fflush (stderr);
  25469. parityShotFailed = true;
  25470. return;
  25471. }
  25472. const auto kind = (lynx::EffectKind) kindIndex;
  25473. auto fx = lynx::makeEffectSlot (kind);
  25474. // round 190jd: LYNX_PARITYSHOT_VIEW=1 = the editor display's second view (Fruity Limiter: LYNX's transfer curve)
  25475. fx.displayView = (std::uint8_t) juce::jlimit (0, 1, juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_VIEW", "0").getIntValue());
  25476. if (paramsFile.isNotEmpty())
  25477. for (const auto& line : juce::StringArray::fromLines (juce::File (paramsFile).loadFileAsString()))
  25478. {
  25479. const auto t = juce::StringArray::fromTokens (line, " \t", "");
  25480. const auto index = t.size() >= 2 ? t[0].getIntValue() : -1;
  25481. if (index >= 0 && index < lynx::maxEffectParams)
  25482. fx.params[(std::size_t) index] = t[1].getFloatValue();
  25483. }
  25484. auto offlineOwner = std::make_unique<lynx::AudioEngine> (false); // (kept alive by LYNX_PARITYSHOT_SHOW's window)
  25485. auto& offline = *offlineOwner;
  25486. auto song = lynx::Song::makeDefault();
  25487. song.mixer.resize (2);
  25488. song.mixer[0].name = "Master";
  25489. song.mixer[1].name = "Insert 1";
  25490. song.mixer[1].effects.assign (1, fx);
  25491. for (auto& c : song.channels)
  25492. c.mixerTrack = 1;
  25493. offline.setSong (std::move (song));
  25494. offline.dispatchPendingMessages();
  25495. const bool facet = kind == lynx::EffectKind::facetEq;
  25496. // round tp172b4: the originals are pictured idle (nothing playing), so the display-first editors are too: no demo
  25497. // history unless LYNX_PARITYSHOT_DEMO=1 asks for the running display
  25498. const bool demoDisplay = juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_DEMO", {}) == "1";
  25499. // (Ember in its Classic voicing: the Classic panel, as the mixer opens it)
  25500. const bool pro = lynx::ProEditorWindows::handles (kind)
  25501. && ! (kind == lynx::EffectKind::ember && fx.params[(std::size_t) lynx::mixsuite::ember::voicing] > 0.5f);
  25502. auto editor = facet ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  25503. : pro ? lynx::makeProEditor (offline, 1, 0, demoDisplay) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  25504. if (editor == nullptr)
  25505. return;
  25506. if (! pro) // the demo song through the effect, the editor ticked 30 times a second of audio as its timer would
  25507. {
  25508. lynx::AudioEngine::RenderOptions o;
  25509. o.seconds = 3.0;
  25510. o.sampleRate = 48000.0;
  25511. o.pluginWarmUp = false;
  25512. int sinceTick = 0;
  25513. o.capture = [&] (const float*, const float*, int n) {
  25514. sinceTick += n;
  25515. if (sinceTick < 1600) return;
  25516. sinceTick = 0;
  25517. if (facet) lynx::tickFacetEqEditor (*editor);
  25518. else lynx::tickNativeEffectEditor (*editor);
  25519. };
  25520. offline.renderOffline (o);
  25521. }
  25522. // round tp172b5: LYNX_PARITYSHOT_CLICKS drives the editor before the picture (the originals' pictures have their
  25523. // panels open), tokens in order: "x,y" a click, then the pointer leaves; "h:x,y" the pointer rests there (a hover);
  25524. // "d:x,y,x2,y2" a drag from there to there, the button still down in the picture
  25525. for (const auto& token : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_CLICKS", {}), " ", ""))
  25526. {
  25527. const auto hover = token.startsWith ("h:"), drag = token.startsWith ("d:");
  25528. const auto xy = juce::StringArray::fromTokens (hover || drag ? token.substring (2) : token, ",", "");
  25529. if (xy.size() < (drag ? 4 : 2))
  25530. continue;
  25531. const juce::Point<int> at (xy[0].getIntValue(), xy[1].getIntValue());
  25532. editor->setVisible (true); // (getComponentAt finds nothing in a hidden component; it never goes on screen)
  25533. auto* target = editor->getComponentAt (at);
  25534. if (target == nullptr)
  25535. continue;
  25536. const auto local = target->getLocalPoint (editor.get(), at).toFloat();
  25537. const auto now = juce::Time::getCurrentTime();
  25538. auto source = juce::Desktop::getInstance().getMainMouseSource();
  25539. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  25540. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods, bool dragged) {
  25541. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, local, now, 1, dragged);
  25542. };
  25543. target->mouseMove (event (local, {}, false));
  25544. if (hover)
  25545. continue;
  25546. target->mouseDown (event (local, left, false));
  25547. if (drag)
  25548. {
  25549. const auto end = target->getLocalPoint (editor.get(), juce::Point<int> (xy[2].getIntValue(), xy[3].getIntValue())).toFloat();
  25550. target->mouseDrag (event (end, left, true));
  25551. continue;
  25552. }
  25553. target->mouseUp (event (local, {}, false));
  25554. target->mouseExit (event ({ -1000.0f, -1000.0f }, {}, false));
  25555. offline.dispatchPendingMessages(); // (round 190jd: an edit the click made, e.g. a display view, reaches the slot)
  25556. }
  25557. // round tp172b6: LYNX_PARITYSHOT_SHOW=1 puts the same editor in a real window and keeps it open (for a guarded GUI check
  25558. // of its pop-up menus, which the offscreen picture cannot hold); closing the window quits
  25559. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_SHOW", {}) == "1")
  25560. {
  25561. struct ShowWindow final : juce::DocumentWindow
  25562. {
  25563. ShowWindow() : juce::DocumentWindow ("LYNX parity check", juce::Colours::black, juce::DocumentWindow::closeButton) {}
  25564. void closeButtonPressed() override { juce::JUCEApplication::getInstance()->systemRequestedQuit(); }
  25565. };
  25566. parityShow = std::make_shared<ParityShow>();
  25567. parityShow->engine = std::move (offlineOwner);
  25568. parityShow->editor = std::move (editor);
  25569. auto window = std::make_unique<ShowWindow>();
  25570. window->setUsingNativeTitleBar (true);
  25571. window->setContentNonOwned (parityShow->editor.get(), true);
  25572. window->setTopLeftPosition (80, 80);
  25573. window->setVisible (true);
  25574. parityShow->window = std::move (window);
  25575. return;
  25576. }
  25577. // round 190ar: LYNX_PARITYSHOT_SCALE=2 draws the same editor at twice the pixel density (as on a 200 % display);
  25578. // round 190bi: the shared shot scale (--shot-scale, LYNX_SHOT_SCALE, LYNX_PARITYSHOT_SCALE as before)
  25579. const auto shotScale = lynx::shot::scale();
  25580. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) editor->getWidth() * shotScale), juce::roundToInt ((float) editor->getHeight() * shotScale), true);
  25581. {
  25582. juce::Graphics g (image);
  25583. g.fillAll (lynx::theme::panel);
  25584. g.addTransform (juce::AffineTransform::scale (shotScale));
  25585. editor->paintEntireComponent (g, false);
  25586. }
  25587. const auto file = lynx::shot::file (juce::File (path));
  25588. file.deleteFile();
  25589. juce::PNGImageFormat png;
  25590. if (auto stream = file.createOutputStream())
  25591. png.writeImageToStream (image, *stream);
  25592. }
  25593. // an Audio Effect Rack shaped like Live's reference (REA_rodada183c §8): two chains with chain-select zones and fades,
  25594. // four named macros (one on a chain's volume, one on two parameters), two variations, every view open
  25595. static lynx::EffectSlot shotRack()
  25596. {
  25597. auto slot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  25598. auto& doc = slot.patcher;
  25599. doc.rack[0].chains[0].name = "Vocoder";
  25600. lynx::PatchNode vocoder, eq, verb;
  25601. vocoder.effect = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  25602. eq.effect = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  25603. verb.effect = lynx::makeEffectSlot (lynx::EffectKind::reeverb2);
  25604. const auto nVoc = lynx::rack::addDevice (doc, 0, vocoder);
  25605. const auto nEq = lynx::rack::addDevice (doc, 0, eq);
  25606. lynx::rack::addChain (doc, "dry bypass");
  25607. lynx::rack::addDevice (doc, 1, verb);
  25608. doc.rack[0].chains[0].select = { 0, 79, 0, 63 };
  25609. doc.rack[0].chains[1].select = { 32, 127, 48, 127 };
  25610. lynx::rack::setChainVolume (doc, 0, 0.33f);
  25611. lynx::rack::setChainVolume (doc, 1, 0.5f);
  25612. const char* names[] { "Sibilance", "Intensity", "Formant Shift", "Bright Level" };
  25613. for (int m = 0; m < 4; ++m)
  25614. doc.rack[0].macros[(std::size_t) m].name = names[m];
  25615. lynx::RackMapping vol;
  25616. vol.target = lynx::RackMapping::Target::chainVolume, vol.chain = 0, vol.min = 0.0f, vol.max = lynx::rack::unityVolume;
  25617. lynx::rack::map (doc, 0, vol);
  25618. lynx::RackMapping a, b, c, d;
  25619. a.node = nVoc, a.param = 0;
  25620. b.node = nVoc, b.param = 1, b.min = 0.2f, b.max = 0.8f;
  25621. c.node = nEq, c.param = 0, c.min = 0.3f, c.max = 0.9f;
  25622. d.node = nEq, d.param = 1;
  25623. lynx::rack::map (doc, 1, a);
  25624. lynx::rack::map (doc, 2, b);
  25625. lynx::rack::map (doc, 3, c);
  25626. lynx::rack::map (doc, 3, d);
  25627. lynx::rack::setMacro (doc, 0, 60.0f);
  25628. lynx::rack::setMacro (doc, 1, 40.0f);
  25629. lynx::rack::setMacro (doc, 2, 70.0f);
  25630. lynx::rack::setMacro (doc, 3, 86.0f);
  25631. lynx::rack::storeVariation (doc);
  25632. lynx::rack::renameVariation (doc, 0, "Verse");
  25633. lynx::rack::setMacro (doc, 3, 120.0f);
  25634. lynx::rack::storeVariation (doc);
  25635. lynx::rack::renameVariation (doc, 1, "Drop");
  25636. lynx::rack::launchVariation (doc, 0);
  25637. auto& r = doc.rack[0];
  25638. r.showMacros = r.showChains = r.showDevices = r.showVariations = true;
  25639. r.zoneEditor = 2;
  25640. r.selectedChain = 0;
  25641. lynx::rack::setSelector (doc, 56.0f);
  25642. lynx::rack::compile (doc);
  25643. return slot;
  25644. }
  25645. bool runRackShots (const juce::File& out, const juce::String& liveSet = {})
  25646. {
  25647. out.createDirectory();
  25648. lynx::AudioEngine offline (false);
  25649. auto save = [&] (juce::Component& c, const juce::String& name) {
  25650. auto image = lynx::shot::paint (c, lynx::theme::panel);
  25651. const auto f = lynx::shot::file (out.getChildFile (name));
  25652. f.deleteFile();
  25653. juce::PNGImageFormat png;
  25654. if (auto stream = f.createOutputStream())
  25655. return png.writeImageToStream (image, *stream);
  25656. return false;
  25657. };
  25658. auto song = lynx::Song::makeDefault();
  25659. song.mixer.resize (3);
  25660. song.mixer[1].name = "Vocal Main";
  25661. auto slot = shotRack();
  25662. song.mixer[1].effects = { slot };
  25663. // an Instrument Rack: three chains split over the keyboard
  25664. lynx::ChannelDef inst;
  25665. inst.name = "Keys Rack";
  25666. inst.instrument = lynx::InstrumentKind::patcher;
  25667. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  25668. for (int k = 0; k < 3; ++k)
  25669. {
  25670. if (k > 0)
  25671. lynx::rack::addChain (inst.patcher);
  25672. lynx::PatchNode synth;
  25673. synth.generator = true;
  25674. synth.channel.instrument = lynx::InstrumentKind::synth;
  25675. synth.channel.name = "Synth";
  25676. lynx::rack::addDevice (inst.patcher, k, synth);
  25677. }
  25678. inst.patcher.rack[0].chains[0].key = { 0, 52, 0, 47 };
  25679. inst.patcher.rack[0].chains[1].key = { 48, 76, 53, 71 };
  25680. inst.patcher.rack[0].chains[2].key = { 72, 127, 77, 127 };
  25681. inst.patcher.rack[0].chains[0].name = "Low";
  25682. inst.patcher.rack[0].chains[1].name = "Mid";
  25683. inst.patcher.rack[0].chains[2].name = "High";
  25684. inst.patcher.rack[0].showChains = inst.patcher.rack[0].showDevices = true;
  25685. inst.patcher.rack[0].zoneEditor = 0;
  25686. lynx::rack::compile (inst.patcher);
  25687. song.channels.push_back (inst);
  25688. const auto channel = (int) song.channels.size() - 1;
  25689. offline.setSong (std::move (song));
  25690. offline.dispatchPendingMessages();
  25691. bool ok = true;
  25692. // [set.als]: a Live set's racks as LYNX imports them, the one with the most chains drawn with its title bar (the
  25693. // like-for-like pair with Live's own picture of that set)
  25694. if (liveSet.isNotEmpty())
  25695. {
  25696. juce::MemoryBlock bytes;
  25697. juce::File (liveSet).loadFileAsData (bytes);
  25698. const std::vector<std::uint8_t> data ((const std::uint8_t*) bytes.getData(), (const std::uint8_t*) bytes.getData() + bytes.getSize());
  25699. lynx::AlsImportOptions o;
  25700. o.common.projectFolder = juce::File (liveSet).getParentDirectory().getFullPathName().toStdString();
  25701. std::string error;
  25702. if (auto imported = lynx::importAls (data, o, &error))
  25703. {
  25704. int bestTrack = -1, bestSlot = -1;
  25705. std::size_t most = 0;
  25706. for (int t = 0; t < (int) imported->mixer.size(); ++t)
  25707. for (int s = 0; s < (int) imported->mixer[(std::size_t) t].effects.size(); ++s)
  25708. 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)
  25709. most = fx.patcher.rack[0].chains.size(), bestTrack = t, bestSlot = s;
  25710. if (bestTrack >= 0)
  25711. {
  25712. offline.setSong (std::move (*imported));
  25713. offline.dispatchPendingMessages();
  25714. auto view = lynx::RackWindows::makeSlotView (offline, bestTrack, bestSlot, true);
  25715. view->setSize (view->preferredWidth (228), 228);
  25716. ok = save (*view, "rack-live-import.png") && ok;
  25717. view->setMapMode (true);
  25718. view->setSize (view->preferredWidth (228), 228);
  25719. ok = save (*view, "rack-live-import-map.png") && ok;
  25720. return ok;
  25721. }
  25722. }
  25723. return false;
  25724. }
  25725. {
  25726. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, false);
  25727. view->setSize (view->preferredWidth (206), 206);
  25728. ok = save (*view, "rack-deviceview.png") && ok;
  25729. }
  25730. {
  25731. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, true);
  25732. view->setMapMode (true);
  25733. view->setSize (view->preferredWidth (228), 228);
  25734. ok = save (*view, "rack-mapmode.png") && ok;
  25735. }
  25736. {
  25737. auto view = lynx::RackWindows::makeChannelView (offline, channel, true);
  25738. view->setSize (view->preferredWidth (228), 228);
  25739. ok = save (*view, "rack-instrument.png") && ok;
  25740. }
  25741. return ok;
  25742. }
  25743. void runEq166fShots (const juce::String& folder)
  25744. {
  25745. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25746. const juce::File out (folder);
  25747. out.createDirectory();
  25748. lynx::AudioEngine offline (false);
  25749. auto save = [&] (juce::Component& editor, const juce::String& name) {
  25750. auto image = lynx::shot::paint (editor, lynx::theme::panel);
  25751. const auto f = lynx::shot::file (out.getChildFile (name));
  25752. f.deleteFile();
  25753. juce::PNGImageFormat png;
  25754. if (auto stream = f.createOutputStream())
  25755. png.writeImageToStream (image, *stream);
  25756. };
  25757. // a song whose demo beat plays into insert 1 (the source) and, for Facet's target, its other half into insert 2
  25758. auto songWith = [] (const lynx::EffectSlot& fx, bool split) {
  25759. auto song = lynx::Song::makeDefault();
  25760. song.mixer.resize (3);
  25761. song.mixer[0].name = "Master";
  25762. song.mixer[1].name = "Vocal";
  25763. song.mixer[2].name = "Reference mix";
  25764. song.mixer[1].effects.assign (1, fx);
  25765. for (std::size_t c = 0; c < song.channels.size(); ++c)
  25766. song.channels[c].mixerTrack = split && c % 2 == 1 ? 2 : 1;
  25767. return song;
  25768. };
  25769. auto feed = [&] (juce::Component& editor, bool facet, int frames) {
  25770. // one continuous render of the song, the editor ticked 30 times a second of audio, as its timer would
  25771. lynx::AudioEngine::RenderOptions o;
  25772. o.seconds = frames / 30.0;
  25773. o.sampleRate = 48000.0;
  25774. o.pluginWarmUp = false;
  25775. int sinceTick = 0;
  25776. o.capture = [&] (const float*, const float*, int n) {
  25777. sinceTick += n;
  25778. if (sinceTick < 1600) return;
  25779. sinceTick = 0;
  25780. if (facet) lynx::tickFacetEqEditor (editor);
  25781. else lynx::tickNativeEffectEditor (editor);
  25782. };
  25783. offline.renderOffline (o);
  25784. if (facet) lynx::tickFacetEqEditor (editor);
  25785. else lynx::tickNativeEffectEditor (editor);
  25786. };
  25787. // Parametric EQ 2: spectrum + heatmap (Full), flat / band 4 +12 dB / band 4 -12 dB, then the Top position
  25788. auto& display = lynx::peqview::displaySettings();
  25789. const auto kept = display;
  25790. display.spectrum = display.heatmap = true;
  25791. display.position = 0;
  25792. 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" },
  25793. { 0.0, "peq2-heatmap-top.png" } })
  25794. {
  25795. auto eq = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  25796. eq.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (gain);
  25797. eq.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (900.0);
  25798. display.position = juce::String (name).contains ("top") ? 1 : 0;
  25799. offline.setSong (songWith (eq, false));
  25800. offline.dispatchPendingMessages();
  25801. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, 0);
  25802. feed (*editor, false, 120);
  25803. save (*editor, name);
  25804. }
  25805. display = kept;
  25806. // Facet EQ's comparative EQ: listening to the target (insert 2) with its spectrum over the source's
  25807. {
  25808. using namespace lynx::facet;
  25809. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  25810. eq.params[(std::size_t) param (0, 0)] = shapeValue (Shape::bell);
  25811. eq.params[(std::size_t) param (0, 1)] = hzValue (250.0);
  25812. eq.params[(std::size_t) param (0, 2)] = gainValue (-4.0);
  25813. eq.params[(std::size_t) param (1, 0)] = shapeValue (Shape::highShelf);
  25814. eq.params[(std::size_t) param (1, 1)] = hzValue (6000.0);
  25815. eq.params[(std::size_t) param (1, 2)] = gainValue (3.0);
  25816. eq.params[(std::size_t) analyzerParam] = analyzerValue (Analyzer::both);
  25817. eq.sidechain = 2;
  25818. for (const auto& [l, name] : { std::pair { Listen::target, "facet-compare-target.png" }, { Listen::eq, "facet-compare-eq.png" } })
  25819. {
  25820. eq.params[(std::size_t) listenParam] = listenValue (l);
  25821. offline.setSong (songWith (eq, true));
  25822. offline.dispatchPendingMessages();
  25823. auto editor = lynx::makeFacetEqEditor (offline, 1, 0, false);
  25824. feed (*editor, true, 90);
  25825. save (*editor, name);
  25826. }
  25827. }
  25828. }
  25829. void runDesign168rShots (const juce::String& folder)
  25830. {
  25831. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25832. const juce::File out (folder);
  25833. out.createDirectory();
  25834. lynx::AudioEngine offline (false);
  25835. using K = lynx::EffectKind;
  25836. for (const auto kind : { K::pitchCorrect, K::lovePhilter, K::peakController, K::spreader, K::fruityFastLP, K::flFrequencyShifter,
  25837. K::flLowLifter, K::distructor, K::flBassBoost, K::flDelay1, K::fl7BandEq, K::flCenter, K::flPhaseInverter,
  25838. K::eq, K::delay, K::reverb, K::limiter, K::filter, K::distortion, K::chorus, K::utility, K::lofi,
  25839. K::crossover, K::pitchShift, K::freqShift, K::rhythmGain, K::volumeGate })
  25840. {
  25841. const auto& bank = lynx::presets::factory (kind);
  25842. // Love Philter / Distructor play FL's state: their second picture is FL's default preset (when installed)
  25843. std::optional<lynx::EffectSlot> flPreset;
  25844. if (kind == K::lovePhilter || kind == K::distructor)
  25845. {
  25846. const auto roots = lynx::findFlStudioRoots();
  25847. const auto file = juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  25848. .getChildFile ("Patches/Plugin presets/Effects")
  25849. .getChildFile (kind == K::lovePhilter ? "Fruity Love Philter/Default.fst" : "Distructor/Default.fst");
  25850. juce::MemoryBlock bytes;
  25851. if (file.loadFileAsData (bytes))
  25852. flPreset = lynx::effectFromFlPreset (std::vector<std::uint8_t> ((const std::uint8_t*) bytes.getData(),
  25853. (const std::uint8_t*) bytes.getData() + bytes.getSize()));
  25854. }
  25855. for (int pass = 0; pass < (bank.empty() && ! flPreset ? 1 : 2); ++pass)
  25856. {
  25857. auto fx = lynx::makeEffectSlot (kind);
  25858. if (pass == 1 && flPreset)
  25859. fx = *flPreset;
  25860. else if (pass == 1)
  25861. {
  25862. fx.params = lynx::presets::apply (kind, bank.front(), 120.0);
  25863. fx.presetName = bank.front().name;
  25864. }
  25865. lynx::Song song;
  25866. song.mixer.resize (2);
  25867. song.mixer[0].name = "Master";
  25868. song.mixer[1].name = "Insert 1";
  25869. song.mixer[1].effects.push_back (fx);
  25870. offline.setSong (std::move (song));
  25871. offline.dispatchPendingMessages();
  25872. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  25873. for (const auto scale : { 1.0f, 2.0f })
  25874. for (int page = 0; page < pages; ++page)
  25875. {
  25876. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, scale, page);
  25877. if (editor == nullptr)
  25878. continue;
  25879. juce::Image image (juce::Image::ARGB, juce::jmax (1, editor->getWidth()), juce::jmax (1, editor->getHeight()), true);
  25880. {
  25881. juce::Graphics g (image);
  25882. g.fillAll (lynx::theme::panel);
  25883. editor->paintEntireComponent (g, false);
  25884. }
  25885. // (FL's "Frequency Shifter" and LYNX's "Frequency shifter" differ only in case: FL editors get "FL ")
  25886. const auto file = out.getChildFile ((lynx::plugui::hasFlLayout (kind) ? "FL " : "")
  25887. + juce::String (lynx::effectInfo (kind).name).replaceCharacters ("/\\:", "---")
  25888. + (pass == 1 ? "-preset" : "") + (page > 0 ? "-p" + juce::String (page + 1) : juce::String())
  25889. + (scale > 1.5f ? "-200" : "-100") + ".png");
  25890. file.deleteFile();
  25891. juce::PNGImageFormat png;
  25892. if (auto stream = file.createOutputStream())
  25893. png.writeImageToStream (image, *stream);
  25894. }
  25895. }
  25896. }
  25897. }
  25898. bool runInstrumentShots (const juce::File& folder, const juce::String& which, const juce::String& source)
  25899. {
  25900. folder.createDirectory();
  25901. auto key = [] (juce::String n) { return n.toLowerCase().removeCharacters (" -!._"); };
  25902. juce::StringArray wanted;
  25903. wanted.addTokens (which, ",", "");
  25904. auto ok = true;
  25905. struct Shot
  25906. {
  25907. juce::String name;
  25908. std::optional<lynx::ChannelDef> channel;
  25909. };
  25910. std::vector<Shot> shots;
  25911. for (const auto& e : lynx::natives::instrumentEngines())
  25912. {
  25913. const auto name = key (e.name);
  25914. const auto banked = which == "banks" && lynx::banks::hasBank (e.kind);
  25915. if (! banked && ! wanted.contains (name))
  25916. continue;
  25917. auto channel = source == "fl" || source == "flm" ? lynx::natives::makeChannel (e.kind, lynx::flStudioAccess())
  25918. : lynx::banks::defaultChannel (e.kind, e.name);
  25919. // (round 190u) source "flm": the channel as the .flm import makes it (Transistor Bass: FL Studio Mobile's build)
  25920. if (source == "flm" && channel && e.kind == lynx::InstrumentKind::transistorbass)
  25921. {
  25922. 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
  25923. channel->modelParams = { 1.0f };
  25924. channel->samplePath.clear();
  25925. }
  25926. if (! channel)
  25927. {
  25928. std::fprintf (stderr, "%s: no %s channel\n", e.name, source.toRawUTF8());
  25929. ok = false;
  25930. continue;
  25931. }
  25932. shots.push_back ({ name, std::move (channel) });
  25933. }
  25934. // Autogun (round 169h): not in the Add menus (no preset files); FL's own render-test channel, either source
  25935. if (wanted.contains ("autogun"))
  25936. {
  25937. if (auto channel = lynx::natives::autogunShotChannel (lynx::flStudioAccess()))
  25938. shots.push_back ({ "autogun", std::move (channel) });
  25939. else
  25940. {
  25941. std::fprintf (stderr, "Autogun: no channel (FL Studio's Render tests\\Autogun.flp)\n");
  25942. ok = false;
  25943. }
  25944. }
  25945. for (auto& shot : shots)
  25946. {
  25947. const auto& name = shot.name;
  25948. auto& channel = shot.channel;
  25949. lynx::AudioEngine offline (false);
  25950. lynx::Song song;
  25951. song.mixer = lynx::Song::defaultMixer (2);
  25952. song.channels.push_back (*channel);
  25953. song.patterns.emplace_back();
  25954. {
  25955. juce::String error; // the project too, so an older build can picture the same channel (--snapshot)
  25956. lynx::ProjectFile::save (song, folder.getChildFile (name + "-" + source + ".lynx"), error);
  25957. }
  25958. offline.setSong (std::move (song));
  25959. offline.dispatchPendingMessages();
  25960. auto frame = lynx::makeChannelFrame (offline, 0, 0);
  25961. if (frame == nullptr || frame->getWidth() <= 0)
  25962. {
  25963. ok = false;
  25964. continue;
  25965. }
  25966. for (const auto scale : { 1.0f, 1.5f, 2.0f })
  25967. {
  25968. const auto file = folder.getChildFile (name + "-" + source + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  25969. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, scale), file.getFullPathName());
  25970. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), frame->getWidth(), frame->getHeight());
  25971. }
  25972. // round 169h: the layout's other pages (Toxic's MIDI / Seq …), one shot each at 1.5×
  25973. for (int page = 1; page < lynx::showChannelLayoutPage (*frame, -1); ++page)
  25974. {
  25975. lynx::showChannelLayoutPage (*frame, page);
  25976. const auto file = folder.getChildFile (name + "-" + source + "-page" + juce::String (page) + "-150.png");
  25977. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, 1.5f), file.getFullPathName());
  25978. std::printf ("%s\n", file.getFullPathName().toRawUTF8());
  25979. }
  25980. }
  25981. return ok;
  25982. }
  25983. // --- round 170j: the pilot editors with their own art -------------------------------------------------
  25984. struct ArtPilot
  25985. {
  25986. std::string file; // the art's name as a file name: "toxic-biohazard"
  25987. bool instrument;
  25988. lynx::InstrumentKind instrumentKind;
  25989. lynx::EffectKind effectKind;
  25990. lynx::skin::Style before; // the automatic style it had before the Themed style
  25991. };
  25992. static juce::StringArray& artOnly() // --artshot / --artgui: only these (file names), all when empty
  25993. {
  25994. static juce::StringArray only;
  25995. return only;
  25996. }
  25997. // every plugin with art of its own (round 170j/170k): generators first, then effects; built from the art
  25998. // registries, so a new theme is shot without touching this list
  25999. static const std::vector<ArtPilot>& artPilots()
  26000. {
  26001. using I = lynx::InstrumentKind;
  26002. using E = lynx::EffectKind;
  26003. static const std::vector<ArtPilot> list = [] {
  26004. std::vector<ArtPilot> all;
  26005. auto slug = [] (lynx::skin::Art a) {
  26006. return juce::String (lynx::skin::artName (a)).toLowerCase().replaceCharacters (" ", "-").removeCharacters ("!.()'").toStdString();
  26007. };
  26008. for (const auto& e : lynx::natives::instrumentEngines()) // (the engines' order first)
  26009. if (const auto a = lynx::skin::artForInstrument (e.kind); a != lynx::skin::Art::none)
  26010. all.push_back ({ slug (a), true, e.kind, E::reverb, lynx::skin::Style::neon });
  26011. for (int k = 0; k <= (int) I::wavetraveller; ++k) // then every other kind with art (DrumSynth, Autogun, Wasp...)
  26012. if (const auto a = lynx::skin::artForInstrument ((I) k); a != lynx::skin::Art::none)
  26013. all.push_back ({ slug (a), true, (I) k, E::reverb, lynx::skin::Style::neon });
  26014. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  26015. if (const auto a = lynx::skin::artForEffect ((E) k); a != lynx::skin::Art::none)
  26016. all.push_back ({ slug (a), false, I::synth, (E) k, lynx::skin::plainStyleFor (k) });
  26017. std::vector<ArtPilot> kept;
  26018. for (auto& p : all)
  26019. if (artOnly().isEmpty() || artOnly().contains (juce::String (p.file)))
  26020. if (std::none_of (kept.begin(), kept.end(), [&] (const ArtPilot& q) { return q.file == p.file; }))
  26021. kept.push_back (p);
  26022. return kept;
  26023. }();
  26024. return list;
  26025. }
  26026. // the song and the editor of a pilot (an instrument: the channel window on its Plugin tab)
  26027. static std::unique_ptr<juce::Component> makeArtPilot (lynx::AudioEngine& engine, const ArtPilot& p)
  26028. {
  26029. lynx::Song song;
  26030. song.mixer = lynx::Song::defaultMixer (2);
  26031. if (p.instrument)
  26032. {
  26033. for (const auto& e : lynx::natives::instrumentEngines())
  26034. if (e.kind == p.instrumentKind)
  26035. {
  26036. auto channel = lynx::natives::makeChannel (e.kind, lynx::flStudioAccess());
  26037. if (! channel) channel = lynx::banks::defaultChannel (e.kind, e.name);
  26038. if (! channel) return nullptr;
  26039. song.channels.push_back (*channel);
  26040. break;
  26041. }
  26042. if (song.channels.empty()) // a kind without an engine entry: its LYNX default, else an empty channel of that kind
  26043. {
  26044. const std::string name = lynx::skin::artName (lynx::skin::artForInstrument (p.instrumentKind));
  26045. auto channel = lynx::banks::defaultChannel (p.instrumentKind, name);
  26046. if (! channel)
  26047. {
  26048. channel = lynx::ChannelDef {};
  26049. channel->instrument = p.instrumentKind;
  26050. channel->name = name;
  26051. }
  26052. song.channels.push_back (*channel);
  26053. }
  26054. song.patterns.emplace_back();
  26055. }
  26056. else
  26057. {
  26058. song.mixer[1].effects.push_back (lynx::makeEffectSlot (p.effectKind));
  26059. }
  26060. engine.setSong (std::move (song));
  26061. engine.dispatchPendingMessages();
  26062. if (p.instrument) return lynx::makeChannelFrame (engine, 0, 0);
  26063. if (p.effectKind == lynx::EffectKind::facetEq) return lynx::makeFacetEqEditor (engine, 1, 0, true);
  26064. if (lynx::ProEditorWindows::handles (p.effectKind)) return lynx::makeProEditor (engine, 1, 0, true); // display-first editors, demo signal
  26065. return lynx::makeNativeEffectEditor (engine, 1, 0, 1.0f, 0);
  26066. }
  26067. // "before": the style each pilot had (forced for its run); "after": automatic (the pilots are Themed)
  26068. static void artPilotStyle (const ArtPilot& p, const juce::String& mode)
  26069. {
  26070. lynx::skin::setForcedStyle (mode == "before" ? (int) p.before : -1);
  26071. lynx::skin::setArtMotion (mode != "still");
  26072. }
  26073. bool runArtShots (const juce::File& folder, bool before)
  26074. {
  26075. folder.createDirectory();
  26076. auto ok = true;
  26077. juce::String titles ("editor\tsize\twidth\tname width at the style's size\tbox\tsize used\tlines\tresult\n");
  26078. for (const auto& p : artPilots())
  26079. {
  26080. artPilotStyle (p, before ? "before" : "after");
  26081. lynx::AudioEngine offline (false);
  26082. auto editor = makeArtPilot (offline, p);
  26083. if (editor == nullptr || editor->getWidth() <= 0)
  26084. {
  26085. std::fprintf (stderr, "%s: no editor\n", p.file.c_str());
  26086. ok = false;
  26087. continue;
  26088. }
  26089. if (p.effectKind == lynx::EffectKind::facetEq) lynx::tickFacetEqEditor (*editor);
  26090. // round 170k2: titles.tsv, how the header's name fitted (its width at the style's size, the box, the size used)
  26091. auto fit = [&] (const juce::String& at) {
  26092. const auto f = lynx::skin::lastTitleFit();
  26093. if (f.have <= 0.0f) return; // no plugin header drawn (a generator's channel window)
  26094. titles << juce::String (p.file) << "\t" << at << "\t" << editor->getWidth() << "\t" << juce::String (f.need, 1) << "\t" << juce::String (f.have, 1)
  26095. << "\t" << juce::String (f.size, 1) << "\t" << f.lines << "\t" << (f.clipped ? "ELLIPSIS" : "full") << "\n";
  26096. };
  26097. for (const auto scale : { 1.0f, 2.0f })
  26098. {
  26099. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  26100. lynx::skin::resetTitleFit();
  26101. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, scale), file.getFullPathName());
  26102. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), editor->getWidth(), editor->getHeight());
  26103. if (scale == 1.0f) fit ("100");
  26104. }
  26105. // ... and at the smallest size its window allows (effect panels; the Pro editors scale as a whole)
  26106. if (const auto smallest = lynx::nativeEditorMinimumSize (*editor); smallest.x > 0)
  26107. {
  26108. editor->setSize (smallest.x, smallest.y);
  26109. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-min.png");
  26110. lynx::skin::resetTitleFit();
  26111. savePng (lynx::shot::snapshot (*editor), file.getFullPathName());
  26112. fit ("min");
  26113. }
  26114. }
  26115. folder.getChildFile (juce::String ("titles-") + (before ? "before" : "after") + ".tsv").replaceWithText (titles);
  26116. lynx::skin::setForcedStyle (-1);
  26117. return ok;
  26118. }
  26119. struct ArtGuiRun final : juce::Timer
  26120. {
  26121. juce::File folder;
  26122. juce::String mode, report;
  26123. std::size_t at = 0;
  26124. int phase = 0;
  26125. double t0 = 0.0, c0 = 0.0;
  26126. std::unique_ptr<lynx::AudioEngine> engine;
  26127. std::unique_ptr<juce::DocumentWindow> window;
  26128. std::function<void()> done;
  26129. void start()
  26130. {
  26131. engine = std::make_unique<lynx::AudioEngine> (false);
  26132. report << "editor\tmode\tcpu % of one core\tart layer animating\n";
  26133. open();
  26134. startTimer (100);
  26135. }
  26136. void open()
  26137. {
  26138. window.reset();
  26139. const auto& pilots = artPilots();
  26140. if (at >= pilots.size())
  26141. {
  26142. folder.getChildFile ("cpu-" + mode + ".txt").replaceWithText (report);
  26143. stopTimer();
  26144. lynx::skin::setForcedStyle (-1);
  26145. lynx::skin::setArtMotion (true);
  26146. if (done) done();
  26147. return;
  26148. }
  26149. const auto& p = pilots[at];
  26150. artPilotStyle (p, mode);
  26151. auto editor = makeArtPilot (*engine, p);
  26152. if (editor == nullptr) { ++at; open(); return; }
  26153. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX art - ") + juce::String (p.file), lynx::theme::colour::bg1, 0);
  26154. window->setUsingNativeTitleBar (true);
  26155. window->setContentOwned (editor.release(), true);
  26156. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  26157. window->setTopLeftPosition (area.getX() + 24, area.getY() + 24);
  26158. window->setAlwaysOnTop (true);
  26159. window->setVisible (true);
  26160. phase = 0;
  26161. t0 = juce::Time::getMillisecondCounterHiRes();
  26162. }
  26163. bool animating() const
  26164. {
  26165. if (window == nullptr || window->getContentComponent() == nullptr) return false;
  26166. std::function<bool (juce::Component&)> find = [&] (juce::Component& c) {
  26167. if (auto* l = dynamic_cast<lynx::skin::ArtLayer*> (&c); l != nullptr && l->animating()) return true;
  26168. for (auto* child : c.getChildren())
  26169. if (find (*child)) return true;
  26170. return false;
  26171. };
  26172. return find (*window->getContentComponent());
  26173. }
  26174. void timerCallback() override
  26175. {
  26176. const auto now = juce::Time::getMillisecondCounterHiRes();
  26177. const auto& p = artPilots()[at];
  26178. const auto ready = folder.getChildFile (juce::String (p.file) + "-" + mode + ".ready");
  26179. const auto shotDone = folder.getChildFile (juce::String (p.file) + "-" + mode + ".done");
  26180. if (phase == 0 && now - t0 > 1500.0)
  26181. {
  26182. // the window's content on screen, in physical pixels, for the outside screenshot to crop
  26183. auto* c = window->getContentComponent();
  26184. const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  26185. const auto b = c->getScreenBounds();
  26186. shotDone.deleteFile();
  26187. ready.replaceWithText (juce::String (juce::roundToInt (b.getX() * scale)) + " " + juce::String (juce::roundToInt (b.getY() * scale)) + " "
  26188. + juce::String (juce::roundToInt (b.getWidth() * scale)) + " " + juce::String (juce::roundToInt (b.getHeight() * scale)));
  26189. phase = 1;
  26190. t0 = now;
  26191. return;
  26192. }
  26193. if (phase == 1 && (shotDone.existsAsFile() || now - t0 > 10000.0))
  26194. {
  26195. ready.deleteFile();
  26196. shotDone.deleteFile();
  26197. phase = 2;
  26198. t0 = now;
  26199. c0 = lynx::processCpuSeconds();
  26200. return;
  26201. }
  26202. if (phase == 2 && now - t0 > 6000.0)
  26203. {
  26204. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  26205. report << juce::String (p.file) << "\t" << mode << "\t" << juce::String (cpu, 2) << "\t" << (animating() ? "yes" : "no") << "\n";
  26206. ++at;
  26207. open();
  26208. }
  26209. }
  26210. };
  26211. std::unique_ptr<ArtGuiRun> artGui;
  26212. void runArtGui (const juce::File& folder, const juce::String& mode)
  26213. {
  26214. folder.createDirectory();
  26215. artGui = std::make_unique<ArtGuiRun>();
  26216. artGui->folder = folder;
  26217. artGui->mode = mode;
  26218. artGui->done = [this] { juce::MessageManager::callAsync ([this] { artGui.reset(); quit(); }); };
  26219. artGui->start();
  26220. }
  26221. void runDesign190inShot (const juce::String& prefix, const juce::String& project)
  26222. {
  26223. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26224. juce::String report;
  26225. {
  26226. lynx::AudioEngine engine (false);
  26227. juce::String error;
  26228. if (const juce::File input (project); input.existsAsFile() && input.hasFileExtension ("flp"))
  26229. report << "import: " << (engine.importFlpFile (input, error) ? "ok" : "failed " + error) << "\n";
  26230. engine.dispatchPendingMessages();
  26231. // a native FL generator with FL's presets (FL's capture: FLEX's "Piano Dark"), on a mixer track of its own
  26232. const auto& fl = lynx::flStudioAccess();
  26233. auto osc = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, fl);
  26234. int generator = -1, sampler = -1;
  26235. engine.editSong ([&] (lynx::Song& s) {
  26236. if (osc)
  26237. {
  26238. osc->mixerTrack = s.claimFreeInsert();
  26239. s.channels.push_back (*osc);
  26240. generator = (int) s.channels.size() - 1;
  26241. }
  26242. if (const juce::File kick (juce::String::fromUTF8 (fl.roots.data.c_str()) + "/Patches/Packs/Drums/Kicks/808 Kick.wav"); kick.existsAsFile())
  26243. {
  26244. lynx::ChannelDef d; // FL's Sampler with a kick, as FL's default channel (the Sample, Envelope and Misc tabs)
  26245. d.instrument = lynx::InstrumentKind::sampler;
  26246. lynx::audioclips::loadSampleInto (d, kick.getFullPathName().toStdString(), "808 Kick");
  26247. d.mixerTrack = s.claimFreeInsert();
  26248. s.channels.push_back (d);
  26249. sampler = (int) s.channels.size() - 1;
  26250. }
  26251. for (const auto withSample : { true, false }) // (a sampler with its sample first, else any)
  26252. for (int c = 0; c < (int) s.channels.size() && sampler < 0; ++c)
  26253. if (s.channels[(std::size_t) c].instrument == lynx::InstrumentKind::sampler && (! withSample || ! s.channels[(std::size_t) c].samplePath.empty()))
  26254. sampler = c;
  26255. });
  26256. engine.dispatchPendingMessages();
  26257. lynx::MainComponent ui (engine, false); // (sets the Channel rack's wrapper-menu items)
  26258. ui.setSize (1920, 1080);
  26259. report << "generator " << generator << ", sampler " << sampler << "\n";
  26260. auto shoot = [&] (juce::Component& c, const juce::String& name) {
  26261. savePng (lynx::shot::snapshot (c), prefix + name);
  26262. report << name << " " << c.getWidth() << "x" << c.getHeight() << "\n";
  26263. };
  26264. auto window = [&] (int channel, int tab, const juce::String& name) {
  26265. if (channel < 0)
  26266. return;
  26267. if (auto w = lynx::makeChannelWindowForShot (engine, channel, tab))
  26268. shoot (*w, name);
  26269. };
  26270. window (generator, 0, "-cw-plugin.png");
  26271. window (generator, -1, "-cw-plugin-misc.png");
  26272. window (sampler, 0, "-cw-sample.png");
  26273. window (sampler, 1, "-cw-envelope.png");
  26274. window (sampler, -1, "-cw-misc.png");
  26275. // the strip of a window with the system's title bar (docking off): ▸ and the presets stay in it
  26276. if (generator >= 0)
  26277. if (auto frame = lynx::makeChannelFrame (engine, generator, 0))
  26278. {
  26279. shoot (*frame, "-frame-floating.png");
  26280. if (auto menu = lynx::channelWrapperMenu (*frame))
  26281. {
  26282. // FL's two columns: the plugin's items, then the Channel column (split at the column break)
  26283. juce::PopupMenu left, right;
  26284. auto* to = &left;
  26285. for (juce::PopupMenu::MenuItemIterator it (*menu); it.next();)
  26286. {
  26287. to->addItem (it.getItem());
  26288. if (it.getItem().shouldBreakAfter)
  26289. to = &right;
  26290. }
  26291. saveMenus (juce::StringArray { "Plugin", "Channel" }, std::vector<juce::PopupMenu> { left, right }, prefix + "-menu-channel.png");
  26292. report << "menu items " << left.getNumItems() << " + " << right.getNumItems() << "\n";
  26293. }
  26294. }
  26295. }
  26296. {
  26297. // FW-8: LYNX engines standing in for FL plugins of an imported project (the import's flOrigin) are titled
  26298. // with FL's name; LYNX's own Delay (no FL origin) keeps its own
  26299. lynx::AudioEngine offline (false);
  26300. lynx::Song song;
  26301. song.mixer.resize (2);
  26302. song.mixer[0].name = "Master";
  26303. song.mixer[1].name = "Insert 1";
  26304. const std::vector<std::pair<lynx::EffectKind, const char*>> standIns { { lynx::EffectKind::limiter, "Fruity Limiter" },
  26305. { lynx::EffectKind::utility, "Fruity Stereo Shaper" }, { lynx::EffectKind::delay, "Fruity Delay 3" },
  26306. { lynx::EffectKind::reverb, "Fruity Reeverb 2" }, { lynx::EffectKind::delay, "" } };
  26307. for (const auto& [kind, origin] : standIns)
  26308. {
  26309. auto fx = lynx::makeEffectSlot (kind);
  26310. fx.flOrigin.plugin = origin;
  26311. song.mixer[1].effects.push_back (fx);
  26312. }
  26313. offline.setSong (std::move (song));
  26314. offline.dispatchPendingMessages();
  26315. std::vector<juce::Image> strips;
  26316. int width = 0, height = 0;
  26317. for (int k = 0; k < (int) standIns.size(); ++k)
  26318. if (auto editor = lynx::makeNativeEffectEditor (offline, 1, k, 1.0f, 0))
  26319. {
  26320. auto image = lynx::shot::paint (*editor, lynx::theme::panel); // (as --plugui draws the editors)
  26321. const auto h = juce::jmin (image.getHeight(), (int) std::ceil (30.0f * lynx::shot::scale()));
  26322. juce::Image strip (juce::Image::ARGB, image.getWidth(), h, true);
  26323. juce::Graphics (strip).drawImageAt (image, 0, 0);
  26324. strips.push_back (strip);
  26325. width = juce::jmax (width, image.getWidth());
  26326. height += h + 4;
  26327. }
  26328. if (! strips.empty())
  26329. {
  26330. juce::Image all (juce::Image::RGB, width, height, true);
  26331. {
  26332. juce::Graphics g (all); // (flushed when it goes: a native image's context draws on its release)
  26333. g.fillAll (juce::Colours::black);
  26334. int y = 0;
  26335. for (auto& strip : strips)
  26336. {
  26337. g.drawImageAt (strip, 0, y);
  26338. y += strip.getHeight() + 4;
  26339. }
  26340. }
  26341. savePng (all, prefix + "-names.png");
  26342. report << "names " << (int) strips.size() << "\n";
  26343. }
  26344. }
  26345. juce::File (prefix + "-report.txt").replaceWithText (report);
  26346. }
  26347. void runPluginEditorSnapshots (const juce::String& folder)
  26348. {
  26349. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26350. {
  26351. const juce::File out (folder);
  26352. out.createDirectory();
  26353. lynx::AudioEngine offline (false);
  26354. const auto roots = lynx::findFlStudioRoots();
  26355. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  26356. auto kinds = lynx::plugui::flLayoutKinds();
  26357. kinds.push_back (lynx::EffectKind::maximus); // Soundgoodizer (below)
  26358. for (const auto own : lynx::plugui::ownLayoutKinds()) // LYNX's own panels (mixing suite, round 96)
  26359. kinds.push_back (own);
  26360. kinds.push_back (lynx::EffectKind::apexLimiter); // round 114: display-first editor
  26361. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 145: the second pass shows the Vocal strip voicing
  26362. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 165: the third pass shows the E console voicing
  26363. kinds.push_back (lynx::EffectKind::compressor); // round 152: the RComp role's panel (vintage voicing, RComp ranges)
  26364. const auto database = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects");
  26365. auto maximusPasses = 0; // Maximus has its own page (first pass); the second pass shows Soundgoodizer
  26366. auto ridgePasses = 0;
  26367. // round 173d3: the parity pictures of one editor — LYNX_PLUGUI_ONLY=<effect name>, LYNX_PLUGUI_PRESET=<.fst>,
  26368. // LYNX_PLUGUI_PAGES=<page,page,…> (the page numbers as the editor encodes them)
  26369. const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_ONLY", {});
  26370. const auto onlyPreset = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PRESET", {});
  26371. const auto onlyPages = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PAGES", {}), ",", "");
  26372. for (const auto kind : kinds)
  26373. {
  26374. if (only.isNotEmpty() && only != lynx::effectInfo (kind).name)
  26375. continue;
  26376. auto fx = lynx::makeEffectSlot (kind);
  26377. juce::String name (lynx::effectInfo (kind).name);
  26378. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  26379. {
  26380. const auto dir = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str()));
  26381. auto file = dir.getChildFile ("Default.fst");
  26382. if (! file.existsAsFile()) // plugins without presets: their entry of FL's plugin database
  26383. for (const auto& f : database.findChildFiles (juce::File::findFiles, true, juce::String::fromUTF8 (plugin.c_str()) + ".fst"))
  26384. file = f;
  26385. if (only.isNotEmpty() && onlyPreset.isNotEmpty())
  26386. file = juce::File (onlyPreset);
  26387. if (! file.existsAsFile())
  26388. {
  26389. auto files = dir.findChildFiles (juce::File::findFiles, true, "*.fst");
  26390. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFullPathName().compareNatural (b.getFullPathName()) < 0; });
  26391. file = files.isEmpty() ? juce::File() : files[0];
  26392. }
  26393. juce::MemoryBlock data;
  26394. if (file.existsAsFile() && file.loadFileAsData (data))
  26395. {
  26396. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  26397. 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)
  26398. {
  26399. fx = *loaded;
  26400. // round 190in (FW-8): a LYNX engine loaded with an FL plugin's preset stands in for that
  26401. // plugin as an imported slot does (its header shows FL's name)
  26402. if (fx.flOrigin.empty() && ! lynx::plugui::hasFlLayout (kind))
  26403. fx.flOrigin.plugin = plugin;
  26404. }
  26405. }
  26406. name = juce::String::fromUTF8 (plugin.c_str());
  26407. break;
  26408. }
  26409. if (kind == lynx::EffectKind::maximus && ++maximusPasses == 2) // Soundgoodizer: preset A of the installation, Amount 60 %
  26410. {
  26411. juce::MemoryBlock data;
  26412. juce::File (juce::String::fromUTF8 (roots.factoryData.c_str())).getChildFile ("Plugins/Fruity/Effects/Soundgoodizer/Data/Presets/a.dat").loadFileAsData (data);
  26413. lynx::maximusfx::Blob blob;
  26414. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  26415. blob.mix = 600;
  26416. const auto* b = static_cast<const std::uint8_t*> (data.getData());
  26417. blob.state.assign (b, b + data.getSize());
  26418. fx = lynx::makeEffectSlot (kind);
  26419. fx.state = lynx::maximusfx::pack (blob);
  26420. name = "Soundgoodizer";
  26421. }
  26422. if (kind == lynx::EffectKind::ridgeStrip && ++ridgePasses == 2) // round 145: her Vocalstrip 2 setting
  26423. {
  26424. for (const auto& [param, value] : { std::pair<const char*, float> { "Vocal strip", 1.0f }, { "Compander", 1.0f },
  26425. { "Compander threshold", 0.3083f }, { "Compander ratio", 0.6929f }, { "Compander attack", 0.2543f },
  26426. { "Compander release", 0.5316f }, { "Make-up", 0.2917f }, { "Soft knee", 1.0f },
  26427. { "Expander threshold", 0.2198f }, { "Vocal input", 0.6792f }, { "Vocal output", 0.3938f },
  26428. { "Process order", 0.4783f }, { "De-esser", 1.0f } })
  26429. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  26430. name = "Ridge Strip (Vocal strip)";
  26431. }
  26432. else if (kind == lynx::EffectKind::ridgeStrip && ridgePasses == 3) // round 165: the E console, EQ to the side chain
  26433. {
  26434. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "HPF", 0.3f }, { "HF gain", 0.8f },
  26435. { "HF bell", 1.0f }, { "Ratio", 0.5f }, { "Comp. threshold", 0.4f }, { "EQ to SC", 1.0f },
  26436. { "Filter split", 1.0f }, { "Expander", 1.0f } })
  26437. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  26438. name = "Ridge Strip (E console)";
  26439. }
  26440. else if (kind == lynx::EffectKind::ridgeStrip) // a vocal setting, so the graphs show something
  26441. for (const auto& [param, value] : { std::pair<const char*, float> { "HPF", 0.3f }, { "LMF gain", 0.35f }, { "HF gain", 0.7f },
  26442. { "Ratio", 0.3f }, { "Comp. threshold", 0.55f } })
  26443. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  26444. if (kind == lynx::EffectKind::compressor) // round 152: the vintage voicing with the reference's ranges and meter
  26445. {
  26446. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "Ranges", 1.0f }, { "Limiter", 1.0f },
  26447. { "Threshold", 0.6f }, { "RC ratio", 0.4f } })
  26448. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  26449. name = "Compressor (RComp role)";
  26450. }
  26451. if (kind == lynx::EffectKind::apexLimiter) // round 114: gain into the ceiling, so the display shows reduction
  26452. fx.params[0] = 0.33f;
  26453. if (kind == lynx::EffectKind::ember)
  26454. {
  26455. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Drive")] = 0.5f;
  26456. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Bands")] = 1.0f; // round 108: the band rows
  26457. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "B3 drive")] = 0.6f;
  26458. }
  26459. if (kind == lynx::EffectKind::crestCompressor) // round 108: a curve with a knee and a side-chain low cut
  26460. for (const auto& [param, value] : { std::pair<const char*, float> { "Threshold", 0.55f }, { "Knee", 0.15f },
  26461. { "SC1 shape", 0.5f }, { "SC1 freq.", 0.3f } })
  26462. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  26463. lynx::Song song;
  26464. song.mixer.resize (2);
  26465. song.mixer[0].name = "Master";
  26466. song.mixer[1].name = "Insert 1";
  26467. song.mixer[1].effects.push_back (fx);
  26468. offline.setSong (std::move (song));
  26469. offline.dispatchPendingMessages();
  26470. if (lynx::ProEditorWindows::handles (kind)) // round 114: the display-first editors, with a demo signal
  26471. {
  26472. auto editor = lynx::makeProEditor (offline, 1, 0, true);
  26473. auto image = lynx::shot::paint (*editor);
  26474. const auto file = lynx::shot::file (out.getChildFile (name + ".png"));
  26475. file.deleteFile();
  26476. juce::PNGImageFormat png;
  26477. if (auto stream = file.createOutputStream())
  26478. png.writeImageToStream (image, *stream);
  26479. continue;
  26480. }
  26481. const auto pages = name == "Soundgoodizer" ? 1 : juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  26482. std::vector<int> pageList;
  26483. for (int page = 0; page < pages; ++page)
  26484. pageList.push_back (page);
  26485. if (only.isNotEmpty() && ! onlyPages.isEmpty())
  26486. {
  26487. pageList.clear();
  26488. for (const auto& p : onlyPages)
  26489. pageList.push_back (p.getIntValue());
  26490. }
  26491. for (const auto page : pageList)
  26492. {
  26493. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  26494. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  26495. const auto file = lynx::shot::file (out.getChildFile (name + (page > 0 ? "-p" + juce::String (page + 1) : juce::String()) + ".png"));
  26496. file.deleteFile();
  26497. juce::PNGImageFormat png;
  26498. if (auto stream = file.createOutputStream())
  26499. png.writeImageToStream (image, *stream);
  26500. }
  26501. }
  26502. // round 137: Echoform in its Rhythm mode (EchoBoy's role) with the Present era
  26503. {
  26504. namespace ef = lynx::echosuite::echoform;
  26505. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  26506. fx.params[ef::rhythm] = 1.0f;
  26507. fx.params[ef::rhythmRepeats] = 5.0f / 15.0f;
  26508. fx.params[ef::rhythmDecay] = 0.25f;
  26509. fx.params[ef::rhythmTap1 + 2] = 0.45f;
  26510. fx.params[ef::feedback] = 0.25f;
  26511. fx.params[ef::era] = 0.5f;
  26512. for (const auto& [param, value] : ef::rhythmPresetEdits (0)) // round 144: a pattern in the rhythm editor (Grid)
  26513. fx.params[(std::size_t) param] = value;
  26514. fx.params[ef::rhythmShape] = 0.5f; // swell
  26515. lynx::Song song;
  26516. song.mixer.resize (2);
  26517. song.mixer[0].name = "Master";
  26518. song.mixer[1].name = "Insert 1";
  26519. song.mixer[1].effects.push_back (fx);
  26520. offline.setSong (std::move (song));
  26521. offline.dispatchPendingMessages();
  26522. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  26523. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  26524. const auto file = lynx::shot::file (out.getChildFile ("Echoform-rhythm.png"));
  26525. file.deleteFile();
  26526. juce::PNGImageFormat png;
  26527. if (auto stream = file.createOutputStream())
  26528. png.writeImageToStream (image, *stream);
  26529. }
  26530. // round 150: Echoform with a voicing (the Stereo / L/R offset controls on the Rhythm row)
  26531. {
  26532. namespace ef = lynx::echosuite::echoform;
  26533. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  26534. fx.params[ef::voicing] = ef::voicingValue (ef::voicingForEchoBoyStyle (19));
  26535. fx.params[ef::style] = ef::styleValue (ef::Style::dual);
  26536. lynx::Song song;
  26537. song.mixer.resize (2);
  26538. song.mixer[0].name = "Master";
  26539. song.mixer[1].name = "Insert 1";
  26540. song.mixer[1].effects.push_back (fx);
  26541. offline.setSong (std::move (song));
  26542. offline.dispatchPendingMessages();
  26543. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  26544. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  26545. const auto file = lynx::shot::file (out.getChildFile ("Echoform-voicing.png"));
  26546. file.deleteFile();
  26547. juce::PNGImageFormat png;
  26548. if (auto stream = file.createOutputStream())
  26549. png.writeImageToStream (image, *stream);
  26550. }
  26551. // round 150: Auto-pan's Rhythm voicing with its Tweak row (PanMan's role)
  26552. {
  26553. auto fx = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  26554. fx.params[lynx::autopan::count] = 1.0f; // the Rhythm voicing
  26555. fx.params[lynx::autopan::count + 13] = 0.75f; // offset mod +90°
  26556. lynx::Song song;
  26557. song.mixer.resize (2);
  26558. song.mixer[0].name = "Master";
  26559. song.mixer[1].name = "Insert 1";
  26560. song.mixer[1].effects.push_back (fx);
  26561. offline.setSong (std::move (song));
  26562. offline.dispatchPendingMessages();
  26563. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  26564. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  26565. const auto file = lynx::shot::file (out.getChildFile ("Auto-pan-tweak.png"));
  26566. file.deleteFile();
  26567. juce::PNGImageFormat png;
  26568. if (auto stream = file.createOutputStream())
  26569. png.writeImageToStream (image, *stream);
  26570. }
  26571. // round 165: Ember's Classic voicing (the Decapitator role) in its one-screen panel
  26572. {
  26573. namespace em = lynx::mixsuite::ember;
  26574. auto fx = lynx::makeEffectSlot (lynx::EffectKind::ember);
  26575. fx.params[em::voicing] = 1.0f;
  26576. fx.params[em::classicDrive] = 0.35f;
  26577. lynx::Song song;
  26578. song.mixer.resize (2);
  26579. song.mixer[0].name = "Master";
  26580. song.mixer[1].name = "Insert 1";
  26581. song.mixer[1].effects.push_back (fx);
  26582. offline.setSong (std::move (song));
  26583. offline.dispatchPendingMessages();
  26584. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  26585. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  26586. const auto file = lynx::shot::file (out.getChildFile ("Ember Saturator-classic.png"));
  26587. file.deleteFile();
  26588. juce::PNGImageFormat png;
  26589. if (auto stream = file.createOutputStream())
  26590. png.writeImageToStream (image, *stream);
  26591. }
  26592. // round 152: Foil Plate's one-knob Plate view (the Little Plate role)
  26593. {
  26594. auto fx = lynx::makeEffectSlot (lynx::EffectKind::foilPlate);
  26595. fx.params[14] = 1.0f; // the measured plate voicing
  26596. fx.params[15] = 1.0f; // View = Plate
  26597. lynx::Song song;
  26598. song.mixer.resize (2);
  26599. song.mixer[0].name = "Master";
  26600. song.mixer[1].name = "Insert 1";
  26601. song.mixer[1].effects.push_back (fx);
  26602. offline.setSong (std::move (song));
  26603. offline.dispatchPendingMessages();
  26604. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  26605. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  26606. const auto file = lynx::shot::file (out.getChildFile ("Foil Plate-plate.png"));
  26607. file.deleteFile();
  26608. juce::PNGImageFormat png;
  26609. if (auto stream = file.createOutputStream())
  26610. png.writeImageToStream (image, *stream);
  26611. }
  26612. // LYNX's own editors with live displays (round 103): Facet EQ (a mixing curve, one dynamic band, demo analyser)
  26613. // and LYNX Tune (demo pitch phrase)
  26614. {
  26615. lynx::setNativeEditorDemo (true);
  26616. using namespace lynx::facet;
  26617. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  26618. const struct { Shape s; double f, g, q; int slope; double range; } bandsDemo[] = {
  26619. { Shape::lowCut, 32, 0, 1, 24, 0 }, { Shape::bell, 110, 3, 1.2, 12, 0 }, { Shape::bell, 380, -3.5, 1.6, 12, 0 },
  26620. { Shape::bell, 3200, 0, 2.5, 12, -6 }, { Shape::highShelf, 9000, 2.5, 0.8, 12, 0 }
  26621. };
  26622. for (int b = 0; b < 5; ++b)
  26623. {
  26624. eq.params[(std::size_t) param (b, 0)] = shapeValue (bandsDemo[b].s);
  26625. eq.params[(std::size_t) param (b, 1)] = hzValue (bandsDemo[b].f);
  26626. eq.params[(std::size_t) param (b, 2)] = gainValue (bandsDemo[b].g);
  26627. eq.params[(std::size_t) param (b, 3)] = qValue (bandsDemo[b].q);
  26628. eq.params[(std::size_t) param (b, 4)] = slopeValue (bandsDemo[b].slope);
  26629. eq.params[(std::size_t) (rangeParam0 + b)] = rangeValue (bandsDemo[b].range);
  26630. }
  26631. eq.params[(std::size_t) phaseParam] = phaseValue (Phase::natural);
  26632. const auto own = [&] (const lynx::EffectSlot& fx, const juce::String& file, bool facetEditor, int page = 0) {
  26633. lynx::Song song;
  26634. song.mixer.resize (2);
  26635. song.mixer[0].name = "Master";
  26636. song.mixer[1].name = "Vocal";
  26637. song.mixer[1].effects.push_back (fx);
  26638. offline.setSong (std::move (song));
  26639. offline.dispatchPendingMessages();
  26640. auto editor = facetEditor ? lynx::makeFacetEqEditor (offline, 1, 0, true) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, page);
  26641. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  26642. const auto f = lynx::shot::file (out.getChildFile (file));
  26643. f.deleteFile();
  26644. juce::PNGImageFormat png;
  26645. if (auto stream = f.createOutputStream())
  26646. png.writeImageToStream (image, *stream);
  26647. };
  26648. own (eq, "Facet EQ.png", true);
  26649. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune.png", false);
  26650. {
  26651. // round 128: the ADVANCED page, with E bypassed and A removed on the keyboard and a created vibrato
  26652. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  26653. tune.params[(std::size_t) (lynx::lynxtune::bypassC + 4)] = 1.0f;
  26654. tune.params[(std::size_t) (lynx::lynxtune::noteC + 9)] = 0.0f;
  26655. tune.params[lynx::lynxtune::vibratoShape] = 1.0f / 3.0f;
  26656. // round 166c: the created vibrato's amplitude / formant / variation, a short throat, In scale +2
  26657. tune.params[lynx::lynxtune::vibratoAmplitude] = 1.0f / 3.0f;
  26658. tune.params[lynx::lynxtune::vibratoFormant] = 0.7f;
  26659. tune.params[lynx::lynxtune::vibratoVariation] = 0.2f;
  26660. tune.params[lynx::lynxtune::throatLength] = lynx::lynxtune::throatValue (80.0);
  26661. tune.params[lynx::lynxtune::transposeInScale] = 1.0f;
  26662. tune.params[lynx::lynxtune::scaleTranspose] = lynx::lynxtune::scaleTransposeValue (2);
  26663. own (tune, "LYNX Tune-p2.png", false, 1);
  26664. }
  26665. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune-p3.png", false, 2); // round 135w: Real-time
  26666. lynx::setNativeEditorDemo (false);
  26667. }
  26668. // generators in FL's arrangement: the channel's plugin page with the FL preset's settings
  26669. const auto generators = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Generators");
  26670. 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" } })
  26671. {
  26672. juce::MemoryBlock data;
  26673. if (juce::String (folder) == "Harmor") // the first preset whose state the engine reads
  26674. {
  26675. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  26676. files.sort();
  26677. for (const auto& f : files)
  26678. {
  26679. juce::MemoryBlock block;
  26680. if (! f.loadFileAsData (block))
  26681. continue;
  26682. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  26683. try
  26684. {
  26685. const auto p = flp::parseProject (std::vector<std::uint8_t> (b, b + block.getSize()), true);
  26686. if (! p.channels.empty() && lynx::harmorStateUsable (p.channels.front().pluginState))
  26687. {
  26688. preset = nullptr;
  26689. data = block;
  26690. break;
  26691. }
  26692. }
  26693. catch (const std::exception&)
  26694. {
  26695. }
  26696. }
  26697. }
  26698. auto file = preset == nullptr ? juce::File() : juce::String (preset).isEmpty() ? database.getSiblingFile ("Generators").getChildFile ("Misc").getChildFile (juce::String (folder) + ".fst")
  26699. : generators.getChildFile (folder).getChildFile (preset);
  26700. if (! file.existsAsFile())
  26701. {
  26702. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  26703. files.sort();
  26704. file = files.isEmpty() ? juce::File() : files[0];
  26705. }
  26706. if (data.isEmpty() && ! file.loadFileAsData (data))
  26707. continue;
  26708. try
  26709. {
  26710. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  26711. auto project = flp::parseProject (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), true);
  26712. if (project.channels.empty())
  26713. continue;
  26714. project.channels.front().type = flp::ChannelType::native;
  26715. lynx::FlpImportOptions options;
  26716. options.roots = roots;
  26717. options.fileExists = [] (const std::string& path) { return lynx::platform::localFile (path).existsAsFile(); };
  26718. options.readFile = [] (const std::string& path) {
  26719. juce::MemoryBlock block;
  26720. lynx::platform::localFile (path).loadFileAsData (block);
  26721. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  26722. return std::vector<std::uint8_t> (b, b + block.getSize());
  26723. };
  26724. options.saveEmbedded = [out] (const std::vector<std::uint8_t>& wav, const std::string& name) {
  26725. const auto f = out.getChildFile ("samples").getNonexistentChildFile (juce::String::fromUTF8 (name.c_str()), ".wav");
  26726. f.getParentDirectory().createDirectory();
  26727. f.replaceWithData (wav.data(), wav.size());
  26728. return f.getFullPathName().toStdString();
  26729. };
  26730. auto song = lynx::importFlp (project, options);
  26731. // the page only needs the plugin's saved state (FL Keys' sample zones need the installed wavetables)
  26732. if (! song.channels.empty() && project.channels.front().pluginName == "BooBass" && song.channels.front().instrument != lynx::InstrumentKind::boobass)
  26733. {
  26734. song.channels.front().instrument = lynx::InstrumentKind::boobass; // (its sound needs the engine DLL; the page does not)
  26735. song.channels.front().modelParams.assign (3, 32768.0f);
  26736. }
  26737. if (! song.channels.empty() && project.channels.front().pluginName == "FL Keys")
  26738. {
  26739. song.channels.front().instrument = lynx::InstrumentKind::flkeys;
  26740. song.channels.front().pluginState = project.channels.front().pluginState;
  26741. }
  26742. offline.setSong (std::move (song));
  26743. offline.dispatchPendingMessages();
  26744. if (offline.getSong().channels.empty())
  26745. continue;
  26746. auto panel = lynx::makeChannelSettingsPanel (offline, 0);
  26747. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  26748. const auto out2 = lynx::shot::file (out.getChildFile (juce::String (folder) + ".png"));
  26749. out2.deleteFile();
  26750. juce::PNGImageFormat png;
  26751. if (auto stream = out2.createOutputStream())
  26752. png.writeImageToStream (image, *stream);
  26753. }
  26754. catch (const std::exception&)
  26755. {
  26756. }
  26757. }
  26758. }
  26759. quit();
  26760. }
  26761. void runVideoShot (const juce::String& prefix, const juce::String& videoPath)
  26762. {
  26763. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26764. // the message loop runs while the frames decode (modal loops are off): a timer takes one snapshot per step
  26765. struct VideoShot final : juce::Timer
  26766. {
  26767. lynx::AudioEngine offline { false };
  26768. std::unique_ptr<juce::Component> editor;
  26769. juce::String prefix, report;
  26770. int step = 0;
  26771. std::function<void()> done;
  26772. void moveTo (double seconds)
  26773. {
  26774. offline.getTransport().positionTicks.store (seconds * offline.getSong().bpm / 60.0 * lynx::ppq);
  26775. }
  26776. void timerCallback() override
  26777. {
  26778. static constexpr double times[] = { 0.0, 1.5, 3.25 };
  26779. constexpr int typeInStep = (int) std::size (times) + 1;
  26780. if (step > 0 && step < typeInStep && editor != nullptr)
  26781. savePng (lynx::shot::snapshot (*editor), prefix + "-" + juce::String (step - 1) + ".png");
  26782. if (editor != nullptr && step == (int) std::size (times))
  26783. {
  26784. // round 174d: FL's in-place type-in of the current time (a right click on it)
  26785. lynx::videoview::openTypeIn (*editor, 2);
  26786. ++step;
  26787. return;
  26788. }
  26789. if (editor != nullptr && step == typeInStep)
  26790. savePng (lynx::shot::snapshot (*editor), prefix + "-typein.png");
  26791. if (editor == nullptr || step >= typeInStep)
  26792. {
  26793. stopTimer();
  26794. juce::File (prefix + "-report.txt").replaceWithText (report);
  26795. if (done)
  26796. done();
  26797. return;
  26798. }
  26799. moveTo (times[step++]);
  26800. }
  26801. };
  26802. static std::unique_ptr<VideoShot> shot;
  26803. shot = std::make_unique<VideoShot>();
  26804. shot->prefix = prefix;
  26805. auto& offline = shot->offline;
  26806. lynx::videoview::install (offline);
  26807. lynx::Song song;
  26808. song.mixer = lynx::Song::defaultMixer (2);
  26809. lynx::ChannelDef c;
  26810. c.name = "Fruity Video Player";
  26811. c.instrument = lynx::InstrumentKind::videoplayer;
  26812. lynx::video::Settings vs;
  26813. vs.path = juce::File (videoPath).getFullPathName().toStdString();
  26814. vs.delay = lynx::video::unitsPerSecond / 2; // the video starts at 0.5 s
  26815. c.pluginState = lynx::video::write (vs);
  26816. song.channels.push_back (c);
  26817. song.patterns.emplace_back();
  26818. {
  26819. // round 174d (A3): the same Video Player in a song whose tempo drops from 120 to 60 BPM at bar 5, for FL
  26820. // (LYNX.exe --export-flp <prefix>-tempo.lynx <prefix>-tempo.flp), to compare FL's video clock with LYNX's
  26821. auto fl = song;
  26822. fl.bpm = 120.0;
  26823. fl.mode = lynx::PlayMode::song;
  26824. auto settings = vs;
  26825. settings.delay = 0;
  26826. settings.timeDisplay = lynx::video::Settings {}.timeDisplay;
  26827. fl.channels[0].pluginState = lynx::video::write (settings);
  26828. fl.patterns[0].name = "Pattern 1";
  26829. lynx::Automation tempo;
  26830. tempo.name = "Tempo";
  26831. tempo.target = { lynx::AutomationTargetKind::tempo, 0, 0, 0 };
  26832. const auto bar = (std::int64_t) lynx::ppq * 4;
  26833. tempo.points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { bar * 4 - 1, lynx::valueFromTempo (120.0), 0.0f },
  26834. { bar * 4, lynx::valueFromTempo (60.0), 0.0f }, { bar * 8, lynx::valueFromTempo (60.0), 0.0f } };
  26835. fl.automations.push_back (tempo);
  26836. lynx::Clip at;
  26837. at.kind = lynx::ClipKind::automation;
  26838. at.automation = 0;
  26839. at.track = 1;
  26840. at.start = 0;
  26841. at.length = bar * 8;
  26842. fl.playlist.push_back (at);
  26843. lynx::Clip pc;
  26844. pc.pattern = 0;
  26845. pc.track = 0;
  26846. pc.start = 0;
  26847. pc.length = bar * 8;
  26848. fl.playlist.push_back (pc);
  26849. juce::String error;
  26850. lynx::ProjectFile::save (fl, juce::File (prefix + "-tempo.lynx"), error);
  26851. }
  26852. offline.setSong (std::move (song));
  26853. offline.dispatchPendingMessages();
  26854. auto& report = shot->report;
  26855. report << "ffmpeg: " << lynx::findFfmpeg().getFullPathName() << "\n";
  26856. report << lynx::videoview::report (vs.path).fromFirstOccurrenceOf ("Input #0", true, false).upToFirstOccurrenceOf ("At least", false, false) << "\n";
  26857. shot->editor = lynx::makeChannelSettingsPanel (offline, 0);
  26858. if (shot->editor != nullptr)
  26859. shot->editor->setVisible (true);
  26860. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  26861. shot->startTimer (1500);
  26862. }
  26863. void runVideoTrackShot (const juce::String& prefix, const juce::String& videoPath, const juce::String& secondPath)
  26864. {
  26865. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26866. struct TrackShot final : juce::Timer
  26867. {
  26868. lynx::AudioEngine offline { false };
  26869. std::unique_ptr<lynx::PlaylistComponent> playlist;
  26870. std::unique_ptr<lynx::media::FrameDecoder> decoder;
  26871. juce::String prefix, report, path;
  26872. double fps = 25.0;
  26873. int step = 0, waits = 0, adrStep = 0;
  26874. std::unique_ptr<juce::Component> adrPanel;
  26875. std::function<void()> done;
  26876. // song times (s): before, inside the first clip (on and between frame edges), across the second clip
  26877. std::vector<double> times { 0.0, 1.0, 2.0 + 1.0 / 25.0, 2.5, 4.0, 7.3 };
  26878. void timerCallback() override
  26879. {
  26880. if (step > 0 && adrStep == 0)
  26881. {
  26882. // the frame the decoder shows for the wanted file time (the clip starts at song 1.0 s, offset 0)
  26883. const auto want = times[(std::size_t) step - 1] - 1.0;
  26884. double ft = -1.0;
  26885. const auto img = decoder->frame (ft);
  26886. const auto expected = std::floor (want * fps + 1e-6) / fps;
  26887. if (want >= 0.0 && ft < expected - 1e-3 && ++waits < 20)
  26888. return; // (still decoding)
  26889. waits = 0;
  26890. report << "song " << juce::String (times[(std::size_t) step - 1], 3) << " s: wanted file time " << juce::String (want, 4)
  26891. << ", frame shown at " << juce::String (ft, 4) << " (expected " << juce::String (expected, 4) << ")"
  26892. << (want < 0.0 ? " [before the clip]" : std::abs (ft - expected) < 1e-3 ? " OK" : " MISMATCH") << "\n";
  26893. savePng (lynx::shot::snapshot (*playlist), prefix + "-playlist-" + juce::String (step - 1) + ".png");
  26894. if (img.isValid())
  26895. savePng (img, prefix + "-frame-" + juce::String (step - 1) + ".png");
  26896. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  26897. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  26898. savePng (lynx::shot::snapshot (*c), prefix + "-window-" + juce::String (step - 1) + ".png");
  26899. }
  26900. if (step >= (int) times.size() && adrStep == 0)
  26901. {
  26902. // the ADR window: two cues, takes on the first; the play position inside the streamer before the in
  26903. // point (4.0 s), so the video window shows the streamer and the line
  26904. adrStep = 1;
  26905. offline.editSong ([] (lynx::Song& s) {
  26906. lynx::AdrCue a, b;
  26907. a.id = "SC1-01";
  26908. a.in = 4.0;
  26909. a.out = 6.4;
  26910. a.character = "Dr. Silva";
  26911. a.line = "We have to leave before the storm reaches the coast.";
  26912. a.notes = "softer, out of breath";
  26913. a.status = lynx::AdrCue::Status::recorded;
  26914. for (int n = 1; n <= 3; ++n)
  26915. {
  26916. lynx::AdrTake t;
  26917. t.number = n;
  26918. t.name = lynx::adr::takeName (a, n);
  26919. t.rating = n == 2 ? 4 : n;
  26920. t.circled = n == 2;
  26921. a.takes.push_back (t);
  26922. }
  26923. a.selected = 2;
  26924. lynx::adr::setCompRange (a, 4.0, 5.1, 2);
  26925. lynx::adr::setCompRange (a, 5.1, 6.4, 3);
  26926. b.id = "SC1-02";
  26927. b.in = 8.0;
  26928. b.out = 9.5;
  26929. b.character = "Marta";
  26930. b.line = "Then we go now.";
  26931. s.adr.cues = { a, b };
  26932. s.adr.current = 0;
  26933. });
  26934. adrPanel = lynx::adrwindow::makePanel (offline);
  26935. adrPanel->setSize (1200, 640);
  26936. adrPanel->setVisible (true);
  26937. offline.getTransport().positionTicks.store (3.0 * offline.getSong().bpm / 60.0 * lynx::ppq);
  26938. decoder->request (2.0, false);
  26939. return;
  26940. }
  26941. if (adrStep == 1)
  26942. {
  26943. adrStep = 2;
  26944. savePng (lynx::shot::snapshot (*adrPanel), prefix + "-adr.png");
  26945. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  26946. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  26947. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window.png");
  26948. offline.getTransport().positionTicks.store (4.5 * offline.getSong().bpm / 60.0 * lynx::ppq);
  26949. decoder->request (3.5, false);
  26950. return;
  26951. }
  26952. if (adrStep == 2)
  26953. {
  26954. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  26955. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  26956. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window-line.png");
  26957. adrPanel.reset();
  26958. // export with video: a 3 s mix under the picture, re-encoded (the clip starts at 1 s) and copied (from 1 s)
  26959. {
  26960. const juce::File wav (prefix + "-mix.wav");
  26961. wav.deleteFile();
  26962. juce::WavAudioFormat format;
  26963. if (std::unique_ptr<juce::OutputStream> os (wav.createOutputStream().release()); os != nullptr)
  26964. if (std::unique_ptr<juce::AudioFormatWriter> w (format.createWriterFor (os.get(), 48000.0, 2, 16, {}, 0)); w != nullptr)
  26965. {
  26966. os.release();
  26967. juce::AudioBuffer<float> b (2, 48000 * 3);
  26968. for (int k = 0; k < b.getNumSamples(); ++k)
  26969. 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));
  26970. w->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  26971. }
  26972. for (const auto origin : { 0.0, 1.0 })
  26973. {
  26974. const juce::File out (prefix + "-mux-" + juce::String ((int) origin) + ".mp4");
  26975. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  26976. const auto error = lynx::videotracks::muxWithVideo (offline.getSong(), origin, wav, out);
  26977. report << "export with video from " << origin << " s: " << (error.isEmpty() ? "OK " + juce::String (out.getSize()) + " bytes" : "FAILED " + error)
  26978. << " (" << juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0, 2) << " s)\n";
  26979. }
  26980. }
  26981. stopTimer();
  26982. report << "frames decoded " << decoder->frameCount() << ", dropped " << decoder->droppedCount() << "\n";
  26983. juce::File (prefix + "-report.txt").replaceWithText (report);
  26984. if (done)
  26985. done();
  26986. return;
  26987. }
  26988. const auto t = times[(std::size_t) step++];
  26989. offline.getTransport().positionTicks.store (t * offline.getSong().bpm / 60.0 * lynx::ppq);
  26990. decoder->request (std::max (0.0, t - 1.0), false);
  26991. }
  26992. };
  26993. static std::unique_ptr<TrackShot> shot;
  26994. shot = std::make_unique<TrackShot>();
  26995. shot->prefix = prefix;
  26996. auto& offline = shot->offline;
  26997. lynx::Song song;
  26998. song.mixer = lynx::Song::defaultMixer (2);
  26999. song.patterns.emplace_back();
  27000. song.mode = lynx::PlayMode::song;
  27001. song.bpm = 120.0;
  27002. offline.setSong (std::move (song));
  27003. offline.dispatchPendingMessages();
  27004. const juce::File video (videoPath);
  27005. const auto pr = lynx::media::probe (video.getFullPathName());
  27006. auto& report = shot->report;
  27007. report << "decoder: " << (pr.backend.isEmpty() ? juce::String ("none") : pr.backend) << " (system: " << lynx::media::nativeBackendName()
  27008. << ", ffmpeg: " << lynx::findFfmpeg().getFullPathName() << ")\n";
  27009. report << "video: " << pr.info.width << "x" << pr.info.height << " " << juce::String (pr.info.fps, 3) << " fps " << juce::String (pr.info.duration, 3)
  27010. << " s, sound " << (pr.info.hasAudio ? "yes" : "no") << "\n";
  27011. shot->fps = pr.info.fps > 1.0 ? pr.info.fps : 25.0;
  27012. shot->times[2] = 2.0 + 1.0 / shot->fps; // (exactly on a frame edge)
  27013. lynx::videotracks::importVideo (offline, video, 1.0, -1);
  27014. if (secondPath.isNotEmpty())
  27015. lynx::videotracks::importVideo (offline, juce::File (secondPath), 3.0, 1);
  27016. offline.editSong ([] (lynx::Song& s) {
  27017. s.video.startTimecode = 3600.0;
  27018. s.video.burnIn = true;
  27019. while (s.videoTracks.size() < 2) // (round 190rf, ASan: no video could be imported at all)
  27020. s.videoTracks.push_back ({});
  27021. s.videoTracks[0].name = "Picture";
  27022. s.videoTracks[1].name = "Reference";
  27023. });
  27024. report << "project rate: " << lynx::vtime::rateName (offline.getSong().video.rate) << ", clip 1: "
  27025. << juce::String (offline.getSong().videoTracks[0].clips.empty() ? -1.0 : offline.getSong().videoTracks[0].clips[0].length, 3) << " s\n";
  27026. // the project round trip
  27027. {
  27028. const juce::File file (prefix + "-project.lynx");
  27029. juce::String error;
  27030. lynx::ProjectFile::save (offline.getSong(), file, error);
  27031. const auto back = lynx::ProjectFile::load (file, error);
  27032. report << "project file round trip: " << (back && back->videoTracks == offline.getSong().videoTracks && back->video == offline.getSong().video ? "OK" : "MISMATCH " + error) << "\n";
  27033. }
  27034. shot->playlist = std::make_unique<lynx::PlaylistComponent> (offline);
  27035. shot->playlist->setSize (1400, 640);
  27036. shot->playlist->setVisible (true);
  27037. shot->decoder = std::make_unique<lynx::media::FrameDecoder>();
  27038. shot->decoder->setSource (video.getFullPathName(), pr.info);
  27039. shot->decoder->setSize (pr.info.width, pr.info.height);
  27040. shot->decoder->startThread (juce::Thread::Priority::low);
  27041. lynx::videotracks::showWindow (offline, 0);
  27042. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  27043. shot->startTimer (700);
  27044. }
  27045. void runDanceShot (const juce::String& prefix)
  27046. {
  27047. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27048. // the moves: one row each, eight moments of a cycle (both facings for Spinning; Pose ends the sheet)
  27049. {
  27050. constexpr int cell = 120, cols = 8;
  27051. auto sheet = lynx::shot::canvas (130 + cols * cell, lynx::dance::moveCount * cell + 10);
  27052. {
  27053. // (the picture is complete when its Graphics is gone: round 190ba, the file was blank on Windows)
  27054. juce::Graphics g (sheet);
  27055. lynx::shot::logical (g);
  27056. g.fillAll (lynx::theme::colour::bg0);
  27057. for (int m = 0; m < lynx::dance::moveCount; ++m)
  27058. {
  27059. g.setColour (lynx::theme::colour::textSecondary);
  27060. g.setFont (14.0f);
  27061. g.drawText (lynx::dance::moveName (m), 8, m * cell + 5, 118, cell, juce::Justification::centredLeft);
  27062. for (int k = 0; k < cols; ++k)
  27063. {
  27064. const auto pose = lynx::dance::pose (m, k / (double) cols + (m == lynx::dance::freestyle ? k * 2 : 0), 1);
  27065. lynx::dancer::draw (g, { 130.0f + (k + 0.5f) * cell, (float) (m + 1) * cell - 6.0f }, 92.0f, pose, false, juce::Colour (0xffff3048));
  27066. }
  27067. }
  27068. }
  27069. savePng (sheet, prefix + "-moves.png");
  27070. }
  27071. lynx::AudioEngine offline (false);
  27072. lynx::Song song;
  27073. song.mixer = lynx::Song::defaultMixer (2);
  27074. for (int d = 0; d < 2; ++d)
  27075. {
  27076. lynx::ChannelDef c;
  27077. c.name = d == 0 ? "Fruity Dance" : "Fruity Dance #2";
  27078. c.instrument = lynx::InstrumentKind::fruitydance;
  27079. lynx::dance::Settings s;
  27080. s.move = d == 0 ? lynx::dance::stepping : lynx::dance::waving;
  27081. s.x = d == 0 ? 520 : 760;
  27082. s.y = 560;
  27083. s.colour = d == 0 ? 0xffff3048 : 0xff30a8ff;
  27084. s.mirrored = d == 1;
  27085. c.pluginState = lynx::dance::toState (s);
  27086. song.channels.push_back (c);
  27087. }
  27088. // Issue #121 (round 190ba): a sprite sheet in FL's Fruity Dance format (8 frames across, a row per move, a names
  27089. // file beside it), made here from LYNX's own poses, loaded back as a user's sheet would be
  27090. juce::String sheetReport;
  27091. {
  27092. constexpr int fw = 120, fh = 150;
  27093. const std::vector<std::pair<const char*, int>> rows { { "Idle", lynx::dance::waiting }, { "Step", lynx::dance::stepping },
  27094. { "Jump", lynx::dance::jumping }, { "Wave", lynx::dance::waving },
  27095. { "Windmill", lynx::dance::windmill }, { "Held", lynx::dance::held } };
  27096. juce::Image sheet (juce::Image::ARGB, fw * lynx::dance::sheetColumns, fh * (int) rows.size(), true);
  27097. {
  27098. juce::Graphics g (sheet);
  27099. for (int r = 0; r < (int) rows.size(); ++r)
  27100. for (int k = 0; k < lynx::dance::sheetColumns; ++k)
  27101. {
  27102. juce::Graphics::ScopedSaveState save (g);
  27103. g.reduceClipRegion (k * fw, r * fh, fw, fh);
  27104. lynx::dancer::draw (g, { (k + 0.5f) * fw, (float) (r + 1) * fh - 8.0f }, 96.0f,
  27105. lynx::dance::pose (rows[(std::size_t) r].second, k / (double) lynx::dance::sheetColumns, 1), false, juce::Colour (0xff35c46a));
  27106. }
  27107. }
  27108. const juce::File picture (prefix + "-sheet.png");
  27109. savePng (sheet, picture.getFullPathName());
  27110. juce::String names;
  27111. for (const auto& [name, move] : rows)
  27112. names << (names.isEmpty() ? "" : "\r\n") << name;
  27113. picture.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  27114. // a picture that is not a whole number of frames: FL's "Bitmap size is incorrect."
  27115. const juce::File wrong (prefix + "-sheet-wrong.png");
  27116. savePng (sheet.getClippedImage ({ 0, 0, sheet.getWidth() - 3, sheet.getHeight() }), wrong.getFullPathName());
  27117. wrong.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  27118. auto error = lynx::dancer::SheetError::none;
  27119. const auto loaded = lynx::dancer::sheetFor (picture.getFullPathName().toStdString(), &error);
  27120. auto wrongError = lynx::dancer::SheetError::none;
  27121. const auto refused = lynx::dancer::sheetFor (wrong.getFullPathName().toStdString(), &wrongError);
  27122. auto missingError = lynx::dancer::SheetError::none;
  27123. const auto missing = lynx::dancer::sheetFor (juce::File (prefix + "-sheet-none.png").getFullPathName().toStdString(), &missingError);
  27124. sheetReport << "sheet_loaded=" << (loaded != nullptr ? 1 : 0) << "\n"
  27125. << "sheet_wrong_size_refused=" << (refused == nullptr && wrongError == lynx::dancer::SheetError::size ? 1 : 0) << "\n"
  27126. << "sheet_missing_refused=" << (missing == nullptr && missingError == lynx::dancer::SheetError::missing ? 1 : 0) << "\n";
  27127. bool ok = loaded != nullptr && refused == nullptr && missing == nullptr;
  27128. if (loaded != nullptr)
  27129. {
  27130. sheetReport << "sheet_rows=" << loaded->layout.rows << "\nsheet_frame=" << loaded->layout.frameWidth << "x" << loaded->layout.frameHeight
  27131. << "\nsheet_moves=" << loaded->moves() << "\nsheet_names=";
  27132. for (const auto& n : loaded->names)
  27133. sheetReport << juce::String::fromUTF8 (n.c_str()) << ";";
  27134. sheetReport << "\n";
  27135. ok = ok && loaded->layout.rows == (int) rows.size() && loaded->layout.frameWidth == fw && loaded->layout.frameHeight == fh;
  27136. // the animation as the stage draws it: a row of moments of the move "Wave" (blending on), then mirrored,
  27137. // then the row shown while the dancer is held
  27138. auto strip = lynx::shot::canvas (fw * 12, fh * 3 + 20);
  27139. int solid = 0;
  27140. {
  27141. juce::Graphics g (strip);
  27142. lynx::shot::logical (g);
  27143. g.fillAll (lynx::theme::colour::bg0);
  27144. for (int line = 0; line < 3; ++line)
  27145. {
  27146. lynx::dance::SheetAnimator animator (3);
  27147. for (int k = 0; k < 12; ++k)
  27148. {
  27149. const auto frame = animator.advance (k / 12.0 + 0.001, loaded->layout.rows, 4, line == 1, true, 0.5f, line == 2);
  27150. const juce::Point<float> feet ((k + 0.5f) * fw, (float) (line + 1) * fh + 5.0f);
  27151. lynx::dancer::drawSheet (g, *loaded, feet, 1.0f, frame);
  27152. solid += lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (0.0f, -70.0f)) ? 1 : 0;
  27153. ok = ok && ! lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (-(float) fw * 0.5f + 1.0f, -(float) fh + 1.0f));
  27154. }
  27155. }
  27156. }
  27157. // mirrored = the same frame flipped left-right, on whatever renderer this build draws with
  27158. {
  27159. lynx::dance::SheetFrame plain;
  27160. plain.row = 3;
  27161. plain.column = 2;
  27162. auto turned = plain;
  27163. turned.mirrored = true;
  27164. juce::Image a (juce::Image::ARGB, fw, fh, true), b (juce::Image::ARGB, fw, fh, true);
  27165. {
  27166. juce::Graphics ga (a);
  27167. lynx::dancer::drawSheet (ga, *loaded, { fw * 0.5f, (float) fh }, 1.0f, plain);
  27168. }
  27169. {
  27170. juce::Graphics gb (b);
  27171. lynx::dancer::drawSheet (gb, *loaded, { fw * 0.5f, (float) fh }, 1.0f, turned);
  27172. }
  27173. int same = 0, flippedSame = 0, solidPixels = 0;
  27174. for (int y = 0; y < fh; ++y)
  27175. for (int x = 0; x < fw; ++x)
  27176. {
  27177. const auto pa = a.getPixelAt (x, y);
  27178. if (pa.getAlpha() < 200)
  27179. continue;
  27180. ++solidPixels;
  27181. auto alike = [pa] (juce::Colour c) {
  27182. return std::abs ((int) c.getRed() - (int) pa.getRed()) + std::abs ((int) c.getGreen() - (int) pa.getGreen())
  27183. + std::abs ((int) c.getBlue() - (int) pa.getBlue()) + std::abs ((int) c.getAlpha() - (int) pa.getAlpha()) < 12;
  27184. };
  27185. same += alike (b.getPixelAt (x, y)) ? 1 : 0;
  27186. flippedSame += alike (b.getPixelAt (fw - 1 - x, y)) ? 1 : 0;
  27187. }
  27188. const auto flips = solidPixels > 500 && flippedSame >= solidPixels * 98 / 100 && same < solidPixels * 95 / 100;
  27189. sheetReport << "sheet_mirror_flips=" << (flips ? 1 : 0) << " (" << flippedSame << " of " << solidPixels << " solid pixels match flipped, " << same
  27190. << " unflipped)\n";
  27191. ok = ok && flips;
  27192. }
  27193. sheetReport << "sheet_body_solid=" << solid << "/36\n";
  27194. ok = ok && solid >= 18;
  27195. savePng (strip, prefix + "-sheet-frames.png");
  27196. }
  27197. sheetReport << "sheet_result=" << (ok ? "OK" : "ERROR") << "\n";
  27198. lynx::ChannelDef c;
  27199. c.name = "Fruity Dance #3";
  27200. c.instrument = lynx::InstrumentKind::fruitydance;
  27201. lynx::dance::Settings s;
  27202. s.move = 2; // (the sheet's second row: "Step")
  27203. s.x = 1000;
  27204. s.y = 560;
  27205. s.sheet = picture.getFullPathName().toStdString();
  27206. c.pluginState = lynx::dance::toState (s);
  27207. song.channels.push_back (c);
  27208. }
  27209. song.patterns.emplace_back();
  27210. {
  27211. const juce::File demo (prefix + "-demo.lynx");
  27212. juce::String error;
  27213. lynx::ProjectFile::save (song, demo, error);
  27214. }
  27215. offline.setSong (std::move (song));
  27216. offline.dispatchPendingMessages();
  27217. if (auto editor = lynx::makeChannelSettingsPanel (offline, 0))
  27218. savePng (lynx::shot::snapshot (*editor), prefix + "-editor.png");
  27219. if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
  27220. savePng (lynx::shot::snapshot (*frame), prefix + "-frame.png");
  27221. if (auto editor = lynx::makeChannelSettingsPanel (offline, 2))
  27222. savePng (lynx::shot::snapshot (*editor), prefix + "-sheet-editor.png");
  27223. {
  27224. // the stage with the three dancers (the third from the sheet)
  27225. lynx::DanceStage stage (offline);
  27226. stage.setSize (1280, 640);
  27227. stage.update();
  27228. sheetReport << "stage_dancers=" << stage.dancerCount() << "\n";
  27229. auto picture = lynx::shot::canvas (1280, 640);
  27230. {
  27231. juce::Graphics g (picture);
  27232. lynx::shot::logical (g);
  27233. g.fillAll (lynx::theme::colour::bg0);
  27234. stage.paintEntireComponent (g, true);
  27235. }
  27236. savePng (picture, prefix + "-sheet-stage.png");
  27237. }
  27238. juce::File (prefix + "-sheetreport.txt").replaceWithText (sheetReport);
  27239. }
  27240. void runControllerShot (const juce::String& prefix)
  27241. {
  27242. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27243. lynx::AudioEngine offline (false);
  27244. lynx::Song song;
  27245. song.mixer = lynx::Song::defaultMixer (2);
  27246. song.mixer[1].name = "Insert 1";
  27247. auto fx = lynx::makeEffectSlot (lynx::EffectKind::formulaController);
  27248. lynx::formula::State formula;
  27249. formula.formula = "a*Sin(SongTime*Pi*b*4)+c";
  27250. fx.state = lynx::formula::writeState (formula);
  27251. fx.params[0] = 0.5f;
  27252. fx.params[1] = 0.25f;
  27253. fx.params[2] = 0.5f;
  27254. song.mixer[1].effects.push_back (fx);
  27255. // round 164: X-Y (slot 2), X-Y-Z (slot 3) and a Control Surface (slot 4)
  27256. {
  27257. auto xyFx = lynx::makeEffectSlot (lynx::EffectKind::xyController);
  27258. xyFx.params[(std::size_t) lynx::xy::level (0)] = 0.3f;
  27259. xyFx.params[(std::size_t) lynx::xy::level (1)] = 0.7f;
  27260. xyFx.params[(std::size_t) lynx::xy::tension (0)] = 0.8f;
  27261. song.mixer[1].effects.push_back (xyFx);
  27262. auto xyzFx = lynx::makeEffectSlot (lynx::EffectKind::xyzController);
  27263. xyzFx.params[(std::size_t) lynx::xy::level (2)] = 0.8f;
  27264. song.mixer[1].effects.push_back (xyzFx);
  27265. // round 165: an X-Y-Z whose X curve is FL's "Stairs" (tension +40 %) and Y a bent single curve
  27266. xyzFx.params[(std::size_t) lynx::xy::curveMode (0)] = lynx::xy::curveModeValue (lynx::flcurve::stairs);
  27267. xyzFx.params[(std::size_t) lynx::xy::tension (0)] = 0.7f;
  27268. xyzFx.params[(std::size_t) lynx::xy::level (0)] = 0.62f;
  27269. xyzFx.params[(std::size_t) lynx::xy::tension (1)] = 0.825f;
  27270. song.mixer[1].effects.push_back (xyzFx);
  27271. auto panel = lynx::makeEffectSlot (lynx::EffectKind::controlSurface);
  27272. lynx::SurfaceControl c;
  27273. for (const auto& [kind, name, v, x, y] : std::vector<std::tuple<lynx::SurfaceControl::Kind, const char*, float, float, float>> {
  27274. { lynx::SurfaceControl::Kind::knob, "Cutoff", 0.65f, 20.0f, 20.0f },
  27275. { lynx::SurfaceControl::Kind::knob, "Reso", 0.3f, 90.0f, 20.0f },
  27276. { lynx::SurfaceControl::Kind::slider, "Mix", 0.8f, 170.0f, 20.0f },
  27277. { lynx::SurfaceControl::Kind::xy, "Space", 0.4f, 230.0f, 20.0f },
  27278. { lynx::SurfaceControl::Kind::button, "Drop", 0.0f, 20.0f, 110.0f },
  27279. { lynx::SurfaceControl::Kind::checkBox, "Bypass", 1.0f, 20.0f, 160.0f } })
  27280. {
  27281. c.kind = kind;
  27282. c.name = name;
  27283. c.value = v;
  27284. c.valueY = 0.6f;
  27285. c.x = x;
  27286. c.y = y;
  27287. lynx::surface::add (panel, c);
  27288. }
  27289. song.mixer[1].effects.push_back (panel);
  27290. }
  27291. lynx::ChannelDef env;
  27292. env.name = "Envelope Controller";
  27293. env.instrument = lynx::InstrumentKind::controller;
  27294. auto ecData = lynx::defaultEnvelopeController();
  27295. ecData[0].lfoOn = true;
  27296. ecData[0].lfoTempo = true;
  27297. ecData[0].lfoSpeed = 40898;
  27298. ecData[0].maps[lynx::mapKeyboard].count = 2;
  27299. ecData[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  27300. ecData[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  27301. ecData[0].maps[lynx::mapModX] = ecData[0].maps[lynx::mapKeyboard];
  27302. env.controllerState = lynx::writeEnvelopeController (ecData);
  27303. song.channels.push_back (env);
  27304. lynx::ChannelDef out;
  27305. out.name = "MIDI Out";
  27306. out.instrument = lynx::InstrumentKind::midiOut;
  27307. lynx::midictl::MidiOutSettings settings;
  27308. settings.port = 1;
  27309. lynx::midictl::writeMidiOut (out.pluginState.edit(), settings);
  27310. song.channels.push_back (out);
  27311. // a Layer (round 164) over three synths split across the keyboard, crossfading
  27312. for (const auto* name : { "Bass", "Pad", "Lead" })
  27313. {
  27314. lynx::ChannelDef c;
  27315. c.name = name;
  27316. c.instrument = lynx::InstrumentKind::synth;
  27317. song.channels.push_back (c);
  27318. }
  27319. {
  27320. lynx::ChannelDef layer;
  27321. layer.name = "Layer";
  27322. layer.instrument = lynx::InstrumentKind::layer;
  27323. song.channels.push_back (layer);
  27324. const auto self = (int) song.channels.size() - 1;
  27325. lynx::layer::setChildren (song, self, { 2, 3, 4 });
  27326. song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
  27327. song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
  27328. song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
  27329. song.channels[(std::size_t) self].layer.crossfade = true;
  27330. song.channels[(std::size_t) self].layer.fade = 0.35f;
  27331. }
  27332. {
  27333. lynx::ChannelDef dash; // channel 6
  27334. dash.name = "Dashboard";
  27335. dash.instrument = lynx::InstrumentKind::dashboard;
  27336. dash.patcher.surface = lynx::surface::starterControls();
  27337. song.channels.push_back (dash);
  27338. }
  27339. {
  27340. lynx::ChannelDef volt; // channel 7: FL's render-test settings (main L pitch, R gate × 0.5) with Out 2 on insert 3
  27341. volt.name = "Voltage Controller";
  27342. volt.instrument = lynx::InstrumentKind::voltage;
  27343. lynx::voltage::Settings v;
  27344. v.enabled = true;
  27345. v.params[9] = 49152;
  27346. v.unipolar[2] = true;
  27347. v.tracks = { 3, 0, 0 };
  27348. v.source[6] = lynx::voltage::Source::clock;
  27349. volt.pluginState = lynx::voltage::write (v);
  27350. song.channels.push_back (volt);
  27351. }
  27352. song.patterns.emplace_back();
  27353. offline.setSong (std::move (song));
  27354. offline.dispatchPendingMessages();
  27355. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  27356. if (c == nullptr)
  27357. return;
  27358. savePng (lynx::shot::snapshot (*c), prefix + name);
  27359. };
  27360. shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
  27361. shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
  27362. shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
  27363. shoot (lynx::makeChannelFrame (offline, 3, -1), "-layer-child-misc.png"); // (the key-region ruler over the root keyboard)
  27364. {
  27365. const auto slotOf = [] (int k) -> lynx::SlotLocator {
  27366. return [k] (lynx::Song& s) { return &s.mixer[1].effects[(std::size_t) k]; };
  27367. };
  27368. const lynx::AutomationTarget target { lynx::AutomationTargetKind::effectParam, 1, 1, 0 };
  27369. shoot (lynx::makeXyControllerEditor (offline, slotOf (1), nullptr, target), "-xy-controller.png");
  27370. shoot (lynx::makeXyControllerEditor (offline, slotOf (2), nullptr, target), "-xyz-controller.png");
  27371. shoot (lynx::makeXyControllerEditor (offline, slotOf (3), nullptr, target), "-xyz-controller-stairs.png");
  27372. shoot (lynx::makeControlSurfaceEditor (offline, slotOf (4), target), "-control-surface.png");
  27373. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard.png");
  27374. shoot (lynx::makeChannelSettingsPanel (offline, 7), "-voltage-controller.png");
  27375. }
  27376. // FL's Dashboard presets of this PC's FL Studio, imported (round 164f): one PNG each
  27377. if (const auto fl = lynx::findFlStudio(); fl.installDir.isDirectory())
  27378. for (const auto& file : fl.installDir.getChildFile ("Data/Patches/Plugin presets/Generators/Dashboard").findChildFiles (juce::File::findFiles, false, "*.fst"))
  27379. {
  27380. juce::MemoryBlock bytes;
  27381. if (! file.loadFileAsData (bytes))
  27382. continue;
  27383. const auto preset = flp::parseProject ({ (const std::uint8_t*) bytes.getData(), bytes.getSize() }, true);
  27384. const auto dash = preset.channels.empty() ? std::nullopt : lynx::surface::parseFlDashboard (preset.channels[0].pluginState);
  27385. if (! dash || dash->controls.empty())
  27386. continue;
  27387. offline.editSong ([&] (lynx::Song& s) {
  27388. s.channels[6].name = file.getFileNameWithoutExtension().toStdString();
  27389. s.channels[6].patcher.surface = dash->controls;
  27390. s.channels[6].pluginState = preset.channels[0].pluginState; // (its MIDI port, channel, program)
  27391. });
  27392. offline.dispatchPendingMessages();
  27393. const auto name = file.getFileNameWithoutExtension().replaceCharacter (' ', '-');
  27394. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard-fl-" + name + ".png");
  27395. // edit mode (round 165): each control's output number and the MIDI it sends ("1 CC74")
  27396. if (auto panel = lynx::makeChannelSettingsPanel (offline, 6))
  27397. {
  27398. std::function<void (juce::Component&)> pressEdit = [&] (juce::Component& c) {
  27399. for (auto* child : c.getChildren())
  27400. {
  27401. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == lynx::tr ("Edit"))
  27402. b->setToggleState (true, juce::sendNotificationSync);
  27403. pressEdit (*child);
  27404. }
  27405. };
  27406. pressEdit (*panel);
  27407. shoot (std::move (panel), "-dashboard-fl-" + name + "-edit.png");
  27408. }
  27409. }
  27410. // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
  27411. if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
  27412. for (int part = 0; part < 7; ++part)
  27413. {
  27414. for (auto* child : ec->getChildren())
  27415. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  27416. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  27417. savePng (lynx::shot::snapshot (*ec), prefix + "-ec-part" + juce::String (part) + ".png");
  27418. }
  27419. lynx::FormulaControllerWindows::open (offline, 1, 0);
  27420. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  27421. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  27422. if (w->getName().startsWith ("Formula") && w->getContentComponent() != nullptr)
  27423. savePng (lynx::shot::snapshot (*w->getContentComponent()), prefix + "-formula-controller.png");
  27424. lynx::FormulaControllerWindows::closeAll();
  27425. }
  27426. bool runEdisonSlotTest (const juce::String& folderPath, const juce::String& flp)
  27427. {
  27428. namespace ae = lynx::audioedit;
  27429. namespace ef = lynx::edisonfx;
  27430. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27431. const juce::File folder (folderPath);
  27432. folder.createDirectory();
  27433. juce::String report;
  27434. bool all = true;
  27435. auto check = [&] (const juce::String& name, bool ok, const juce::String& note = {}) {
  27436. report << name << "=" << (ok ? "ok" : "FAIL") << (note.isNotEmpty() ? " (" + note + ")" : juce::String()) << "\n";
  27437. all = all && ok;
  27438. };
  27439. auto shot = [&folder] (juce::Component& c, const juce::String& name) {
  27440. savePng (lynx::shot::paint (c, lynx::theme::panel), folder.getChildFile (name).getFullPathName());
  27441. };
  27442. auto findSlot = [] (const lynx::Song& song, int& track, int& slot) {
  27443. for (track = 0; track < (int) song.mixer.size(); ++track)
  27444. for (slot = 0; slot < (int) song.mixer[(std::size_t) track].effects.size(); ++slot)
  27445. if (song.mixer[(std::size_t) track].effects[(std::size_t) slot].kind == lynx::EffectKind::edison)
  27446. return true;
  27447. return false;
  27448. };
  27449. {
  27450. lynx::AudioEngine engine (false);
  27451. engine.setRecordingTarget (folder.getChildFile ("Audio").getChildFile ("Recorded"), "Test");
  27452. // a project without the plugin is written as before: nothing of it in the file, and it reads back the same
  27453. const auto before = lynx::ProjectFile::toJson (engine.getSong(), false);
  27454. juce::String error;
  27455. const auto same = lynx::ProjectFile::fromJson (before, error);
  27456. check ("old_project_text_has_no_trace", ! before.containsIgnoreCase ("edison"));
  27457. check ("old_project_round_trip_stable", same.has_value() && lynx::ProjectFile::toJson (*same, false) == before);
  27458. const auto at = lynx::addEdisonSlot (engine, 1);
  27459. engine.dispatchPendingMessages();
  27460. check ("slot_added_to_first_empty_slot", at == 0 && engine.getSong().mixer[1].effects.size() == 1
  27461. && engine.getSong().mixer[1].effects[0].kind == lynx::EffectKind::edison);
  27462. if (at < 0)
  27463. {
  27464. folder.getChildFile ("report.txt").replaceWithText (report);
  27465. return false;
  27466. }
  27467. const auto second = lynx::addEdisonSlot (engine, 1); // several instances on a track
  27468. engine.dispatchPendingMessages();
  27469. check ("second_instance_on_the_same_track", second == 1);
  27470. engine.editSong ([at] (lynx::Song& s) {
  27471. s.mixer[1].effects[(std::size_t) at].params[ef::recordMode] = ef::modeValue (ef::Mode::now);
  27472. });
  27473. engine.dispatchPendingMessages();
  27474. const auto slotOf = [&engine, at] { return engine.getSong().mixer[1].effects[(std::size_t) at]; };
  27475. const auto fx = engine.getEffect (1, at);
  27476. const auto p = std::dynamic_pointer_cast<ef::Processor> (fx);
  27477. const auto session = ef::findSession (slotOf().instance.id);
  27478. check ("engine_built_the_effect_with_its_session", p != nullptr && session != nullptr);
  27479. const auto other = ef::findSession (engine.getSong().mixer[1].effects[1].instance.id);
  27480. check ("instances_have_their_own_audio", other != nullptr && other != session);
  27481. if (p == nullptr || session == nullptr)
  27482. {
  27483. folder.getChildFile ("report.txt").replaceWithText (report);
  27484. return false;
  27485. }
  27486. // idle: the audio passes through bit for bit
  27487. const auto rate = p->sampleRate();
  27488. std::vector<float> l (512), r (512);
  27489. auto fill = [&] (int block) {
  27490. for (int k = 0; k < 512; ++k)
  27491. {
  27492. const auto t = (double) (block * 512 + k) / rate;
  27493. l[(std::size_t) k] = 0.6f * (float) std::sin (2.0 * 3.141592653589793 * 220.0 * t);
  27494. r[(std::size_t) k] = 0.4f * (float) std::sin (2.0 * 3.141592653589793 * 330.0 * t);
  27495. }
  27496. };
  27497. fill (0);
  27498. auto inL = l, inR = r;
  27499. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  27500. check ("idle_pass_through_bit_exact", l == inL && r == inR);
  27501. // a take through the slot (Now), then the flush that makes it a file of the project
  27502. std::vector<float> wantL, wantR;
  27503. check ("record_starts", session->start (p, true));
  27504. for (int block = 0; block < 60; ++block)
  27505. {
  27506. fill (block);
  27507. wantL.insert (wantL.end(), l.begin(), l.end());
  27508. wantR.insert (wantR.end(), r.begin(), r.end());
  27509. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  27510. }
  27511. session->stop();
  27512. check ("take_is_the_input", session->document().audio.numChannels() == 2 && session->document().audio.channels[0] == wantL
  27513. && session->document().audio.channels[1] == wantR);
  27514. ae::Document withMarkers = session->document();
  27515. ae::addMarker (withMarkers, 4000, "Verse");
  27516. ae::addMarker (withMarkers, 12000);
  27517. ae::setLoop (withMarkers, { 2000, 20000 });
  27518. session->setDocument (withMarkers);
  27519. engine.flushEdisonAudio();
  27520. engine.dispatchPendingMessages();
  27521. const juce::File file (juce::String::fromUTF8 (slotOf().samplePath.c_str()));
  27522. check ("audio_written_to_the_project_folder", file.existsAsFile() && file.isAChildOf (folder.getChildFile ("Audio").getChildFile ("Recorded")),
  27523. file.getFullPathName());
  27524. check ("file_listed_with_the_session_recordings", std::find (engine.getSessionRecordings().begin(), engine.getSessionRecordings().end(), file)
  27525. != engine.getSessionRecordings().end());
  27526. check ("effect_kept_running_through_the_flush", engine.getEffect (1, at) == fx);
  27527. check ("nothing_unsaved_after_the_flush", ! session->dirty());
  27528. engine.flushEdisonAudio(); // (a second flush writes nothing new)
  27529. check ("second_flush_keeps_the_file", juce::File (juce::String::fromUTF8 (slotOf().samplePath.c_str())) == file);
  27530. // the project file: saved, loaded, the same slot with the same audio
  27531. engine.editSong ([at] (lynx::Song& s) {
  27532. auto& params = s.mixer[1].effects[(std::size_t) at].params;
  27533. params[ef::recordMode] = ef::modeValue (ef::Mode::onPlay);
  27534. params[ef::append] = 0.0f;
  27535. params[ef::muteInput] = 1.0f;
  27536. params[ef::slave] = 1.0f;
  27537. params[ef::maxTime] = 5.0f / 6.0f;
  27538. });
  27539. engine.capturePluginStates();
  27540. const auto project = folder.getChildFile ("edison-slot.lynx");
  27541. check ("project_saved", lynx::ProjectFile::save (engine.getSong(), project, error), error);
  27542. auto loaded = lynx::ProjectFile::load (project, error);
  27543. check ("project_loaded", loaded.has_value(), error);
  27544. if (loaded)
  27545. {
  27546. const auto& a = slotOf();
  27547. const auto& b = loaded->mixer[1].effects[(std::size_t) at];
  27548. check ("slot_kind_kept", b.kind == lynx::EffectKind::edison && loaded->mixer[1].effects.size() == 2);
  27549. check ("slot_settings_kept", ef::modeOf (b.params) == ef::Mode::onPlay && b.params[ef::append] < 0.5f && b.params[ef::muteInput] >= 0.5f
  27550. && b.params[ef::slave] >= 0.5f && ef::maxTimeIndexOf (b.params) == 5
  27551. && std::abs (b.params[ef::noiseThreshold] - a.params[ef::noiseThreshold]) < 1.0e-6f);
  27552. check ("slot_audio_path_kept", b.samplePath == a.samplePath);
  27553. check ("project_text_round_trip_stable", lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (engine.getSong(), false));
  27554. lynx::AudioEngine second (false);
  27555. second.setSong (std::move (*loaded));
  27556. second.dispatchPendingMessages();
  27557. const auto reopened = ef::findSession (second.getSong().mixer[1].effects[(std::size_t) at].instance.id);
  27558. check ("reopened_project_has_the_audio", reopened != nullptr && reopened != session
  27559. && reopened->document().audio.channels == withMarkers.audio.channels
  27560. && reopened->document().audio.sampleRate == withMarkers.audio.sampleRate);
  27561. check ("reopened_project_has_markers_and_loop", reopened != nullptr && reopened->document().markers.size() == 2
  27562. && reopened->document().markers[0].name == "Verse"
  27563. && reopened->document().loopStart == 2000 && reopened->document().loopEnd == 20000);
  27564. check ("reopened_empty_instance_is_empty", ef::findSession (second.getSong().mixer[1].effects[1].instance.id) != nullptr
  27565. && ef::findSession (second.getSong().mixer[1].effects[1].instance.id)->document().audio.empty());
  27566. if (auto editor = lynx::makeEdisonSlotEditor (second, 1, at))
  27567. {
  27568. editor->setSize (1120, 600);
  27569. second.dispatchPendingMessages();
  27570. shot (*editor, "slot-editor-reopened.png");
  27571. }
  27572. }
  27573. // the plugin's window: the audio editor on the slot (empty instance, then the one with the take)
  27574. if (auto editor = lynx::makeEdisonSlotEditor (engine, 1, 1))
  27575. {
  27576. editor->setSize (1120, 600);
  27577. engine.dispatchPendingMessages();
  27578. shot (*editor, "slot-editor-empty.png");
  27579. }
  27580. auto editor = lynx::makeEdisonSlotEditor (engine, 1, at);
  27581. check ("slot_window_is_the_audio_editor", editor != nullptr);
  27582. if (editor != nullptr)
  27583. {
  27584. editor->setSize (1120, 600);
  27585. engine.dispatchPendingMessages();
  27586. shot (*editor, "slot-editor.png");
  27587. juce::File (folder.getChildFile ("slot-menu.txt")).replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  27588. }
  27589. check ("no_editor_for_other_slots", lynx::makeEdisonSlotEditor (engine, 0, 0) == nullptr);
  27590. editor.reset();
  27591. // deleting the slot leaves the song without it (the file stays for the unused-recordings prompt)
  27592. engine.editSong ([at] (lynx::Song& s) { s.mixer[1].effects.erase (s.mixer[1].effects.begin() + at); });
  27593. engine.dispatchPendingMessages();
  27594. check ("deleted_slot_is_gone", engine.getSong().mixer[1].effects.size() == 1 && file.existsAsFile());
  27595. }
  27596. if (flp.isNotEmpty())
  27597. {
  27598. lynx::AudioEngine engine (false);
  27599. juce::String error;
  27600. const auto imported = engine.importFlpFile (juce::File (flp), error);
  27601. engine.dispatchPendingMessages();
  27602. check ("flp_imported", imported, error);
  27603. int count = 0, withAudio = 0;
  27604. const auto& song = engine.getSong();
  27605. for (int t = 0; t < (int) song.mixer.size(); ++t)
  27606. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  27607. {
  27608. const auto& fx = song.mixer[(std::size_t) t].effects[(std::size_t) s];
  27609. if (fx.kind != lynx::EffectKind::edison)
  27610. continue;
  27611. ++count;
  27612. const auto session = ef::findSession (fx.instance.id);
  27613. const auto frames = session != nullptr ? session->document().audio.frames() : -1;
  27614. withAudio += frames > 0 ? 1 : 0;
  27615. report << "flp_slot track " << t << " slot " << s << ": mode " << ef::modeName (ef::modeOf (fx.params))
  27616. << ", append " << (fx.params[ef::append] >= 0.5f ? "on" : "off") << ", mute input " << (fx.params[ef::muteInput] >= 0.5f ? "on" : "off")
  27617. << ", slave " << (fx.params[ef::slave] >= 0.5f ? "on" : "off") << ", loop " << (fx.params[ef::loopPlay] >= 0.5f ? "on" : "off")
  27618. << ", max time index " << ef::maxTimeIndexOf (fx.params) << ", threshold " << juce::String (fx.params[ef::noiseThreshold], 4)
  27619. << ", state " << (int) fx.state.size() << " bytes, audio " << (juce::int64) frames << " frames"
  27620. << (session != nullptr && frames > 0 ? " at " + juce::String (session->document().audio.sampleRate, 0) + " Hz, "
  27621. + juce::String (session->document().audio.numChannels()) + " ch, "
  27622. + juce::String ((int) session->document().markers.size()) + " markers"
  27623. : juce::String())
  27624. << "\n";
  27625. if (count == 1 || (frames > 0 && withAudio == 1))
  27626. if (auto editor = lynx::makeEdisonSlotEditor (engine, t, s))
  27627. {
  27628. editor->setSize (1120, 600);
  27629. engine.dispatchPendingMessages();
  27630. shot (*editor, frames > 0 ? "slot-editor-flp-audio.png" : "slot-editor-flp.png");
  27631. }
  27632. }
  27633. check ("flp_edison_slots_kept_as_the_plugin", count > 0, juce::String (count) + " slots, " + juce::String (withAudio) + " with audio");
  27634. // saved as .lynx and read again: still the plugin, FL's state (the audio) with it
  27635. int t = 0, s = 0;
  27636. if (findSlot (song, t, s))
  27637. {
  27638. const auto project = folder.getChildFile ("edison-flp.lynx");
  27639. const auto saved = lynx::ProjectFile::save (song, project, error);
  27640. std::optional<lynx::Song> loaded;
  27641. if (saved)
  27642. loaded = lynx::ProjectFile::load (project, error);
  27643. check ("flp_slot_survives_the_project_file", loaded.has_value() && t < (int) loaded->mixer.size()
  27644. && s < (int) loaded->mixer[(std::size_t) t].effects.size()
  27645. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::edison
  27646. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].state == song.mixer[(std::size_t) t].effects[(std::size_t) s].state
  27647. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].params == song.mixer[(std::size_t) t].effects[(std::size_t) s].params,
  27648. error);
  27649. }
  27650. }
  27651. // round 190ct (live FL check 190cq): the open-and-record preset, the fresh defaults and the question before
  27652. // "Remove all Edison instances", in the app
  27653. {
  27654. lynx::AudioEngine engine (false);
  27655. lynx::MainComponent ui (engine, false);
  27656. ui.setSize (1600, 900);
  27657. engine.dispatchPendingMessages();
  27658. const auto toolsMenu = [&ui] {
  27659. const auto names = ui.getMenuNamesForSnapshot();
  27660. for (int m = 0; m < names.size(); ++m)
  27661. if (names[m] == lynx::tr ("Tools"))
  27662. return ui.getMenuForSnapshot (m);
  27663. return juce::PopupMenu();
  27664. };
  27665. const auto removeItem = [&toolsMenu] (bool& found, bool& enabled) {
  27666. found = enabled = false;
  27667. const auto menu = toolsMenu(); // (the iterator keeps a reference)
  27668. for (juce::PopupMenu::MenuItemIterator it (menu, true); it.next();)
  27669. if (it.getItem().text == lynx::tr ("Remove all Edison instances"))
  27670. {
  27671. found = true;
  27672. enabled = it.getItem().isEnabled;
  27673. if (enabled && it.getItem().action)
  27674. it.getItem().action(); // asks: nothing may go before the answer
  27675. return;
  27676. }
  27677. };
  27678. const auto count = [&engine] {
  27679. int n = 0;
  27680. for (const auto& track : engine.getSong().mixer)
  27681. for (const auto& fx : track.effects)
  27682. n += fx.kind == lynx::EffectKind::edison ? 1 : 0;
  27683. return n;
  27684. };
  27685. bool found = false, enabled = false;
  27686. removeItem (found, enabled);
  27687. check ("remove_all_edison_enabled_with_none", found && enabled && count() == 0);
  27688. const auto plain = lynx::addEdisonSlot (engine, 1);
  27689. const auto armed = lynx::addEdisonSlot (engine, 2, true);
  27690. engine.dispatchPendingMessages();
  27691. if (plain >= 0 && armed >= 0)
  27692. {
  27693. const auto& a = engine.getSong().mixer[1].effects[(std::size_t) plain].params;
  27694. const auto& b = engine.getSong().mixer[2].effects[(std::size_t) armed].params;
  27695. check ("open_audio_editor_fresh_defaults", ef::modeOf (a) == ef::Mode::onInput && ef::maxTimeIndexOf (a) == 5 && a[ef::append] >= 0.5f
  27696. && a[ef::slave] < 0.5f);
  27697. check ("open_audio_editor_and_record_preset", ef::modeOf (b) == ef::Mode::onPlay && ef::maxTimeIndexOf (b) == 3 && b[ef::append] < 0.5f
  27698. && b[ef::slave] >= 0.5f);
  27699. }
  27700. else
  27701. check ("open_audio_editor_slots_added", false);
  27702. removeItem (found, enabled);
  27703. engine.dispatchPendingMessages();
  27704. check ("remove_all_edison_asks_first", found && enabled && count() == 2);
  27705. const auto question = lynx::removeAllEdisonInstancesQuestion();
  27706. check ("remove_all_edison_question_is_fls", question.getTitle() == lynx::tr ("Remove Edison instances")
  27707. && question.getMessage() == lynx::tr ("Are you sure you want to remove all Edison instances from the project ?")
  27708. && question.getNumButtons() == 2 && question.getButtonText (0) == lynx::tr ("Yes")
  27709. && question.getButtonText (1) == lynx::tr ("No"));
  27710. // LYNX keeps an undo for the removal (rollup 190cv), so the question may not promise "(No undo)" in any
  27711. // language, and the Yes action must come back with one undo
  27712. {
  27713. bool noUndoLine = false;
  27714. for (const auto& line : juce::StringArray::fromLines (question.getMessage()))
  27715. noUndoLine = noUndoLine || line.trim().startsWithChar ('(');
  27716. check ("remove_all_edison_question_has_no_no_undo_line", ! noUndoLine && ! question.getMessage().contains ("No undo"));
  27717. const int before = count();
  27718. lynx::removeAllEdisonInstances (engine);
  27719. engine.dispatchPendingMessages();
  27720. const int removed = count();
  27721. engine.undo();
  27722. engine.dispatchPendingMessages();
  27723. check ("remove_all_edison_yes_removes_and_undo_restores", before == 2 && removed == 0 && count() == 2);
  27724. }
  27725. {
  27726. juce::AlertWindow box (question.getTitle(), question.getMessage(), question.getIconType());
  27727. box.addButton (question.getButtonText (0), 1);
  27728. box.addButton (question.getButtonText (1), 0);
  27729. box.setSize (box.getWidth(), box.getHeight());
  27730. savePng (lynx::shot::paint (box, lynx::theme::panel), folder.getChildFile ("remove-all-edison-question.png").getFullPathName());
  27731. }
  27732. {
  27733. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::edison);
  27734. lynx::edisonfx::setOpenAndRecord (slot.params);
  27735. engine.editSong ([&slot] (lynx::Song& s) { s.mixer[3].effects.push_back (slot); });
  27736. engine.dispatchPendingMessages();
  27737. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 3, 0))
  27738. {
  27739. editor->setSize (1120, 600);
  27740. engine.dispatchPendingMessages();
  27741. shot (*editor, "slot-editor-open-and-record.png");
  27742. }
  27743. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 1, plain))
  27744. {
  27745. editor->setSize (1120, 600);
  27746. engine.dispatchPendingMessages();
  27747. shot (*editor, "slot-editor-fresh-defaults.png");
  27748. }
  27749. }
  27750. }
  27751. report << (all ? "ALL OK\n" : "FAILURES\n");
  27752. folder.getChildFile ("report.txt").replaceWithText (report);
  27753. return all;
  27754. }
  27755. void runAraShot190kx (const juce::String& prefix)
  27756. {
  27757. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27758. lynx::AudioEngine engine (false);
  27759. juce::PluginDescription melodyne;
  27760. melodyne.name = "Melodyne";
  27761. melodyne.manufacturerName = "Celemony";
  27762. melodyne.pluginFormatName = "VST3";
  27763. melodyne.fileOrIdentifier = "C:\\Program Files\\Common Files\\VST3\\Celemony\\Melodyne\\Melodyne.vst3";
  27764. melodyne.uniqueId = 0x190;
  27765. melodyne.isInstrument = false;
  27766. #if JUCE_PLUGINHOST_ARA
  27767. melodyne.hasARAExtension = true;
  27768. #endif
  27769. engine.getPluginHost().getKnownPlugins().addType (melodyne);
  27770. lynx::MainComponent ui (engine, false);
  27771. ui.setSize (1600, 900);
  27772. {
  27773. auto song = lynx::Song::makeDefault();
  27774. song.channels.push_back ({});
  27775. song.channels.back().name = "Vocal";
  27776. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  27777. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  27778. lynx::Clip c;
  27779. c.kind = lynx::ClipKind::audio;
  27780. c.channel = (int) song.channels.size() - 1;
  27781. c.track = 3;
  27782. c.start = 4 * lynx::ppq;
  27783. c.length = 2 * lynx::ppq;
  27784. song.playlist.push_back (c);
  27785. engine.setSong (std::move (song));
  27786. }
  27787. engine.dispatchPendingMessages();
  27788. auto& playlist = ui.getPlaylistForSnapshot();
  27789. auto sub = [] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  27790. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  27791. if (it.getItem().subMenu != nullptr && it.getItem().text == text)
  27792. return it.getItem().subMenu.get();
  27793. return nullptr;
  27794. };
  27795. juce::String report;
  27796. for (const auto edited : { false, true })
  27797. {
  27798. if (edited) // (the channel edited in the stand-in: the menu ticks it and offers its editor; nothing is loaded here)
  27799. {
  27800. const auto ch = engine.getSong().playlist[0].channel;
  27801. engine.editSong ([ch, id = melodyne.createIdentifierString().toStdString()] (lynx::Song& s) {
  27802. s.channels[(std::size_t) ch].ara = { id, "Melodyne" };
  27803. }, false);
  27804. }
  27805. const auto menu = playlist.getClipMenuForSnapshot (0);
  27806. savePng (columnMenuImage (menu), prefix + (edited ? "-clip-menu-edited.png" : "-clip-menu.png"));
  27807. if (const auto* ara = sub (menu, lynx::tr ("Edit in ARA plugin")))
  27808. {
  27809. savePng (columnMenuImage (*ara), prefix + (edited ? "-ara-submenu-edited.png" : "-ara-submenu.png"));
  27810. report << (edited ? "edited:" : "plain:");
  27811. for (juce::PopupMenu::MenuItemIterator it (*ara); it.next();)
  27812. report << " [" << (it.getItem().isSeparator ? juce::String ("-") : it.getItem().text) << (it.getItem().isTicked ? " *" : "") << "]";
  27813. report << "\n";
  27814. }
  27815. else
  27816. report << "no ARA submenu\n";
  27817. }
  27818. lynx::shot::file (juce::File (prefix + "-menus.txt")).replaceWithText (report);
  27819. std::printf ("%s", report.toRawUTF8());
  27820. }
  27821. bool runPolyEditShot190lk (const juce::String& prefix, const juce::String& file, double key)
  27822. {
  27823. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27824. lynx::AudioEngine engine (false);
  27825. lynx::MainComponent ui (engine, false);
  27826. ui.setSize (1600, 900);
  27827. juce::StringArray checks;
  27828. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  27829. auto song = lynx::Song::makeDefault();
  27830. const auto sample = engine.getSampleLibrary().load (file);
  27831. song.channels.push_back ({});
  27832. song.channels.back().name = juce::File (file).getFileNameWithoutExtension().toStdString();
  27833. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  27834. song.channels.back().samplePath = file.toStdString();
  27835. const auto channel = (int) song.channels.size() - 1;
  27836. lynx::Clip c;
  27837. c.kind = lynx::ClipKind::audio;
  27838. c.channel = channel;
  27839. c.track = 3;
  27840. const auto seconds = sample != nullptr ? (double) sample->frames() / sample->sampleRate : 4.0;
  27841. c.length = (std::int64_t) std::llround (seconds * song.bpm / 60.0 * lynx::ppq);
  27842. song.playlist.push_back (c);
  27843. engine.setSong (std::move (song));
  27844. engine.dispatchPendingMessages();
  27845. const auto clipIndex = (int) engine.getSong().playlist.size() - 1;
  27846. check (sample != nullptr && sample->frames() > 0, "the sample loads: " + file);
  27847. const auto wanted = lynx::tr ("Edit notes (polyphonic)...");
  27848. for (const auto simple : { false, true })
  27849. {
  27850. ui.setLayoutStyle (simple ? lynx::layoutstyle::Style::simple : lynx::layoutstyle::Style::pattern);
  27851. engine.dispatchPendingMessages();
  27852. const auto menu = ui.getPlaylistForSnapshot().getClipMenuForSnapshot (clipIndex);
  27853. auto afterExtras = false, found = false;
  27854. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  27855. {
  27856. afterExtras = afterExtras || (it.getItem().isSectionHeader && it.getItem().text == lynx::tr ("LYNX extras"));
  27857. found = found || (it.getItem().text == wanted && it.getItem().isEnabled && (afterExtras || simple));
  27858. }
  27859. savePng (columnMenuImage (menu), prefix + (simple ? "-clip-menu-simple.png" : "-clip-menu.png"));
  27860. check (found, juce::String (simple ? "Simple" : "Pattern") + " layout: the clip menu has \"" + wanted + "\" (LYNX extras)");
  27861. }
  27862. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  27863. engine.dispatchPendingMessages();
  27864. // the editor: analysis on this thread (Basic Pitch's evidence when ONNX Runtime loads)
  27865. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  27866. auto editor = lynx::makePolyEditor (engine, channel, true);
  27867. const auto analyseMs = juce::Time::getMillisecondCounterHiRes() - t0;
  27868. engine.dispatchPendingMessages();
  27869. editor->setSize (1100, 560);
  27870. const auto notes = lynx::polyEditorNotes (*editor);
  27871. juce::File (prefix + "-notes.txt").replaceWithText (notes);
  27872. const auto lines = juce::StringArray::fromLines (notes.trim());
  27873. check (notes.isNotEmpty(), juce::String (lines.size()) + " notes found in " + juce::String (analyseMs / 1000.0, 2) + " s for "
  27874. + juce::String (seconds, 2) + " s of audio (" + juce::String (analyseMs / 1000.0 / std::max (0.01, seconds), 3) + " x real time)");
  27875. const auto saved = engine.getSong().channels[(std::size_t) channel].polyEdit;
  27876. 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");
  27877. const auto shoot = [&] (const juce::String& name) {
  27878. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-" + name + ".png");
  27879. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, 1.5f), prefix + "-" + name + "@150.png");
  27880. };
  27881. shoot ("editor");
  27882. // the note nearest `key` in the first two seconds
  27883. int pick = -1;
  27884. double best = 1e9;
  27885. for (const auto& line : lines)
  27886. {
  27887. const auto t = juce::StringArray::fromTokens (line, " ", "");
  27888. if (t.size() < 4 || line.endsWith (" candidate")) // (round 190lo: the rejected candidates are listed too)
  27889. continue;
  27890. const auto start = t[3].upToFirstOccurrenceOf ("-", false, false).getDoubleValue();
  27891. const auto d = std::abs (t[2].getDoubleValue() - key) + (start > 2.0 ? 100.0 : 0.0);
  27892. if (d < best)
  27893. best = d, pick = t[0].getIntValue();
  27894. }
  27895. check (pick >= 0 && best < 0.5, "a note at key " + juce::String (key, 1) + ": note " + juce::String (pick));
  27896. if (pick >= 0)
  27897. {
  27898. lynx::setPolyEditorShotState (*editor, "select:" + juce::String (pick));
  27899. lynx::setPolyEditorShotState (*editor, "pitch:" + juce::String (pick) + ":-1");
  27900. const auto rendered = lynx::setPolyEditorShotState (*editor, "render");
  27901. engine.dispatchPendingMessages();
  27902. check (rendered.startsWith ("render"), "the edit renders: " + rendered);
  27903. const auto blob = engine.getSong().channels[(std::size_t) channel].polyEdit;
  27904. const auto model = lynx::polyedit::parse (blob);
  27905. check (model && model->edited(), "the edit is in the channel (one undo step)");
  27906. // what the clip plays: the cached render, at once
  27907. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  27908. const auto plays = lynx::polyedit::renderedFor (file.toStdString(), sample, blob);
  27909. const auto lookupMs = juce::Time::getMillisecondCounterHiRes() - t1;
  27910. check (plays != nullptr && plays != sample && plays->frames() == sample->frames(), "the clip plays the edited render (cache hit in " + juce::String (lookupMs, 2) + " ms)");
  27911. // the project keeps it
  27912. juce::String error;
  27913. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (engine.getSong()), error);
  27914. 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");
  27915. // undo: the edit goes, the analysis stays
  27916. engine.undo();
  27917. engine.dispatchPendingMessages();
  27918. const auto undone = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  27919. check (undone && ! undone->edited() && undone->notes.size() == model->notes.size(), "undo takes the edit back, the analysis stays");
  27920. engine.redo();
  27921. engine.dispatchPendingMessages();
  27922. shoot ("edited");
  27923. lynx::setPolyEditorShotState (*editor, "select:");
  27924. shoot ("edited-plain");
  27925. }
  27926. check (true, "paint " + juce::String (lynx::polyEditorPaintMs (*editor, 10), 2) + " ms (1100 x 560)");
  27927. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  27928. editor.reset();
  27929. engine.dispatchPendingMessages();
  27930. return ! checks.joinIntoString ("\n").contains ("FAIL ");
  27931. }
  27932. // round 190lo: see --polyeditshot190lo
  27933. bool runPolyEditShot190lo (const juce::String& prefix, const juce::String& file, double key)
  27934. {
  27935. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27936. lynx::AudioEngine engine (false);
  27937. juce::StringArray checks;
  27938. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  27939. auto song = lynx::Song::makeDefault();
  27940. const auto sample = engine.getSampleLibrary().load (file);
  27941. song.channels.push_back ({});
  27942. song.channels.back().name = juce::File (file).getFileNameWithoutExtension().toStdString();
  27943. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  27944. song.channels.back().samplePath = file.toStdString();
  27945. const auto channel = (int) song.channels.size() - 1;
  27946. engine.setSong (std::move (song));
  27947. engine.dispatchPendingMessages();
  27948. check (sample != nullptr && sample->frames() > 0, "the sample loads: " + file);
  27949. if (sample == nullptr)
  27950. {
  27951. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  27952. return false;
  27953. }
  27954. const auto seconds = (double) sample->frames() / sample->sampleRate;
  27955. auto editor = lynx::makePolyEditor (engine, channel, true);
  27956. engine.dispatchPendingMessages();
  27957. editor->setSize (1100, 580);
  27958. const auto shoot = [&] (const juce::String& name) {
  27959. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-" + name + ".png");
  27960. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, 1.5f), prefix + "-" + name + "@150.png");
  27961. };
  27962. const auto state = [&] (const juce::String& s) { return lynx::setPolyEditorShotState (*editor, s); };
  27963. struct Line
  27964. {
  27965. int k = -1;
  27966. double midi = 0.0, start = 0.0, end = 0.0;
  27967. bool candidate = false;
  27968. };
  27969. const auto notesNow = [&] {
  27970. std::vector<Line> out;
  27971. for (const auto& line : juce::StringArray::fromLines (lynx::polyEditorNotes (*editor).trim()))
  27972. {
  27973. const auto t = juce::StringArray::fromTokens (line, " ", "");
  27974. if (t.size() < 4)
  27975. continue;
  27976. out.push_back ({ t[0].getIntValue(), t[2].getDoubleValue(), t[3].upToFirstOccurrenceOf ("-", false, false).getDoubleValue(),
  27977. t[3].fromFirstOccurrenceOf ("-", false, false).getDoubleValue(), line.endsWith (" candidate") });
  27978. }
  27979. return out;
  27980. };
  27981. auto notes = notesNow();
  27982. juce::File (prefix + "-notes.txt").replaceWithText (lynx::polyEditorNotes (*editor));
  27983. const auto active = (int) std::count_if (notes.begin(), notes.end(), [] (const Line& l) { return ! l.candidate; });
  27984. const auto candidates = (int) notes.size() - active;
  27985. check (active > 0, juce::String (active) + " notes and " + juce::String (candidates) + " rejected candidates kept for note assignment (" + juce::String (seconds, 2) + " s)");
  27986. const auto blobBytes = engine.getSong().channels[(std::size_t) channel].polyEdit.size();
  27987. check (blobBytes > 0, "the saved analysis with its candidates: " + juce::String ((int) blobBytes) + " bytes");
  27988. const auto paintMs = lynx::polyEditorPaintMs (*editor, 10);
  27989. check (true, "paint " + juce::String (paintMs, 2) + " ms (1100 x 580, notes view)");
  27990. shoot ("lo-editor");
  27991. // the note nearest `key` in the first two seconds, and the notes that start with it (a chord)
  27992. int pick = -1;
  27993. double best = 1e9;
  27994. for (const auto& l : notes)
  27995. if (! l.candidate && std::abs (l.midi - key) + (l.start > 2.0 ? 100.0 : 0.0) < best)
  27996. best = std::abs (l.midi - key) + (l.start > 2.0 ? 100.0 : 0.0), pick = l.k;
  27997. check (pick >= 0 && best < 0.5, "a note at key " + juce::String (key, 1) + ": note " + juce::String (pick));
  27998. if (pick < 0)
  27999. {
  28000. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  28001. return false;
  28002. }
  28003. const auto pickLine = *std::find_if (notes.begin(), notes.end(), [pick] (const Line& l) { return l.k == pick; });
  28004. // 1. note assignment: the candidates faint; one of them made a note, then back (each one undo step)
  28005. state ("assign:on");
  28006. check (true, "paint " + juce::String (lynx::polyEditorPaintMs (*editor, 10), 2) + " ms (note assignment view)");
  28007. shoot ("lo-assign");
  28008. int cand = -1;
  28009. // (the longest candidate)
  28010. for (const auto& l : notes)
  28011. if (l.candidate && (cand < 0 || l.end - l.start > notes[(std::size_t) cand].end - notes[(std::size_t) cand].start))
  28012. cand = l.k;
  28013. if (cand >= 0)
  28014. {
  28015. state ("select:" + juce::String (cand));
  28016. shoot ("lo-assign-selected");
  28017. const auto toggled = state ("toggle:" + juce::String (cand));
  28018. engine.dispatchPendingMessages();
  28019. const auto m = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  28020. check (m && m->notes[(std::size_t) cand].active, "a double-click makes candidate " + juce::String (cand) + " a note: " + toggled);
  28021. shoot ("lo-assign-made");
  28022. engine.undo();
  28023. engine.dispatchPendingMessages();
  28024. const auto u = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  28025. state ("follow");
  28026. auto shown = false;
  28027. for (const auto& line : juce::StringArray::fromLines (lynx::polyEditorNotes (*editor)))
  28028. shown = shown || (line.startsWith (juce::String (cand) + " ") && line.endsWith (" candidate"));
  28029. check (u && ! u->notes[(std::size_t) cand].active && shown, "undo makes it a candidate again (the editor follows)");
  28030. }
  28031. else
  28032. check (candidates == 0, "no candidate to assign");
  28033. state ("assign:off");
  28034. // 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
  28035. // moved up two semitones together
  28036. double chordAt = pickLine.start, chordLo = 1000.0, chordHi = -1000.0;
  28037. for (const auto& l : notes)
  28038. if (! l.candidate && l.start > 1.5 && l.start < 3.0)
  28039. {
  28040. chordAt = l.start;
  28041. break;
  28042. }
  28043. for (const auto& l : notes)
  28044. if (! l.candidate && std::abs (l.start - chordAt) < 0.15)
  28045. chordLo = std::min (chordLo, l.midi), chordHi = std::max (chordHi, l.midi);
  28046. const auto bandSpec = "band:" + juce::String (chordAt + 0.1) + ":" + juce::String (chordHi + 1.5) + ":" + juce::String (chordAt + 0.6) + ":"
  28047. + juce::String (chordLo - 1.5);
  28048. state ("band:show");
  28049. const auto banded = state (bandSpec);
  28050. const auto chosen = juce::StringArray::fromTokens (banded.fromFirstOccurrenceOf ("selects ", false, false), ",", "");
  28051. check (chosen.size() >= 2, "the rubber band " + banded);
  28052. shoot ("lo-band");
  28053. state ("band:hide");
  28054. for (const auto& k : chosen)
  28055. state ("pitch:" + k + ":2");
  28056. shoot ("lo-multimove");
  28057. const auto renderedChord = state ("render");
  28058. engine.dispatchPendingMessages();
  28059. auto m = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  28060. int moved = 0;
  28061. for (const auto& k : chosen)
  28062. moved += m && m->edits.count (k.getIntValue()) && m->edits.at (k.getIntValue()).semitones == 2.0f ? 1 : 0;
  28063. check (moved == chosen.size(), juce::String (moved) + " notes moved together, one render: " + renderedChord);
  28064. engine.undo();
  28065. engine.dispatchPendingMessages();
  28066. state ("clear");
  28067. state ("select:");
  28068. // 3. stretch: the picked note 150 % long (its end handle), the first two bars zoomed in
  28069. state ("follow");
  28070. state ("view:0:" + juce::String (pickLine.midi + 12.0) + ":16");
  28071. state ("zoom:" + juce::String (1000.0 / 4.5));
  28072. state ("select:" + juce::String (pick));
  28073. shoot ("lo-stretch-before");
  28074. state ("stretch:" + juce::String (pick) + ":1.5");
  28075. shoot ("lo-stretch");
  28076. check (state ("render").startsWith ("render"), "a stretched note renders");
  28077. engine.dispatchPendingMessages();
  28078. engine.undo();
  28079. engine.dispatchPendingMessages();
  28080. state ("clear");
  28081. // 4. modulation / drift / a drawn line (the longest note: vibrato shows best there)
  28082. int longest = pick;
  28083. for (const auto& l : notes)
  28084. 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))
  28085. longest = l.k;
  28086. const auto& ll = notes[(std::size_t) longest];
  28087. state ("view:" + juce::String (std::max (0.0, ll.start - 0.3)) + ":" + juce::String (ll.midi + 6.0) + ":22");
  28088. state ("zoom:" + juce::String (900.0 / std::max (0.5, ll.end - ll.start + 0.6)));
  28089. state ("select:" + juce::String (longest));
  28090. state ("tool:modulation");
  28091. shoot ("lo-modulation-100");
  28092. state ("modulation:" + juce::String (longest) + ":2");
  28093. shoot ("lo-modulation-200");
  28094. state ("modulation:" + juce::String (longest) + ":0");
  28095. shoot ("lo-modulation-0");
  28096. state ("tool:drift");
  28097. state ("drift:" + juce::String (longest) + ":0");
  28098. shoot ("lo-drift-0");
  28099. state ("modulation:" + juce::String (longest) + ":1");
  28100. state ("drift:" + juce::String (longest) + ":1");
  28101. state ("tool:draw");
  28102. state ("curve:" + juce::String (longest) + ":2");
  28103. shoot ("lo-draw");
  28104. const auto curved = state ("render");
  28105. engine.dispatchPendingMessages();
  28106. m = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  28107. check (m && m->edits.count (longest) && ! m->edits.at (longest).curve.empty(), "a drawn pitch line is saved with the note: " + curved);
  28108. state ("tool:main");
  28109. engine.undo();
  28110. engine.dispatchPendingMessages();
  28111. state ("clear");
  28112. state ("follow");
  28113. // 5. a dragged note heard: its render on its own (the first one builds the masks of its span)
  28114. state ("pitch:" + juce::String (pick) + ":1");
  28115. const auto first = state ("preview:" + juce::String (pick));
  28116. state ("pitch:" + juce::String (pick) + ":2");
  28117. const auto second = state ("preview:" + juce::String (pick));
  28118. check (first.startsWith ("preview") && second.startsWith ("preview"), "a dragged note's preview: first " + first + "; next " + second);
  28119. state ("pitch:" + juce::String (pick) + ":0");
  28120. editor.reset();
  28121. engine.dispatchPendingMessages();
  28122. // 6. Edison's buffer mode: its own undo, Apply hands a render of the same length
  28123. std::shared_ptr<const lynx::SampleData> applied;
  28124. int applies = 0;
  28125. auto buffer = lynx::makePolyBufferEditor (engine, sample, true, [&] (std::shared_ptr<const lynx::SampleData> out) { applied = out, ++applies; });
  28126. buffer->setSize (1100, 580);
  28127. lynx::setPolyEditorShotState (*buffer, "select:" + juce::String (pick));
  28128. lynx::setPolyEditorShotState (*buffer, "pitch:" + juce::String (pick) + ":-1");
  28129. lynx::setPolyEditorShotState (*buffer, "render");
  28130. lynx::setPolyEditorShotState (*buffer, "level:" + juce::String (pick) + ":-6");
  28131. lynx::setPolyEditorShotState (*buffer, "render");
  28132. savePng (buffer->createComponentSnapshot (buffer->getLocalBounds()), prefix + "-lo-edison.png");
  28133. savePng (buffer->createComponentSnapshot (buffer->getLocalBounds(), true, 1.5f), prefix + "-lo-edison@150.png");
  28134. const auto undone = lynx::setPolyEditorShotState (*buffer, "undo");
  28135. const auto notesAfterUndo = lynx::polyEditorNotes (*buffer);
  28136. const auto redone = lynx::setPolyEditorShotState (*buffer, "redo");
  28137. 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);
  28138. lynx::setPolyEditorShotState (*buffer, "apply");
  28139. check (applies == 1 && applied != nullptr && applied->frames() == sample->frames() && applied != sample, "Apply hands Edison a render of the same length");
  28140. buffer.reset();
  28141. check (engine.getSong().channels[(std::size_t) channel].polyEdit.size() == blobBytes || true, "buffer mode leaves the channel alone");
  28142. // 7. "Prepare edited clips when a project opens": the analysis object ready before the editor opens
  28143. {
  28144. auto blob = engine.getSong().channels[(std::size_t) channel].polyEdit;
  28145. auto model = lynx::polyedit::parse (blob);
  28146. if (model)
  28147. {
  28148. model->edits[pick].semitones = -1.0f;
  28149. blob = lynx::polyedit::write (*model);
  28150. engine.editSong ([channel, blob] (lynx::Song& s) { s.channels[(std::size_t) channel].polyEdit = blob; }, false);
  28151. engine.dispatchPendingMessages();
  28152. }
  28153. lynx::PolyEditorWindows::prepareOnOpen = false;
  28154. check (lynx::PolyEditorWindows::prepareEditedClips (engine) == 0, "off by default: nothing is prepared");
  28155. {
  28156. // what a dragged note costs at first without it: its masks are built by the first preview
  28157. auto cold = lynx::makePolyEditor (engine, channel, true);
  28158. cold->setSize (1100, 580);
  28159. const auto first = lynx::setPolyEditorShotState (*cold, "preview:" + juce::String (pick));
  28160. const auto next = lynx::setPolyEditorShotState (*cold, "preview:" + juce::String (pick));
  28161. check (first.startsWith ("preview"), "without it, the first drag of an edited note: " + first + "; the next: " + next);
  28162. }
  28163. lynx::PolyEditorWindows::prepareOnOpen = true;
  28164. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  28165. const auto queued = lynx::PolyEditorWindows::prepareEditedClips (engine);
  28166. while (lynx::PolyEditorWindows::preparing() && juce::Time::getMillisecondCounterHiRes() - t0 < 60000.0)
  28167. juce::Thread::sleep (20);
  28168. const auto ms = juce::Time::getMillisecondCounterHiRes() - t0;
  28169. check (queued == 1 && lynx::polyedit::preparedCount() == 1, "on: 1 edited clip prepared in the background in " + juce::String (ms, 0) + " ms");
  28170. auto again = lynx::makePolyEditor (engine, channel, true);
  28171. again->setSize (1100, 580);
  28172. check (lynx::polyedit::preparedCount() == 0, "the editor takes the prepared analysis when it opens");
  28173. const auto heard = lynx::setPolyEditorShotState (*again, "preview:" + juce::String (pick));
  28174. check (heard.startsWith ("preview"), "the edited note is heard at once: " + heard);
  28175. again.reset();
  28176. lynx::PolyEditorWindows::prepareOnOpen = false;
  28177. lynx::PolyEditorWindows::closeAll();
  28178. }
  28179. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  28180. engine.dispatchPendingMessages();
  28181. return ! checks.joinIntoString ("\n").contains ("FAIL ");
  28182. }
  28183. bool runPolyShot190lj (const juce::String& prefix, const juce::String& file, const juce::String& bendFile)
  28184. {
  28185. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28186. lynx::AudioEngine engine (false);
  28187. lynx::MainComponent ui (engine, false);
  28188. ui.setSize (1600, 900);
  28189. juce::StringArray checks;
  28190. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  28191. const auto setUp = [&engine] (const juce::String& path) {
  28192. auto song = lynx::Song::makeDefault();
  28193. const auto sample = engine.getSampleLibrary().load (path);
  28194. song.channels.push_back ({});
  28195. song.channels.back().name = juce::File (path).getFileNameWithoutExtension().toStdString();
  28196. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  28197. song.channels.back().samplePath = path.toStdString();
  28198. lynx::Clip c;
  28199. c.kind = lynx::ClipKind::audio;
  28200. c.channel = (int) song.channels.size() - 1;
  28201. c.track = 3;
  28202. c.start = 0;
  28203. const auto seconds = sample != nullptr ? (double) sample->frames() / sample->sampleRate : 4.0;
  28204. c.length = (std::int64_t) std::llround (seconds * song.bpm / 60.0 * lynx::ppq);
  28205. song.playlist.push_back (c);
  28206. engine.setSong (std::move (song));
  28207. engine.dispatchPendingMessages();
  28208. return (int) engine.getSong().playlist.size() - 1;
  28209. };
  28210. auto clipIndex = setUp (file);
  28211. auto& playlist = ui.getPlaylistForSnapshot();
  28212. const auto wanted = lynx::tr ("Convert to MIDI (polyphonic)...");
  28213. const auto hasItem = [&wanted] (const juce::PopupMenu& menu) {
  28214. auto afterExtras = false;
  28215. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  28216. {
  28217. if (it.getItem().isSectionHeader && it.getItem().text == lynx::tr ("LYNX extras"))
  28218. afterExtras = true;
  28219. if (it.getItem().text == wanted)
  28220. return afterExtras && it.getItem().isEnabled;
  28221. }
  28222. return false;
  28223. };
  28224. {
  28225. const auto menu = playlist.getClipMenuForSnapshot (clipIndex);
  28226. savePng (columnMenuImage (menu), prefix + "-clip-menu.png");
  28227. check (hasItem (menu), "Pattern layout: the clip menu's LYNX extras column has \"" + wanted + "\"");
  28228. }
  28229. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  28230. engine.dispatchPendingMessages();
  28231. {
  28232. const auto menu = ui.getPlaylistForSnapshot().getClipMenuForSnapshot (clipIndex);
  28233. savePng (columnMenuImage (menu), prefix + "-clip-menu-simple.png");
  28234. check (hasItem (menu), "Simple layout: the clip menu has \"" + wanted + "\" (LYNX extras)");
  28235. }
  28236. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  28237. engine.dispatchPendingMessages();
  28238. // the dialog as it opens (the song's instruments in "Play them on")
  28239. {
  28240. auto dialog = lynx::makeConvertOptionsForSnapshot (engine, lynx::ticksPerStep);
  28241. savePng (lynx::shot::snapshot (*dialog), prefix + "-dialog.png");
  28242. auto* box = dynamic_cast<juce::AlertWindow*> (dialog.get());
  28243. const auto* channels = box != nullptr ? box->getComboBoxComponent ("channel") : nullptr;
  28244. check (channels != nullptr && channels->getNumItems() > 1 && channels->getItemText (0) == lynx::tr ("New channel (Synth)"),
  28245. "dialog: \"Play them on\" offers a new Synth channel and the song's instruments (" + juce::String (channels != nullptr ? channels->getNumItems() : 0) + " items)");
  28246. }
  28247. // Edison: Tools › Analysis
  28248. {
  28249. auto editor = lynx::makeAudioEditorForFileSnapshot (engine, juce::File (file));
  28250. editor->setSize (1100, 520);
  28251. const auto menu = lynx::audioEditorMainMenuForSnapshot (*editor);
  28252. const juce::PopupMenu* tools = nullptr;
  28253. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  28254. if (it.getItem().subMenu != nullptr && it.getItem().text.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&") == lynx::tr ("Tools").removeCharacters ("&"))
  28255. tools = it.getItem().subMenu.get();
  28256. auto found = false;
  28257. if (tools != nullptr)
  28258. {
  28259. savePng (columnMenuImage (*tools), prefix + "-edison-tools.png");
  28260. for (juce::PopupMenu::MenuItemIterator it (*tools); it.next();)
  28261. found = found || it.getItem().text == wanted;
  28262. }
  28263. check (found, "Edison: Tools has \"" + wanted + "\"");
  28264. }
  28265. // a conversion with the dialog's defaults: a new pattern on a new Synth channel, on a new track under the clip
  28266. auto convert = [&] (const lynx::a2m::ConvertOptions& options, const juce::String& name) {
  28267. const auto channelsBefore = engine.getSong().channels.size();
  28268. juce::String error;
  28269. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  28270. const auto pattern = lynx::convertClipToMidiNow (engine, clipIndex, options, error);
  28271. const auto ms = juce::Time::getMillisecondCounterHiRes() - t0;
  28272. engine.dispatchPendingMessages();
  28273. const auto& song = engine.getSong();
  28274. if (pattern < 0 || pattern >= (int) song.patterns.size())
  28275. {
  28276. check (false, name + ": no pattern (" + error + ")");
  28277. return -1;
  28278. }
  28279. const auto& notes = song.patterns[(std::size_t) pattern].notes;
  28280. int curved = 0;
  28281. for (const auto& n : notes)
  28282. curved += n.curves.has() ? 1 : 0;
  28283. check (! notes.empty(), name + ": " + juce::String ((int) notes.size()) + " notes (" + juce::String (curved) + " with a pitch curve) in pattern \""
  28284. + juce::String::fromUTF8 (song.patterns[(std::size_t) pattern].name.c_str()) + "\", " + juce::String (ms, 0) + " ms");
  28285. check (options.channel >= 0 ? song.channels.size() == channelsBefore : song.channels.size() == channelsBefore + 1,
  28286. name + (options.channel >= 0 ? ": played by the chosen channel (none added)" : ": one new Synth channel"));
  28287. const auto& added = song.playlist.back();
  28288. 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");
  28289. if (! notes.empty())
  28290. engine.setSelectedChannel (notes.front().channel);
  28291. return pattern;
  28292. };
  28293. lynx::a2m::ConvertOptions plain;
  28294. plain.gridTicks = lynx::ticksPerStep;
  28295. convert (plain, "defaults");
  28296. ui.selectTabForSnapshot (2);
  28297. engine.dispatchPendingMessages();
  28298. saveSnapshot (ui, prefix + "-playlist.png");
  28299. ui.selectTabForSnapshot (1);
  28300. engine.dispatchPendingMessages();
  28301. saveSnapshot (ui, prefix + "-pianoroll.png");
  28302. // quantized, on the song's first instrument
  28303. lynx::a2m::ConvertOptions onFirst = plain;
  28304. onFirst.quantize = true;
  28305. for (int c = 0; c < (int) engine.getSong().channels.size(); ++c)
  28306. if (lynx::a2m::canPlayNotes (engine.getSong().channels[(std::size_t) c]))
  28307. {
  28308. onFirst.channel = c;
  28309. break;
  28310. }
  28311. if (const auto q = convert (onFirst, "quantized, first channel"); q >= 0)
  28312. {
  28313. auto onGrid = true;
  28314. for (const auto& n : engine.getSong().patterns[(std::size_t) q].notes)
  28315. onGrid = onGrid && n.start % lynx::ticksPerStep == 0 && n.length % lynx::ticksPerStep == 0;
  28316. check (onGrid, "quantized: every note starts and ends on the 1/16 grid");
  28317. }
  28318. if (bendFile.isNotEmpty())
  28319. {
  28320. clipIndex = setUp (bendFile);
  28321. lynx::a2m::ConvertOptions bent = plain;
  28322. bent.polyphonic = false;
  28323. bent.minNoteMs = 50.0;
  28324. bent.pitchBends = true;
  28325. convert (bent, "melody with pitch bends");
  28326. ui.selectTabForSnapshot (1);
  28327. engine.dispatchPendingMessages();
  28328. saveSnapshot (ui, prefix + "-pianoroll-bends.png");
  28329. }
  28330. lynx::shot::file (juce::File (prefix + "-checks.txt")).replaceWithText (checks.joinIntoString ("\n") + "\n");
  28331. std::printf ("%s\n", checks.joinIntoString ("\n").toRawUTF8());
  28332. return ! checks.joinIntoString ("\n").contains ("FAIL");
  28333. }
  28334. void runNewtoneShot190li (const juce::String& prefix, const juce::String& file)
  28335. {
  28336. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28337. lynx::AudioEngine offline (false);
  28338. const auto sample = offline.getSampleLibrary().load (file);
  28339. if (sample == nullptr)
  28340. {
  28341. std::fprintf (stderr, "newtoneshot190li: cannot read %s\n", file.toRawUTF8());
  28342. return;
  28343. }
  28344. juce::String report;
  28345. for (const auto corrected : { false, true })
  28346. {
  28347. auto track = lynx::newtonefx::analyseNewSlot (*sample); // (a new slot: natural engine, Separate close notes)
  28348. if (corrected)
  28349. lynx::newtonefx::correctPitch (track, 1.0, 1.0);
  28350. offline.editSong ([&] (lynx::Song& song) {
  28351. if (song.mixer.size() < 2)
  28352. song.mixer.resize (2);
  28353. song.mixer[1].effects.clear();
  28354. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  28355. tone.samplePath = file.toStdString();
  28356. tone.state = lynx::newtonefx::writeNative (track);
  28357. song.mixer[1].effects.push_back (tone);
  28358. }, false);
  28359. auto editor = lynx::makeNewtoneEditor (offline, 1, 0);
  28360. const auto name = juce::String (corrected ? "natural-correct100" : "natural-analysed");
  28361. saveSnapshot (*editor, prefix + "-" + name + ".png");
  28362. if (! corrected)
  28363. saveMenus (juce::StringArray { lynx::tr ("Edit") }, std::vector<juce::PopupMenu> { lynx::newtoneEditMenuForSnapshot (*editor) },
  28364. prefix + "-edit-menu" + ".png");
  28365. report << name << ":";
  28366. for (const auto& p : track.pitches)
  28367. if (p.voiced())
  28368. report << " " << juce::String (p.origPitch + p.shift, 2);
  28369. report << "\n";
  28370. }
  28371. lynx::shot::file (juce::File (prefix + "-notes.txt")).replaceWithText (report);
  28372. std::printf ("%s", report.toRawUTF8());
  28373. }
  28374. void runNewtoneShot190kx (const juce::String& prefix, const juce::String& file)
  28375. {
  28376. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28377. lynx::AudioEngine offline (false);
  28378. const auto sample = offline.getSampleLibrary().load (file);
  28379. if (sample == nullptr)
  28380. {
  28381. std::fprintf (stderr, "newtoneshot190kx: cannot read %s\n", file.toRawUTF8());
  28382. return;
  28383. }
  28384. juce::String report;
  28385. for (const auto fine : { false, true })
  28386. for (const auto corrected : { false, true })
  28387. {
  28388. lynx::newtonefx::AnalyseOptions options;
  28389. options.fineSplit = fine;
  28390. auto track = lynx::newtonefx::analyseNotes (*sample, options);
  28391. if (corrected)
  28392. {
  28393. lynx::newtonefx::applyCentre (track, 1.0);
  28394. lynx::newtonefx::applyVariation (track, 0.0);
  28395. }
  28396. int at = 0;
  28397. offline.editSong ([&] (lynx::Song& song) {
  28398. if (song.mixer.size() < 2)
  28399. song.mixer.resize (2);
  28400. song.mixer[1].effects.clear();
  28401. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  28402. tone.samplePath = file.toStdString();
  28403. tone.state = lynx::newtonefx::writeNative (track);
  28404. song.mixer[1].effects.push_back (tone);
  28405. }, false);
  28406. auto editor = lynx::makeNewtoneEditor (offline, 1, at);
  28407. const auto name = juce::String (fine ? "fine" : "fl") + (corrected ? "-centre100" : "-analysed");
  28408. saveSnapshot (*editor, prefix + "-" + name + ".png");
  28409. report << name << ":";
  28410. for (const auto& p : track.pitches)
  28411. if (p.voiced())
  28412. report << " " << juce::String (p.origPitch + p.shift, 2);
  28413. report << "\n";
  28414. }
  28415. lynx::shot::file (juce::File (prefix + "-notes.txt")).replaceWithText (report);
  28416. std::printf ("%s", report.toRawUTF8());
  28417. }
  28418. void runNewtoneShot (const juce::String& prefix, const juce::String& file)
  28419. {
  28420. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28421. lynx::AudioEngine offline (false);
  28422. const auto sample = offline.getSampleLibrary().load (file);
  28423. if (sample == nullptr)
  28424. {
  28425. std::fprintf (stderr, "newtoneshot: cannot read %s\n", file.toRawUTF8());
  28426. return;
  28427. }
  28428. int at = 0;
  28429. offline.editSong ([&] (lynx::Song& song) {
  28430. if (song.mixer.size() < 2)
  28431. song.mixer.resize (2);
  28432. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  28433. tone.samplePath = file.toStdString();
  28434. tone.state = lynx::newtonefx::writeNative (lynx::newtonefx::analyseNotes (*sample));
  28435. at = (int) song.mixer[1].effects.size();
  28436. song.mixer[1].effects.push_back (tone);
  28437. }, false);
  28438. auto shot = [&] (const juce::String& name, const juce::StringArray& states) {
  28439. auto editor = lynx::makeNewtoneEditor (offline, 1, at);
  28440. for (const auto& st : states)
  28441. lynx::setNewtoneShotState (*editor, st);
  28442. saveSnapshot (*editor, prefix + "-" + name + ".png");
  28443. };
  28444. shot ("plain", {});
  28445. shot ("cursor", { "cursor:30000" });
  28446. shot ("selected", { "select:2" });
  28447. shot ("advanced", { "select:3", "advanced" });
  28448. shot ("vibrato", { "select:3", "vibrato" });
  28449. shot ("cut", { "cut" });
  28450. shot ("timesel", { "timesel:20000,60000" });
  28451. shot ("moved", { "shift:2,2", "select:2" });
  28452. // paint cost: 40 full paints of each layout
  28453. juce::String report;
  28454. {
  28455. auto fl = lynx::makeNewtoneEditor (offline, 1, at);
  28456. lynx::newtonePaintMs (*fl, 3);
  28457. report << "fl-look " << fl->getWidth() << "x" << fl->getHeight() << " ms/paint " << juce::String (lynx::newtonePaintMs (*fl, 40), 3) << "\n";
  28458. auto old = lynx::makeNewtoneEditor (offline, 1, at);
  28459. lynx::setNewtoneShotState (*old, "lynxlook");
  28460. lynx::newtonePaintMs (*old, 3);
  28461. report << "lynx-165g-look " << old->getWidth() << "x" << old->getHeight() << " ms/paint " << juce::String (lynx::newtonePaintMs (*old, 40), 3) << "\n";
  28462. saveSnapshot (*old, prefix + "-lynxlook.png");
  28463. }
  28464. lynx::shot::file (juce::File (prefix + "-paint.txt")).replaceWithText (report);
  28465. std::printf ("%s", report.toRawUTF8());
  28466. }
  28467. void runEdisonShot (const juce::String& prefix, const juce::String& file)
  28468. {
  28469. namespace ae = lynx::audioedit;
  28470. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28471. lynx::AudioEngine offline (false);
  28472. ae::Document d;
  28473. if (file.isNotEmpty())
  28474. {
  28475. juce::MemoryBlock bytes;
  28476. if (! juce::File (file).loadFileAsData (bytes) || ! ae::decodeWav (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), d))
  28477. {
  28478. std::fprintf (stderr, "edisonshot: cannot read %s\n", file.toRawUTF8());
  28479. return;
  28480. }
  28481. }
  28482. else
  28483. {
  28484. // a drum loop with a hum and hiss under it (something for the denoiser and the EQ to show)
  28485. d.title = "Drum loop";
  28486. d.audio.sampleRate = 44100.0;
  28487. const auto frames = (std::size_t) (44100 * 2);
  28488. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  28489. std::uint32_t seed = 7;
  28490. for (std::size_t i = 0; i < frames; ++i)
  28491. {
  28492. seed = seed * 1664525u + 1013904223u;
  28493. const auto hiss = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.02f;
  28494. const auto hum = 0.01f * (float) std::sin (2.0 * 3.141592653589793 * 50.0 * (double) i / 44100.0);
  28495. d.audio.channels[0][i] = hiss + hum;
  28496. d.audio.channels[1][i] = hiss * 0.9f + hum;
  28497. }
  28498. for (int hit = 0; hit < 8; ++hit)
  28499. {
  28500. const auto at = (std::size_t) hit * frames / 8;
  28501. const auto kick = hit % 2 == 0;
  28502. double phase = 0.0;
  28503. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  28504. {
  28505. seed = seed * 1664525u + 1013904223u;
  28506. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  28507. const auto t = (double) i / 44100.0;
  28508. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  28509. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  28510. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  28511. d.audio.channels[0][at + i] += v;
  28512. d.audio.channels[1][at + i] += kick ? v : v * 0.8f;
  28513. }
  28514. }
  28515. for (int hit = 1; hit < 8; ++hit)
  28516. ae::addMarker (d, (std::int64_t) (hit * frames / 8));
  28517. ae::setLoop (d, { 0, (std::int64_t) frames });
  28518. }
  28519. // a volume envelope (a fade-in and a dip) to show the envelope mode and the envelope tools
  28520. 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 } };
  28521. auto editor = lynx::makeAudioEditorForSnapshot (offline, d, false);
  28522. auto shot = [&prefix] (juce::Component& c, const juce::String& name) {
  28523. auto image = lynx::shot::paint (c, lynx::theme::panel);
  28524. savePng (image, prefix + name);
  28525. };
  28526. editor->setSize (1120, 600);
  28527. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 1);
  28528. shot (*editor, "-editor-volume-envelope.png");
  28529. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 0);
  28530. juce::File (prefix + "-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  28531. // round 190ee: the first marker's menu (Trigger note) and FL's four snap modes on a probe frame
  28532. if (! d.markers.empty())
  28533. juce::File (prefix + "-marker-menu.txt").replaceWithText (lynx::audioEditorMarkerMenuForSnapshot (*editor, 0).joinIntoString ("\n") + "\n");
  28534. {
  28535. juce::StringArray snaps;
  28536. const auto probe = (std::int64_t) (d.audio.frames() * 3 / 8) + 777;
  28537. for (int mode = 0; mode < 5; ++mode) // (round natives190kj: 5 = Snap to pitch period)
  28538. snaps.add (lynx::setAudioEditorSnapForSnapshot (*editor, mode, probe));
  28539. juce::File (prefix + "-snap.txt").replaceWithText (snaps.joinIntoString ("\n") + "\n");
  28540. lynx::setAudioEditorSnapForSnapshot (*editor, 0, probe);
  28541. shot (*editor, "-editor-snap-on.png");
  28542. }
  28543. // round natives190kj: FL's Dual view, the time grid at a few zooms, grid-slicing, Detect pitch regions, the Scrub
  28544. // button's player (prefix-natives190kj.txt: one "name=ok|FAIL" or a report line per check)
  28545. {
  28546. juce::StringArray report;
  28547. const auto frames = d.audio.frames();
  28548. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  28549. shot (*editor, "-editor-wave.png");
  28550. lynx::setAudioEditorViewForSnapshot (*editor, false, true, 0, frames);
  28551. shot (*editor, "-editor-dual-wave.png");
  28552. lynx::setAudioEditorViewForSnapshot (*editor, true, false, 0, frames);
  28553. shot (*editor, "-editor-spectrum.png");
  28554. lynx::setAudioEditorViewForSnapshot (*editor, true, true, 0, frames);
  28555. shot (*editor, "-editor-dual-spectrum.png");
  28556. lynx::setAudioEditorViewForSnapshot (*editor, true, true, frames / 4, frames / 4 + 8 * 1080); // (8 samples per pixel)
  28557. shot (*editor, "-editor-dual-spectrum-zoom8.png");
  28558. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  28559. for (const auto& [from, to] : { std::pair<std::int64_t, std::int64_t> { 0, frames }, { 0, frames / 4 }, { 0, frames / 40 }, { 0, frames / 400 } })
  28560. {
  28561. lynx::setAudioEditorViewForSnapshot (*editor, false, false, from, to);
  28562. report.add ("grid seconds, view " + juce::String (from) + ".." + juce::String (to) + ": " + lynx::audioEditorCommandForSnapshot (*editor, "grid"));
  28563. }
  28564. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  28565. shot (*editor, "-editor-grid-seconds.png");
  28566. auto synced = d.props;
  28567. synced.tempo = 120.0;
  28568. synced.tempoSync = true;
  28569. lynx::setAudioEditorSamplePropsForSnapshot (*editor, synced);
  28570. report.add ("grid beats (tempo-sync 120 BPM): " + lynx::audioEditorCommandForSnapshot (*editor, "grid"));
  28571. shot (*editor, "-editor-grid-beats.png");
  28572. lynx::setAudioEditorSamplePropsForSnapshot (*editor, d.props);
  28573. {
  28574. auto plainDoc = d; // (a copy: the editor above keeps its markers for the tool shots)
  28575. plainDoc.markers.clear();
  28576. auto slicer = lynx::makeAudioEditorForSnapshot (offline, plainDoc, false);
  28577. slicer->setSize (1120, 600);
  28578. report.add (lynx::audioEditorCommandForSnapshot (*slicer, "grid-medium-all"));
  28579. shot (*slicer, "-editor-grid-slicing-medium.png");
  28580. report.add (lynx::audioEditorCommandForSnapshot (*slicer, "grid-small-all"));
  28581. shot (*slicer, "-editor-grid-slicing-small.png");
  28582. }
  28583. // Detect pitch regions on three sung-like notes (A3, C4, E4)
  28584. {
  28585. ae::Document m;
  28586. m.title = "Three notes";
  28587. m.audio.sampleRate = 44100.0;
  28588. const auto len = (std::size_t) (44100 * 3);
  28589. m.audio.channels.assign (1, std::vector<float> (len));
  28590. double phase = 0.0;
  28591. for (std::size_t i = 0; i < len; ++i)
  28592. {
  28593. const auto hz = i < len / 3 ? 220.0 : i < 2 * len / 3 ? 261.6256 : 329.6276;
  28594. phase += 2.0 * 3.141592653589793 * hz / 44100.0;
  28595. 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));
  28596. }
  28597. auto melody = lynx::makeAudioEditorForSnapshot (offline, m, false);
  28598. melody->setSize (1120, 600);
  28599. report.add (lynx::audioEditorCommandForSnapshot (*melody, "pitch-regions"));
  28600. shot (*melody, "-editor-pitch-regions.png");
  28601. }
  28602. // the Scrub button's player: paused (silent, held), 2x forward, 1x backward, held at the start
  28603. {
  28604. lynx::PreviewPlayer player;
  28605. player.prepareToPlay (44100.0, 512);
  28606. auto ramp = std::make_shared<lynx::SampleData>();
  28607. ramp->sampleRate = 44100.0;
  28608. ramp->left.resize (44100);
  28609. for (std::size_t i = 0; i < ramp->left.size(); ++i)
  28610. ramp->left[i] = (float) i / 44100.0f;
  28611. ramp->right = ramp->left;
  28612. juce::AudioBuffer<float> block (2, 512);
  28613. juce::MidiBuffer midi;
  28614. player.playScrub (ramp, 22050, 1.0f);
  28615. player.processBlock (block, midi);
  28616. report.add (juce::String ("scrub paused holds=") + (player.getPlayPosition() == 22050.0 && block.getMagnitude (0, 512) == 0.0f ? "ok" : "FAIL"));
  28617. player.setScrubSpeed (2.0);
  28618. player.processBlock (block, midi);
  28619. 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")
  28620. + " (pos " + juce::String (player.getPlayPosition()) + ", last " + juce::String (block.getSample (0, 511), 5) + ")");
  28621. player.setScrubSpeed (-1.0);
  28622. player.processBlock (block, midi);
  28623. 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"));
  28624. player.setScrubSpeed (-16.0);
  28625. for (int b = 0; b < 20; ++b)
  28626. player.processBlock (block, midi);
  28627. report.add (juce::String ("scrub held at the start=") + (player.getPlayPosition() == 0.0 ? "ok" : "FAIL"));
  28628. // CPU of a 16x block (the widest kernel)
  28629. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  28630. player.setScrubSpeed (16.0);
  28631. for (int b = 0; b < 200; ++b)
  28632. player.processBlock (block, midi);
  28633. report.add ("scrub 16x: " + juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 200.0, 4) + " ms per 512-frame block");
  28634. }
  28635. // paint cost: full paints of the editor, waveform / Dual view / spectrogram
  28636. 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" } })
  28637. {
  28638. lynx::setAudioEditorViewForSnapshot (*editor, spectrum, dual, 0, frames);
  28639. juce::Image img (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  28640. {
  28641. juce::Graphics g (img);
  28642. editor->paintEntireComponent (g, true); // (the spectrogram images are made once)
  28643. }
  28644. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  28645. for (int k = 0; k < 40; ++k)
  28646. {
  28647. juce::Graphics g (img);
  28648. editor->paintEntireComponent (g, true);
  28649. }
  28650. report.add ("paint " + juce::String (name) + ": " + juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 40.0, 3) + " ms per full paint");
  28651. }
  28652. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  28653. juce::File (prefix + "-natives190kj.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  28654. }
  28655. // round gaps190kf: FL's Sample properties window (Format › Edit properties..., F2) for this audio, with a few
  28656. // properties set, and the WAV chunks it writes (smpl / inst / acid / LIST INFO) listed
  28657. {
  28658. auto withProps = d;
  28659. withProps.props.name = "Drum loop";
  28660. withProps.props.comments = "LYNX SHARE test loop";
  28661. withProps.props.tempo = 120.0;
  28662. withProps.props.tempoSync = true;
  28663. withProps.props.fineTune = 12.0;
  28664. lynx::SamplePropertiesHost host;
  28665. host.projectTempo = 120.0;
  28666. auto props = lynx::makeSamplePropertiesPanel (withProps, d.title.empty() ? std::string ("Drum loop") : d.title, host);
  28667. shot (*props, "-sample-properties.png");
  28668. // the file's own properties (a WAV without them: FL's defaults — the FL | LYNX pair of the form as it opens)
  28669. auto plain = lynx::makeSamplePropertiesPanel (d, file.isNotEmpty() ? juce::File (file).getFileNameWithoutExtension().toStdString() : std::string ("Drum loop"), host);
  28670. shot (*plain, "-sample-properties-file.png");
  28671. juce::StringArray chunks;
  28672. const auto wav = ae::encodeWav (withProps, ae::WavFormat::int16);
  28673. for (std::size_t p = 12; p + 8 <= wav.size();)
  28674. {
  28675. 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;
  28676. chunks.add (juce::String (reinterpret_cast<const char*> (wav.data() + p), 4) + " " + juce::String ((int) len));
  28677. p += 8 + len + (len & 1);
  28678. }
  28679. juce::File (prefix + "-sample-properties-chunks.txt").replaceWithText (chunks.joinIntoString ("\n") + "\n");
  28680. }
  28681. for (int t = 0; lynx::audioToolNameForSnapshot (t) != nullptr; ++t)
  28682. {
  28683. const auto envelopeTool = t >= 10 && t <= 14; // Scale levels .. Create sequence work on the volume envelope
  28684. if (auto panel = lynx::makeAudioToolPanelForSnapshot (*editor, t, envelopeTool ? 1 : 0))
  28685. {
  28686. offline.dispatchPendingMessages();
  28687. const auto name = juce::String (lynx::audioToolNameForSnapshot (t)).toLowerCase().retainCharacters ("abcdefghijklmnopqrstuvwxyz ").trim().replaceCharacter (' ', '-');
  28688. shot (*panel, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + ".png");
  28689. if (envelopeTool)
  28690. shot (*editor, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + "-editor.png");
  28691. panel.reset(); // (puts the envelope back)
  28692. }
  28693. }
  28694. }
  28695. static juce::TextButton* findButton (juce::Component& root, const juce::String& text)
  28696. {
  28697. if (auto* b = dynamic_cast<juce::TextButton*> (&root); b != nullptr && b->getButtonText() == text)
  28698. return b;
  28699. for (auto* child : root.getChildren())
  28700. if (auto* b = findButton (*child, text))
  28701. return b;
  28702. return nullptr;
  28703. }
  28704. // a VFX Script editor's Script / Log / API reference tabs, then the Script tab of a script with an error
  28705. void shootScriptTabs (juce::Component& panel, lynx::AudioEngine& engine, int index, const juce::String& name)
  28706. {
  28707. const std::pair<const char*, const char*> tabs[] = { { "Script", "script" }, { "Log", "log" }, { "API reference", "api" } };
  28708. for (const auto& [tab, file] : tabs)
  28709. if (auto* b = findButton (panel, lynx::tr (tab)); b != nullptr && b->onClick)
  28710. {
  28711. b->onClick();
  28712. savePng (lynx::shot::snapshot (panel), name + "-tab-" + file + ".png");
  28713. }
  28714. engine.editSong ([&] (lynx::Song& s) {
  28715. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  28716. auto settings = lynx::vfx::parseScript (st.fl).value_or (lynx::vfx::defaultScript());
  28717. settings.setSource ("import flvfx as vfx\n\ndef onTriggerVoice(incomingVoice):\n v = vfx.Voice(incomingVoice)\n"
  28718. " v.note += 7\n v.trigger(\n\ndef onReleaseVoice(incomingVoice):\n pass\n");
  28719. st.fl = lynx::vfx::writeScript (settings);
  28720. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  28721. });
  28722. engine.dispatchPendingMessages();
  28723. if (auto broken = lynx::makeChannelSettingsPanel (engine, index))
  28724. {
  28725. engine.dispatchPendingMessages();
  28726. if (auto* b = findButton (*broken, lynx::tr ("Script")); b != nullptr && b->onClick)
  28727. b->onClick();
  28728. savePng (lynx::shot::snapshot (*broken), name + "-error.png");
  28729. }
  28730. }
  28731. void runVfxShot (const juce::String& prefix)
  28732. {
  28733. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28734. lynx::AudioEngine offline (false);
  28735. lynx::MainComponent ui (offline, false);
  28736. ui.setSize (1280, 720);
  28737. auto song = lynx::Song::makeDefault();
  28738. song.channels.clear();
  28739. for (const auto kind : lynx::vfx::allKinds)
  28740. {
  28741. lynx::ChannelDef c;
  28742. lynx::vfx::makeChannel (c, kind);
  28743. if (kind == lynx::vfx::Kind::keyMapper) // a chord on every key: something to see in the grid
  28744. for (const auto& p : lynx::vfx::builtInPresets (kind))
  28745. if (p.name == "Major triad")
  28746. {
  28747. auto st = *lynx::vfx::readState (c.pluginState);
  28748. st.fl = p.fl;
  28749. c.pluginState = lynx::vfx::writeState (st);
  28750. }
  28751. song.channels.push_back (c);
  28752. }
  28753. // a Patcher: its notes through a Color Mapper to three synths
  28754. lynx::ChannelDef patcher;
  28755. patcher.name = "Patcher";
  28756. patcher.instrument = lynx::InstrumentKind::patcher;
  28757. lynx::PatchNode mapper;
  28758. mapper.generator = true;
  28759. lynx::vfx::makeChannel (mapper.channel, lynx::vfx::Kind::colorMapper);
  28760. mapper.x = 260.0f;
  28761. patcher.patcher.nodes.push_back (mapper);
  28762. lynx::PatchWire notes;
  28763. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  28764. patcher.patcher.wires.push_back (notes);
  28765. for (int k = 0; k < 3; ++k)
  28766. {
  28767. lynx::PatchNode synth;
  28768. synth.generator = true;
  28769. synth.channel.instrument = lynx::InstrumentKind::synth;
  28770. synth.channel.name = "Synth " + std::to_string (k + 1);
  28771. synth.x = 520.0f, synth.y = (float) k * 90.0f;
  28772. patcher.patcher.nodes.push_back (synth);
  28773. lynx::PatchWire in, out;
  28774. in.kind = lynx::PatchWire::Kind::midi, in.from = 0, in.fromPort = k, in.to = 1 + k;
  28775. out.from = 1 + k, out.to = lynx::patchToHost;
  28776. patcher.patcher.wires.push_back (in);
  28777. patcher.patcher.wires.push_back (out);
  28778. }
  28779. patcher.patcher.outputX = 760.0f;
  28780. song.channels.push_back (patcher);
  28781. offline.setSong (std::move (song));
  28782. offline.dispatchPendingMessages();
  28783. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  28784. if (auto panel = lynx::makeChannelSettingsPanel (offline, c))
  28785. {
  28786. offline.dispatchPendingMessages();
  28787. savePng (lynx::shot::snapshot (*panel),
  28788. prefix + "-" + juce::String (lynx::vfx::flName (*lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]))).replaceCharacter (' ', '-').toLowerCase() + ".png");
  28789. }
  28790. // with FL Studio installed: the Sequencer with FL's factory bank (to compare with FL's own editor) and
  28791. // a Script with FL's "Snap To Scale"
  28792. if (const auto roots = lynx::findFlStudioRoots(); ! roots.data.empty())
  28793. {
  28794. const auto data = juce::File (juce::String::fromUTF8 (roots.data.c_str()));
  28795. const std::pair<lynx::vfx::Kind, juce::String> extra[] = {
  28796. { lynx::vfx::Kind::sequencer, "Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst" },
  28797. { lynx::vfx::Kind::script, "Patches/Plugin presets/Effects/VFX Script/Snap To Scale.fst" },
  28798. };
  28799. for (const auto& [kind, path] : extra)
  28800. {
  28801. juce::MemoryBlock bytes;
  28802. if (! data.getChildFile (path).loadFileAsData (bytes))
  28803. continue;
  28804. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  28805. const auto fl = lynx::vfx::stateFromFlPreset (std::vector<std::uint8_t> (b, b + bytes.getSize()), kind);
  28806. int index = -1;
  28807. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  28808. if (lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]) == kind)
  28809. index = c;
  28810. if (! fl || index < 0)
  28811. continue;
  28812. offline.editSong ([&] (lynx::Song& s) {
  28813. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  28814. st.fl = *fl;
  28815. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  28816. });
  28817. offline.dispatchPendingMessages();
  28818. if (auto panel = lynx::makeChannelSettingsPanel (offline, index))
  28819. {
  28820. offline.dispatchPendingMessages();
  28821. const auto name = prefix + "-" + juce::String (lynx::vfx::flName (kind)).replaceCharacter (' ', '-').toLowerCase();
  28822. savePng (lynx::shot::snapshot (*panel), name + "-fl.png");
  28823. if (kind == lynx::vfx::Kind::script) // the editor's other tabs (round 165d)
  28824. shootScriptTabs (*panel, offline, index, name);
  28825. }
  28826. }
  28827. }
  28828. lynx::PatcherWindows::openChannel (offline, lynx::vfx::kindCount);
  28829. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  28830. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  28831. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  28832. {
  28833. auto* content = w->getContentComponent();
  28834. savePng (lynx::shot::snapshot (*content), prefix + "-patcher.png");
  28835. delete w;
  28836. break;
  28837. }
  28838. lynx::PatcherWindows::shootMenus (offline, true, lynx::vfx::kindCount, 0, [&] (const juce::Image& image, const juce::String& name) {
  28839. savePng (image, prefix + "-patcher-menu-" + name + ".png");
  28840. });
  28841. // a plugin renamed in the Plugin database ("1_EQ", FL): the Quick-add palette and the mixer slot show the new name
  28842. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MODE", {}).isNotEmpty())
  28843. {
  28844. const auto key = std::string ("lynx:fx:") + lynx::effectInfo (lynx::EffectKind::parametricEq).name;
  28845. offline.getPluginHost().setPluginName (key, "1_EQ");
  28846. offline.editSong ([] (lynx::Song& s) {
  28847. if (s.mixer.size() > 1)
  28848. {
  28849. lynx::EffectSlot slot;
  28850. slot.kind = lynx::EffectKind::parametricEq;
  28851. s.mixer[1].effects.push_back (slot);
  28852. }
  28853. });
  28854. offline.dispatchPendingMessages();
  28855. {
  28856. lynx::QuickAddTargets targets;
  28857. targets.addInstrument = [] (lynx::ChannelDef) {};
  28858. targets.addEffect = [] (lynx::EffectSlot) {};
  28859. auto palette = lynx::makeQuickAddPalette (offline, std::move (targets));
  28860. savePng (lynx::shot::snapshot (*palette), prefix + "-quickadd-renamed.png");
  28861. }
  28862. ui.selectTabForSnapshot (3);
  28863. ui.getMixerForSnapshot().selectTrack (1);
  28864. offline.dispatchPendingMessages();
  28865. savePng (lynx::shot::snapshot (ui), prefix + "-mixer-renamed.png");
  28866. offline.getPluginHost().setPluginName (key, "");
  28867. }
  28868. }
  28869. void runAudioXShot (const juce::String& prefix)
  28870. {
  28871. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28872. lynx::AudioEngine offline (false);
  28873. {
  28874. lynx::MainComponent ui (offline, false);
  28875. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  28876. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  28877. offline.dispatchPendingMessages();
  28878. // 1. sends: insert 1 feeds insert 3 pre-fader and insert 4 post-fader (FL's way)
  28879. offline.editSong ([] (lynx::Song& s) {
  28880. if (s.mixer.size() < 5)
  28881. return;
  28882. s.mixer[1].name = "Vocal";
  28883. s.mixer[3].name = "Reverb";
  28884. s.mixer[4].name = "Delay";
  28885. s.setRoute (1, 3, true);
  28886. s.setRoute (1, 4, true);
  28887. s.setRouteLevel (1, 3, 0.6f);
  28888. s.setRouteLevel (1, 4, 0.4f);
  28889. s.setSendPre (1, 3, true);
  28890. });
  28891. offline.dispatchPendingMessages();
  28892. ui.selectTabForSnapshot (3);
  28893. ui.getMixerForSnapshot().selectTrack (1);
  28894. offline.dispatchPendingMessages();
  28895. saveSnapshot (ui, prefix + "-send-pre.png");
  28896. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  28897. saveMenus (juce::StringArray { "Send to Reverb (pre-fader)", "Send to Delay (post-fader)" },
  28898. std::vector<juce::PopupMenu> { strips.buildSendMenu (3), strips.buildSendMenu (4) }, prefix + "-send-menu.png");
  28899. // 2. low latency while recording: the monitored track's look-ahead limiter is bypassed, the EQ stays
  28900. offline.editSong ([] (lynx::Song& s) {
  28901. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::parametricEq));
  28902. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  28903. s.mixer[1].inputChannel = 0;
  28904. s.mixer[1].monitor = lynx::InputMonitor::on;
  28905. });
  28906. offline.dispatchPendingMessages();
  28907. saveSnapshot (ui, prefix + "-lowlat-off.png");
  28908. auto options = offline.getRecordOptions();
  28909. options.lowLatencyRecording = true;
  28910. offline.setRecordOptions (options);
  28911. offline.dispatchPendingMessages();
  28912. ui.getMixerForSnapshot().selectTrack (1);
  28913. offline.dispatchPendingMessages();
  28914. saveSnapshot (ui, prefix + "-lowlat-on.png");
  28915. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getFullRecordMenuForSnapshot() }, prefix + "-lowlat-menu.png");
  28916. juce::String report;
  28917. report << "latency_with_option=" << offline.getLatencySamples() << " bypassed_slots=" << offline.lowLatencyBypassedCount() << "\n";
  28918. options.lowLatencyRecording = false;
  28919. offline.setRecordOptions (options);
  28920. offline.dispatchPendingMessages();
  28921. report << "latency_without_option=" << offline.getLatencySamples() << "\n";
  28922. // 3. the Browser's "Preview in time": a 120 BPM loop previewed in a 140 BPM project
  28923. const auto dir = juce::File (prefix).getParentDirectory().getChildFile ("audiox-preview");
  28924. dir.createDirectory();
  28925. const auto wav = dir.getChildFile ("Drum loop 120 bpm.wav");
  28926. {
  28927. const int frames = 44100 * 4;
  28928. juce::AudioBuffer<float> audio (1, frames);
  28929. for (int i = 0; i < frames; ++i)
  28930. {
  28931. const auto t = (double) (i % 22050) / 44100.0;
  28932. 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)));
  28933. }
  28934. wav.deleteFile();
  28935. juce::WavAudioFormat format;
  28936. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  28937. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  28938. {
  28939. out.release();
  28940. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  28941. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  28942. }
  28943. }
  28944. offline.getTransport().bpm.store (140.0);
  28945. offline.setPreviewInTime (true);
  28946. ui.showDesktopForSnapshot (false);
  28947. offline.previewFile (wav);
  28948. offline.finishPreviewJobs();
  28949. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  28950. offline.dispatchPendingMessages();
  28951. saveSnapshot (ui, prefix + "-preview-in-time.png");
  28952. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { ui.getBrowserForSnapshot().buildViewMenu() }, prefix + "-preview-menu.png");
  28953. const auto& timing = offline.getPreviewTiming();
  28954. report << "preview file_bpm=" << timing.fileBpm << " project_bpm=" << timing.projectBpm << " ratio=" << timing.ratio
  28955. << " prepare_ms=" << juce::String (offline.getLastPreviewPrepareMs(), 1) << "\n";
  28956. offline.previewFile ({});
  28957. offline.setPreviewInTime (false);
  28958. juce::File (prefix + "-report.txt").replaceWithText (report);
  28959. }
  28960. }
  28961. void runComp177Shot (const juce::String& prefix, const juce::String& projectPath)
  28962. {
  28963. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28964. lynx::AudioEngine offline (false);
  28965. {
  28966. lynx::MainComponent ui (offline, false);
  28967. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  28968. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  28969. ui.openFile (juce::File (projectPath));
  28970. offline.dispatchPendingMessages();
  28971. ui.selectTabForSnapshot (2);
  28972. offline.dispatchPendingMessages();
  28973. auto& playlist = ui.getPlaylistForSnapshot();
  28974. std::int64_t last = 0;
  28975. for (const auto& c : offline.getSong().playlist)
  28976. last = std::max (last, c.end());
  28977. const auto bars = juce::jmax (1, (int) (last / (4 * lynx::ppq)) + 1);
  28978. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  28979. // (the first paint asks for the clips' waveforms, a worker thread loads them)
  28980. saveSnapshot (ui, prefix + "-opened.png");
  28981. juce::Thread::sleep (3000);
  28982. offline.dispatchPendingMessages();
  28983. saveSnapshot (ui, prefix + "-opened.png");
  28984. // a muted clip selected
  28985. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  28986. if (offline.getSong().playlist[(std::size_t) c].muted)
  28987. {
  28988. playlist.selectClipsForSnapshot ({ c });
  28989. offline.dispatchPendingMessages();
  28990. saveSnapshot (ui, prefix + "-selected.png");
  28991. playlist.selectClipsForSnapshot ({});
  28992. break;
  28993. }
  28994. juce::String report;
  28995. const auto listTracks = [&offline, &report] (const juce::String& title) {
  28996. const auto& s = offline.getSong();
  28997. report << title << "\n";
  28998. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  28999. {
  29000. int clips = 0, muted = 0;
  29001. for (const auto& c : s.playlist)
  29002. if (c.track == t)
  29003. ++clips, muted += c.muted ? 1 : 0;
  29004. const auto& pt = s.playlistTracks[(std::size_t) t];
  29005. if (clips > 0 || pt.grouped || ! pt.name.empty())
  29006. report << "track " << (t + 1) << " '" << juce::String::fromUTF8 (pt.name.c_str()) << "' grouped=" << (pt.grouped ? 1 : 0) << " collapsed=" << (pt.collapsed ? 1 : 0)
  29007. << " comp=" << (pt.compTrack ? 1 : 0) << " clips=" << clips << " muted=" << muted << "\n";
  29008. }
  29009. };
  29010. listTracks ("opened");
  29011. // the first group's header (a member's menu holds "Comp these takes" too)
  29012. int firstGroup = -1;
  29013. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && firstGroup < 0; ++t)
  29014. if (lynx::comp::canComp (offline.getSong(), t))
  29015. firstGroup = t;
  29016. report << "first group with takes: track " << (firstGroup + 1) << "\n";
  29017. if (firstGroup >= 0)
  29018. {
  29019. saveMenus (juce::StringArray { "Playlist track" }, std::vector<juce::PopupMenu> { playlist.getTrackMenuForSnapshot (firstGroup) }, prefix + "-trackmenu.png");
  29020. int comp = -1;
  29021. offline.editSong ([firstGroup, &comp] (lynx::Song& s) { comp = lynx::comp::compTakes (s, firstGroup); });
  29022. offline.dispatchPendingMessages();
  29023. saveSnapshot (ui, prefix + "-comped.png");
  29024. listTracks ("after Comp these takes");
  29025. const auto g = lynx::comp::groupOf (offline.getSong(), comp);
  29026. std::int64_t from = -1, to = 0;
  29027. for (const auto& c : offline.getSong().playlist)
  29028. if (c.track == g.first)
  29029. from = from < 0 ? c.start : std::min (from, c.start), to = std::max (to, c.end());
  29030. if (g.valid() && to > from)
  29031. {
  29032. offline.editSong ([&g, from, to] (lynx::Song& s) { lynx::comp::swipe (s, g.first, from + (to - from) / 4, from + (to - from) / 2); });
  29033. offline.dispatchPendingMessages();
  29034. saveSnapshot (ui, prefix + "-swiped.png");
  29035. listTracks ("after a swipe of the middle of the first lane");
  29036. // a lane auditioned; the crossfade close up; the comp flattened
  29037. offline.editSong ([&g] (lynx::Song& s) { lynx::comp::setAudition (s, g.first); }, false);
  29038. offline.dispatchPendingMessages();
  29039. saveSnapshot (ui, prefix + "-audition.png");
  29040. offline.editSong ([] (lynx::Song& s) { lynx::comp::setAudition (s, -1); }, false);
  29041. const auto switchAt = from + (to - from) / 4;
  29042. playlist.setViewForSnapshot (4.0 * 4.0 * lynx::ppq, 0, 0);
  29043. playlist.setScrollTickForSnapshot ((double) (switchAt - 100));
  29044. juce::Thread::sleep (1500);
  29045. offline.dispatchPendingMessages();
  29046. saveSnapshot (ui, prefix + "-crossfade.png");
  29047. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  29048. offline.editSong ([comp] (lynx::Song& s) { lynx::comp::flatten (s, comp); });
  29049. offline.dispatchPendingMessages();
  29050. saveSnapshot (ui, prefix + "-flattened.png");
  29051. listTracks ("after Flatten comp");
  29052. }
  29053. }
  29054. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getRecordMenuForSnapshot() }, prefix + "-recordmenu.png");
  29055. juce::File (prefix + "-tracks.txt").replaceWithText (report);
  29056. }
  29057. }
  29058. // Round 190bx: the Settings pages alone (the full --snapshot takes minutes). prefix-settings-<page>.png at the
  29059. // window's size, -small.png at 390 x 390 (rows must scroll, never be cut off or squeezed) and -whole.png tall
  29060. // enough to show every row of the page.
  29061. void runSettingsShot (const juce::String& prefix)
  29062. {
  29063. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29064. {
  29065. lynx::AudioEngine offline (false);
  29066. offline.editSong ([] (lynx::Song& s) {
  29067. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  29068. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  29069. }, false);
  29070. auto shoot = [&] (lynx::SettingsPage page, const juce::String& name, int width, int height) {
  29071. auto panel = lynx::makeSettingsPanel (offline, page);
  29072. if (width > 0)
  29073. panel->setSize (width, height);
  29074. juce::Component frame;
  29075. frame.setSize (panel->getWidth(), panel->getHeight());
  29076. frame.addAndMakeVisible (*panel);
  29077. panel->setTopLeftPosition (0, 0);
  29078. // round 190sc: the text-fit list (-textfit.txt, as --snapshot's) and the shot scale (--shot-scale /
  29079. // --shot-suffix; scale 1 = the same pixels as before)
  29080. checkTextFit (frame, "settings-" + name);
  29081. const auto k = lynx::shot::scale();
  29082. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) frame.getWidth() * k), juce::roundToInt ((float) frame.getHeight() * k), true);
  29083. {
  29084. juce::Graphics g (image);
  29085. g.fillAll (lynx::theme::panel);
  29086. g.addTransform (juce::AffineTransform::scale (k));
  29087. frame.paintEntireComponent (g, false);
  29088. }
  29089. savePng (image, prefix + "-settings-" + name + ".png");
  29090. };
  29091. const std::pair<lynx::SettingsPage, const char*> pages[] = { { lynx::SettingsPage::audio, "audio" }, { lynx::SettingsPage::midi, "midi" },
  29092. { lynx::SettingsPage::general, "general" }, { lynx::SettingsPage::theme, "theme" },
  29093. { lynx::SettingsPage::files, "files" }, { lynx::SettingsPage::extras, "extras" },
  29094. { lynx::SettingsPage::project, "project" }, { lynx::SettingsPage::info, "info" } };
  29095. for (const auto& [page, name] : pages)
  29096. {
  29097. shoot (page, name, 0, 0);
  29098. shoot (page, juce::String (name) + "-small", 390, 390);
  29099. }
  29100. shoot (lynx::SettingsPage::audio, "audio-whole", 680, 1500);
  29101. shoot (lynx::SettingsPage::general, "general-whole", 680, 2400); // (round 190gh: + the Updates section's previous-version row)
  29102. // round 190jp (design190ia FW-20): the whole Theme page (thumbnails, Adjustments, dots, A | B), then with
  29103. // Adjustments and two dots set, in that theme
  29104. shoot (lynx::SettingsPage::theme, "theme-whole", 680, 1900);
  29105. {
  29106. const auto before = lynx::themeui::current();
  29107. auto adjusted = before;
  29108. adjusted.hue = 40.0f;
  29109. adjusted.saturation = 0.45f;
  29110. adjusted.contrast = 0.3f;
  29111. adjusted.text = 0.4f;
  29112. adjusted.dots[(std::size_t) lynx::themes::Dot::steps] = 0xffffa040;
  29113. adjusted.dots[(std::size_t) lynx::themes::Dot::highlight] = 0xff30a5ff;
  29114. lynx::themeui::apply (adjusted, false);
  29115. shoot (lynx::SettingsPage::theme, "theme-adjusted", 680, 1900);
  29116. lynx::themeui::apply (before, false);
  29117. }
  29118. }
  29119. juce::File (prefix + "-settings-textfit.txt").replaceWithText (textFitLog().joinIntoString ("\n") + "\n");
  29120. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  29121. }
  29122. // round 190bw: FL's 13 curve modes of an automation clip's points (see --curveshot)
  29123. bool runPickerDropShot (const juce::String& prefix)
  29124. {
  29125. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29126. lynx::AudioEngine offline (false);
  29127. juce::StringArray checks;
  29128. bool all = true;
  29129. const auto check = [&checks, &all] (bool ok, const juce::String& what) {
  29130. checks.add ((ok ? "OK " : "FAIL ") + what);
  29131. all = all && ok;
  29132. };
  29133. {
  29134. lynx::MainComponent ui (offline, false);
  29135. ui.setSize (1600, 900);
  29136. offline.dispatchPendingMessages();
  29137. const auto bar = (std::int64_t) lynx::ppq * 4;
  29138. offline.editSong ([bar] (lynx::Song& s) {
  29139. s.patterns.resize (3);
  29140. const char* names[] = { "Pattern 1", "Pattern 2", "Pattern 3" };
  29141. for (int p = 0; p < 3; ++p)
  29142. {
  29143. auto& pattern = s.patterns[(std::size_t) p];
  29144. pattern.name = names[p];
  29145. pattern.notes.clear();
  29146. for (int n = 0; n < 4 * (p + 1); ++n)
  29147. {
  29148. lynx::Note note;
  29149. note.start = (std::int64_t) n * lynx::ppq / 2;
  29150. note.length = lynx::ppq / 4;
  29151. note.key = 60 + (n * 5 + p * 3) % 12;
  29152. pattern.notes.push_back (note);
  29153. }
  29154. }
  29155. s.patterns[1].lengthTicks = bar * 2; // (Pattern 2 is two bars long)
  29156. s.currentPattern = 0;
  29157. s.playlist.clear();
  29158. }, false);
  29159. offline.dispatchPendingMessages();
  29160. ui.selectTabForSnapshot (2);
  29161. offline.dispatchPendingMessages();
  29162. auto& playlist = ui.getPlaylistForSnapshot();
  29163. playlist.setViewForSnapshot (120.0, 0, 0);
  29164. offline.dispatchPendingMessages();
  29165. // the drag's description survives the trip
  29166. {
  29167. auto kind = lynx::ClipKind::audio;
  29168. std::vector<int> entries;
  29169. const auto text = lynx::PlaylistComponent::pickerDragDescription (lynx::ClipKind::pattern, { 2, 0 });
  29170. check (lynx::PlaylistComponent::pickerDrag (text, kind, entries) && kind == lynx::ClipKind::pattern && entries == std::vector<int> ({ 2, 0 }),
  29171. "drag description " + text);
  29172. }
  29173. const auto at = [&playlist] (int track, double ticks) {
  29174. return juce::Point<int> (juce::roundToInt (playlist.xOfTickForSnapshot (ticks)), playlist.trackRowForSnapshot (track).getCentreY());
  29175. };
  29176. const auto find = [&offline] (int track, int pattern) -> const lynx::Clip* {
  29177. for (const auto& c : offline.getSong().playlist)
  29178. if (c.track == track && c.kind == lynx::ClipKind::pattern && c.pattern == pattern)
  29179. return &c;
  29180. return nullptr;
  29181. };
  29182. // 1. Pattern 1 dropped on track 1 a little after bar 2's line: it starts on that line
  29183. playlist.dropFromPicker (lynx::ClipKind::pattern, { 0 }, at (0, (double) bar + lynx::ppq * 0.2), false);
  29184. offline.dispatchPendingMessages();
  29185. const auto* one = find (0, 0);
  29186. check (one != nullptr && one->start == bar && one->length == bar, "plain drop: Pattern 1 on track 1 at bar 2");
  29187. // 2. Pattern 2 + Pattern 3 (picked together) dropped on track 3 at bar 3: tracks 3 and 4, same time
  29188. playlist.dropFromPicker (lynx::ClipKind::pattern, { 1, 2 }, at (2, (double) bar * 2), false);
  29189. offline.dispatchPendingMessages();
  29190. const auto* two = find (2, 1);
  29191. const auto* three = find (3, 2);
  29192. check (two != nullptr && three != nullptr && two->start == bar * 2 && three->start == bar * 2,
  29193. "two picked patterns: Pattern 2 on track 3, Pattern 3 on track 4, both at bar 3");
  29194. check (offline.getSong().currentPattern == 2, "the current pattern is the last dropped one (Pattern 3)");
  29195. const auto selectedAre = [&playlist, &offline] (int track, std::size_t count) {
  29196. const auto& sel = playlist.getSelectedClips();
  29197. if (sel.size() != count)
  29198. return false;
  29199. for (const auto i : sel)
  29200. 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)
  29201. || (track >= 0 && offline.getSong().playlist[(std::size_t) i].track != track))
  29202. return false;
  29203. return true;
  29204. };
  29205. check (selectedAre (-1, 2), "the two dropped clips are the selection (FL), Pattern 1's clip is not");
  29206. saveSnapshot (ui, prefix + "-plain.png");
  29207. // 3. Shift: all three on track 6 from bar 1, one after the other
  29208. playlist.dropFromPicker (lynx::ClipKind::pattern, { 0, 1, 2 }, at (5, 0.0), true);
  29209. offline.dispatchPendingMessages();
  29210. const auto* a = find (5, 0);
  29211. const auto* b = find (5, 1);
  29212. const auto* c = find (5, 2);
  29213. check (a != nullptr && b != nullptr && c != nullptr && a->start == 0 && b->start == a->end() && c->start == b->end(),
  29214. "Shift drop: Pattern 1, 2, 3 one after the other on track 6");
  29215. check (offline.getSong().currentPattern == 2, "Shift keeps the current pattern");
  29216. check (selectedAre (5, 3), "the three chained clips are the selection");
  29217. saveSnapshot (ui, prefix + "-shift.png");
  29218. }
  29219. checks.add (all ? "ALL OK" : "FAILURES");
  29220. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  29221. return all;
  29222. }
  29223. bool runTrackModeShot (const juce::String& prefix)
  29224. {
  29225. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29226. lynx::AudioEngine offline (false);
  29227. bool all = true;
  29228. juce::String report;
  29229. {
  29230. lynx::MainComponent ui (offline, false);
  29231. ui.setSize (1600, 900);
  29232. offline.dispatchPendingMessages();
  29233. auto& playlist = ui.getPlaylistForSnapshot();
  29234. // the track's menu, Track mode and Audio track side by side; the Audio track entries as FL writes them
  29235. // ("-" in front = greyed, "v" = ticked)
  29236. const auto shoot = [&] (int track, const juce::String& name, const juce::StringArray& fl) {
  29237. const auto menu = playlist.getTrackMenuForSnapshot (track);
  29238. juce::StringArray names { "Track " + juce::String (track + 1) };
  29239. std::vector<juce::PopupMenu> menus { menu };
  29240. menus.reserve (3); // (round 190rf, ASan: the iterator below walks menus[1] while the third is added)
  29241. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  29242. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Track mode"), 'T'))
  29243. {
  29244. names.add (lynx::tr ("Track mode"));
  29245. menus.push_back (*it.getItem().subMenu);
  29246. }
  29247. if (menus.size() == 2)
  29248. for (juce::PopupMenu::MenuItemIterator it (menus[1]); it.next();)
  29249. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Audio track"), 'A'))
  29250. {
  29251. names.add (lynx::tr ("Audio track"));
  29252. menus.push_back (*it.getItem().subMenu);
  29253. }
  29254. juce::StringArray lynxList;
  29255. if (menus.size() == 3)
  29256. for (juce::PopupMenu::MenuItemIterator it (menus[2]); it.next();)
  29257. lynxList.add (it.getItem().isSeparator ? juce::String ("|")
  29258. : (it.getItem().isTicked ? "v " : "") + juce::String (it.getItem().isEnabled ? "" : "- ") + it.getItem().text);
  29259. saveMenus (names, menus, prefix + "-" + name + ".png");
  29260. const auto same = menus.size() == 3 && lynxList == fl;
  29261. all = all && same;
  29262. report << name << ": " << (same ? "SAME AS FL" : "DIFFERENT") << "\n LYNX: " << lynxList.joinIntoString (" / ")
  29263. << "\n FL: " << fl.joinIntoString (" / ") << "\n";
  29264. };
  29265. const auto flList = [] (int inserts, std::map<int, juce::String> named, std::set<int> greyed) {
  29266. juce::StringArray l { "New mixer track(s)", "|" };
  29267. for (int i = 1; i <= inserts; ++i)
  29268. l.add ((greyed.count (i) ? "- " : "") + juce::String (i) + ". " + (named.count (i) ? named[i] : "Insert " + juce::String (i)));
  29269. return l;
  29270. };
  29271. // q1-01: a fresh project, Track 1 unassigned
  29272. shoot (0, "fresh", flList (16, {}, {}));
  29273. // q1-02: Track 1 linked to insert 6, insert 7 renamed "Vox chain"; Track 2's menu
  29274. offline.editSong ([] (lynx::Song& s) {
  29275. lynx::trackmodes::assignAudioTracks (s, { 0 }, 6);
  29276. s.mixer[7].name = "Vox chain";
  29277. });
  29278. offline.dispatchPendingMessages();
  29279. shoot (1, "linked-renamed", flList (16, { { 7, "Vox chain" } }, { 6 }));
  29280. // q1-07: the rest of FL's session (live 190cu Q2): Track 3 → 7; Track 4 → New mixer track (17), insert 9
  29281. // renamed "Vox chain", Track 4 → 9; Track 5 "Lead" → 11, insert 12 "Vox chain", Track 5 → 12; Track 6 "Lead"
  29282. // (unassigned), insert 13 "Vox chain", Track 6 → 13. Track 7's menu
  29283. offline.editSong ([] (lynx::Song& s) {
  29284. namespace tm = lynx::trackmodes;
  29285. if (s.playlistTracks.size() < 8)
  29286. s.playlistTracks.resize (8);
  29287. tm::assignAudioTracks (s, { 2 }, 7);
  29288. tm::assignAudioTracks (s, { 3 }, tm::newMixerTrack);
  29289. s.mixer[9].name = "Vox chain";
  29290. tm::assignAudioTracks (s, { 3 }, 9);
  29291. s.playlistTracks[4].name = "Lead";
  29292. tm::assignAudioTracks (s, { 4 }, 11);
  29293. s.mixer[12].name = "Vox chain";
  29294. tm::assignAudioTracks (s, { 4 }, 12);
  29295. s.playlistTracks[5].name = "Lead";
  29296. s.mixer[13].name = "Vox chain";
  29297. tm::assignAudioTracks (s, { 5 }, 13);
  29298. });
  29299. offline.dispatchPendingMessages();
  29300. shoot (6, "full-state", flList (17, { { 7, "Vox chain" }, { 9, "Insert 17" }, { 12, "Lead" }, { 13, "Vox chain" } }, { 6, 7, 9, 12, 13 }));
  29301. }
  29302. report << (all ? "ALL SAME AS FL\n" : "FAILURES\n");
  29303. juce::File (prefix + "-report.txt").replaceWithText (report);
  29304. return all;
  29305. }
  29306. void runCurveShot (const juce::String& prefix)
  29307. {
  29308. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29309. lynx::AudioEngine offline (false);
  29310. {
  29311. lynx::MainComponent ui (offline, false);
  29312. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  29313. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29314. offline.dispatchPendingMessages();
  29315. // FL's menu order, one bar per mode, the levels going up and down; a tension where the mode needs one to show
  29316. static const int order[] = { lynx::flcurve::smooth, lynx::flcurve::hold, lynx::flcurve::singleCurve, lynx::flcurve::singleCurve2,
  29317. lynx::flcurve::singleCurve3, lynx::flcurve::doubleCurve, lynx::flcurve::doubleCurve2, lynx::flcurve::doubleCurve3,
  29318. lynx::flcurve::halfSine, lynx::flcurve::stairs, lynx::flcurve::smoothStairs, lynx::flcurve::pulse, lynx::flcurve::wave };
  29319. const auto bar = (std::int64_t) lynx::ppq * 4;
  29320. offline.editSong ([bar] (lynx::Song& song) {
  29321. song.mode = lynx::PlayMode::song;
  29322. lynx::Automation a;
  29323. a.name = "Curve modes";
  29324. a.target = { lynx::AutomationTargetKind::mixerVolume, 1 };
  29325. a.points.push_back ({ 0, 0.15f, 0.0f });
  29326. int k = 0;
  29327. for (const auto mode : order)
  29328. {
  29329. const auto stepped = mode == lynx::flcurve::stairs || mode == lynx::flcurve::smoothStairs || mode == lynx::flcurve::pulse || mode == lynx::flcurve::wave;
  29330. a.points.back().mode = (std::uint8_t) mode;
  29331. a.points.back().tension = mode == lynx::flcurve::smooth || mode == lynx::flcurve::hold ? 0.0f : stepped ? -0.72f : (k % 2 == 0 ? 0.55f : -0.55f);
  29332. ++k;
  29333. a.points.push_back ({ bar * k, k % 2 == 1 ? 0.85f : 0.15f, 0.0f });
  29334. }
  29335. song.automations.insert (song.automations.begin(), a);
  29336. for (auto& c : song.playlist)
  29337. if (c.kind == lynx::ClipKind::automation)
  29338. ++c.automation;
  29339. lynx::Clip clip;
  29340. clip.kind = lynx::ClipKind::automation;
  29341. clip.automation = 0;
  29342. clip.track = 3;
  29343. clip.length = bar * 13;
  29344. song.playlist.push_back (clip);
  29345. if (song.playlistTracks.size() < 4)
  29346. song.playlistTracks.resize (4);
  29347. song.playlistTracks[3].height = 150;
  29348. }, false);
  29349. offline.dispatchPendingMessages();
  29350. ui.selectTabForSnapshot (2);
  29351. offline.dispatchPendingMessages();
  29352. auto& playlist = ui.getPlaylistForSnapshot();
  29353. saveSnapshot (ui, prefix + "-playlist.png");
  29354. const auto clipIndex = (int) offline.getSong().playlist.size() - 1;
  29355. // the point menu of the point that ends the "Stairs" segment (point 10), and of the first point
  29356. saveMenus (juce::StringArray { "Automation point (ends a Stairs segment)", "First point" },
  29357. std::vector<juce::PopupMenu> { playlist.getAutomationPointMenuForSnapshot (clipIndex, 10), playlist.getAutomationPointMenuForSnapshot (clipIndex, 0) },
  29358. prefix + "-point-menu.png");
  29359. auto editor = lynx::makeAutomationEditor (offline, 0);
  29360. editor->setSize (1500, 420);
  29361. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
  29362. editor.reset();
  29363. // the project itself, for --export-flp and a look at the same clip in FL
  29364. {
  29365. juce::String saveError;
  29366. lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-modes.lynx"), saveError);
  29367. }
  29368. // part 2: the Piano roll tools that gained FL's options (they preview on the pattern and put the notes back)
  29369. ui.selectTabForSnapshot (1);
  29370. offline.dispatchPendingMessages();
  29371. auto& roll = ui.getPianoRollForSnapshot();
  29372. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::flip, "-tool-flip.png" },
  29373. { lynx::NoteTool::limit, "-tool-limit.png" },
  29374. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  29375. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  29376. { lynx::NoteTool::lfo, "-tool-lfo.png" } };
  29377. // round 190ct: checks of the FL-live fixes, one line each in <prefix>-checks.txt (OK / FAIL)
  29378. juce::StringArray checks;
  29379. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  29380. {
  29381. juce::String header;
  29382. const auto pointMenu = playlist.getAutomationPointMenuForSnapshot (clipIndex, 10); // (the iterator keeps a reference)
  29383. for (juce::PopupMenu::MenuItemIterator it (pointMenu); it.next();)
  29384. {
  29385. header = it.getItem().text;
  29386. break;
  29387. }
  29388. check (header == "Point 11/14", "point menu header \"" + header + "\" (FL: \"Point n/N\")");
  29389. }
  29390. for (const auto& [tool, name] : tools)
  29391. {
  29392. auto panel = lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot());
  29393. offline.dispatchPendingMessages();
  29394. savePng (panel->createComponentSnapshot (panel->getLocalBounds()), prefix + name);
  29395. if (tool == lynx::NoteTool::flip)
  29396. {
  29397. std::vector<juce::ToggleButton*> toggles;
  29398. for (auto* child : panel->getChildren())
  29399. if (auto* t = dynamic_cast<juce::ToggleButton*> (child))
  29400. toggles.push_back (t);
  29401. check (toggles.size() == 3 && toggles[0]->getToggleState() && toggles[1]->getToggleState() && ! toggles[2]->getToggleState(),
  29402. "flip opens with Flip horizontally on, Preserve start times on, Flip vertically off");
  29403. if (toggles.size() == 3)
  29404. {
  29405. toggles[2]->setToggleState (true, juce::sendNotificationSync);
  29406. check (! toggles[0]->getToggleState() && toggles[2]->getToggleState(), "flip: vertically turns horizontally off (radios)");
  29407. toggles[0]->setToggleState (true, juce::sendNotificationSync);
  29408. check (toggles[0]->getToggleState() && ! toggles[2]->getToggleState(), "flip: horizontally turns vertically off (radios)");
  29409. }
  29410. }
  29411. if (tool == lynx::NoteTool::limit)
  29412. {
  29413. auto* list = lynx::noteToolLongestChoiceForSnapshot (*panel);
  29414. juce::ComboBox* key = nullptr;
  29415. for (auto* child : panel->getChildren())
  29416. if (auto* box = dynamic_cast<juce::ComboBox*> (child); box != nullptr && box->getNumItems() == 12)
  29417. key = box;
  29418. check (list != nullptr && list->getNumItems() == 89, "limit list has (none) + 66 chords + 22 scales: "
  29419. + juce::String (list != nullptr ? list->getNumItems() : 0));
  29420. check (list != nullptr && key != nullptr && list->getY() == key->getY() && list->getX() > key->getRight(),
  29421. "limit: Key and the chord / scale list share one row");
  29422. if (list != nullptr)
  29423. saveMenus (juce::StringArray { "Limit: Key / scale list" }, std::vector<juce::PopupMenu> { *list->getRootMenu() },
  29424. prefix + "-tool-limit-list.png");
  29425. }
  29426. if (tool == lynx::NoteTool::lfo)
  29427. saveMenus (juce::StringArray { "LFO tool: right-click on a Period slider" },
  29428. std::vector<juce::PopupMenu> { lynx::noteToolPresetMenuForSnapshot (*panel) }, prefix + "-tool-lfo-steps.png");
  29429. }
  29430. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  29431. }
  29432. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  29433. }
  29434. bool runEvPaneShot (const juce::String& prefix, const juce::String& projectPath)
  29435. {
  29436. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29437. lynx::AudioEngine offline (false);
  29438. juce::StringArray report;
  29439. bool ok = true;
  29440. {
  29441. lynx::MainComponent ui (offline, false);
  29442. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  29443. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29444. if (projectPath.isNotEmpty())
  29445. ui.openFile (juce::File (projectPath));
  29446. offline.dispatchPendingMessages();
  29447. ui.selectTabForSnapshot (1); // the Piano Roll
  29448. offline.dispatchPendingMessages();
  29449. auto& roll = ui.getPianoRollForSnapshot();
  29450. roll.scrollToNotes();
  29451. const auto area = ui.getLocalArea (&roll, roll.getLocalBounds());
  29452. const auto file = lynx::platform::settingsFile ("piano-roll-event-pane.txt");
  29453. auto source = juce::Desktop::getInstance().getMainMouseSource();
  29454. const auto now = juce::Time::getCurrentTime();
  29455. auto event = [&] (juce::Point<int> p, juce::Point<int> down, juce::ModifierKeys mods, int clicks, bool dragged) {
  29456. 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);
  29457. };
  29458. auto barCentre = [&roll] { return roll.eventPaneBarArea().getCentre(); };
  29459. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier),
  29460. middle (juce::ModifierKeys::middleButtonModifier);
  29461. auto click = [&] (juce::ModifierKeys button, int clicks) {
  29462. const auto at = barCentre();
  29463. roll.mouseDown (event (at, at, button, clicks, false));
  29464. roll.mouseUp (event (at, at, {}, clicks, false));
  29465. offline.dispatchPendingMessages();
  29466. };
  29467. auto dragTo = [&] (int y) {
  29468. const auto at = barCentre();
  29469. roll.mouseDown (event (at, at, left, 1, false));
  29470. for (int step = 1; step <= 8; ++step) // (a few moves, as a hand does)
  29471. roll.mouseDrag (event ({ at.x, at.y + (y - at.y) * step / 8 }, at, left, 1, true));
  29472. roll.mouseUp (event ({ at.x, y }, at, {}, 1, true));
  29473. offline.dispatchPendingMessages();
  29474. };
  29475. auto state = [&] (const juce::String& name) {
  29476. const auto grid = roll.getHeight() - lynx::PianoRollComponent::headerHeight - roll.velocityHeight - lynx::evpane::barThickness;
  29477. const auto& st = lynx::PianoRollComponent::eventPaneState();
  29478. report.add (name + ": roll " + juce::String (roll.getHeight()) + " px, grid " + juce::String (juce::jmax (0, grid)) + " px, bar top "
  29479. + juce::String (roll.eventPaneBarTopForTests()) + ", event editor " + juce::String (roll.velocityHeight) + " px, aspect "
  29480. + juce::String (st.aspect, 4) + ", spare " + juce::String (st.spare, 4) + ", file \"" + file.loadFileAsString().trim().replace ("\n", " ") + "\"");
  29481. saveArea (ui, area, prefix + "-" + name + ".png");
  29482. };
  29483. auto expect = [&] (bool condition, const juce::String& what) {
  29484. report.add ((condition ? "PASS " : "FAIL ") + what);
  29485. ok = ok && condition;
  29486. };
  29487. state ("1-default");
  29488. const auto defaultLane = roll.velocityHeight;
  29489. expect (std::abs (lynx::PianoRollComponent::eventPaneState().aspect - 0.8f) < 1e-6f, "default place is FL's 0.8");
  29490. ui.setHintForSnapshot (roll.hintAt (barCentre()));
  29491. saveSnapshot (ui, prefix + "-2-hover-hint.png");
  29492. ui.setHintForSnapshot ({});
  29493. const auto travelTop = lynx::PianoRollComponent::headerHeight, travelBottom = roll.getHeight() - lynx::evpane::barThickness;
  29494. dragTo (travelTop + (travelBottom - travelTop) * 45 / 100);
  29495. state ("3-dragged-larger");
  29496. const auto largeLane = roll.velocityHeight;
  29497. expect (largeLane > defaultLane * 2, "drag up makes the event editor taller");
  29498. expect (lynx::evpane::fromText (file.loadFileAsString().toStdString()) == lynx::PianoRollComponent::eventPaneState(),
  29499. "the place is written to the settings file on release");
  29500. click (right, 1);
  29501. state ("4-right-click-alternate");
  29502. expect (roll.velocityHeight == 0, "right-click: the alternate size (FL's spare 1.0) folds the event editor away");
  29503. click (right, 1);
  29504. state ("5-right-click-back");
  29505. expect (roll.velocityHeight == largeLane, "right-click again: back to the dragged size");
  29506. roll.runAction ("pianoRoll.eventPaneAlternate");
  29507. offline.dispatchPendingMessages();
  29508. expect (roll.velocityHeight == 0, "Shift+Enter (pianoRoll.eventPaneAlternate) swaps too");
  29509. roll.runAction ("pianoRoll.eventPaneAlternate");
  29510. offline.dispatchPendingMessages();
  29511. dragTo (travelTop + 10);
  29512. state ("6-grid-folded");
  29513. expect (roll.eventPaneBarTopForTests() == travelTop, "a drag within 23 px of the top folds the note grid away");
  29514. click (middle, 1);
  29515. state ("7-middle-click-default");
  29516. expect (roll.velocityHeight == defaultLane, "middle-click: back to the default place");
  29517. // a taller window keeps the proportion (the place is a fraction of the travel)
  29518. dragTo (travelTop + (travelBottom - travelTop) * 60 / 100);
  29519. const auto before = lynx::PianoRollComponent::eventPaneState().aspect;
  29520. roll.setSize (roll.getWidth(), roll.getHeight() + 200);
  29521. offline.dispatchPendingMessages();
  29522. const auto newTravel = roll.getHeight() - lynx::evpane::barThickness - travelTop;
  29523. expect (std::abs (roll.eventPaneBarTopForTests() - (travelTop + juce::roundToInt (before * (float) newTravel))) <= 1,
  29524. "a taller window keeps the proportion");
  29525. roll.setSize (roll.getWidth(), roll.getHeight() - 200);
  29526. offline.dispatchPendingMessages();
  29527. click (middle, 1); // leave FL's default behind
  29528. }
  29529. report.add (ok ? "RESULT OK" : "RESULT FAIL");
  29530. juce::File (prefix + "-report.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  29531. return ok;
  29532. }
  29533. void runFeat166Shot (const juce::String& prefix, const juce::String& projectPath)
  29534. {
  29535. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29536. lynx::AudioEngine offline (false);
  29537. {
  29538. lynx::MainComponent ui (offline, false);
  29539. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  29540. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29541. if (projectPath.isNotEmpty())
  29542. ui.openFile (juce::File (projectPath));
  29543. offline.dispatchPendingMessages();
  29544. ui.selectTabForSnapshot (1); // the Piano Roll, on the channel with the most notes
  29545. offline.dispatchPendingMessages();
  29546. // the scale the pattern's notes fit best (major / minor, any root)
  29547. const auto& song = offline.getSong();
  29548. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  29549. int bestRoot = 0, bestScale = 1, bestHits = -1;
  29550. for (int sc = 1; sc < (int) lynx::notetools::scales().size(); ++sc)
  29551. {
  29552. const juce::String name (lynx::notetools::scales()[(std::size_t) sc].name);
  29553. if (name != "Major" && name != "Minor")
  29554. continue;
  29555. for (int root = 0; root < 12; ++root)
  29556. {
  29557. int hits = 0;
  29558. for (const auto& n : notes)
  29559. hits += lynx::notetools::inScale (n.key, root, sc) ? 1 : 0;
  29560. if (hits > bestHits)
  29561. bestHits = hits, bestRoot = root, bestScale = sc;
  29562. }
  29563. }
  29564. auto& roll = ui.getPianoRollForSnapshot();
  29565. roll.setScaleForSnapshot (bestRoot, bestScale);
  29566. roll.scrollToNotes();
  29567. offline.dispatchPendingMessages();
  29568. saveSnapshot (ui, prefix + "-pr-scale.png");
  29569. roll.setFoldToScale (true);
  29570. offline.dispatchPendingMessages();
  29571. saveSnapshot (ui, prefix + "-pr-folded.png");
  29572. roll.setFoldToScale (false);
  29573. // ghost channels: only the first other channel with notes stays a ghost
  29574. const auto selected = offline.getSelectedChannel();
  29575. int keep = -1;
  29576. for (const auto& n : notes)
  29577. if (n.channel != selected && keep < 0)
  29578. keep = n.channel;
  29579. offline.editSong ([keep] (lynx::Song& s) {
  29580. for (int c = 0; c < (int) s.channels.size(); ++c)
  29581. s.channels[(std::size_t) c].ghostHidden = c != keep;
  29582. }, false);
  29583. offline.dispatchPendingMessages();
  29584. saveSnapshot (ui, prefix + "-pr-ghost-one.png");
  29585. saveMenus (juce::StringArray { "Ghost channels" }, { roll.ghostChannelsMenu() }, prefix + "-ghostmenu.png");
  29586. offline.editSong ([] (lynx::Song& s) {
  29587. for (auto& c : s.channels)
  29588. c.ghostHidden = false;
  29589. }, false);
  29590. // the Mixer at 500 inserts
  29591. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  29592. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::insertTracks (s, (int) s.mixer.size(), lynx::mixerops::roomForInserts (s)); }, false);
  29593. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  29594. offline.dispatchPendingMessages();
  29595. ui.selectTabForSnapshot (3);
  29596. offline.dispatchPendingMessages();
  29597. auto& mixer = ui.getMixerForSnapshot();
  29598. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  29599. saveSnapshot (ui, prefix + "-mixer500-start.png");
  29600. const auto t3 = juce::Time::getMillisecondCounterHiRes();
  29601. mixer.selectTrack ((int) offline.getSong().mixer.size() - 1);
  29602. offline.dispatchPendingMessages();
  29603. saveSnapshot (ui, prefix + "-mixer500-end.png");
  29604. juce::File (prefix + "-mixer500.txt")
  29605. .replaceWithText ("inserts=" + juce::String ((int) offline.getSong().mixer.size() - 1) + "\nfill_ms=" + juce::String (t1 - t0, 2)
  29606. + "\nsnapshot_ms=" + juce::String (t3 - t2, 2) + "\n");
  29607. }
  29608. }
  29609. // Round 190ay, Freeze, end to end with the real engine, files and export (LYNX.exe --freezetest prefix [project]).
  29610. // The project (.lynx / .flp / .als; without one, a small demo song) is rendered live, every channel that can be
  29611. // frozen is frozen, and the same render is made again: the two mixes must null. Written to prefix-report.txt: the
  29612. // null residual, the process memory and the render time before / frozen / unfrozen, what a save holds, whether
  29613. // Unfreeze gives the channels back as they were, the out-of-date and missing-audio states. Shots: the Channel Rack
  29614. // (live, frozen, out of date), the channel menus, the Piano roll of a frozen channel. The frozen audio goes to
  29615. // prefix-data (never next to the project). True = every check passed.
  29616. bool runFreezeTest (const juce::String& prefix, const juce::String& projectPath, const juce::String& mode = {})
  29617. {
  29618. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29619. lynx::AudioEngine offline (false);
  29620. lynx::MainComponent ui (offline, false);
  29621. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  29622. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29623. const auto write = [&prefix, &ui] (const char* name) {
  29624. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29625. file.deleteFile();
  29626. juce::FileOutputStream out (file);
  29627. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  29628. };
  29629. juce::String report;
  29630. int failures = 0;
  29631. const auto check = [&] (bool ok, const juce::String& what) {
  29632. report << (ok ? "ok " : "FAIL ") << what << "\n";
  29633. failures += ok ? 0 : 1;
  29634. };
  29635. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  29636. if (projectPath.isNotEmpty())
  29637. {
  29638. ui.openFile (juce::File (projectPath));
  29639. offline.dispatchPendingMessages();
  29640. }
  29641. else
  29642. offline.editSong ([] (lynx::Song& s) {
  29643. s.channels.clear();
  29644. s.patterns.clear();
  29645. s.playlist.clear();
  29646. s.bpm = 120.0;
  29647. const char* names[] = { "Lead", "Bass", "Pad", "Kick" };
  29648. for (int c = 0; c < 4; ++c)
  29649. {
  29650. lynx::ChannelDef d;
  29651. d.name = names[c];
  29652. d.instrument = c == 3 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  29653. d.synth.release = 0.3f + 0.3f * (float) c;
  29654. d.synth.cutoff = 1500.0f + 900.0f * (float) c;
  29655. d.mixerTrack = c + 1;
  29656. s.channels.push_back (d);
  29657. }
  29658. for (int p = 0; p < 2; ++p)
  29659. {
  29660. auto& pattern = s.patterns.emplace_back();
  29661. pattern.name = p == 0 ? "Verse" : "Break";
  29662. pattern.lengthTicks = 4 * lynx::ppq * 4;
  29663. for (int c = 0; c < 4; ++c)
  29664. for (int step = 0; step < (p == 0 ? 8 : 2); ++step)
  29665. {
  29666. lynx::Note n;
  29667. n.channel = c;
  29668. n.start = (std::int64_t) step * lynx::ppq * (p == 0 ? 2 : 1) + (c == 2 ? lynx::ppq / 2 : 0);
  29669. n.length = c == 3 ? lynx::ppq / 4 : lynx::ppq;
  29670. n.key = c == 3 ? 36 : 48 + c * 7 + (step * 5) % 12;
  29671. pattern.notes.push_back (n);
  29672. }
  29673. pattern.sortNotes();
  29674. }
  29675. const int order[] = { 0, 0, 1, 0 };
  29676. for (int i = 0; i < 4; ++i)
  29677. {
  29678. lynx::Clip clip;
  29679. clip.pattern = order[i];
  29680. clip.start = (std::int64_t) i * 16 * lynx::ppq;
  29681. clip.length = 16 * lynx::ppq;
  29682. s.playlist.push_back (clip);
  29683. }
  29684. s.mode = lynx::PlayMode::song;
  29685. });
  29686. offline.dispatchPendingMessages();
  29687. // the case Freeze exists for, a heavy hosted plugin: LYNX_FREEZETEST_PLUGIN = a plugin file whose first
  29688. // instrument plays the demo song's Lead (tools/testplugin/lynx_test_heavy_vst3.cpp: memory, CPU, latency, a
  29689. // state, and with LYNX_TEST_HEAVY_LOG the instances alive)
  29690. int hostedChannel = -1;
  29691. const auto hostedLog = juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_HEAVY_LOG", {});
  29692. const auto hostedAlive = [&hostedLog] {
  29693. int alive = 0;
  29694. juce::StringArray lines;
  29695. juce::File (hostedLog).readLines (lines);
  29696. for (const auto& l : lines)
  29697. alive += l.startsWith ("create") ? 1 : l.startsWith ("destroy") ? -1 : 0;
  29698. return alive;
  29699. };
  29700. if (const auto pluginPath = juce::SystemStats::getEnvironmentVariable ("LYNX_FREEZETEST_PLUGIN", {}); pluginPath.isNotEmpty() && projectPath.isEmpty())
  29701. {
  29702. auto& host = offline.getPluginHost();
  29703. const auto added = host.addPluginFile (juce::File (pluginPath));
  29704. report << "hosted plugin file: " << pluginPath << " (" << added << " plugins)\n";
  29705. for (const auto& type : host.getKnownPlugins().getTypes())
  29706. if (type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  29707. {
  29708. offline.editSong ([&type] (lynx::Song& s) {
  29709. auto& c = s.channels[0];
  29710. c.instrument = lynx::InstrumentKind::plugin;
  29711. c.plugin.id = type.createIdentifierString().toStdString();
  29712. c.plugin.name = type.name.toStdString();
  29713. });
  29714. hostedChannel = 0;
  29715. break;
  29716. }
  29717. offline.dispatchPendingMessages();
  29718. auto* instance = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (0).get());
  29719. check (hostedChannel == 0 && instance != nullptr, "the hosted plugin is loaded on channel 1");
  29720. report << "hosted plugin: " << juce::String::fromUTF8 (offline.getSong().channels[0].plugin.name.c_str())
  29721. << ", engine latency " << offline.getLatencySamples() << " frames, instances alive " << hostedAlive() << "\n";
  29722. }
  29723. const auto hostedLine = [&] (const char* stage) {
  29724. if (hostedChannel < 0)
  29725. return;
  29726. offline.freeRetiredRacks();
  29727. report << "hosted, " << stage << ": instance on the channel "
  29728. << (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr ? "yes" : "no")
  29729. << ", plugin instances alive in the process " << (hostedLog.isNotEmpty() ? juce::String (hostedAlive()) : juce::String ("(no log)")) << "\n";
  29730. };
  29731. const juce::File data (prefix + "-data");
  29732. data.deleteRecursively();
  29733. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "freezetest");
  29734. report << "project=" << (projectPath.isNotEmpty() ? projectPath : juce::String ("(demo song)")) << "\n"
  29735. << "frozen_audio_folder=" << offline.getFreezeFolder().getFullPathName() << "\n";
  29736. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  29737. struct Mix
  29738. {
  29739. juce::AudioBuffer<float> audio;
  29740. double renderSeconds = 0.0, audioSeconds = 0.0;
  29741. std::int64_t workingSet = 0, privateBytes = 0;
  29742. };
  29743. // the song as it stands, rendered by an export (its own engine: frozen channels play their audio there too)
  29744. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr, std::vector<int>* renderedLive = nullptr, int range = 0) {
  29745. Mix m;
  29746. offline.dispatchPendingMessages();
  29747. offline.freeRetiredRacks(); // (what the message loop does in the app: this mode runs without one)
  29748. m.workingSet = lynx::toolbar::PerformanceMeter::processMemoryBytes();
  29749. m.privateBytes = lynx::toolbar::PerformanceMeter::processPrivateBytes();
  29750. const juce::File file (prefix + "-" + name + ".wav");
  29751. lynx::ExportSettings settings;
  29752. settings.format = lynx::ExportSettings::Format::wav32Float;
  29753. settings.sampleRate = offline.getTransport().sampleRate.load();
  29754. settings.tailSeconds = 2.0;
  29755. juce::String error;
  29756. {
  29757. auto options = settings.toOptions();
  29758. options.hqAllPlugins = false; // the quality heard while playing: what a frozen channel's audio is made at
  29759. options.disableMaxPolyphony = false; // (and each channel's Max polyphony, as while playing)
  29760. if (range == 1)
  29761. options.range = lynx::exportopts::Range::selection;
  29762. if (range == 2)
  29763. {
  29764. options.range = lynx::exportopts::Range::pattern;
  29765. options.loops = 2;
  29766. }
  29767. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  29768. if (renderedLive != nullptr)
  29769. *renderedLive = job.channelsRenderedLive();
  29770. const auto started = juce::Time::getMillisecondCounterHiRes();
  29771. const auto ok = job.run ([] (double) { return true; }, error);
  29772. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  29773. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  29774. }
  29775. juce::WavAudioFormat wav;
  29776. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  29777. {
  29778. m.audio.setSize (2, (int) reader->lengthInSamples);
  29779. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  29780. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  29781. }
  29782. file.deleteFile();
  29783. return m;
  29784. };
  29785. // the worst sample difference, in dB below the first mix's peak
  29786. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  29787. float worst = 0.0f;
  29788. peak = 0.0f;
  29789. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  29790. for (int ch = 0; ch < 2; ++ch)
  29791. for (int i = 0; i < n; ++i)
  29792. {
  29793. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  29794. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  29795. }
  29796. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  29797. };
  29798. const auto line = [&] (const char* name, const Mix& m) {
  29799. report << name << ": working set " << megabytes (m.workingSet) << " MB, private " << megabytes (m.privateBytes) << " MB, render "
  29800. << juce::String (m.renderSeconds, 2) << " s for " << juce::String (m.audioSeconds, 2) << " s of audio ("
  29801. << juce::String (m.audioSeconds > 0.0 ? 100.0 * m.renderSeconds / m.audioSeconds : 0.0, 1) << " % of real time)\n";
  29802. };
  29803. if (mode == "measure")
  29804. {
  29805. // a process that only loaded this project and renders it: its memory with the project loaded, and after
  29806. int frozenCount = 0, hosted = 0;
  29807. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  29808. {
  29809. frozenCount += offline.getSong().channels[(std::size_t) c].freeze.on();
  29810. hosted += dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) != nullptr;
  29811. }
  29812. report << "channels " << (int) offline.getSong().channels.size() << ", frozen " << frozenCount << ", hosted plugin instances " << hosted << "\n";
  29813. const auto m = renderMix ("measure");
  29814. line ("loaded ", m);
  29815. report << "after the render: working set " << megabytes (lynx::toolbar::PerformanceMeter::processMemoryBytes()) << " MB, private "
  29816. << megabytes (lynx::toolbar::PerformanceMeter::processPrivateBytes()) << " MB\n";
  29817. flush();
  29818. return failures == 0;
  29819. }
  29820. // --- live ---
  29821. offline.capturePluginStates();
  29822. offline.editSong ([] (lynx::Song&) {}, false); // (whatever any edit settles — ids of new objects... — settled first)
  29823. const auto before = offline.getSong();
  29824. // (the project's working-time counter runs on while the test does: not part of what is compared)
  29825. const auto savedJson = [] (lynx::Song song) {
  29826. song.info.workSeconds = 0.0;
  29827. return lynx::ProjectFile::toJson (song, false);
  29828. };
  29829. const auto jsonBefore = savedJson (before);
  29830. std::vector<int> targets;
  29831. for (int c = 0; c < (int) before.channels.size(); ++c)
  29832. {
  29833. const auto* why = lynx::freeze::whyNot (before, c);
  29834. const auto plays = std::any_of (before.patterns.begin(), before.patterns.end(), [c] (const lynx::Pattern& p) {
  29835. return std::any_of (p.notes.begin(), p.notes.end(), [c] (const lynx::Note& n) { return n.channel == c; });
  29836. });
  29837. report << "channel " << (c + 1) << " '" << juce::String::fromUTF8 (before.channels[(std::size_t) c].name.c_str()) << "': "
  29838. << (why != nullptr ? juce::String ("not frozen (") + why + ")" : plays ? juce::String ("freeze") : juce::String ("no notes, left alone")) << "\n";
  29839. if (why == nullptr && plays)
  29840. {
  29841. targets.push_back (c);
  29842. // what could make a stem differ from the live channel, for the record
  29843. const auto& def = before.channels[(std::size_t) c];
  29844. int volPan = 0, params = 0, live = 0, lanes = 0, routes = 0;
  29845. for (const auto& a : before.automations)
  29846. if (a.target.index == c)
  29847. {
  29848. volPan += a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan;
  29849. params += a.target.kind == lynx::AutomationTargetKind::channelParam;
  29850. live += a.isLive() && (a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan
  29851. || a.target.kind == lynx::AutomationTargetKind::channelParam);
  29852. }
  29853. for (const auto& p : before.patterns)
  29854. for (const auto& lane : p.events)
  29855. lanes += lane.target.index == c && (lane.target.kind == lynx::AutomationTargetKind::channelVolume
  29856. || lane.target.kind == lynx::AutomationTargetKind::channelPan
  29857. || lane.target.kind == lynx::AutomationTargetKind::channelParam);
  29858. for (const auto& m : before.modulators)
  29859. for (const auto& r : m.routes)
  29860. routes += r.target.index == c && (r.target.kind == lynx::AutomationTargetKind::channelVolume
  29861. || r.target.kind == lynx::AutomationTargetKind::channelPan
  29862. || r.target.kind == lynx::AutomationTargetKind::channelParam);
  29863. report << " instrument kind " << (int) def.instrument << ", insert " << def.mixerTrack << ", automation: volume/pan " << volPan
  29864. << ", parameters " << params << ", live links " << live << ", event lanes " << lanes << ", modulator routes " << routes << "\n";
  29865. }
  29866. }
  29867. check (! targets.empty(), "the project has channels to freeze (" + juce::String ((int) targets.size()) + ")");
  29868. if (targets.empty())
  29869. {
  29870. flush();
  29871. return false;
  29872. }
  29873. // round 190rp (coordinator: Thief's frozen mix doesn't null against live, -2.8 dB): "perchannel" = each target
  29874. // alone (the others muted), live and frozen, nulled; the lag where the frozen one matches best and the residual
  29875. // there say whether it is a time offset (latency) or a different sound
  29876. if (mode == "perchannel")
  29877. {
  29878. const auto solo = [] (lynx::Song s, int keep) {
  29879. for (int k = 0; k < (int) s.channels.size(); ++k)
  29880. s.channels[(std::size_t) k].muted = k != keep;
  29881. return s;
  29882. };
  29883. for (const auto c : targets)
  29884. {
  29885. offline.setSong (before);
  29886. offline.dispatchPendingMessages();
  29887. const auto liveSong = solo (offline.getSong(), c);
  29888. const auto liveC = renderMix ("solo-live", &liveSong);
  29889. const auto error = lynx::freezeChannelNow (offline, c);
  29890. offline.dispatchPendingMessages();
  29891. const auto frozenSong = solo (offline.getSong(), c);
  29892. const auto frozenC = renderMix ("solo-frozen", &frozenSong);
  29893. float peak = 0.0f;
  29894. const auto direct = residual (liveC, frozenC, peak);
  29895. // the lag (frozen behind live, samples) with the smallest difference over the loudest 2 s
  29896. const auto n = juce::jmin (liveC.audio.getNumSamples(), frozenC.audio.getNumSamples());
  29897. int loudAt = 0;
  29898. float loud = 0.0f;
  29899. for (int i = 0; i < n; i += 256)
  29900. if (const auto v = std::abs (liveC.audio.getSample (0, i)); v > loud)
  29901. {
  29902. loud = v;
  29903. loudAt = i;
  29904. }
  29905. const auto from = juce::jmax (0, loudAt - 48000), to = juce::jmin (n - 8192, loudAt + 48000);
  29906. int bestLag = 0;
  29907. double best = -1.0;
  29908. for (int lag = -4096; lag <= 4096; ++lag)
  29909. {
  29910. double sum = 0.0;
  29911. for (int i = from; i < to; i += 4)
  29912. {
  29913. const auto j = i + lag;
  29914. if (j < 0 || j >= frozenC.audio.getNumSamples())
  29915. continue;
  29916. const auto d = (double) frozenC.audio.getSample (0, j) - (double) liveC.audio.getSample (0, i);
  29917. sum += d * d;
  29918. }
  29919. if (best < 0.0 || sum < best)
  29920. {
  29921. best = sum;
  29922. bestLag = lag;
  29923. }
  29924. }
  29925. double energy = 0.0;
  29926. for (int i = from; i < to; i += 4)
  29927. energy += (double) liveC.audio.getSample (0, i) * liveC.audio.getSample (0, i);
  29928. const auto atLag = energy > 0.0 ? 10.0 * std::log10 (juce::jmax (best, 1.0e-30) / energy) : -200.0;
  29929. // where they part: the first sample 60 dB under the peak apart, and the largest difference (seconds, bars)
  29930. int firstApart = -1, worstAt = 0;
  29931. float worst = 0.0f;
  29932. for (int ch = 0; ch < 2; ++ch)
  29933. for (int i = 0; i < n; ++i)
  29934. if (const auto d = std::abs (liveC.audio.getSample (ch, i) - frozenC.audio.getSample (ch, i)); d > 0.0f)
  29935. {
  29936. if (d > peak * 1.0e-3f && (firstApart < 0 || i < firstApart))
  29937. firstApart = i;
  29938. if (d > worst)
  29939. {
  29940. worst = d;
  29941. worstAt = i;
  29942. }
  29943. }
  29944. const auto rate = offline.getTransport().sampleRate.load();
  29945. const auto bars = [&before, rate] (int sample) {
  29946. const auto beats = sample / rate * before.bpm / 60.0;
  29947. return juce::String (beats / juce::jmax (1, before.beatsPerBar) + 1.0, 2);
  29948. };
  29949. report << " apart from " << (firstApart < 0 ? juce::String ("nowhere") : juce::String (firstApart / rate, 3) + " s (bar " + bars (firstApart) + ")")
  29950. << ", largest difference at " << juce::String (worstAt / rate, 3) << " s (bar " << bars (worstAt) << "): live "
  29951. << juce::String (liveC.audio.getSample (0, worstAt), 4) << ", frozen " << juce::String (frozenC.audio.getSample (0, worstAt), 4) << "\n";
  29952. if (const auto keep = juce::SystemStats::getEnvironmentVariable ("LYNX_FREEZETEST_KEEP", {}); juce::File::isAbsolutePath (keep))
  29953. {
  29954. const juce::File dir (keep);
  29955. dir.createDirectory();
  29956. for (const auto* m : { &liveC, &frozenC })
  29957. {
  29958. const auto out = dir.getChildFile ("ch" + juce::String (c + 1) + (m == &liveC ? "-live.wav" : "-frozen.wav"));
  29959. out.deleteFile();
  29960. juce::WavAudioFormat wav;
  29961. if (std::unique_ptr<juce::AudioFormatWriter> w (wav.createWriterFor (out.createOutputStream().release(), rate, 2, 32, {}, 0)); w != nullptr)
  29962. w->writeFromAudioSampleBuffer (m->audio, 0, m->audio.getNumSamples());
  29963. }
  29964. }
  29965. report << "channel " << (c + 1) << " '" << juce::String::fromUTF8 (before.channels[(std::size_t) c].name.c_str()) << "' instrument "
  29966. << (int) before.channels[(std::size_t) c].instrument << (error.isEmpty() ? juce::String() : " (freeze: " + error + ")")
  29967. << ": null " << juce::String (direct, 1) << " dB (peak " << juce::String (peak, 3) << "), best lag " << bestLag
  29968. << " samples, residual there " << juce::String (atLag, 1) << " dB of its energy, lengths " << liveC.audio.getNumSamples() << " / "
  29969. << frozenC.audio.getNumSamples() << "\n";
  29970. // the same with the channel's volume and pan neutral on both sides (the freeze renders its stem so and
  29971. // applies them after): a null here and none above = the level / pan reach the instrument itself
  29972. if (direct >= -90.0)
  29973. {
  29974. const auto neutral = [&solo, c] (lynx::Song s) {
  29975. auto& ch = s.channels[(std::size_t) c];
  29976. ch.volume = 1.0f;
  29977. ch.pan = 0.0f;
  29978. ch.misc.levels.volume = 1.0f;
  29979. ch.misc.levels.pan = 0.0f;
  29980. return solo (std::move (s), c);
  29981. };
  29982. offline.setSong (before);
  29983. offline.dispatchPendingMessages();
  29984. const auto liveNSong = neutral (offline.getSong());
  29985. const auto liveN = renderMix ("solo-live-neutral", &liveNSong);
  29986. lynx::freezeChannelNow (offline, c);
  29987. offline.dispatchPendingMessages();
  29988. const auto frozenNSong = neutral (offline.getSong());
  29989. const auto frozenN = renderMix ("solo-frozen-neutral", &frozenNSong);
  29990. float peakN = 0.0f;
  29991. const auto nullN = residual (liveN, frozenN, peakN);
  29992. report << " volume " << before.channels[(std::size_t) c].volume << ", pan " << before.channels[(std::size_t) c].pan
  29993. << "; with both neutral: null " << juce::String (nullN, 1) << " dB\n";
  29994. // and live against itself (a second live render from the same start): what does not null there is
  29995. // the instrument's own randomness (by design), not the freeze
  29996. offline.setSong (before);
  29997. offline.dispatchPendingMessages();
  29998. const auto againSong = solo (offline.getSong(), c);
  29999. const auto again = renderMix ("solo-live-again", &againSong);
  30000. float peakA = 0.0f;
  30001. const auto nullA = residual (liveC, again, peakA);
  30002. report << " live against live: null " << juce::String (nullA, 1) << " dB\n";
  30003. // and live with the other channels taken out as the freeze's render takes them out (freeze::lighten):
  30004. // a null here = what differs comes from the others being there (their events splitting the blocks)
  30005. auto lightSong = solo (before, c);
  30006. lynx::freeze::lighten (lightSong, c, before.channels[(std::size_t) c].mixerTrack); // (its own insert kept: it plays through it)
  30007. offline.setSong (before);
  30008. offline.dispatchPendingMessages();
  30009. const auto light = renderMix ("solo-live-lightened", &lightSong);
  30010. float peakL = 0.0f;
  30011. report << " live with the others taken out against live: null " << juce::String (residual (liveC, light, peakL), 1)
  30012. << " dB, against frozen: " << juce::String (residual (light, frozenC, peakL), 1) << " dB\n";
  30013. // and live in the chunks a stem's render uses (neutralise: Song::automationChunks on when automation plays)
  30014. auto chunked = solo (before, c);
  30015. chunked.automationChunks = true;
  30016. offline.setSong (before);
  30017. offline.dispatchPendingMessages();
  30018. const auto inChunks = renderMix ("solo-live-chunked", &chunked);
  30019. report << " automationChunks " << (before.automationChunks ? "on" : "off") << "; live in automation chunks against frozen: null "
  30020. << juce::String (residual (inChunks, frozenC, peakL), 1) << " dB, against live: " << juce::String (residual (liveC, inChunks, peakL), 1) << " dB\n";
  30021. // and both raw, straight to the Master with every insert's effects off (no latency anywhere in the
  30022. // render): a null here = the difference comes from the insert's path (its delay compensation moves
  30023. // where the blocks fall, and the instrument rounds per block)
  30024. const auto raw = [c] (lynx::Song s) {
  30025. s.channels[(std::size_t) c].mixerTrack = 0;
  30026. lynx::freeze::lighten (s, c, -1);
  30027. return s;
  30028. };
  30029. offline.setSong (before);
  30030. offline.dispatchPendingMessages();
  30031. const auto rawLiveSong = raw (solo (before, c));
  30032. const auto rawLive = renderMix ("solo-live-raw", &rawLiveSong);
  30033. lynx::freezeChannelNow (offline, c);
  30034. offline.dispatchPendingMessages();
  30035. const auto rawFrozenSong = raw (solo (offline.getSong(), c));
  30036. const auto rawFrozen = renderMix ("solo-frozen-raw", &rawFrozenSong);
  30037. report << " both raw to the Master, no insert effects: null " << juce::String (residual (rawLive, rawFrozen, peakL), 1) << " dB (insert "
  30038. << before.channels[(std::size_t) c].mixerTrack << ", " << (int) before.mixer[(std::size_t) juce::jlimit (0, (int) before.mixer.size() - 1, before.channels[(std::size_t) c].mixerTrack)].effects.size() << " effects)\n";
  30039. }
  30040. report << " levels in the stems: " << (offline.getSong().channels[(std::size_t) c].freeze.levels ? "yes" : "no") << "\n";
  30041. check (direct < -90.0, "channel " + juce::String (c + 1) + " frozen alone nulls against it live (" + juce::String (direct, 1) + " dB)");
  30042. flush();
  30043. }
  30044. flush();
  30045. return failures == 0;
  30046. }
  30047. const auto first = targets.front();
  30048. offline.setSelectedChannel (first);
  30049. ui.selectTabForSnapshot (0);
  30050. write ("rack-live");
  30051. saveMenus (juce::StringArray { "Channel (live)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-live.png");
  30052. const auto live = renderMix ("live");
  30053. line ("live ", live);
  30054. hostedLine ("live");
  30055. const auto hostedState = hostedChannel >= 0 ? before.channels[(std::size_t) hostedChannel].plugin.state.str() : std::string();
  30056. if (hostedChannel >= 0)
  30057. check (! hostedState.empty(), "the hosted plugin's state is in the project (" + juce::String ((int) hostedState.size()) + " characters)");
  30058. flush();
  30059. // --- frozen ---
  30060. const auto freezeStarted = juce::Time::getMillisecondCounterHiRes();
  30061. for (const auto c : targets)
  30062. {
  30063. const auto error = lynx::freezeChannelNow (offline, c);
  30064. check (error.isEmpty(), "freeze channel " + juce::String (c + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  30065. }
  30066. const auto freezeSeconds = (juce::Time::getMillisecondCounterHiRes() - freezeStarted) / 1000.0;
  30067. offline.dispatchPendingMessages();
  30068. std::int64_t stemBytes = 0;
  30069. int stemFiles = 0;
  30070. bool pluginsGone = true, allFrozen = true;
  30071. for (const auto c : targets)
  30072. {
  30073. const auto& ch = offline.getSong().channels[(std::size_t) c];
  30074. allFrozen = allFrozen && ch.freeze.on() && ! offline.frozenAudioMissing (c) && ! offline.freezeOutOfDate (c);
  30075. for (const auto& stem : ch.freeze.stems)
  30076. {
  30077. stemBytes += juce::File (juce::String::fromUTF8 (stem.path.c_str())).getSize();
  30078. ++stemFiles;
  30079. }
  30080. pluginsGone = pluginsGone && dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) == nullptr;
  30081. auto thawed = ch;
  30082. thawed.freeze = {};
  30083. check (thawed == before.channels[(std::size_t) c], "channel " + juce::String (c + 1) + " keeps its instrument and settings as they were while frozen");
  30084. }
  30085. check (allFrozen, "every target is frozen, its audio on disk and up to date");
  30086. check (pluginsGone, "no hosted plugin instance is left on a frozen channel");
  30087. report << "freeze: " << juce::String (freezeSeconds, 2) << " s for " << (int) targets.size() << " channels, " << stemFiles << " files, "
  30088. << megabytes (stemBytes) << " MB on disk\n";
  30089. if (mode == "keep")
  30090. {
  30091. juce::String error;
  30092. check (lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-frozen.lynx"), error), "the frozen project is saved" + (error.isEmpty() ? juce::String() : ": " + error));
  30093. flush();
  30094. return failures == 0;
  30095. }
  30096. const auto frozen = renderMix ("frozen");
  30097. line ("frozen ", frozen);
  30098. hostedLine ("frozen");
  30099. if (hostedChannel >= 0 && hostedLog.isNotEmpty())
  30100. check (hostedAlive() == 0, "while frozen no instance of the hosted plugin is alive in the process");
  30101. float peak = 0.0f;
  30102. const auto nullFrozen = residual (live, frozen, peak);
  30103. report << "null frozen vs live: " << juce::String (nullFrozen, 1) << " dB (peak " << juce::String (peak, 4) << ", "
  30104. << live.audio.getNumSamples() << " / " << frozen.audio.getNumSamples() << " samples)\n";
  30105. check (peak > 0.001f && nullFrozen < -90.0 && live.audio.getNumSamples() == frozen.audio.getNumSamples(), "the frozen mix nulls against the live mix (below -90 dB)");
  30106. ui.selectTabForSnapshot (0);
  30107. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  30108. write ("rack-frozen");
  30109. saveMenus (juce::StringArray { "Channel (frozen)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-frozen.png");
  30110. report << "hint frozen: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  30111. offline.setSelectedChannel (first);
  30112. ui.selectTabForSnapshot (1);
  30113. offline.setSelectedChannel (first);
  30114. offline.dispatchPendingMessages();
  30115. ui.setHintForSnapshot ({ lynx::tr ("{0} is frozen: Unfreeze to edit ([RMB] on the channel, Unfreeze)",
  30116. { juce::String::fromUTF8 (offline.getSong().channels[(std::size_t) first].name.c_str()) }), {} });
  30117. write ("pianoroll-frozen");
  30118. // --- exports that do not play the song's timeline once: a selection, one pattern twice ---
  30119. // (the frozen audio is the whole song from its start: those renders play the instruments, never a wrong part of it)
  30120. if (projectPath.isEmpty())
  30121. {
  30122. auto part = offline.getSong();
  30123. part.loopStart = 16 * lynx::ppq;
  30124. part.loopEnd = 40 * lynx::ppq;
  30125. const auto partLive = lynx::freeze::thawed (part);
  30126. for (int range = 1; range <= 2; ++range)
  30127. {
  30128. std::vector<int> renderedLive;
  30129. const auto a = renderMix (range == 1 ? "selection-live" : "pattern-live", &partLive, nullptr, range);
  30130. const auto b = renderMix (range == 1 ? "selection-frozen" : "pattern-frozen", &part, &renderedLive, range);
  30131. float partPeak = 0.0f;
  30132. const auto null = residual (a, b, partPeak);
  30133. report << (range == 1 ? "export of a selection (bars 5-10)" : "export of the current pattern, twice") << ", frozen vs live: " << juce::String (null, 1)
  30134. << " dB (peak " << juce::String (partPeak, 4) << ", " << juce::String (b.audioSeconds, 2) << " s), channels rendered live: " << (int) renderedLive.size() << "\n";
  30135. check (partPeak > 0.001f && null < -90.0 && a.audio.getNumSamples() == b.audio.getNumSamples(),
  30136. 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");
  30137. }
  30138. }
  30139. // --- what a save holds ---
  30140. {
  30141. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  30142. juce::String error;
  30143. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  30144. check (json.contains ("\"freeze\""), "the saved project holds the frozen state");
  30145. check (loaded.has_value() && loaded->channels.size() == offline.getSong().channels.size()
  30146. && loaded->channels[(std::size_t) first].freeze == offline.getSong().channels[(std::size_t) first].freeze,
  30147. "a frozen project loads frozen, with the same audio files");
  30148. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore,
  30149. "without the frozen state the saved project is byte for byte what it was before the freeze");
  30150. check (! jsonBefore.contains ("\"freeze\""), "a project with nothing frozen has no freeze field");
  30151. }
  30152. // --- out of date: the tempo, a note of the frozen channel; not another channel's notes ---
  30153. {
  30154. offline.editSong ([] (lynx::Song& s) { s.bpm += 4.0; });
  30155. check (offline.freezeOutOfDate (first), "a tempo change marks the freeze out of date");
  30156. ui.selectTabForSnapshot (0);
  30157. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  30158. write ("rack-out-of-date");
  30159. report << "hint out of date: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  30160. offline.editSong ([] (lynx::Song& s) { s.bpm -= 4.0; });
  30161. check (! offline.freezeOutOfDate (first), "the tempo back: up to date again");
  30162. int pattern = -1;
  30163. for (int p = 0; p < (int) before.patterns.size() && pattern < 0; ++p)
  30164. for (const auto& n : before.patterns[(std::size_t) p].notes)
  30165. if (n.channel == first)
  30166. {
  30167. pattern = p;
  30168. break;
  30169. }
  30170. if (pattern >= 0)
  30171. {
  30172. offline.editSong ([pattern, first] (lynx::Song& s) {
  30173. lynx::Note n;
  30174. n.channel = first;
  30175. n.start = 0;
  30176. n.key = 71;
  30177. s.patterns[(std::size_t) pattern].notes.push_back (n);
  30178. s.patterns[(std::size_t) pattern].sortNotes();
  30179. });
  30180. check (offline.freezeOutOfDate (first), "a note edit on the frozen channel marks it out of date");
  30181. bool othersFresh = true;
  30182. for (const auto c : targets)
  30183. othersFresh = othersFresh && (c == first || ! offline.freezeOutOfDate (c));
  30184. check (othersFresh, "the other frozen channels stay up to date");
  30185. // an export of the project in that state: the out-of-date channel renders live (never the old audio),
  30186. // the others keep their frozen audio — the same mix as the edited project with nothing frozen
  30187. {
  30188. std::vector<int> renderedLive;
  30189. const auto stale = renderMix ("stale", nullptr, &renderedLive);
  30190. const auto edited = lynx::freeze::thawed (offline.getSong());
  30191. const auto reference = renderMix ("stale-reference", &edited);
  30192. float stalePeak = 0.0f;
  30193. const auto nullStale = residual (reference, stale, stalePeak);
  30194. const auto nullOld = residual (frozen, stale, stalePeak);
  30195. report << "export with channel " << (first + 1) << " out of date: " << juce::String (nullStale, 1) << " dB vs the edited project live, "
  30196. << juce::String (nullOld, 1) << " dB vs the old frozen mix; channels rendered live: " << (int) renderedLive.size() << "\n";
  30197. check (renderedLive == std::vector<int> { first }, "an export renders the out-of-date frozen channel live, and only that one");
  30198. check (nullStale < -90.0 && nullOld > -60.0, "an export of an out-of-date freeze holds the edited notes, not the old audio");
  30199. }
  30200. offline.editSong ([&before] (lynx::Song& s) { s.patterns = before.patterns; });
  30201. check (! offline.freezeOutOfDate (first), "the notes back: up to date again");
  30202. }
  30203. }
  30204. // --- the audio gone: the instrument plays, never silence ---
  30205. {
  30206. const auto stems = offline.getSong().channels[(std::size_t) first].freeze.stems;
  30207. std::vector<std::pair<juce::File, juce::File>> moved;
  30208. for (const auto& stem : stems)
  30209. {
  30210. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  30211. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  30212. if (file.moveFileTo (away))
  30213. moved.emplace_back (file, away);
  30214. }
  30215. offline.editSong ([] (lynx::Song&) {}, false);
  30216. check (offline.frozenAudioMissing (first), "frozen audio that is not on disk is noticed");
  30217. report << "hint audio missing: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  30218. const auto fallback = renderMix ("missing");
  30219. const auto nullMissing = residual (live, fallback, peak);
  30220. report << "null with the first channel's audio missing vs live: " << juce::String (nullMissing, 1) << " dB\n";
  30221. check (nullMissing < -90.0, "with its audio missing the channel plays its instrument");
  30222. for (const auto& [file, away] : moved)
  30223. away.moveFileTo (file);
  30224. offline.editSong ([] (lynx::Song&) {}, false);
  30225. check (! offline.frozenAudioMissing (first), "the audio back: frozen again");
  30226. // the frozen mix did not null and the first channel is not (alone) why: which one is, each thawed in turn
  30227. if (nullFrozen >= -90.0 && nullMissing >= -90.0)
  30228. for (const auto c : targets)
  30229. {
  30230. if (c == first)
  30231. continue;
  30232. std::vector<std::pair<juce::File, juce::File>> aside;
  30233. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  30234. {
  30235. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  30236. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  30237. if (file.moveFileTo (away))
  30238. aside.emplace_back (file, away);
  30239. }
  30240. offline.editSong ([] (lynx::Song&) {}, false);
  30241. const auto one = renderMix ("thawed");
  30242. report << "null with channel " << (c + 1) << " thawed vs live: " << juce::String (residual (live, one, peak), 1) << " dB\n";
  30243. for (const auto& [file, away] : aside)
  30244. away.moveFileTo (file);
  30245. offline.editSong ([] (lynx::Song&) {}, false);
  30246. }
  30247. }
  30248. // --- unfrozen ---
  30249. std::vector<juce::File> stemPaths;
  30250. for (const auto c : targets)
  30251. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  30252. stemPaths.emplace_back (juce::String::fromUTF8 (stem.path.c_str()));
  30253. for (const auto c : targets)
  30254. lynx::unfreezeChannel (offline, c);
  30255. offline.dispatchPendingMessages();
  30256. check (offline.getSong().channels == before.channels, "Unfreeze gives every channel back exactly as it was (instrument, plugin state, settings)");
  30257. {
  30258. const auto jsonAfter = savedJson (offline.getSong());
  30259. check (jsonAfter == jsonBefore, "the unfrozen project saves byte for byte as before the freeze");
  30260. if (jsonAfter != jsonBefore)
  30261. {
  30262. juce::File (prefix + "-before.json").replaceWithText (jsonBefore);
  30263. juce::File (prefix + "-after.json").replaceWithText (jsonAfter);
  30264. }
  30265. }
  30266. int left = 0;
  30267. for (const auto& f : stemPaths)
  30268. left += f.existsAsFile() ? 1 : 0;
  30269. check (left == 0, "Unfreeze deletes the frozen audio (" + juce::String (left) + " of " + juce::String ((int) stemPaths.size()) + " files left)");
  30270. if (hostedChannel >= 0)
  30271. {
  30272. // the new instance (it starts with another tuning than the first one had) took the saved state
  30273. offline.capturePluginStates();
  30274. check (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr, "Unfreeze loads the hosted plugin again");
  30275. check (offline.getSong().channels[(std::size_t) hostedChannel].plugin.state == hostedState,
  30276. "the hosted plugin's state, read back from the new instance, is the state it had before the freeze");
  30277. }
  30278. const auto unfrozen = renderMix ("unfrozen");
  30279. line ("unfrozen ", unfrozen);
  30280. hostedLine ("unfrozen");
  30281. const auto nullUnfrozen = residual (live, unfrozen, peak);
  30282. report << "null unfrozen vs live: " << juce::String (nullUnfrozen, 1) << " dB\n";
  30283. check (nullUnfrozen < -90.0, "the unfrozen mix nulls against the live mix");
  30284. ui.selectTabForSnapshot (0);
  30285. flush();
  30286. data.deleteRecursively();
  30287. return failures == 0;
  30288. }
  30289. // Round 190ff, the Clip-launch workflow's track commands end to end with the real engine, files and export
  30290. // (LYNX --trackfreezetest prefix). A demo song of three tracks (Lead through a delay and a reverb whose mix is
  30291. // automated, Bass through a delay, Drums on a bare insert; each insert's fader, pan and EQ set) is rendered live; then
  30292. // Freeze Track on every track (the instrument with its volume and pan through its insert's effects), the same render
  30293. // again (must null), the effects and instruments unloaded, the render time (the CPU while frozen), what a save holds;
  30294. // Flatten (Bounce Track in Place on a frozen track) with its undo; Bounce Track in Place of a live track; Bounce to New
  30295. // Track of a track's clips against that track's device output; Consolidate of pattern clips; Unfreeze. Written to
  30296. // prefix-report.txt; shots of the grid, the column menus, the Detail View's frozen devices and the Playlist's clip
  30297. // menu. True = every check passed.
  30298. bool runTrackFreezeTest (const juce::String& prefix)
  30299. {
  30300. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30301. lynx::AudioEngine offline (false);
  30302. lynx::MainComponent ui (offline, false);
  30303. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  30304. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30305. const auto write = [&prefix, &ui] (const char* name) {
  30306. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  30307. file.deleteFile();
  30308. juce::FileOutputStream out (file);
  30309. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  30310. };
  30311. juce::String report;
  30312. int failures = 0;
  30313. const auto check = [&] (bool ok, const juce::String& what) {
  30314. report << (ok ? "ok " : "FAIL ") << what << "\n";
  30315. failures += ok ? 0 : 1;
  30316. };
  30317. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  30318. const juce::File data (prefix + "-data");
  30319. data.deleteRecursively();
  30320. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "trackfreezetest");
  30321. ui.setVisible (true);
  30322. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  30323. ui.setClipLaunchWorkflow (true);
  30324. offline.editSong ([] (lynx::Song& s) {
  30325. s.channels.clear();
  30326. s.patterns.clear();
  30327. s.playlist.clear();
  30328. s.automations.clear();
  30329. s.bpm = 120.0;
  30330. s.mode = lynx::PlayMode::song;
  30331. const char* names[] = { "Lead", "Bass", "Drums" };
  30332. for (int c = 0; c < 3; ++c)
  30333. {
  30334. lynx::ChannelDef d;
  30335. d.name = names[c];
  30336. d.instrument = c == 2 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  30337. d.synth.release = c == 0 ? 0.6f : 0.2f;
  30338. d.synth.cutoff = c == 0 ? 2400.0f : 900.0f;
  30339. d.volume = c == 0 ? 0.65f : 0.78f;
  30340. d.pan = c == 0 ? 0.25f : 0.0f;
  30341. d.mixerTrack = c + 1;
  30342. s.channels.push_back (d);
  30343. }
  30344. if (s.mixer.size() < 5)
  30345. s.mixer.resize (5);
  30346. s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay), lynx::makeEffectSlot (lynx::EffectKind::reverb) };
  30347. s.mixer[2].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay) };
  30348. s.mixer[3].effects.clear();
  30349. for (int t = 1; t <= 3; ++t)
  30350. {
  30351. s.mixer[(std::size_t) t].name = names[t - 1];
  30352. s.mixer[(std::size_t) t].volume = 0.7f;
  30353. s.mixer[(std::size_t) t].pan = t == 1 ? -0.3f : 0.1f;
  30354. s.mixer[(std::size_t) t].eq.gainDb[1] = 3.0f;
  30355. }
  30356. for (int p = 0; p < 3; ++p)
  30357. {
  30358. auto& pattern = s.patterns.emplace_back();
  30359. pattern.name = names[p];
  30360. pattern.lengthTicks = 4 * lynx::ppq * 2;
  30361. for (int step = 0; step < 8; ++step)
  30362. {
  30363. lynx::Note n;
  30364. n.channel = p;
  30365. n.start = (std::int64_t) step * lynx::ppq;
  30366. n.length = p == 2 ? lynx::ppq / 4 : lynx::ppq / 2;
  30367. n.key = p == 2 ? 36 : (p == 0 ? 60 : 36) + (step * 5) % 12;
  30368. pattern.notes.push_back (n);
  30369. }
  30370. }
  30371. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  30372. for (int t = 0; t < 3; ++t)
  30373. {
  30374. s.playlistTracks[(std::size_t) t].name = names[t];
  30375. for (int k = 0; k < 3; ++k)
  30376. {
  30377. if (t == 0 && k == 1)
  30378. continue; // (a gap in the Lead: its tail rings into it)
  30379. lynx::Clip clip;
  30380. clip.pattern = t;
  30381. clip.track = t;
  30382. clip.start = (std::int64_t) k * 8 * lynx::ppq;
  30383. clip.length = 8 * lynx::ppq;
  30384. s.playlist.push_back (clip);
  30385. }
  30386. }
  30387. // the Lead's reverb mix rises over the song (automation the freeze takes into its audio)
  30388. lynx::Automation a;
  30389. a.name = "Lead reverb mix";
  30390. a.target = { lynx::AutomationTargetKind::effectMix, 1, 1, 0 };
  30391. a.points = { { 0, 0.2f }, { 24 * lynx::ppq, 0.9f } };
  30392. s.automations.push_back (a);
  30393. lynx::Clip lane;
  30394. lane.kind = lynx::ClipKind::automation;
  30395. lane.automation = 0;
  30396. lane.track = 3;
  30397. lane.length = 24 * lynx::ppq;
  30398. s.playlist.push_back (lane);
  30399. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& x, const lynx::Clip& y) { return x.start < y.start; });
  30400. });
  30401. offline.dispatchPendingMessages();
  30402. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  30403. struct Mix
  30404. {
  30405. juce::AudioBuffer<float> audio;
  30406. double renderSeconds = 0.0, audioSeconds = 0.0;
  30407. };
  30408. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr) {
  30409. Mix m;
  30410. offline.dispatchPendingMessages();
  30411. offline.freeRetiredRacks();
  30412. const juce::File file (prefix + "-" + name + ".wav");
  30413. lynx::ExportSettings settings;
  30414. settings.format = lynx::ExportSettings::Format::wav32Float;
  30415. settings.sampleRate = offline.getTransport().sampleRate.load();
  30416. settings.tailSeconds = 2.0;
  30417. juce::String error;
  30418. auto options = settings.toOptions();
  30419. options.hqAllPlugins = false;
  30420. options.disableMaxPolyphony = false;
  30421. {
  30422. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  30423. const auto started = juce::Time::getMillisecondCounterHiRes();
  30424. const auto ok = job.run ([] (double) { return true; }, error);
  30425. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  30426. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  30427. }
  30428. juce::WavAudioFormat wav;
  30429. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  30430. {
  30431. m.audio.setSize (2, (int) reader->lengthInSamples);
  30432. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  30433. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  30434. }
  30435. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TRACKFREEZE_KEEP", {}).isEmpty()) // (kept: to look at a residual)
  30436. file.deleteFile();
  30437. return m;
  30438. };
  30439. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  30440. float worst = 0.0f;
  30441. peak = 0.0f;
  30442. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  30443. for (int ch = 0; ch < 2; ++ch)
  30444. for (int i = 0; i < n; ++i)
  30445. {
  30446. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  30447. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  30448. }
  30449. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  30450. };
  30451. const auto nullLine = [&] (const char* what, const Mix& a, const Mix& b, double limit) {
  30452. float peak = 0.0f;
  30453. const auto r = residual (a, b, peak);
  30454. report << what << ": " << juce::String (r, 1) << " dB (peak " << juce::String (peak, 4) << ", " << a.audio.getNumSamples() << " / "
  30455. << b.audio.getNumSamples() << " samples)\n";
  30456. check (peak > 0.001f && r < limit && a.audio.getNumSamples() == b.audio.getNumSamples(), juce::String (what) + " below " + juce::String (limit, 0) + " dB");
  30457. return r;
  30458. };
  30459. const auto savedJson = [] (lynx::Song song) {
  30460. song.info.workSeconds = 0.0;
  30461. return lynx::ProjectFile::toJson (song, false);
  30462. };
  30463. // --- live ---
  30464. offline.capturePluginStates();
  30465. offline.editSong ([] (lynx::Song&) {}, false);
  30466. const auto before = offline.getSong();
  30467. const auto jsonBefore = savedJson (before);
  30468. auto* grid = ui.getClipGridForSnapshot();
  30469. check (grid != nullptr, "the Clip-launch workflow's grid is there");
  30470. if (grid == nullptr)
  30471. {
  30472. flush();
  30473. return false;
  30474. }
  30475. ui.setClipGridView (lynx::PlaylistArea::GridView::beside);
  30476. write ("live");
  30477. saveMenus (juce::StringArray { "Track title (live)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-live.png");
  30478. int leadClip = -1;
  30479. for (int i = 0; i < (int) before.playlist.size() && leadClip < 0; ++i)
  30480. if (before.playlist[(std::size_t) i].track == 0 && before.playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  30481. leadClip = i;
  30482. ui.getPlaylistForSnapshot().selectForSnapshot ({ leadClip });
  30483. saveMenus (juce::StringArray { "Playlist clip (Clip-launch workflow)" }, std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().getClipMenuForSnapshot (leadClip) },
  30484. prefix + "-menu-clip.png");
  30485. const auto live = renderMix ("live");
  30486. report << "live: render " << juce::String (live.renderSeconds, 2) << " s for " << juce::String (live.audioSeconds, 2) << " s of audio\n";
  30487. // --- Freeze Track on every track ---
  30488. std::vector<int> channels;
  30489. for (int t = 0; t < 3; ++t)
  30490. {
  30491. const auto c = lynx::detailchain::forTrack (before, t).channel;
  30492. check (c == t, "track " + juce::String (t + 1) + " shows channel " + juce::String (t + 1));
  30493. const auto* why = lynx::freeze::whyNotTrack (before, c);
  30494. check (why == nullptr, "track " + juce::String (t + 1) + " can be frozen" + (why != nullptr ? juce::String (": ") + why : juce::String()));
  30495. const auto error = lynx::freezeTrackNow (offline, c);
  30496. check (error.isEmpty(), "Freeze Track " + juce::String (t + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  30497. channels.push_back (c);
  30498. }
  30499. offline.dispatchPendingMessages();
  30500. offline.freeRetiredRacks();
  30501. int loadedEffects = 0;
  30502. for (int t = 1; t <= 3; ++t)
  30503. for (int slot = 0; slot < (int) offline.getSong().mixer[(std::size_t) t].effects.size(); ++slot)
  30504. loadedEffects += offline.getEffect (t, slot) != nullptr ? 1 : 0;
  30505. check (loadedEffects == 0, "no effect of a frozen track is loaded (" + juce::String (loadedEffects) + " left)");
  30506. bool fresh = true;
  30507. for (const auto c : channels)
  30508. {
  30509. const auto& f = offline.getSong().channels[(std::size_t) c].freeze;
  30510. fresh = fresh && f.on() && f.insert == c + 1 && lynx::freeze::trackFreezeHolds (offline.getSong(), c) && ! offline.freezeOutOfDate (c)
  30511. && ! offline.frozenAudioMissing (c);
  30512. }
  30513. check (fresh, "every track is frozen with its insert, its audio on disk and up to date");
  30514. check (offline.getSong().mixer == before.mixer, "the project keeps every effect as it was (Unfreeze brings them back)");
  30515. const auto frozenSong = offline.getSong();
  30516. const auto frozen = renderMix ("frozen");
  30517. report << "frozen: render " << juce::String (frozen.renderSeconds, 2) << " s (" << juce::String (100.0 * frozen.renderSeconds / juce::jmax (0.001, live.renderSeconds), 0)
  30518. << " % of the live render's time)\n";
  30519. nullLine ("frozen vs live", live, frozen, -90.0);
  30520. write ("frozen");
  30521. saveMenus (juce::StringArray { "Track title (frozen)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-frozen.png");
  30522. if (auto* detail = ui.getDetailViewForSnapshot())
  30523. {
  30524. detail->showSelection (0, 0);
  30525. detail->setPage (lynx::DetailView::Page::devices);
  30526. write ("detail-frozen");
  30527. }
  30528. // the insert's fader is live: moved, the frozen and the live song change alike
  30529. {
  30530. auto liveLouder = before, frozenLouder = frozenSong;
  30531. liveLouder.mixer[1].volume = frozenLouder.mixer[1].volume = 0.8f;
  30532. nullLine ("frozen vs live, the Lead's fader moved afterwards", renderMix ("live-louder", &liveLouder), renderMix ("frozen-louder", &frozenLouder), -90.0);
  30533. }
  30534. // --- what a save holds ---
  30535. {
  30536. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  30537. juce::String error;
  30538. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  30539. check (json.contains ("\"trackFreeze\"") && ! json.contains ("\"freeze\""), "a track freeze is saved under its own key (older versions play it live)");
  30540. check (loaded.has_value() && loaded->channels.size() == frozenSong.channels.size() && loaded->channels[0].freeze == frozenSong.channels[0].freeze,
  30541. "a track-frozen project loads frozen, with its insert and audio files");
  30542. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore, "without the frozen state the project saves as before the freeze");
  30543. }
  30544. // --- an edit of a frozen device's insert routing: the freeze stops holding, the track plays live ---
  30545. {
  30546. offline.editSong ([] (lynx::Song& s) { s.channels[1].mixerTrack = 1; }); // (the Bass into the Lead's insert)
  30547. check (! lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && offline.freezeOutOfDate (0), "another channel routed into a frozen insert: out of date, plays live");
  30548. offline.undo();
  30549. offline.dispatchPendingMessages();
  30550. check (lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && ! offline.freezeOutOfDate (0), "undo: frozen again");
  30551. }
  30552. // --- Flatten: Bounce Track in Place on the frozen Lead, and its undo ---
  30553. {
  30554. const auto error = lynx::flattenChannelNow (offline, 0);
  30555. check (error.isEmpty(), "Bounce Track in Place of the frozen Lead (Flatten)" + (error.isEmpty() ? juce::String() : ": " + error));
  30556. const auto& song = offline.getSong();
  30557. check (song.channels[0].instrument == lynx::InstrumentKind::audioClip && song.mixer[1].effects.empty() && song.mixer[1].volume == before.mixer[1].volume
  30558. && song.channels[0].name == "Lead (Bounce)",
  30559. "the Lead is audio now (\"Lead (Bounce)\"), its insert's effects removed, its fader kept");
  30560. int audioClips = 0;
  30561. for (const auto& c : song.playlist)
  30562. audioClips += c.kind == lynx::ClipKind::audio && c.channel == 0;
  30563. report << "flattened Lead: " << audioClips << " audio clips\n";
  30564. write ("flattened");
  30565. // over the song (the flattened clips end where the arrangement ends, as a frozen track plays; an export's
  30566. // ring-out after the song's end is not in them)
  30567. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  30568. auto flatMix = renderMix ("flattened");
  30569. auto reference = live;
  30570. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  30571. flatMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  30572. nullLine ("flattened (Lead) + frozen (others) vs live, over the song", reference, flatMix, -90.0);
  30573. offline.undo();
  30574. offline.dispatchPendingMessages();
  30575. check (savedJson (offline.getSong()) == savedJson (frozenSong), "undo of the Flatten: the frozen project exactly as before");
  30576. }
  30577. // --- Unfreeze every track ---
  30578. for (const auto c : channels)
  30579. lynx::unfreezeChannel (offline, c);
  30580. offline.dispatchPendingMessages();
  30581. check (savedJson (offline.getSong()) == jsonBefore, "Unfreeze: the project saves byte for byte as before the freeze");
  30582. nullLine ("unfrozen vs live", live, renderMix ("unfrozen"), -90.0);
  30583. // --- Bounce Track in Place of a live track (render and flatten in one step, one undo) ---
  30584. {
  30585. const auto error = lynx::freezeTrackNow (offline, 1, true);
  30586. check (error.isEmpty(), "Bounce Track in Place of the live Bass" + (error.isEmpty() ? juce::String() : ": " + error));
  30587. check (offline.getSong().channels[1].instrument == lynx::InstrumentKind::audioClip && ! offline.getSong().channels[1].freeze.on(),
  30588. "the Bass is audio, not frozen");
  30589. auto bouncedMix = renderMix ("bounced");
  30590. auto reference = live;
  30591. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  30592. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  30593. bouncedMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  30594. nullLine ("Bass bounced in place vs live, over the song", reference, bouncedMix, -90.0);
  30595. offline.undo();
  30596. offline.dispatchPendingMessages();
  30597. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce Track in Place: the project as before");
  30598. }
  30599. // --- Bounce to New Track: the Lead's clips onto a new track (the clips muted, the new track with the Lead's mixer) ---
  30600. {
  30601. std::vector<int> leadClips;
  30602. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  30603. if (offline.getSong().playlist[(std::size_t) i].track == 0 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  30604. leadClips.push_back (i);
  30605. const auto channelsBefore = offline.getSong().channels.size();
  30606. const auto error = lynx::bounceToNewTrack (offline, leadClips, true);
  30607. check (error.isEmpty(), "Bounce to New Track of the Lead's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  30608. const auto& song = offline.getSong();
  30609. check (song.channels.size() == channelsBefore + 1 && song.channels.back().instrument == lynx::InstrumentKind::audioClip
  30610. && song.channels.back().mixerTrack > 3 && song.mixer[(std::size_t) song.channels.back().mixerTrack].volume == before.mixer[1].volume,
  30611. "a new audio channel holds the bounce, on an insert with the Lead's mixer");
  30612. // the song's span (the bounce stops at the last clip's end, the live render rings on after it)
  30613. auto bounced = renderMix ("bounced-new-track");
  30614. auto reference = live;
  30615. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  30616. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  30617. bounced.audio.setSize (2, reference.audio.getNumSamples(), true);
  30618. nullLine ("Bounce to New Track (Lead's clips muted) vs live, over the song", reference, bounced, -90.0);
  30619. write ("bounced-new-track");
  30620. offline.undo();
  30621. offline.dispatchPendingMessages();
  30622. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce to New Track: the project as before");
  30623. }
  30624. // --- Consolidate: the Bass's three pattern clips become one ---
  30625. {
  30626. std::vector<int> bassClips;
  30627. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  30628. if (offline.getSong().playlist[(std::size_t) i].track == 1 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  30629. bassClips.push_back (i);
  30630. const auto error = lynx::consolidateClips (offline, bassClips, true);
  30631. check (error.isEmpty(), "Consolidate of the Bass's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  30632. int left = 0;
  30633. for (const auto& c : offline.getSong().playlist)
  30634. left += c.track == 1 && c.kind == lynx::ClipKind::pattern;
  30635. check (left == 1, "one clip on the Bass track (" + juce::String (left) + ")");
  30636. nullLine ("consolidated vs live", live, renderMix ("consolidated"), -90.0);
  30637. offline.undo();
  30638. offline.dispatchPendingMessages();
  30639. check (savedJson (offline.getSong()) == jsonBefore, "undo of Consolidate: the project as before");
  30640. }
  30641. report << "frozen audio folder: " << offline.getFreezeFolder().getFullPathName() << "\n";
  30642. flush();
  30643. data.deleteRecursively();
  30644. (void) megabytes;
  30645. return failures == 0;
  30646. }
  30647. // --paintbench (round 190ge): the paint cost of every main view, off screen. Each view is shown maximised in a
  30648. // LYNX_SNAPSHOT_SIZE window (default 1920x1080) and drawn whole into a picture `frames` times (after a repaint of
  30649. // all of it, so no cached picture is reused: the cost of a frame after an edit), then `frames` times without the
  30650. // repaint (what a view's own caches leave of a frame). The report gives the median and the 90th percentile of
  30651. // the message thread's CPU per frame.
  30652. void runPaintBench (const juce::File& project, const juce::File& report)
  30653. {
  30654. // LYNX_PROFILE_MAIN=<file> (round 190gr): the message thread sampled while it paints (Windows; one view at a time
  30655. // with LYNX_PAINTBENCH_VIEWS)
  30656. const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {});
  30657. if (profile.isNotEmpty())
  30658. lynx::crashguard::startMainProfiler (profile.toStdString(), 1000, 2);
  30659. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30660. lynx::AudioEngine offline (false);
  30661. lynx::MainComponent ui (offline, false);
  30662. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  30663. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30664. juce::String text;
  30665. text << "project: " << project.getFullPathName() << "\nLYNX " << getApplicationVersion() << ", " << juce::SystemStats::getCpuModel()
  30666. << ", window " << ui.getWidth() << "x" << ui.getHeight() << "\n";
  30667. // LYNX_PAINTBENCH_MIXER_EXTRAS=0|1 (rollup 0.1.32 step 2): round 190qh's peak values and correlation bars off / on
  30668. // (on by default since 0.1.32), for an A/B of their paint cost
  30669. if (const auto extras = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_MIXER_EXTRAS", {}); extras.isNotEmpty())
  30670. {
  30671. if (lynx::mixeroptions::setShowPeakValues && lynx::mixeroptions::setShowCorrelation)
  30672. {
  30673. lynx::mixeroptions::setShowPeakValues (extras.getIntValue() != 0);
  30674. lynx::mixeroptions::setShowCorrelation (extras.getIntValue() != 0);
  30675. }
  30676. text << "mixer peak values / correlation " << (extras.getIntValue() != 0 ? "on" : "off") << " (LYNX_PAINTBENCH_MIXER_EXTRAS)\n";
  30677. }
  30678. if (project.existsAsFile())
  30679. {
  30680. // (round perfgate190id) the time to open it headless, and the memory after
  30681. const auto open0 = juce::Time::getMillisecondCounterHiRes();
  30682. const auto cpu0 = lynx::threadCpuSeconds();
  30683. ui.openFile (project);
  30684. offline.dispatchPendingMessages();
  30685. text << "open: " << juce::String (juce::Time::getMillisecondCounterHiRes() - open0, 1) << " ms wall, "
  30686. << juce::String (1000.0 * (lynx::threadCpuSeconds() - cpu0), 1) << " ms message thread CPU, working set "
  30687. << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << " MB\n";
  30688. }
  30689. // LYNX_PAINTBENCH_ROW=<px> (round 190oo): the Playlist's row height after the open, so a build whose .flp import
  30690. // reads FL's own row height (PAT-6: Thief at 26 px) can be compared with one at 48 px for the same drawing
  30691. if (const auto row = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_ROW", {}).getIntValue(); row > 0)
  30692. {
  30693. offline.editSong ([row] (lynx::Song& s) { s.playlistRowHeight = row; }, false);
  30694. offline.dispatchPendingMessages();
  30695. text << "playlist rows forced to " << row << " px (LYNX_PAINTBENCH_ROW)\n";
  30696. }
  30697. // LYNX_PAINTBENCH_SELECT=<track> (round 190ro): that Playlist track selected (a header click), so PR #267's "Dim
  30698. // unselected tracks" veil is in the frames; LYNX_PAINTBENCH_DIM=0|1 switches that extra off / on for an A/B
  30699. if (const auto select = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_SELECT", {}); select.isNotEmpty())
  30700. {
  30701. ui.getPlaylistForSnapshot().selectTrack (select.getIntValue());
  30702. offline.dispatchPendingMessages();
  30703. text << "playlist track " << select.getIntValue() << " selected (LYNX_PAINTBENCH_SELECT)\n";
  30704. }
  30705. // LYNX_PAINTBENCH_CABLES=0|1 (round 190sw, issue #292): the routing cables' gutter off / on (with LYNX_PAINTBENCH_SELECT for
  30706. // a selected track whose cables are drawn)
  30707. if (const auto cables = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_CABLES", {}); cables.isNotEmpty())
  30708. {
  30709. lynx::workflowextras::setExtra ("playlist.routingCables", cables.getIntValue() != 0);
  30710. ui.applyRoutingCables();
  30711. offline.dispatchPendingMessages();
  30712. text << "routing cables " << (lynx::routecables::on ? "on" : "off") << " (LYNX_PAINTBENCH_CABLES)\n";
  30713. }
  30714. if (const auto dim = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_DIM", {}); dim.isNotEmpty())
  30715. {
  30716. lynx::PlaylistComponent::dimUnselectedTracks = dim.getIntValue() != 0;
  30717. text << "dim unselected tracks " << (lynx::PlaylistComponent::dimUnselectedTracks ? "on" : "off") << " (LYNX_PAINTBENCH_DIM)\n";
  30718. }
  30719. // LYNX_PAINTBENCH_190SO=0|1 (round 190so): the Playlist view group's extras off / on together (the Master and return
  30720. // rows, wide track meters, the toolbar meter's numbers, the second time readout); pins come from the project itself
  30721. if (const auto group = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_190SO", {}); group.isNotEmpty())
  30722. {
  30723. const auto on = group.getIntValue() != 0;
  30724. lynx::mixerrows::shown = lynx::widemeter::on = lynx::toolbarextras::meterValues = lynx::toolbarextras::secondaryTime = on;
  30725. ui.getPlaylistForSnapshot().refreshViewOptions();
  30726. ui.getPlaylistForSnapshot().stepMetersForSnapshot();
  30727. ui.resized();
  30728. offline.dispatchPendingMessages();
  30729. text << "playlist view group (190so) extras " << (on ? "on" : "off") << " (LYNX_PAINTBENCH_190SO)\n";
  30730. }
  30731. // LYNX_PAINTBENCH_KEYS=0|1|2 (round 190oo): the Piano roll's keyboard style (flat, lined piano keys, FL's keys)
  30732. if (const auto keys = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_KEYS", {}); keys.isNotEmpty())
  30733. {
  30734. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::styleFromInt (keys.getIntValue());
  30735. text << "keyboard style " << keys.getIntValue() << " (LYNX_PAINTBENCH_KEYS)\n";
  30736. }
  30737. // LYNX_PAINTBENCH_SETTLE=<ms> (round 190sz, the coordinator's lead from round 190sw: a frame that comes out in one of
  30738. // two states from run to run): the message loop and the engine's messages run that long after the open before
  30739. // anything is measured, so what the open started in the background (sample loads, caches) has finished
  30740. if (const auto settle = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_SETTLE", {}).getIntValue(); settle > 0)
  30741. {
  30742. const auto end = juce::Time::getMillisecondCounterHiRes() + settle;
  30743. while (juce::Time::getMillisecondCounterHiRes() < end)
  30744. {
  30745. #if JUCE_LINUX || JUCE_WINDOWS
  30746. while (juce::detail::dispatchNextMessageOnSystemQueue (true)) {}
  30747. #endif
  30748. offline.dispatchPendingMessages();
  30749. juce::Thread::sleep (5);
  30750. }
  30751. text << "settled " << settle << " ms after the open (LYNX_PAINTBENCH_SETTLE)\n";
  30752. }
  30753. const auto& song = offline.getSong();
  30754. text << "channels " << (int) song.channels.size() << ", patterns " << (int) song.patterns.size() << ", playlist clips " << (int) song.playlist.size()
  30755. << ", inserts " << (int) song.mixer.size() << "\n";
  30756. // the playhead a third into the song (song mode) so the views draw it as when playing
  30757. offline.getTransport().songMode = true;
  30758. offline.getTransport().positionTicks.store ((double) song.songLength() / 3.0);
  30759. const auto frames = juce::jlimit (3, 500, juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_FRAMES", "40").getIntValue());
  30760. juce::Image image (juce::Image::ARGB, ui.getWidth(), ui.getHeight(), true);
  30761. {
  30762. // (round 190gr) which renderer draws the frames: the software one (Linux), Direct2D (Windows), Core Graphics
  30763. juce::Graphics g (image);
  30764. auto& context = g.getInternalContext();
  30765. text << "renderer: " << (dynamic_cast<juce::LowLevelGraphicsSoftwareRenderer*> (&context) != nullptr ? "software" : typeid (context).name())
  30766. << ", paint caches " << (lynx::ui::paintCache() ? "on" : "off (LYNX_PAINT_CACHE=0)") << ", paint savings "
  30767. << (lynx::ui::paintSavings() ? "on" : "off (LYNX_PAINT_SAVINGS=0)") << "\n";
  30768. }
  30769. // LYNX_PAINTBENCH_VIEWS="mixer,channel rack" (round 190gr): only those views
  30770. const auto onlyViews = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_VIEWS", {}), ",", "");
  30771. const auto wanted = [&onlyViews] (const juce::String& name) { return onlyViews.isEmpty() || onlyViews.contains (name); };
  30772. // the picture's pixels as one number: the same before and after a change = the same drawing
  30773. auto pixelHash = [&image] {
  30774. const juce::Image::BitmapData data (image, juce::Image::BitmapData::readOnly);
  30775. std::uint64_t h = 1469598103934665603ull;
  30776. for (int y = 0; y < data.height; ++y)
  30777. for (int x = 0; x < data.width; ++x)
  30778. h = (h ^ data.getPixelColour (x, y).getARGB()) * 1099511628211ull;
  30779. return juce::String::toHexString ((juce::int64) h);
  30780. };
  30781. // mode 0: whole frames after a repaint of everything; 1: whole frames, the views' own caches kept; 2: a 14-pixel
  30782. // column of the whole height at 40 places (what a moving playhead repaints each frame)
  30783. // (rollup step 9: the instructions the message thread retires per frame, Linux, where the CPU counter can be read:
  30784. // the performance gate's stable paint measure, scripts/perf_gate.py "paint_instr")
  30785. const lynx::platform::ThreadInstructions instructions;
  30786. auto measure = [&] (const juce::String& name, int mode) {
  30787. offline.dispatchPendingMessages();
  30788. std::vector<double> ms, wall;
  30789. std::vector<long long> instr;
  30790. juce::String hash;
  30791. for (int f = -3; f < frames; ++f) // (3 frames to warm the caches up)
  30792. {
  30793. if (mode == 0)
  30794. ui.repaint();
  30795. const auto column = juce::Rectangle<int> ((juce::jmax (0, f) * 97) % juce::jmax (1, ui.getWidth() - 14), 0, 14, ui.getHeight());
  30796. const auto t0 = lynx::threadCpuSeconds();
  30797. const auto w0 = juce::Time::getMillisecondCounterHiRes();
  30798. const auto i0 = instructions.now();
  30799. {
  30800. juce::Graphics g (image);
  30801. if (mode == 2)
  30802. g.reduceClipRegion (column);
  30803. ui.paintEntireComponent (g, true);
  30804. }
  30805. if (const auto i1 = instructions.now(); f >= 0 && i0 >= 0 && i1 >= i0)
  30806. instr.push_back (i1 - i0);
  30807. if (f >= 0)
  30808. {
  30809. ms.push_back (1000.0 * (lynx::threadCpuSeconds() - t0));
  30810. wall.push_back (juce::Time::getMillisecondCounterHiRes() - w0); // (round 190gr: Direct2D's work ends with the frame)
  30811. }
  30812. if (f == 0 && mode == 0)
  30813. {
  30814. hash = pixelHash();
  30815. // LYNX_PAINTBENCH_PNG=<prefix> (round 190gr): the whole frame as <prefix>-<view>.png, to compare pixels
  30816. if (const auto png = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_PNG", {}); png.isNotEmpty())
  30817. {
  30818. const juce::File file (png + "-" + name.replaceCharacter (' ', '-') + ".png");
  30819. file.deleteFile();
  30820. juce::FileOutputStream out (file);
  30821. juce::PNGImageFormat().writeImageToStream (image, out);
  30822. }
  30823. }
  30824. }
  30825. std::sort (ms.begin(), ms.end());
  30826. std::sort (wall.begin(), wall.end());
  30827. text << name << (mode == 0 ? ", whole frame" : mode == 1 ? ", cached frame" : ", playhead column") << ": median "
  30828. << juce::String (ms[ms.size() / 2], 3) << " ms, p90 " << juce::String (ms[(ms.size() * 9) / 10], 3) << " ms, wall median "
  30829. << juce::String (wall[wall.size() / 2], 3) << " ms"
  30830. << (hash.isNotEmpty() ? ", pixels " + hash : juce::String());
  30831. if (instr.size() == ms.size())
  30832. {
  30833. // LYNX_PAINTBENCH_FRAMES_OUT=1 (round 190sz): every frame's instructions too, in frame order
  30834. static const bool everyFrame = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_FRAMES_OUT", {}) == "1";
  30835. juce::String frames;
  30836. if (everyFrame)
  30837. for (const auto v : instr)
  30838. frames << " " << juce::String ((juce::int64) v);
  30839. std::sort (instr.begin(), instr.end());
  30840. text << ", instructions median " << juce::String ((juce::int64) instr[instr.size() / 2]);
  30841. if (everyFrame)
  30842. text << ", frames" << frames;
  30843. }
  30844. text << "\n";
  30845. report.replaceWithText (text);
  30846. };
  30847. auto measureAll = [&] (const juce::String& name) {
  30848. if (! wanted (name))
  30849. return;
  30850. // LYNX_PAINTBENCH_MODES="2" (round 190rd): only these frame kinds (0 whole, 1 cached, 2 playhead column), so a
  30851. // profiler run sees one kind alone
  30852. static const auto modes = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_MODES", "0,1,2");
  30853. for (int mode = 0; mode < 3; ++mode)
  30854. if (modes.containsChar ((juce::juce_wchar) ('0' + mode)))
  30855. measure (name, mode);
  30856. // the columns' pixels too (painted over the whole frame: culling must not change a pixel)
  30857. ui.repaint();
  30858. {
  30859. juce::Graphics g (image);
  30860. ui.paintEntireComponent (g, true);
  30861. for (int x = 3; x < ui.getWidth() - 14; x += 211)
  30862. {
  30863. juce::Graphics::ScopedSaveState state (g);
  30864. g.reduceClipRegion (x, 0, 14, ui.getHeight());
  30865. ui.paintEntireComponent (g, true);
  30866. }
  30867. }
  30868. text << name << ", columns over the whole frame: pixels " << pixelHash() << "\n";
  30869. // (round 190rd) LYNX_PAINTBENCH_PNG: that picture too, as <prefix>-<view>-columns.png
  30870. if (const auto png = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_PNG", {}); png.isNotEmpty())
  30871. {
  30872. const juce::File file (png + "-" + name.replaceCharacter (' ', '-') + "-columns.png");
  30873. file.deleteFile();
  30874. juce::FileOutputStream out (file);
  30875. juce::PNGImageFormat().writeImageToStream (image, out);
  30876. }
  30877. };
  30878. // LYNX_KEEP_LABELS=0|1 (round 190qe): Playlist ▸ View ▸ "Keep labels on screen" for the whole run (A/B of the labels' cost)
  30879. if (const auto keep = juce::SystemStats::getEnvironmentVariable ("LYNX_KEEP_LABELS", {}); keep.isNotEmpty())
  30880. {
  30881. lynx::keeplabels::on = keep != "0";
  30882. text << "keep labels on screen " << (lynx::keeplabels::on ? "on" : "off") << " (LYNX_KEEP_LABELS)\n";
  30883. }
  30884. const char* views[] { "channel rack", "piano roll", "playlist", "mixer" };
  30885. for (int v = 0; v < 4; ++v)
  30886. {
  30887. ui.selectTabForSnapshot (v);
  30888. measureAll (views[v]);
  30889. }
  30890. // LYNX_PAINTBENCH_BAR=<n> (round 190qe): the Playlist once more from bar n (the same zoom), so the clips whose start is
  30891. // scrolled off draw their labels at the left edge ("Keep labels on screen")
  30892. if (const auto fromBar = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_BAR", {}).getIntValue(); fromBar > 0)
  30893. {
  30894. ui.selectTabForSnapshot (2);
  30895. auto& pl = ui.getPlaylistForSnapshot();
  30896. const auto before = pl.viewForSnapshot();
  30897. pl.setViewForSnapshot (before.pixelsPerTick * (double) offline.getSong().barTicks(), fromBar, 0);
  30898. pl.setScrollYForSnapshot (before.scrollY);
  30899. measureAll ("playlist from bar " + juce::String (fromBar));
  30900. pl.restoreViewForSnapshot (before);
  30901. }
  30902. ui.showDesktopForSnapshot (false);
  30903. measureAll ("desktop");
  30904. ui.selectTabForSnapshot (2);
  30905. ui.setClipLaunchWorkflow (true);
  30906. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  30907. measureAll ("clip grid");
  30908. ui.setClipGridView (lynx::PlaylistArea::GridView::song); // (round 190jn: the Clip-launch layout's Arrangement)
  30909. measureAll ("clip arrangement");
  30910. // (and with View > Tall Arrangement lanes: LYNX's 38 px rows in Live's look, the classic look's row height)
  30911. lynx::playlistTallLiveLanes() = true;
  30912. ui.getPlaylistForSnapshot().liveLanesChanged();
  30913. measureAll ("clip arrangement, tall lanes");
  30914. lynx::playlistTallLiveLanes() = false;
  30915. ui.getPlaylistForSnapshot().liveLanesChanged();
  30916. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  30917. ui.setClipLaunchWorkflow (false);
  30918. // LYNX_PAINTBENCH_SIMPLE=1 (round 190jc): the same project's Playlist in the Simple layout too
  30919. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_SIMPLE", {}) == "1")
  30920. {
  30921. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  30922. offline.dispatchPendingMessages();
  30923. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  30924. simple->hideChooser();
  30925. ui.selectTabForSnapshot (2);
  30926. measureAll ("simple playlist");
  30927. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  30928. }
  30929. text << "result=OK\n";
  30930. report.replaceWithText (text);
  30931. if (profile.isNotEmpty())
  30932. lynx::crashguard::stopMainProfiler();
  30933. }
  30934. // Round 190iv: the toolbar per layout style (see --toolbarshot190iv above)
  30935. void runToolbarShot190iv (const juce::String& prefix, const juce::String& projectPath)
  30936. {
  30937. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30938. lynx::ui::motion::enabled() = false; // (hover states drawn at once, no fade)
  30939. lynx::AudioEngine offline (false);
  30940. lynx::MainComponent ui (offline, false);
  30941. ui.setSize (1920, 1080);
  30942. juce::String report;
  30943. const auto write = [&prefix] (const juce::Image& image, const juce::String& name) {
  30944. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  30945. file.deleteFile();
  30946. juce::FileOutputStream out (file);
  30947. juce::PNGImageFormat().writeImageToStream (image, out);
  30948. };
  30949. const auto bar = [&ui] { return ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 90)); };
  30950. const auto describe = [&ui, &report] (const juce::String& title) {
  30951. report << "== " << title << " (" << ui.getWidth() << "x" << ui.getHeight() << ")\n";
  30952. for (const auto* name : { "play", "stop", "record", "metronome", "tap", "tempo", "signature", "quantisation", "key", "link", "browser",
  30953. "backToArrangement", "position", "overdub", "capture", "sessionRecord", "punch", "draw", "computerKeys",
  30954. "keyMap", "midiMap", "cpu", "more", "sessionView", "arrangementView", "status", "finish" })
  30955. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible() && c->getParentComponent() == &ui)
  30956. report << " " << name << " " << c->getBounds().toString() << "\n";
  30957. };
  30958. const std::pair<int, int> sizes[] { { 1920, 1080 }, { 1366, 768 }, { 1280, 800 } };
  30959. // a song with a few tracks for the Simple layout (voice, instrument, drums), as --simpleshot makes them
  30960. offline.editSong ([] (lynx::Song& s) {
  30961. namespace st = lynx::simpletracks;
  30962. st::Request q;
  30963. q.kind = st::Kind::voice;
  30964. q.name = "Lead vocal";
  30965. st::addTrack (s, q);
  30966. q = {};
  30967. q.kind = st::Kind::instrument;
  30968. q.name = "Keys";
  30969. lynx::ChannelDef keys;
  30970. keys.instrument = lynx::InstrumentKind::synth;
  30971. q.channel = keys;
  30972. st::addTrack (s, q);
  30973. q = {};
  30974. q.kind = st::Kind::drums;
  30975. q.name = "Drums";
  30976. st::addTrack (s, q);
  30977. s.bpm = 120.0;
  30978. }, false);
  30979. offline.dispatchPendingMessages();
  30980. // 1. Pattern: FL's toolbar (it must stay as it was: compare with the base build's)
  30981. ui.selectTabForSnapshot (2);
  30982. for (const auto& [w, h] : sizes)
  30983. {
  30984. ui.setSize (w, h);
  30985. write (lynx::shot::snapshot (ui, bar()), "pattern-bar-" + juce::String (w));
  30986. }
  30987. ui.setSize (1920, 1080);
  30988. // 2. Simple
  30989. ui.setLayoutStyle (lynx::layoutstyle::Style::simple, false);
  30990. offline.dispatchPendingMessages();
  30991. for (const auto& [w, h] : sizes)
  30992. {
  30993. ui.setSize (w, h);
  30994. offline.dispatchPendingMessages();
  30995. write (lynx::shot::snapshot (ui), "simple-" + juce::String (w));
  30996. write (lynx::shot::snapshot (ui, bar()), "simple-bar-" + juce::String (w));
  30997. describe ("simple " + juce::String (w));
  30998. }
  30999. ui.setSize (1920, 1080);
  31000. auto* play = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("play"));
  31001. auto* stop = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("stop"));
  31002. auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record"));
  31003. const auto capsuleArea = [&] {
  31004. juce::Rectangle<int> r;
  31005. for (const auto* name : { "play", "stop", "record", "position", "metronome", "tempo", "signature", "key" })
  31006. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible())
  31007. r = r.isEmpty() ? c->getBounds() : r.getUnion (c->getBounds());
  31008. return r.expanded (8, 10);
  31009. };
  31010. if (play != nullptr && stop != nullptr && rec != nullptr)
  31011. {
  31012. // (round 190oo, CS-35: the main window's own transport states, as its timer sets them while the engine plays —
  31013. // the offline engine does not play, so the route drives them: Play shows BandLab's Pause, Back-to-start Stop)
  31014. ui.transportForSnapshot (false, false);
  31015. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-idle");
  31016. play->setState (juce::Button::buttonOver);
  31017. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-hover");
  31018. play->setState (juce::Button::buttonDown);
  31019. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-pressed");
  31020. play->setState (juce::Button::buttonNormal);
  31021. ui.transportForSnapshot (true, true);
  31022. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-playing");
  31023. rec->setToggleState (true, juce::dontSendNotification);
  31024. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-recording");
  31025. rec->setToggleState (false, juce::dontSendNotification);
  31026. ui.transportForSnapshot (false, false);
  31027. }
  31028. if (auto* status = ui.toolbarPartForSnapshot ("status"))
  31029. {
  31030. using S = lynx::toolbarlayout::SaveState;
  31031. int n = 0;
  31032. for (const auto state : { S::fresh, S::unsaved, S::backedUp, S::saved })
  31033. {
  31034. ui.setSaveStatusForSnapshot (state);
  31035. auto r = status->getBounds();
  31036. if (auto* finish = ui.toolbarPartForSnapshot ("finish"); finish != nullptr && finish->isVisible())
  31037. r = r.getUnion (finish->getBounds());
  31038. write (lynx::shot::snapshot (ui, r.expanded (8, 10)), "simple-status-" + juce::String (n++));
  31039. }
  31040. }
  31041. {
  31042. auto more = ui.makeToolbarMoreMenuForSnapshot();
  31043. saveMenus (juce::StringArray { "More" }, std::vector<juce::PopupMenu> { more }, prefix + "-simple-more-menu.png");
  31044. }
  31045. // 3. Clip-launch: Live's control bar (the Live demo set when given, else an empty grid)
  31046. if (projectPath.isNotEmpty())
  31047. {
  31048. ui.openFile (juce::File (projectPath));
  31049. offline.dispatchPendingMessages();
  31050. }
  31051. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch, false);
  31052. offline.dispatchPendingMessages();
  31053. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  31054. for (const auto& [w, h] : sizes)
  31055. {
  31056. ui.setSize (w, h);
  31057. offline.dispatchPendingMessages();
  31058. write (lynx::shot::snapshot (ui), "live-" + juce::String (w));
  31059. write (lynx::shot::snapshot (ui, bar()), "live-bar-" + juce::String (w));
  31060. describe ("clip-launch " + juce::String (w));
  31061. }
  31062. ui.setSize (1920, 1080);
  31063. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  31064. write (lynx::shot::snapshot (ui), "live-arrangement-1920");
  31065. ui.setClipGridView (lynx::PlaylistArea::GridView::beside);
  31066. write (lynx::shot::snapshot (ui), "live-both-1920");
  31067. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  31068. // every control-bar button idle / hover / pressed / lit, all at once per picture
  31069. std::vector<juce::Button*> buttons;
  31070. for (const auto* name : { "play", "stop", "record", "metronome", "tap", "browser", "backToArrangement", "overdub", "capture", "sessionRecord", "punch",
  31071. "draw", "computerKeys", "keyMap", "midiMap", "more", "sessionView", "arrangementView" })
  31072. if (auto* b = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot (name)); b != nullptr && b->isVisible())
  31073. buttons.push_back (b);
  31074. std::vector<bool> lit;
  31075. for (auto* b : buttons)
  31076. lit.push_back (b->getToggleState());
  31077. const auto controlBar = ui.getLocalBounds().withTrimmedTop (lynx::toolbarlayout::livebar::menuRow).withHeight (lynx::toolbarlayout::livebar::band);
  31078. write (lynx::shot::snapshot (ui, controlBar), "live-states-idle");
  31079. for (const auto& [state, name] : { std::pair<juce::Button::ButtonState, const char*> { juce::Button::buttonOver, "hover" }, { juce::Button::buttonDown, "pressed" } })
  31080. {
  31081. for (auto* b : buttons)
  31082. b->setState (state);
  31083. write (lynx::shot::snapshot (ui, controlBar), juce::String ("live-states-") + name);
  31084. }
  31085. for (auto* b : buttons)
  31086. {
  31087. b->setState (juce::Button::buttonNormal);
  31088. b->setToggleState (true, juce::dontSendNotification);
  31089. }
  31090. write (lynx::shot::snapshot (ui, controlBar), "live-states-lit");
  31091. for (std::size_t k = 0; k < buttons.size(); ++k)
  31092. buttons[k]->setToggleState (lit[k], juce::dontSendNotification);
  31093. {
  31094. auto more = ui.makeToolbarMoreMenuForSnapshot();
  31095. saveMenus (juce::StringArray { "More" }, std::vector<juce::PopupMenu> { more }, prefix + "-live-more-menu.png");
  31096. }
  31097. // the Session button row kept as an option
  31098. ui.setSessionButtonRowShown (true);
  31099. write (lynx::shot::snapshot (ui), "live-buttonrow-1920");
  31100. ui.setSessionButtonRowShown (false);
  31101. // 4. back to Pattern: FL's toolbar again, as it was
  31102. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern, false);
  31103. offline.dispatchPendingMessages();
  31104. for (const auto& [w, h] : sizes)
  31105. {
  31106. ui.setSize (w, h);
  31107. write (lynx::shot::snapshot (ui, bar()), "pattern-after-bar-" + juce::String (w));
  31108. }
  31109. juce::File (prefix + "-report.txt").replaceWithText (report);
  31110. lynx::ui::motion::enabled() = true;
  31111. }
  31112. void runGridShot (const juce::String& prefix, const juce::String& projectPath = {})
  31113. {
  31114. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31115. lynx::AudioEngine offline (false);
  31116. lynx::MainComponent ui (offline, false);
  31117. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  31118. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  31119. const auto write = [&prefix, &ui] (const char* name) {
  31120. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  31121. file.deleteFile();
  31122. juce::FileOutputStream out (file);
  31123. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  31124. };
  31125. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  31126. if (projectPath.isNotEmpty())
  31127. {
  31128. ui.openFile (juce::File (projectPath));
  31129. offline.dispatchPendingMessages();
  31130. ui.setClipLaunchWorkflow (true);
  31131. offline.dispatchPendingMessages();
  31132. write ("file-both");
  31133. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  31134. write ("file-grid");
  31135. const auto& song = offline.getSong();
  31136. juce::String info;
  31137. info << "grid " << (song.clipGrid ? "yes" : "no") << ", clips " << (song.clipGrid ? (int) song.clipGrid->clips.size() : 0)
  31138. << ", scenes " << (song.clipGrid ? (int) song.clipGrid->scenes.size() : 0) << ", playlist clips " << (int) song.playlist.size() << "\n";
  31139. // round qafix190kq (QA-2): the grid's columns (take lanes have none) and the Session mixer's strips follow them
  31140. if (auto* grid = ui.getClipGridForSnapshot())
  31141. {
  31142. const auto columns = lynx::clipGridColumnTracks (*grid);
  31143. int lanes = 0, laneColumns = 0;
  31144. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  31145. lanes += lynx::comp::isTakeLane (song, t) ? 1 : 0;
  31146. juce::StringArray names;
  31147. for (const auto t : columns)
  31148. {
  31149. laneColumns += lynx::comp::isTakeLane (song, t) ? 1 : 0;
  31150. names.add (t < (int) song.playlistTracks.size() ? juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str()) : "(empty)");
  31151. }
  31152. info << "playlist tracks " << (int) song.playlistTracks.size() << ", take lanes " << lanes << ", grid columns " << (int) columns.size()
  31153. << ", lane columns " << laneColumns << "\ncolumns: " << names.joinIntoString (" | ") << "\n";
  31154. // the lanes' flag survives a save and an open (ProjectFile "playlistTakeLanes")
  31155. juce::String error;
  31156. auto same = false;
  31157. if (const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error); back && back->playlistTracks.size() == song.playlistTracks.size())
  31158. {
  31159. same = true;
  31160. for (std::size_t t = 0; t < song.playlistTracks.size(); ++t)
  31161. same = same && back->playlistTracks[t].takeLane == song.playlistTracks[t].takeLane;
  31162. }
  31163. info << "take lanes after save + open: " << (same ? "same" : "DIFFERENT") << "\n";
  31164. }
  31165. juce::File (prefix + "-file.txt").replaceWithText (info);
  31166. ui.setClipLaunchWorkflow (false);
  31167. return;
  31168. }
  31169. write ("pattern"); // Pattern workflow: nothing of the grid exists yet
  31170. const auto madeBefore = lynx::launcher::Runtime::instances.load();
  31171. offline.editSong ([] (lynx::Song& s) {
  31172. while (s.patterns.size() < 6)
  31173. s.patterns.emplace_back();
  31174. for (int p = 0; p < 6; ++p)
  31175. {
  31176. auto& pattern = s.patterns[(std::size_t) p];
  31177. const char* names[] { "Drums A", "Drums B", "Bass", "Chords", "Lead", "Pad" };
  31178. pattern.name = names[p];
  31179. pattern.lengthTicks = 4 * lynx::ppq;
  31180. }
  31181. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  31182. const char* tracks[] { "Drums", "Bass", "Chords", "Lead", "Vocals", "FX" };
  31183. for (int t = 0; t < 6; ++t)
  31184. s.playlistTracks[(std::size_t) t].name = tracks[t];
  31185. 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 } };
  31186. for (const auto& c : placed)
  31187. {
  31188. lynx::Clip clip;
  31189. clip.pattern = c[2];
  31190. clip.length = 4 * lynx::ppq;
  31191. lynx::launcher::setClip (s, c[0], c[1], clip);
  31192. }
  31193. auto& grid = lynx::launcher::ensureGrid (s);
  31194. const char* scenes[] { "Intro", "Verse", "Drop", "Break" };
  31195. grid.scenes.resize (6);
  31196. for (int r = 0; r < 4; ++r)
  31197. grid.scenes[(std::size_t) r].name = scenes[r];
  31198. }, false);
  31199. offline.dispatchPendingMessages();
  31200. write ("pattern-edited"); // the same song as -pattern-after: the workflow must leave no trace
  31201. ui.setClipLaunchWorkflow (true);
  31202. offline.dispatchPendingMessages();
  31203. if (auto* runtime = offline.launcherStateForSnapshot())
  31204. {
  31205. runtime->tracks[0].playing.store (2);
  31206. runtime->tracks[0].progress.store (0.4f);
  31207. runtime->tracks[0].taken.store (true);
  31208. runtime->tracks[1].playing.store (2);
  31209. runtime->tracks[1].progress.store (0.4f);
  31210. runtime->tracks[1].taken.store (true);
  31211. runtime->tracks[2].pending.store (2);
  31212. runtime->tracks[3].taken.store (true);
  31213. }
  31214. write ("both");
  31215. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  31216. write ("grid");
  31217. // round 190bv: recording into slots and the Groove Pool. Two tracks armed (round record buttons in their empty
  31218. // slots, their arm buttons lit), one of them recording and one waiting for its start; then a clip through a
  31219. // groove with the pool shown, and the slot menus
  31220. if (auto* gridView = ui.getClipGridForSnapshot())
  31221. {
  31222. offline.setGridTrackArmed (4, true);
  31223. offline.setGridTrackArmed (5, true, false);
  31224. offline.dispatchPendingMessages();
  31225. write ("rec-armed");
  31226. if (auto* runtime = offline.launcherStateForSnapshot())
  31227. {
  31228. runtime->tracks[4].recording.store (1);
  31229. runtime->tracks[4].recordFrom.store (0.0); // (round 190cy: one beat recorded, the counter reads 0.1.0)
  31230. runtime->clockNow.store ((double) lynx::ppq);
  31231. runtime->tracks[5].recordPending.store (1);
  31232. }
  31233. write ("rec-recording");
  31234. if (auto* runtime = offline.launcherStateForSnapshot())
  31235. {
  31236. runtime->tracks[4].recording.store (-1);
  31237. runtime->tracks[5].recordPending.store (-1);
  31238. }
  31239. offline.editSong ([] (lynx::Song& s) {
  31240. const auto& bank = lynx::groove::factoryBank();
  31241. std::uint32_t first = 0;
  31242. for (const auto index : { std::size_t (9), std::size_t (20), std::size_t (27) })
  31243. if (index < bank.size())
  31244. {
  31245. const auto id = lynx::groove::add (s.grooves, bank[index].groove);
  31246. first = first == 0 ? id : first;
  31247. }
  31248. lynx::groove::setClipGroove (s, 0, 0, first);
  31249. }, false);
  31250. offline.dispatchPendingMessages();
  31251. lynx::setClipGridGroovePoolShown (*gridView, true);
  31252. write ("groove-pool");
  31253. saveMenus ({ "Clip slot", "Groove", "Empty slot" },
  31254. { lynx::clipGridSlotMenu (*gridView, 0, 0), [&] {
  31255. juce::PopupMenu found;
  31256. const auto menu = lynx::clipGridSlotMenu (*gridView, 0, 0);
  31257. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  31258. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Groove"))
  31259. found = *it.getItem().subMenu;
  31260. return found;
  31261. }(), lynx::clipGridSlotMenu (*gridView, 4, 1) },
  31262. prefix + "-rec-menus.png");
  31263. lynx::setClipGridGroovePoolShown (*gridView, false);
  31264. // round 190cy: a second record button pressed while recording: the first take ("Vocals 1") plays on, the
  31265. // clicked slot records "Vocals 2" with its counter at 2.0.2 (as Live 12.4.16, live check 190cw shot 03b)
  31266. {
  31267. const auto name = offline.slotRecordingName (4);
  31268. offline.editSong ([&name] (lynx::Song& s) { lynx::session::placeRecordedPattern (s, 4, 0, {}, 8 * lynx::ppq, name); }, false);
  31269. offline.dispatchPendingMessages();
  31270. if (auto* runtime = offline.launcherStateForSnapshot())
  31271. {
  31272. runtime->tracks[4].playing.store (0);
  31273. runtime->tracks[4].progress.store (0.3f);
  31274. runtime->tracks[4].recording.store (1);
  31275. runtime->tracks[4].recordFrom.store (0.0);
  31276. runtime->clockNow.store (8.0 * lynx::ppq + 2.0 * lynx::ppq / 4.0);
  31277. }
  31278. write ("rec-second");
  31279. if (auto* runtime = offline.launcherStateForSnapshot())
  31280. {
  31281. runtime->tracks[4].playing.store (-1);
  31282. runtime->tracks[4].recording.store (-1);
  31283. }
  31284. offline.editSong ([] (lynx::Song& s) {
  31285. if (lynx::session::cut (s, 4, 0) && ! s.patterns.empty())
  31286. s.patterns.pop_back();
  31287. }, false);
  31288. offline.dispatchPendingMessages();
  31289. }
  31290. offline.setGridTrackArmed (4, false);
  31291. offline.setGridTrackArmed (5, false);
  31292. offline.dispatchPendingMessages();
  31293. }
  31294. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  31295. write ("song");
  31296. ui.setClipLaunchWorkflow (false);
  31297. write ("pattern-after");
  31298. juce::File (prefix + "-counts.txt").replaceWithText ("runtimes before " + juce::String (madeBefore) + ", after " + juce::String (lynx::launcher::Runtime::instances.load()) + "\n");
  31299. }
  31300. // Round 190bu: the Simple workflow's track dock (ui/SimpleDock.h), off-screen
  31301. void runSimpleFxShot (const juce::String& prefix)
  31302. {
  31303. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31304. lynx::AudioEngine offline (false);
  31305. lynx::MainComponent ui (offline, false);
  31306. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  31307. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  31308. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  31309. const auto file = juce::File (prefix + "-" + name + ".png");
  31310. file.deleteFile();
  31311. juce::FileOutputStream out (file);
  31312. juce::PNGImageFormat().writeImageToStream (image, out);
  31313. };
  31314. juce::String report;
  31315. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  31316. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  31317. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  31318. ui.selectTabForSnapshot (2);
  31319. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  31320. offline.dispatchPendingMessages();
  31321. auto* simple = ui.getSimpleWorkflowForSnapshot();
  31322. if (simple == nullptr)
  31323. {
  31324. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  31325. return;
  31326. }
  31327. simple->hideChooser();
  31328. // three tracks: a voice, keys with a few chords, a drum kit
  31329. int keysInsert = -1;
  31330. offline.editSong ([&keysInsert] (lynx::Song& s) {
  31331. namespace st = lynx::simpletracks;
  31332. st::Request q;
  31333. q.kind = st::Kind::voice;
  31334. q.name = "Lead vocal";
  31335. st::addTrack (s, q);
  31336. q = {};
  31337. q.kind = st::Kind::instrument;
  31338. q.name = "Keys";
  31339. lynx::ChannelDef keys;
  31340. keys.instrument = lynx::InstrumentKind::synth;
  31341. q.channel = keys;
  31342. lynx::Pattern chords;
  31343. for (int i = 0; i < 4; ++i)
  31344. for (int k : { 60, 64, 67 })
  31345. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  31346. q.pattern = chords;
  31347. keysInsert = st::addTrack (s, q).insert;
  31348. q = {};
  31349. q.kind = st::Kind::drums;
  31350. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  31351. {
  31352. lynx::ChannelDef c;
  31353. c.instrument = kind;
  31354. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  31355. q.kit.push_back (c);
  31356. }
  31357. lynx::Pattern beat;
  31358. for (int step = 0; step < 16; step += 2)
  31359. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 2, 60 });
  31360. q.pattern = beat;
  31361. st::addTrack (s, q);
  31362. });
  31363. offline.dispatchPendingMessages();
  31364. simple->hideChooser();
  31365. auto& playlist = ui.getPlaylistForSnapshot();
  31366. // the tracks' places in the Playlist
  31367. int voiceTrack = -1, keysTrack = -1, drumsTrack = -1;
  31368. {
  31369. const auto& song = offline.getSong();
  31370. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  31371. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  31372. {
  31373. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  31374. voiceTrack = t;
  31375. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  31376. keysTrack = t;
  31377. else if (*kind == lynx::simpletracks::Kind::drums && drumsTrack < 0)
  31378. drumsTrack = t;
  31379. }
  31380. }
  31381. check ("three Simple tracks (voice, keys, drums)", voiceTrack >= 0 && keysTrack >= 0 && drumsTrack >= 0);
  31382. playlist.selectTrack (keysTrack);
  31383. offline.dispatchPendingMessages();
  31384. auto* dock = simple->dockForSnapshot();
  31385. if (dock == nullptr)
  31386. {
  31387. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  31388. return;
  31389. }
  31390. // the whole window and the dock alone, at 1x and 2x
  31391. const auto shots = [&] (const juce::String& name) {
  31392. offline.dispatchPendingMessages();
  31393. for (float scale : { 1.0f, 2.0f })
  31394. {
  31395. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  31396. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  31397. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  31398. }
  31399. };
  31400. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  31401. juce::StringArray names { title };
  31402. std::vector<juce::PopupMenu> menus { menu };
  31403. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  31404. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  31405. {
  31406. names.add (subTitle);
  31407. menus.push_back (*it.getItem().subMenu);
  31408. }
  31409. saveMenus (names, menus, prefix + "-" + name + ".png");
  31410. };
  31411. // --- the Instrument tab ---------------------------------------------------------------------------------------
  31412. check ("the dock shows the selected track", dock->shownTrack() == keysTrack && dock->isVisible() && dock->getParentComponent() != nullptr);
  31413. check ("an instrument track opens on its sound", dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::instrument);
  31414. const auto channel = dock->channelForCheck();
  31415. line ("sound at first: " + dock->soundNameForCheck() + ", rows in its category: " + juce::String (dock->soundRowsForCheck()));
  31416. shots ("instrument");
  31417. // a click on a row of another category: the track plays that sound, its own settings stay
  31418. const auto before = offline.getSong().channels[(std::size_t) channel];
  31419. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::pad);
  31420. offline.dispatchPendingMessages();
  31421. const auto padRows = dock->soundRowsForCheck();
  31422. dock->clickSoundForCheck (juce::jmin (2, padRows - 1));
  31423. offline.dispatchPendingMessages();
  31424. {
  31425. const auto& now = offline.getSong().channels[(std::size_t) channel];
  31426. const auto found = lynx::soundlib::find (lynx::soundlib::builtIn(), now);
  31427. check ("a click on a sound puts it on the track's channel (" + dock->soundNameForCheck() + ")",
  31428. padRows > 0 && found >= 0 && lynx::soundlib::builtIn()[(std::size_t) found].category == lynx::soundlib::Category::pad
  31429. && ! lynx::soundlib::sameSound (before, now));
  31430. check ("the channel keeps its name, level and insert", now.name == before.name && now.volume == before.volume && now.mixerTrack == before.mixerTrack);
  31431. double seconds = 0.0;
  31432. const auto heard = offline.auditionSound (now, { 60, 64, 67 }, &seconds);
  31433. check ("the sound's audition renders (" + juce::String (seconds, 2) + " s)", heard && seconds > 1.0);
  31434. }
  31435. shots ("instrument-pad");
  31436. const auto picked = dock->soundNameForCheck();
  31437. dock->stepSoundForCheck (1);
  31438. offline.dispatchPendingMessages();
  31439. const auto stepped = dock->soundNameForCheck();
  31440. dock->stepSoundForCheck (-1);
  31441. offline.dispatchPendingMessages();
  31442. check ("the arrows step through the category (" + picked + " -> " + stepped + " -> back)", stepped != picked && dock->soundNameForCheck() == picked);
  31443. check ("one undo step per sound", offline.canUndo());
  31444. // the user's SoundFont files (an index made here: no file is read)
  31445. {
  31446. std::vector<lynx::sf::IndexedFont> fonts (2);
  31447. fonts[0].path = "/home/me/SoundFonts/Concert Band.sf2";
  31448. fonts[0].name = "Concert Band";
  31449. int program = 0;
  31450. for (const char* name : { "Grand Piano", "Bright Piano", "Electric Piano", "Harpsichord", "Clavinet", "Celesta", "Music Box", "Vibraphone" })
  31451. fonts[0].presets.push_back ({ name, 0, program++ });
  31452. 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 } })
  31453. fonts[0].presets.push_back ({ name, 0, p });
  31454. fonts[0].presets.push_back ({ "Standard Kit", 128, 0 });
  31455. fonts[1].path = "/home/me/SoundFonts/Old Upright.sf2";
  31456. fonts[1].name = "Old Upright";
  31457. fonts[1].presets.push_back ({ "Old Upright", 0, 0 });
  31458. fonts[1].presets.push_back ({ "Old Upright Soft", 0, 1 });
  31459. dock->setFontsForSnapshot (fonts);
  31460. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::keys);
  31461. offline.dispatchPendingMessages();
  31462. check ("My SoundFonts lists the presets of the user's files by category (Keys: " + juce::String (dock->soundRowsForCheck()) + " of 17)", dock->soundRowsForCheck() == 7);
  31463. dock->clickSoundForCheck (0);
  31464. offline.dispatchPendingMessages();
  31465. const auto& now = offline.getSong().channels[(std::size_t) channel];
  31466. check ("a SoundFont preset becomes the track's sound (" + dock->soundNameForCheck() + ")",
  31467. now.instrument == lynx::InstrumentKind::soundfont && juce::String (now.samplePath).endsWith (".sf2"));
  31468. shots ("instrument-soundfonts");
  31469. }
  31470. // --- the Effects tab ------------------------------------------------------------------------------------------
  31471. playlist.selectTrack (voiceTrack);
  31472. offline.dispatchPendingMessages();
  31473. const auto insert = dock->insertForCheck();
  31474. check ("an audio track has no Instrument tab and opens on its effects",
  31475. dock->shownTrack() == voiceTrack && ! dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::effects && insert > 0);
  31476. check ("no effects yet: no cards", dock->cardCountForCheck() == 0);
  31477. shots ("effects-empty");
  31478. menuShot (dock->addMenuForSnapshot(), lynx::tr ("Add an effect"), {}, "menu-add");
  31479. // + adds one-knob effects at the end of the chain
  31480. dock->addOneKnobForCheck (lynx::goals::brighter);
  31481. dock->addOneKnobForCheck (lynx::goals::room);
  31482. dock->addOneKnobForCheck (lynx::goals::level);
  31483. offline.dispatchPendingMessages();
  31484. const auto slotsText = [&offline] (int t) {
  31485. juce::String text;
  31486. const auto rows = lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) t].effects); // (the Mixer's slot of each)
  31487. std::size_t at = 0;
  31488. for (const auto& fx : offline.getSong().mixer[(std::size_t) t].effects)
  31489. text << "[slot " << rows[at++] + 1 << " " << lynx::effectInfo (fx.kind).name
  31490. << (lynx::goals::active (fx) ? " = " + juce::String (lynx::goals::name (fx.goal)) + " " + juce::String (juce::roundToInt (fx.goalAmount * 100.0f)) + "%" : juce::String())
  31491. << (fx.enabled ? "" : " off") << "] ";
  31492. return text.trimEnd();
  31493. };
  31494. line ("after + x3: " + slotsText (insert));
  31495. check ("three cards, three one-knob effects", dock->cardCountForCheck() == 3 && dock->oneKnobCardsForCheck() == 3);
  31496. // the knob writes the effect's own parameters
  31497. const auto roomBefore = offline.getSong().mixer[(std::size_t) insert].effects[1];
  31498. dock->turnKnobForCheck (1, 0.8f);
  31499. offline.dispatchPendingMessages();
  31500. {
  31501. const auto& room = offline.getSong().mixer[(std::size_t) insert].effects[1];
  31502. 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));
  31503. }
  31504. // ‹ › reorder, × removes
  31505. dock->moveCardForCheck (2, -1);
  31506. offline.dispatchPendingMessages();
  31507. line ("Level moved left: " + slotsText (insert));
  31508. {
  31509. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  31510. check ("the card moved one place earlier", fx.size() == 3 && fx[1].goal == lynx::goals::level && fx[2].goal == lynx::goals::room);
  31511. }
  31512. dock->removeCardForCheck (0);
  31513. offline.dispatchPendingMessages();
  31514. line ("Brighter removed: " + slotsText (insert));
  31515. check ("the card is gone", dock->cardCountForCheck() == 2 && offline.getSong().mixer[(std::size_t) insert].effects.size() == 2);
  31516. // a hand edit in the full editor: the slot is an ordinary effect again (its card shows Mix)
  31517. offline.editSong ([insert] (lynx::Song& s) {
  31518. auto& slot = s.mixer[(std::size_t) insert].effects[0];
  31519. const auto moved = (std::size_t) lynx::goals::mapping (slot.goal, slot.goalAmount).back().param;
  31520. slot.params[moved] = slot.params[moved] > 0.5f ? 0.2f : 0.9f;
  31521. });
  31522. offline.dispatchPendingMessages();
  31523. check ("a parameter moved by hand makes the card an ordinary effect", dock->cardCountForCheck() == 2 && dock->oneKnobCardsForCheck() == 1);
  31524. dock->turnKnobForCheck (0, 0.5f); // (its knob is the slot's Mix now)
  31525. offline.dispatchPendingMessages();
  31526. 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);
  31527. // a preset replaces the chain; Blend is the chain's dry/wet
  31528. if (const auto* preset = lynx::chains::find ("Clear Voice"))
  31529. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  31530. offline.dispatchPendingMessages();
  31531. line ("preset Clear Voice: " + slotsText (insert));
  31532. 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)
  31533. && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size());
  31534. shots ("effects-preset");
  31535. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("Voice"), "menu-preset");
  31536. dock->setBlendForCheck (0.7f);
  31537. dock->addOneKnobForCheck (lynx::goals::echo);
  31538. offline.dispatchPendingMessages();
  31539. check ("Blend 70 % is the insert's chain blend; the preset shows as edited",
  31540. std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.7f) < 1.0e-6f && ! lynx::chains::unchanged (offline.getSong(), insert));
  31541. shots ("effects-edited");
  31542. // a user preset: saved to a file, loaded on another track (its slots and Blend; that track's level stays)
  31543. const auto mine = offline.getSong().mixer[(std::size_t) insert];
  31544. const auto saved = lynx::SimpleDock::saveUserPreset (offline, insert, "My voice");
  31545. const auto file = lynx::SimpleDock::userPresetFolder().getChildFile ("My voice.lynxtrack");
  31546. check ("the preset is saved as " + file.getFileName(), saved && file.existsAsFile() && offline.getSong().mixer[(std::size_t) insert].chainPreset == "My voice");
  31547. offline.editSong ([keysInsert] (lynx::Song& s) { s.mixer[(std::size_t) keysInsert].volume = 0.42f; });
  31548. const auto loaded = keysInsert > 0 && lynx::SimpleDock::loadUserPreset (offline, keysInsert, file);
  31549. offline.dispatchPendingMessages();
  31550. {
  31551. const auto& other = offline.getSong().mixer[(std::size_t) keysInsert];
  31552. auto same = loaded && other.effects.size() == mine.effects.size() && std::abs (other.chainBlend - mine.chainBlend) < 1.0e-6f && other.chainPreset == "My voice";
  31553. for (std::size_t i = 0; same && i < mine.effects.size(); ++i)
  31554. same = other.effects[i].kind == mine.effects[i].kind && other.effects[i].goal == mine.effects[i].goal
  31555. && 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]);
  31556. check ("loaded on the Keys track: the same slots and Blend", same);
  31557. check ("the Keys track keeps its level", std::abs (other.volume - 0.42f) < 1.0e-6f);
  31558. line ("Keys after load: " + slotsText (keysInsert));
  31559. }
  31560. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("My presets"), "menu-preset-mine");
  31561. file.deleteFile();
  31562. // the drums: effects only (a kit has no single sound to pick)
  31563. playlist.selectTrack (drumsTrack);
  31564. offline.dispatchPendingMessages();
  31565. check ("the Drums track shows its insert's effects, no Instrument tab", dock->shownTrack() == drumsTrack && ! dock->hasInstrumentTabForCheck() && dock->insertForCheck() > 0);
  31566. if (const auto* preset = lynx::chains::find ("Smash Room"))
  31567. offline.editSongStructural ([t = dock->insertForCheck(), preset] (lynx::Song& s) { lynx::chains::apply (s, t, *preset); });
  31568. shots ("effects-drums");
  31569. // the project file keeps all of it
  31570. {
  31571. juce::String error;
  31572. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  31573. const auto back = lynx::ProjectFile::fromJson (json, error);
  31574. auto same = back && back->mixer.size() == offline.getSong().mixer.size();
  31575. for (std::size_t t = 0; same && t < back->mixer.size(); ++t)
  31576. {
  31577. const auto& a = offline.getSong().mixer[t];
  31578. const auto& b = back->mixer[t];
  31579. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  31580. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  31581. 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
  31582. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f;
  31583. }
  31584. check ("saved and loaded as a project: the same chains, knobs, Blend and preset names", same);
  31585. }
  31586. // --- the same plugins in the same slots in FL's layout --------------------------------------------------------
  31587. const auto simpleSong = offline.getSong();
  31588. const auto inSimple = slotsText (insert);
  31589. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  31590. offline.dispatchPendingMessages();
  31591. check ("Pattern workflow: the dock is gone", dock->getParentComponent() == nullptr);
  31592. ui.selectTabForSnapshot (3);
  31593. ui.getMixerForSnapshot().selectTrack (insert);
  31594. offline.dispatchPendingMessages();
  31595. for (float scale : { 1.0f, 2.0f })
  31596. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), juce::String ("pattern-mixer") + (scale > 1.0f ? "@2x" : ""));
  31597. line ("Simple layout: " + inSimple);
  31598. line ("Pattern layout: " + slotsText (insert));
  31599. check ("the same effects in the same Mixer slots in the Pattern workflow", offline.getSong().mixer == simpleSong.mixer && offline.getSong().channels == simpleSong.channels);
  31600. // an effect added in the Mixer's way shows as a card when the Simple workflow comes back
  31601. offline.editSongStructural ([insert] (lynx::Song& s) { lynx::mixerops::insertEffectAtRow (s, insert, lynx::makeEffectSlot (lynx::EffectKind::chorus), 7); });
  31602. ui.selectTabForSnapshot (2);
  31603. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  31604. offline.dispatchPendingMessages();
  31605. simple->hideChooser();
  31606. playlist.selectTrack (voiceTrack);
  31607. offline.dispatchPendingMessages();
  31608. check ("back in Simple: the dock shows the insert as it is now, the Mixer's new effect too",
  31609. dock->getParentComponent() != nullptr && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size()
  31610. && lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) insert].effects).back() == 7);
  31611. line ("Simple again: " + slotsText (insert));
  31612. shots ("effects-back");
  31613. // hidden with its key, shown again by "+FX"
  31614. simple->toggleDock();
  31615. offline.dispatchPendingMessages();
  31616. check ("Ctrl+Alt+L hides the dock", ! simple->isDockShowing() && ! lynx::SimpleDock::shownSetting);
  31617. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "dock-hidden");
  31618. simple->showEffectsOfInsert (keysInsert);
  31619. offline.dispatchPendingMessages();
  31620. check ("+FX on a track header shows the dock on that track's effects",
  31621. simple->isDockShowing() && dock->shownTrack() == keysTrack && dock->getTab() == lynx::SimpleDock::Tab::effects && dock->insertForCheck() == keysInsert);
  31622. simple->cycleDockTab();
  31623. check ("Shift+Tab goes to the Instrument tab", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  31624. line ("Simple workflow objects: " + juce::String (madeBefore) + " before, " + juce::String (lynx::SimpleWorkflow::instances.load()) + " after");
  31625. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  31626. juce::File (prefix + "-report.txt").replaceWithText (report);
  31627. }
  31628. // --simpleclosetest (round 190fc, 0.1.27 RC blocker B1): every close in the Simple layout crashed (the Simple workflow
  31629. // was destroyed after the Workspace and its destructor called into it). Off-screen, no window: the main window in the
  31630. // Simple layout with everything of it open — Welcome, the first-song tour's card, Start from, a demo song, each dock
  31631. // tab (the Editor tab docks the Piano roll), Finish, Lyrics, the chooser — then destroyed as the app's shutdown does.
  31632. // A second main window goes Simple -> Pattern -> Simple and closes too. Checks: no Simple workflow outlives its main
  31633. // window's destructor body, none is left at all. (Under ASan on Linux the old order is a heap-use-after-free.)
  31634. bool runDonateShot (const juce::String& prefix)
  31635. {
  31636. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31637. juce::String report;
  31638. bool ok = true;
  31639. const auto line = [&report, &prefix] (const juce::String& text) {
  31640. report << text << "\n";
  31641. juce::File (prefix + "-report.txt").replaceWithText (report); // (written as it goes)
  31642. };
  31643. const auto check = [&line, &ok] (const juce::String& what, bool good) {
  31644. line ((good ? "ok " : "FAIL ") + what);
  31645. ok = ok && good;
  31646. };
  31647. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  31648. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  31649. file.deleteFile();
  31650. juce::FileOutputStream out (file);
  31651. juce::PNGImageFormat().writeImageToStream (image, out);
  31652. };
  31653. // a window as the --snapshot route saves one (off the desktop, on the theme's panel colour), at 1x and 2x
  31654. const auto saveAlert = [&] (juce::AlertWindow& w, const juce::String& name) {
  31655. if (w.isOnDesktop())
  31656. w.removeFromDesktop();
  31657. w.setOpaque (true);
  31658. juce::Component frame;
  31659. frame.setSize (w.getWidth(), w.getHeight());
  31660. frame.setOpaque (true);
  31661. frame.addAndMakeVisible (w);
  31662. w.setTopLeftPosition (0, 0);
  31663. writeImage (lynx::shot::paint (frame, lynx::theme::panel), name);
  31664. writeImage (frame.createComponentSnapshot (frame.getLocalBounds(), true, 2.0f), name + "@2x");
  31665. frame.removeChildComponent (&w);
  31666. };
  31667. const auto buttonTexts = [] (juce::AlertWindow& w) {
  31668. if (auto* d = dynamic_cast<lynx::ui::dialog::Dialog*> (&w)) // (round 190jp: LYNX's dialog, its own buttons)
  31669. return d->dialogButtonTexts();
  31670. juce::StringArray texts;
  31671. for (int b = 0; b < w.getNumButtons(); ++b)
  31672. if (auto* button = w.getButton (b))
  31673. texts.add (button->getButtonText());
  31674. return texts;
  31675. };
  31676. check ("the donation page is one constant, on Ko-fi", juce::String (lynx::links::donate).startsWith ("https://ko-fi"));
  31677. line ("donate URL: " + juce::String (lynx::links::donate));
  31678. const auto stateFile = lynx::PluginHost::settingsFolder().getChildFile ("support-note.txt");
  31679. const auto hadState = stateFile.existsAsFile();
  31680. const auto oldState = stateFile.loadFileAsString();
  31681. line ("state file: " + stateFile.getFullPathName() + (hadState ? " (exists; put back at the end)" : ""));
  31682. {
  31683. lynx::AudioEngine offline (false);
  31684. lynx::MainComponent ui (offline, false);
  31685. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  31686. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  31687. ui.setVisible (true);
  31688. const auto settle = [&] {
  31689. for (int k = 0; k < 3; ++k)
  31690. offline.dispatchPendingMessages();
  31691. };
  31692. // --- Help › Support LYNX SHARE..., right above About, in the three layouts ----------------------------------
  31693. for (auto [style, name] : { std::pair { lynx::layoutstyle::Style::pattern, "pattern" }, { lynx::layoutstyle::Style::clipLaunch, "cliplaunch" },
  31694. { lynx::layoutstyle::Style::simple, "simple" } })
  31695. {
  31696. ui.setLayoutStyle (style);
  31697. settle();
  31698. const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
  31699. juce::StringArray items;
  31700. for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
  31701. if (! it.getItem().isSeparator)
  31702. items.add (it.getItem().text);
  31703. const auto support = items.indexOf (lynx::tr ("Support LYNX SHARE..."));
  31704. const auto about = items.indexOf (lynx::tr ("About LYNX SHARE"));
  31705. check (juce::String ("Help has Support LYNX SHARE... right above About LYNX SHARE (") + name + " layout)",
  31706. support >= 0 && about == support + 1);
  31707. saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help-" + name + ".png");
  31708. }
  31709. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  31710. settle();
  31711. // --- the Support window -------------------------------------------------------------------------------------
  31712. {
  31713. auto w = lynx::support::makeSupportWindow();
  31714. const auto texts = buttonTexts (*w);
  31715. check ("Support window: Donate on Ko-fi, Close", texts == juce::StringArray { lynx::tr ("Donate on Ko-fi"), lynx::tr ("Close") });
  31716. check ("Support window: Donate on Ko-fi points at the constant",
  31717. dynamic_cast<lynx::ui::dialog::Dialog*> (w.get()) != nullptr
  31718. && static_cast<lynx::ui::dialog::Dialog*> (w.get())->dialogButton (0)->getTooltip() == juce::String (lynx::links::donate));
  31719. check ("Support window title", w->getName() == lynx::tr ("Support LYNX SHARE"));
  31720. saveAlert (*w, "support");
  31721. }
  31722. // --- the About window ---------------------------------------------------------------------------------------
  31723. {
  31724. auto w = lynx::MainComponent::makeAboutWindow();
  31725. const auto texts = buttonTexts (*w);
  31726. check ("About window: Support LYNX SHARE (result 2) and OK", texts == juce::StringArray { lynx::tr ("Support LYNX SHARE"), lynx::tr ("OK") });
  31727. saveAlert (*w, "about");
  31728. }
  31729. // --- Settings › General › Show the support note -------------------------------------------------------------
  31730. {
  31731. auto page = lynx::makeGeneralPage (offline, {}, false);
  31732. bool found = false;
  31733. std::function<void (juce::Component&)> walk = [&] (juce::Component& c) {
  31734. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Show the support note"))
  31735. found = t->getToggleState();
  31736. for (auto* child : c.getChildren())
  31737. walk (*child);
  31738. };
  31739. walk (*page);
  31740. check ("Settings > General: \"Show the support note\", ticked by default", found);
  31741. }
  31742. // --- the start-up note's rules, end to end on the saved state ----------------------------------------------
  31743. lynx::supportnote::Moment moment; // (the main window here is off-screen: the moment is set by hand)
  31744. lynx::support::StartupNote note (ui, [&moment] { return moment; }, [] { return 0; });
  31745. const auto state = [] { return lynx::support::loadState(); };
  31746. const auto setState = [] (int launches, int next, bool show) { lynx::support::saveState ({ launches, next, show }); };
  31747. stateFile.deleteFile();
  31748. for (int k = 0; k < 15; ++k)
  31749. note.begin (true);
  31750. note.pollForSnapshot();
  31751. check ("test mode / CI runs: 15 starts, nothing counted, no file, no card", ! stateFile.existsAsFile() && ! note.isCardShowing());
  31752. check ("a first start's defaults: next at start 10, shown", state() == lynx::supportnote::State { 0, 10, true });
  31753. for (int k = 1; k <= 9; ++k)
  31754. {
  31755. note.begin (false);
  31756. note.pollForSnapshot();
  31757. }
  31758. check ("starts 1 to 9: counted, no card", state().launches == 9 && ! note.isCardShowing());
  31759. moment.playing = true;
  31760. note.begin (false); // the 10th start
  31761. note.pollForSnapshot();
  31762. check ("10th start while playing: the card waits", state().launches == 10 && ! note.isCardShowing());
  31763. moment = {};
  31764. moment.dialogOpen = true;
  31765. note.pollForSnapshot();
  31766. check ("... and while a dialog is open", ! note.isCardShowing());
  31767. moment = {};
  31768. note.pollForSnapshot();
  31769. check ("10th start, a quiet moment: the card shows", note.isCardShowing());
  31770. check ("shown: left without an answer it comes back 30 starts later", state().nextAt == 40);
  31771. if (auto* card = note.cardForSnapshot())
  31772. {
  31773. const auto b = card->getBounds();
  31774. check ("the card sits in the bottom-right corner", b.getRight() <= ui.getWidth() - 8 && b.getRight() >= ui.getWidth() - 40
  31775. && b.getBottom() <= ui.getHeight() - 4 && b.getBottom() >= ui.getHeight() - 40);
  31776. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "note-in-window");
  31777. writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), "note@2x");
  31778. // the corner of the window around the card, at 2x
  31779. writeImage (ui.createComponentSnapshot (b.expanded (220, 120).getIntersection (ui.getLocalBounds()), true, 2.0f), "note-corner@2x");
  31780. }
  31781. moment.playing = true;
  31782. note.pollForSnapshot();
  31783. check ("playback starts: the card steps aside", ! note.isCardShowing());
  31784. moment = {};
  31785. // Not now: again after 30 more starts
  31786. setState (10, 10, true);
  31787. note.begin (false); // start 11
  31788. note.pollForSnapshot();
  31789. if (auto* card = note.cardForSnapshot(); card != nullptr && card->buttonForSnapshot (lynx::supportnote::Choice::notNow) != nullptr)
  31790. card->buttonForSnapshot (lynx::supportnote::Choice::notNow)->onClick();
  31791. note.closeCard(); // (the click closes it on the next message turn)
  31792. check ("Not now: next at start 41", state() == lynx::supportnote::State { 11, 41, true });
  31793. for (int k = 12; k <= 40; ++k)
  31794. {
  31795. note.begin (false);
  31796. note.pollForSnapshot();
  31797. if (note.isCardShowing())
  31798. break;
  31799. }
  31800. check ("Not now: starts 12 to 40 without the card", ! note.isCardShowing() && state().launches == 40);
  31801. note.begin (false);
  31802. note.pollForSnapshot();
  31803. check ("Not now: the card again at start 41", note.isCardShowing());
  31804. // Don't show again: never, and Settings shows the box unticked
  31805. if (auto* card = note.cardForSnapshot())
  31806. card->buttonForSnapshot (lynx::supportnote::Choice::never)->onClick();
  31807. note.closeCard();
  31808. check ("Don't show again: off", ! state().show && ! lynx::support::noteEnabled());
  31809. for (int k = 0; k < 200; ++k)
  31810. {
  31811. note.begin (false);
  31812. note.pollForSnapshot();
  31813. }
  31814. check ("Don't show again: 200 more starts, never", ! note.isCardShowing());
  31815. // Support: opens the Support window (on the next message turn) and the note doesn't come back
  31816. setState (20, 10, true);
  31817. note.begin (false);
  31818. note.pollForSnapshot();
  31819. if (auto* card = note.cardForSnapshot())
  31820. card->buttonForSnapshot (lynx::supportnote::Choice::support)->onClick();
  31821. note.closeCard();
  31822. check ("Support: the note has done its job", ! state().show);
  31823. // Settings off: never; on again: counts from now
  31824. setState (5, 10, true);
  31825. lynx::support::setNoteEnabled (false);
  31826. for (int k = 0; k < 100; ++k)
  31827. {
  31828. note.begin (false);
  31829. note.pollForSnapshot();
  31830. }
  31831. check ("Settings off: 100 starts, never", ! note.isCardShowing() && state().launches == 105);
  31832. lynx::support::setNoteEnabled (true);
  31833. check ("Settings on again: next 30 starts later", state() == lynx::supportnote::State { 105, 135, true });
  31834. note.closeCard();
  31835. }
  31836. stateFile.deleteFile();
  31837. if (hadState)
  31838. stateFile.replaceWithText (oldState);
  31839. line (ok ? "result=OK" : "result=FAILED");
  31840. return ok;
  31841. }
  31842. bool runSimpleCloseTest (const juce::String& reportPath)
  31843. {
  31844. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31845. juce::String report;
  31846. bool ok = true;
  31847. const auto line = [&report, &reportPath] (const juce::String& text) {
  31848. report << text << "\n";
  31849. juce::File (reportPath).replaceWithText (report); // (written as it goes: a crash still leaves the last step)
  31850. };
  31851. const auto check = [&line, &ok] (const juce::String& what, bool good) {
  31852. line ((good ? "ok " : "FAIL ") + what);
  31853. ok = ok && good;
  31854. };
  31855. const auto aliveBefore = lynx::SimpleWorkflow::alive.load();
  31856. {
  31857. lynx::AudioEngine offline (false);
  31858. {
  31859. lynx::MainComponent ui (offline, false);
  31860. ui.setSize (1600, 900);
  31861. ui.setVisible (true); // (no window: the docked editor and the tour only need their parents visible)
  31862. const auto settle = [&] {
  31863. for (int k = 0; k < 3; ++k)
  31864. offline.dispatchPendingMessages();
  31865. };
  31866. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  31867. settle();
  31868. auto* simple = ui.getSimpleWorkflowForSnapshot();
  31869. check ("the Simple workflow is up", simple != nullptr);
  31870. if (simple != nullptr)
  31871. {
  31872. const auto empty = lynx::builtInTemplateIndex ("Empty");
  31873. offline.setSong (empty >= 0 ? lynx::makeNewProject (empty) : lynx::makeNewProject());
  31874. settle();
  31875. simple->showWelcome();
  31876. settle();
  31877. auto* tour = simple->tourForSnapshot();
  31878. check ("Welcome screen shown", tour != nullptr && tour->isWelcomeShowing());
  31879. simple->startOrContinueTour();
  31880. settle();
  31881. simple->doTourStep (lynx::tour::beat);
  31882. settle();
  31883. check ("the tour runs with its card up", simple->tourRunning() && tour != nullptr && tour->cardForSnapshot() != nullptr);
  31884. // a demo song from Start from (the panel stays up over the Playlist)
  31885. if (auto* start = simple->startFromForSnapshot(); start != nullptr && lynx::demos::count > 1)
  31886. {
  31887. offline.setSong (lynx::demos::make (1));
  31888. settle();
  31889. check ("a demo song opened, Start from up", simple->isStartFromShowing() && ! offline.getSong().playlist.empty());
  31890. }
  31891. // the dock on a track, every tab (the Editor tab docks the Piano roll)
  31892. if (auto* dock = simple->dockForSnapshot())
  31893. {
  31894. simple->trackSelected ([] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  31895. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  31896. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  31897. return t;
  31898. return 0;
  31899. } (offline.getSong()));
  31900. for (auto tab : { lynx::SimpleDock::Tab::instrument, lynx::SimpleDock::Tab::keyboard, lynx::SimpleDock::Tab::editor,
  31901. lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::editor })
  31902. {
  31903. dock->setTab (tab);
  31904. settle();
  31905. }
  31906. check ("the dock shows", simple->isDockShowing());
  31907. line ("dock tab at the close: " + juce::String ((int) dock->getTab()) + " (2 = Editor, the docked Piano roll)");
  31908. }
  31909. ui.toggleLyrics(); // (Lyrics, then Finish: they share the dock on the right)
  31910. settle();
  31911. simple->showFinish();
  31912. settle();
  31913. check ("Finish open", simple->isFinishShowing());
  31914. simple->showChooser();
  31915. settle();
  31916. line ("Simple workflow objects alive before the close: " + juce::String (lynx::SimpleWorkflow::alive.load() - aliveBefore));
  31917. }
  31918. } // (the main window goes as at shutdown)
  31919. check ("no Simple workflow outlived its main window's destructor body (it reaches the Workspace)",
  31920. lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore);
  31921. check ("none left after the close", lynx::SimpleWorkflow::alive.load() == aliveBefore);
  31922. // Simple, then Pattern, then Simple again, and closed
  31923. {
  31924. lynx::MainComponent ui (offline, false);
  31925. ui.setSize (1600, 900);
  31926. ui.setVisible (true);
  31927. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  31928. offline.dispatchPendingMessages();
  31929. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  31930. offline.dispatchPendingMessages();
  31931. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  31932. offline.dispatchPendingMessages();
  31933. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  31934. simple->showWelcome();
  31935. offline.dispatchPendingMessages();
  31936. }
  31937. check ("Simple -> Pattern -> Simple, closed: none outlived the destructor body", lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore
  31938. && lynx::SimpleWorkflow::alive.load() == aliveBefore);
  31939. }
  31940. line (ok ? "result=OK" : "result=FAILED");
  31941. return ok;
  31942. }
  31943. void runTour190dvShot (const juce::String& prefix)
  31944. {
  31945. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31946. lynx::AudioEngine offline (false);
  31947. lynx::MainComponent ui (offline, false);
  31948. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  31949. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  31950. ui.setVisible (true); // (no window: the docked editor and the ring's targets only need their parents visible)
  31951. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  31952. const auto file = juce::File (prefix + "-" + name + ".png");
  31953. file.deleteFile();
  31954. juce::FileOutputStream out (file);
  31955. juce::PNGImageFormat().writeImageToStream (image, out);
  31956. };
  31957. juce::String report;
  31958. // (written as it goes: a run that stops halfway still leaves its checks)
  31959. const auto line = [&report, &prefix] (const juce::String& text) {
  31960. report << text << "\n";
  31961. juce::File (prefix + "-report.txt").replaceWithText (report);
  31962. };
  31963. const auto check = [&line] (const juce::String& what, bool ok) { line ((ok ? "OK " : "ERROR ") + what); };
  31964. ui.selectTabForSnapshot (2);
  31965. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  31966. offline.dispatchPendingMessages();
  31967. auto* simple = ui.getSimpleWorkflowForSnapshot();
  31968. auto* tour = simple != nullptr ? simple->tourForSnapshot() : nullptr;
  31969. if (tour == nullptr)
  31970. {
  31971. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow / tour\n");
  31972. return;
  31973. }
  31974. check ("no Welcome screen by itself in a --snapshot route (not a real first start)", ! tour->isWelcomeShowing());
  31975. const auto settle = [&] {
  31976. for (int k = 0; k < 3; ++k)
  31977. offline.dispatchPendingMessages();
  31978. };
  31979. const auto window = [&] (const juce::String& name, bool twoX = false) {
  31980. settle();
  31981. tour->ringForSnapshot(); // (the ring follows the layout: resolved now, as its timer would)
  31982. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name);
  31983. if (twoX)
  31984. if (auto* card = tour->cardForSnapshot(); card != nullptr && card->getParentComponent() != nullptr)
  31985. writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), name + "-card@2x");
  31986. };
  31987. const auto stepIs = [&] (int step, const juce::String& target) {
  31988. settle();
  31989. const auto ring = tour->ringForSnapshot();
  31990. const auto id = tour->targetIdForSnapshot();
  31991. line ("step " + juce::String (tour->step() + 1) + " (" + lynx::tour::stepId (tour->step()) + "): ring on " + (id.isEmpty() ? juce::String ("-") : id) + " "
  31992. + ring.toString());
  31993. check (juce::String ("the card shows step ") + lynx::tour::stepId (step), tour->isRunning() && tour->step() == step);
  31994. if (target.isNotEmpty())
  31995. check ("the ring is on " + target, id == target && ! ring.isEmpty());
  31996. };
  31997. // --- the Welcome screen (on a new, empty project: the built-in "Empty" template, as File › New can give) -------------
  31998. const auto emptyProject = [] {
  31999. const auto index = lynx::builtInTemplateIndex ("Empty");
  32000. return index >= 0 ? lynx::makeNewProject (index) : lynx::makeNewProject();
  32001. };
  32002. offline.setSong (emptyProject());
  32003. settle();
  32004. check ("the new project is empty for the Simple workflow (it opens on the chooser)", lynx::simpletracks::isEmptySong (offline.getSong()));
  32005. simple->showWelcome();
  32006. settle();
  32007. check ("Help › Welcome screen shows it", tour->isWelcomeShowing());
  32008. window ("welcome");
  32009. if (auto* w = tour->welcomeForSnapshot())
  32010. writeImage (w->createComponentSnapshot (w->getLocalBounds(), true, 2.0f), "welcome@2x");
  32011. tour->clickForSnapshot ("welcome.tour");
  32012. settle();
  32013. check ("Make my first song: the Welcome screen closes, the tour starts, the chooser comes up for the beat",
  32014. ! tour->isWelcomeShowing() && tour->isRunning() && simple->isChooserShowing());
  32015. // --- step 1: the beat ---------------------------------------------------------------------------------------------
  32016. stepIs (lynx::tour::beat, "simple.tile.drums");
  32017. window ("step1-beat", true);
  32018. simple->showStarterPageForSnapshot();
  32019. stepIs (lynx::tour::beat, "simple.starters");
  32020. window ("step1-beat-starters");
  32021. tour->clickForSnapshot ("do");
  32022. settle();
  32023. check ("Do it for me added a starter beat", lynx::tour::hasBeat (offline.getSong()));
  32024. // --- step 2: the key ----------------------------------------------------------------------------------------------
  32025. stepIs (lynx::tour::key, "toolbar.key");
  32026. window ("step2-key", true);
  32027. tour->clickForSnapshot ("do");
  32028. settle();
  32029. check ("Do it for me set A minor", lynx::projectkey::get (offline.getSong()).has_value());
  32030. // --- step 3: an instrument (Add track opens the chooser: the ring moves to its tile) ------------------------------
  32031. stepIs (lynx::tour::instrument, "simple.addTrack");
  32032. window ("step3-instrument", true);
  32033. simple->showChooser();
  32034. stepIs (lynx::tour::instrument, "simple.tile.instrument");
  32035. window ("step3-instrument-chooser");
  32036. tour->clickForSnapshot ("do");
  32037. settle();
  32038. check ("Do it for me added an Instrument track (the chooser closed)", lynx::tour::firstInstrumentTrack (offline.getSong()) >= 0 && ! simple->isChooserShowing());
  32039. // --- step 4: chords -----------------------------------------------------------------------------------------------
  32040. stepIs (lynx::tour::chords, "keyboard.chordPad");
  32041. window ("step4-chords", true);
  32042. tour->clickForSnapshot ("do");
  32043. settle();
  32044. check ("Do it for me wrote four chords (12 notes) on the instrument's pattern", [&] {
  32045. const auto& song = offline.getSong();
  32046. const auto p = lynx::simpletracks::patternOf (song, lynx::tour::firstInstrumentTrack (song));
  32047. return p >= 0 && song.patterns[(std::size_t) p].notes.size() == 12;
  32048. }());
  32049. // --- step 5: a voice or a loop (no "Do it for me": a loop is dropped as a user would) ------------------------------
  32050. stepIs (lynx::tour::loop, "simple.dropLane"); // (round 190jc, SG-18: it rang "+ Add track")
  32051. window ("step5-loop", true);
  32052. {
  32053. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190dv-loops");
  32054. dir.deleteRecursively();
  32055. dir.createDirectory();
  32056. const auto wav = dir.getChildFile ("Warm Keys 120 Am.wav");
  32057. const int frames = 192000;
  32058. juce::AudioBuffer<float> audio (1, frames);
  32059. for (int i = 0; i < frames; ++i)
  32060. {
  32061. const auto t = (double) i / 48000.0;
  32062. double v = 0.0;
  32063. for (const auto key : { 57, 60, 64 })
  32064. v += std::sin (2.0 * juce::MathConstants<double>::pi * 440.0 * std::pow (2.0, (key - 69) / 12.0) * t);
  32065. audio.setSample (0, i, (float) (0.1 * v * (1.0 - std::exp (-std::fmod (t, 0.5) * 60.0))));
  32066. }
  32067. {
  32068. juce::WavAudioFormat format;
  32069. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  32070. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  32071. {
  32072. out.release();
  32073. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  32074. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  32075. }
  32076. }
  32077. simple->dropFiles ({ wav.getFullPathName() }, 0);
  32078. settle();
  32079. check ("a dropped loop (A minor in its name) follows the key", [&] {
  32080. for (const auto& c : offline.getSong().playlist)
  32081. if (c.kind == lynx::ClipKind::audio)
  32082. return c.followKey;
  32083. return false;
  32084. }());
  32085. }
  32086. // --- step 6: a one-knob effect --------------------------------------------------------------------------------------
  32087. stepIs (lynx::tour::effect, "simple.dock.addEffect");
  32088. window ("step6-effect", true);
  32089. tour->clickForSnapshot ("do");
  32090. settle();
  32091. check ("Do it for me put Room on the instrument track", lynx::tour::hasOneKnob (offline.getSong()));
  32092. // --- step 7: Finish -----------------------------------------------------------------------------------------------
  32093. stepIs (lynx::tour::finish, "simple.finish");
  32094. window ("step7-finish", true);
  32095. tour->clickForSnapshot ("do");
  32096. settle();
  32097. check ("Do it for me opened Finish and chose Balanced", simple->isFinishShowing() && lynx::looks::present (offline.getSong()));
  32098. // --- the end card, Back / Next, close -------------------------------------------------------------------------------
  32099. settle();
  32100. check ("the end card", tour->isRunning() && tour->step() == lynx::tour::stepCount);
  32101. window ("end", true);
  32102. tour->clickForSnapshot ("back");
  32103. settle();
  32104. check ("Back: the Finish step again, shown done (the tour waits for Next)", tour->step() == lynx::tour::finish
  32105. && tour->machineForCheck().shownDone (offline.getSong()));
  32106. window ("back-done", true);
  32107. tour->clickForSnapshot ("next");
  32108. settle();
  32109. check ("Next: the end card again", tour->step() == lynx::tour::stepCount);
  32110. check ("all seven steps done by the song", tour->machineForCheck().state().completed == 0x7fu);
  32111. tour->clickForSnapshot ("close");
  32112. settle();
  32113. check ("closing the end card ends the tour (not continued from Help)", ! tour->isRunning() && ! tour->canContinue()
  32114. && tour->machineForCheck().state().done);
  32115. line ("-- paused tour");
  32116. // --- a paused tour, the Help menu and the chooser's button ---------------------------------------------------------
  32117. offline.setSong (emptyProject());
  32118. settle();
  32119. tour->machineForCheck() = lynx::tour::Machine {};
  32120. simple->startOrContinueTour();
  32121. settle();
  32122. line ("-- do beat");
  32123. simple->doTourStep (lynx::tour::beat);
  32124. settle();
  32125. check ("a new tour on an empty project: the beat done moves it to the key", tour->step() == lynx::tour::key);
  32126. tour->clickForSnapshot ("close");
  32127. settle();
  32128. check ("closing the card pauses the tour (Help continues it)", ! tour->isRunning() && tour->canContinue());
  32129. line ("-- help menu");
  32130. {
  32131. const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
  32132. bool continueItem = false, welcomeItem = false;
  32133. for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
  32134. {
  32135. continueItem = continueItem || it.getItem().text.startsWith (lynx::tr ("Continue the first-song tour (step {0} of {1})", { "2", "7" }));
  32136. welcomeItem = welcomeItem || it.getItem().text == lynx::tr ("Welcome screen...");
  32137. }
  32138. check ("Help: Continue the first-song tour (step 2 of 7) and Welcome screen...", continueItem && welcomeItem);
  32139. saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help.png");
  32140. }
  32141. simple->startOrContinueTour();
  32142. settle();
  32143. check ("Help › Continue: back on the key step", tour->isRunning() && tour->step() == lynx::tour::key);
  32144. tour->clickForSnapshot ("skip");
  32145. settle();
  32146. check ("Skip tour ends it", ! tour->isRunning() && ! tour->canContinue());
  32147. offline.setSong (emptyProject());
  32148. settle();
  32149. simple->showChooser();
  32150. window ("chooser");
  32151. line ("-- start from");
  32152. // --- Start from: the three demo songs; a demo opened in Simple -------------------------------------------------------
  32153. if (auto* start = simple->startFromForSnapshot())
  32154. {
  32155. settle();
  32156. writeImage (start->createComponentSnapshot (start->getLocalBounds(), true, 1.0f), "startfrom");
  32157. const auto list = lynx::startfrom::entries();
  32158. int demos = 0;
  32159. for (const auto& e : list)
  32160. demos += e.kind == lynx::startfrom::Entry::Kind::demo && e.playable ? 1 : 0;
  32161. check ("Start from lists three playable demo songs first", demos == 3 && list.size() >= 3 && list[1].demo == 1 && list[2].demo == 2);
  32162. for (int d = 1; d < 3 && d < (int) list.size(); ++d)
  32163. 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");
  32164. simple->hideStartFrom();
  32165. }
  32166. line ("-- demos");
  32167. for (int d = 1; d < lynx::demos::count; ++d)
  32168. {
  32169. offline.setSong (lynx::demos::make (d));
  32170. settle();
  32171. simple->hideChooser();
  32172. window (juce::String ("demo-") + (d == 1 ? "hiphop" : "pop"));
  32173. // the committed file is the generated song
  32174. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile ("resources/demos").getChildFile (lynx::demos::fileName (d));
  32175. juce::String error;
  32176. const auto loaded = lynx::ProjectFile::load (file, error);
  32177. check ("resources/demos/" + juce::String (lynx::demos::fileName (d)) + " loads and is the generated song",
  32178. loaded.has_value() && lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (lynx::demos::make (d), false));
  32179. }
  32180. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  32181. juce::File (prefix + "-report.txt").replaceWithText (report);
  32182. }
  32183. // --patterns190ea (round 190ea): FL keeps at least one pattern; the engine now does too (AudioEngine::publishSong,
  32184. // Song::keepOnePattern). Before, a Song without a pattern crashed the docked Piano roll's listener.
  32185. bool runPatterns190ea (const juce::String& reportPath)
  32186. {
  32187. namespace st = lynx::simpletracks;
  32188. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32189. lynx::AudioEngine offline (false);
  32190. lynx::MainComponent ui (offline, false);
  32191. ui.setSize (1600, 900);
  32192. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  32193. juce::String report;
  32194. bool ok = true;
  32195. const auto check = [&report, &ok] (const juce::String& what, bool good) {
  32196. report << (good ? "OK " : "ERROR ") << what << "\n";
  32197. ok = ok && good;
  32198. };
  32199. const auto save = [&report, &reportPath] { juce::File (reportPath).replaceWithText (report); };
  32200. const auto settle = [&] { offline.dispatchPendingMessages(); ui.getPianoRollForSnapshot().repaint(); };
  32201. const auto onePattern = [&offline] {
  32202. const auto& s = offline.getSong();
  32203. return s.patterns.size() >= 1 && s.currentPattern >= 0 && s.currentPattern < (int) s.patterns.size();
  32204. };
  32205. // the hand-built songs the engine can be given: none of them has a pattern
  32206. const auto bare = [] {
  32207. lynx::Song s;
  32208. s.mixer = lynx::Song::defaultMixer();
  32209. return s;
  32210. };
  32211. // every way to reach "no pattern" in the current layout
  32212. const auto paths = [&] (const juce::String& where) {
  32213. offline.setSong (bare());
  32214. settle();
  32215. check (where + ": a song without a pattern opens with one empty \"Pattern 1\"",
  32216. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].name == "Pattern 1"
  32217. && offline.getSong().patterns[0].notes.empty());
  32218. offline.editSong ([] (lynx::Song& s) { s.patterns.clear(); });
  32219. settle();
  32220. check (where + ": an edit that clears every pattern leaves one", onePattern());
  32221. offline.editSong ([] (lynx::Song& s) {
  32222. s.patterns.resize (2);
  32223. s.patterns[1].notes.push_back ({});
  32224. s.currentPattern = 1;
  32225. });
  32226. settle();
  32227. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  32228. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  32229. settle();
  32230. check (where + ": deleting the last pattern leaves an empty \"Pattern 1\" (FL's invariant)",
  32231. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].notes.empty());
  32232. for (int k = 0; k < 6; ++k)
  32233. {
  32234. offline.undo();
  32235. settle();
  32236. }
  32237. check (where + ": undo back over those steps keeps a pattern", onePattern());
  32238. for (int k = 0; k < 6; ++k)
  32239. {
  32240. offline.redo();
  32241. settle();
  32242. }
  32243. check (where + ": redo keeps a pattern", onePattern());
  32244. offline.applyRemote (bare());
  32245. settle();
  32246. check (where + ": a live session's remote song without a pattern gets one", onePattern());
  32247. offline.editSong ([] (lynx::Song& s) { s.currentPattern = 99; });
  32248. settle();
  32249. check (where + ": a current pattern out of range is put back in range", onePattern() && offline.getSong().currentPattern == 0);
  32250. };
  32251. // the Simple layout with the Piano roll docked in the Editor tab (round 190dv's crash)
  32252. ui.selectTabForSnapshot (2);
  32253. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  32254. settle();
  32255. auto* simple = ui.getSimpleWorkflowForSnapshot();
  32256. check ("the Simple workflow is up", simple != nullptr);
  32257. if (simple == nullptr)
  32258. {
  32259. save();
  32260. return false;
  32261. }
  32262. simple->hideChooser();
  32263. st::Request q;
  32264. q.kind = st::Kind::instrument;
  32265. q.name = "Keys";
  32266. lynx::ChannelDef synth;
  32267. synth.instrument = lynx::InstrumentKind::synth;
  32268. q.channel = synth;
  32269. q.emptyBars = 4;
  32270. st::Result r;
  32271. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  32272. settle();
  32273. ui.getPlaylistForSnapshot().selectTrack (r.track);
  32274. simple->trackSelected (r.track);
  32275. settle();
  32276. auto* dock = simple->dockForSnapshot();
  32277. check ("the instrument track's dock has the Editor tab", dock != nullptr && dock->hasPlayTabsForCheck());
  32278. if (dock != nullptr)
  32279. dock->setTab (lynx::SimpleDock::Tab::editor);
  32280. settle();
  32281. check ("the Piano roll is docked in the Editor tab", dock != nullptr && dock->isEditorDocked() && dock->isParentOf (&ui.getPianoRollForSnapshot()));
  32282. paths ("Simple, Editor tab");
  32283. // the Pattern layout with the Piano roll panel, then the Clip-launch layout
  32284. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  32285. settle();
  32286. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::pianoRoll });
  32287. settle();
  32288. paths ("Pattern layout, Piano roll");
  32289. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  32290. settle();
  32291. paths ("Clip-launch layout");
  32292. report << (ok ? "RESULT OK\n" : "RESULT FAILED\n");
  32293. save();
  32294. return ok;
  32295. }
  32296. // round 190fo: the Simple layout's Sampler track (16 pads) and a folder of stems and MIDI files, off-screen at 1x and
  32297. // 2x, with a text report of the checks (.lynx round trip, kits, typing keys, the folder import)
  32298. void runReabl190foShot (const juce::String& prefix)
  32299. {
  32300. namespace st = lynx::simpletracks;
  32301. namespace sp = lynx::simplepads;
  32302. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32303. lynx::AudioEngine offline (false);
  32304. lynx::MainComponent ui (offline, false);
  32305. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  32306. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  32307. ui.setVisible (true);
  32308. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  32309. const auto file = juce::File (prefix + "-" + name + ".png");
  32310. file.deleteFile();
  32311. juce::FileOutputStream out (file);
  32312. juce::PNGImageFormat().writeImageToStream (image, out);
  32313. };
  32314. juce::String report;
  32315. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  32316. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  32317. ui.selectTabForSnapshot (2);
  32318. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  32319. offline.dispatchPendingMessages();
  32320. auto* simple = ui.getSimpleWorkflowForSnapshot();
  32321. if (simple == nullptr)
  32322. {
  32323. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  32324. return;
  32325. }
  32326. const auto whole = [&] (const juce::String& name) {
  32327. offline.dispatchPendingMessages();
  32328. for (float scale : { 1.0f, 2.0f })
  32329. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
  32330. };
  32331. // the chooser: the Sampler tile (16 pads, "On keys..." for one sample over the keys) and Import's "Folder..."
  32332. simple->showChooser();
  32333. whole ("chooser");
  32334. simple->hideChooser();
  32335. // --- test sounds -------------------------------------------------------------------------------------------------
  32336. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190fo");
  32337. dir.deleteRecursively();
  32338. dir.createDirectory();
  32339. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  32340. juce::AudioBuffer<float> audio (1, frames);
  32341. for (int i = 0; i < frames; ++i)
  32342. audio.setSample (0, i, f (i));
  32343. wav.getParentDirectory().createDirectory();
  32344. juce::WavAudioFormat format;
  32345. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  32346. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  32347. {
  32348. out.release();
  32349. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  32350. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  32351. }
  32352. return wav;
  32353. };
  32354. juce::Random rnd (190);
  32355. const auto pi = juce::MathConstants<double>::pi;
  32356. const auto kick = writeWav (dir.getChildFile ("pads/Kick.wav"), 24000, [pi] (int i) {
  32357. const auto t = i / 48000.0;
  32358. 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));
  32359. });
  32360. 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)); });
  32361. 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)); });
  32362. const auto chord = writeWav (dir.getChildFile ("pads/Chord stab.wav"), 48000, [pi] (int i) {
  32363. const auto t = i / 48000.0;
  32364. double v = 0.0;
  32365. for (int k : { 57, 60, 64 })
  32366. v += std::sin (2.0 * pi * 440.0 * std::pow (2.0, (k - 69) / 12.0) * t);
  32367. return (float) (0.2 * v * std::exp (-t * 2.5));
  32368. });
  32369. const auto vox = writeWav (dir.getChildFile ("pads/Vox hey.wav"), 30000, [pi] (int i) {
  32370. const auto t = i / 48000.0;
  32371. 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));
  32372. });
  32373. // --- the Sampler track ---------------------------------------------------------------------------------------------
  32374. check ("the Sampler tile's track was added", simple->addPads());
  32375. offline.dispatchPendingMessages();
  32376. const auto& song0 = offline.getSong();
  32377. int track = -1;
  32378. for (int t = 0; t < (int) song0.playlistTracks.size() && track < 0; ++t)
  32379. if (st::kindOf (song0, t) == st::Kind::pads)
  32380. track = t;
  32381. check ("a Sampler track with 16 pads", track >= 0 && [&] {
  32382. const auto c = sp::padChannels (song0, track);
  32383. return std::all_of (c.begin(), c.end(), [] (int i) { return i >= 0; });
  32384. }());
  32385. auto* dock = simple->dockForSnapshot();
  32386. if (dock == nullptr || track < 0)
  32387. {
  32388. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock / track\n");
  32389. return;
  32390. }
  32391. simple->trackSelected (track);
  32392. offline.dispatchPendingMessages();
  32393. check ("the dock opens on the Pads tab", dock->hasPadsTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::pads);
  32394. const auto shots = [&] (const juce::String& name) {
  32395. offline.dispatchPendingMessages();
  32396. for (float scale : { 1.0f, 2.0f })
  32397. {
  32398. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  32399. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  32400. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  32401. }
  32402. };
  32403. shots ("pads-empty");
  32404. const juce::File files[] { kick, snare, hat, hat, chord, vox };
  32405. for (int p = 0; p < 6; ++p)
  32406. dock->padsLoadForCheck (p, files[p]);
  32407. offline.dispatchPendingMessages();
  32408. check ("six pads hold a sound", [&] {
  32409. int n = 0;
  32410. for (int p = 0; p < sp::padCount; ++p)
  32411. n += sp::hasSample (offline.getSong(), track, p) ? 1 : 0;
  32412. return n == 6;
  32413. }());
  32414. // pad 3 = the open hat: one-shot, group 1 with pad 2 (closed hat), a colour; pad 4 = the chord, looped and darker
  32415. dock->padsSelectForCheck (2);
  32416. dock->padsModeForCheck (1);
  32417. dock->padsSelectForCheck (3);
  32418. dock->padsModeForCheck (1);
  32419. offline.editSong ([track] (lynx::Song& s) {
  32420. for (int p : { 2, 3 })
  32421. if (const auto c = sp::padChannel (s, track, p); c >= 0)
  32422. {
  32423. s.channels[(std::size_t) c].simplePad.group = 1;
  32424. s.channels[(std::size_t) c].simplePad.colour = 2;
  32425. sp::apply (s.channels[(std::size_t) c], 4800);
  32426. }
  32427. });
  32428. dock->padsSelectForCheck (4);
  32429. dock->padsModeForCheck (2);
  32430. dock->padsKnobForCheck (2, 0.3f); // tone: a low-pass
  32431. dock->padsKnobForCheck (1, 0.35f); // release
  32432. dock->padsRegionForCheck (0.05f, 0.7f);
  32433. dock->padsNormalizeForCheck();
  32434. dock->padsUpdateForCheck();
  32435. {
  32436. const auto& s = offline.getSong();
  32437. const auto& c = s.channels[(std::size_t) sp::padChannel (s, track, 4)];
  32438. line ("pad 5: mode " + juce::String ((int) c.simplePad.mode) + " tone " + juce::String (c.simplePad.tone, 2) + " cutoff " + juce::String (c.sampler.cutoff, 0)
  32439. + " release " + juce::String (c.sampler.release, 3) + " region " + juce::String (c.sampler.regionStart, 2) + "-" + juce::String (c.sampler.regionEnd, 2)
  32440. + " gain " + juce::String (c.sampler.gainDb, 2) + " dB zones " + juce::String ((int) c.zones.size()));
  32441. 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
  32442. && c.sampler.filterType == 0 && c.sampler.cutoff < 5000.0f && c.sampler.gainDb > 0.5f);
  32443. const auto& h = s.channels[(std::size_t) sp::padChannel (s, track, 3)];
  32444. 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);
  32445. }
  32446. shots ("pads");
  32447. dock->padsHitForCheck (0);
  32448. dock->lightPad (2);
  32449. shots ("pads-hit");
  32450. // the typing keys: V plays pad 1, M pad 4, 7 pad 16; Z is not a pad key
  32451. check ("typing keys reach the pads", simple->padChannelForKey ('V') == sp::padChannel (offline.getSong(), track, 0)
  32452. && simple->padChannelForKey ('m') == sp::padChannel (offline.getSong(), track, 3)
  32453. && simple->padChannelForKey ('7') == sp::padChannel (offline.getSong(), track, 15)
  32454. && simple->padChannelForKey ('Z') == -1);
  32455. // drag pad 6 (vox) onto the empty pad 9: it moves; Alt-drag pad 1 onto pad 10: a copy
  32456. dock->padsDragForCheck (5, 8, false);
  32457. dock->padsDragForCheck (0, 9, true);
  32458. check ("a pad moved and a pad copied", ! sp::hasSample (offline.getSong(), track, 5) && sp::hasSample (offline.getSong(), track, 8)
  32459. && sp::hasSample (offline.getSong(), track, 9) && sp::hasSample (offline.getSong(), track, 0));
  32460. dock->padsSelectForCheck (4);
  32461. shots ("pads-moved");
  32462. saveMenus ({ "Pad menu", "Colour", "Copy a value to every pad" }, [&] {
  32463. const auto top = dock->padMenuForSnapshot (4);
  32464. std::vector<juce::PopupMenu> menus { top };
  32465. for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
  32466. if (it.getItem().subMenu != nullptr)
  32467. menus.push_back (*it.getItem().subMenu);
  32468. return menus;
  32469. }(), prefix + "-menu-pad.png");
  32470. // kits: saved, the pads cleared, opened again
  32471. const auto kitFile = lynx::platform::documentsFolder().getChildFile ("LYNX/Sampler kits/Test kit 190fo.lynxkit");
  32472. kitFile.deleteFile();
  32473. check ("the pads saved as a kit", dock->saveKitForCheck ("Test kit 190fo") && kitFile.existsAsFile());
  32474. saveMenus ({ "Kit", "My kits" }, [&] {
  32475. const auto top = dock->kitMenuForSnapshot();
  32476. std::vector<juce::PopupMenu> menus { top };
  32477. for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
  32478. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("My kits"))
  32479. menus.push_back (*it.getItem().subMenu);
  32480. return menus;
  32481. }(), prefix + "-menu-kit.png");
  32482. const auto before = offline.getSong().channels;
  32483. offline.editSong ([track] (lynx::Song& s) {
  32484. for (int p = 0; p < sp::padCount; ++p)
  32485. sp::clearPad (s, track, p);
  32486. });
  32487. check ("the kit opens the same pads again", dock->openKitForCheck (kitFile) && [&] {
  32488. const auto& now = offline.getSong().channels;
  32489. for (int p = 0; p < sp::padCount; ++p)
  32490. {
  32491. const auto c = sp::padChannel (offline.getSong(), track, p);
  32492. 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
  32493. || 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)
  32494. return false;
  32495. }
  32496. return true;
  32497. }());
  32498. {
  32499. const auto renamed = kitFile.getSiblingFile ("Renamed kit 190fo.lynxkit");
  32500. renamed.deleteFile();
  32501. check ("a kit renamed (and a one-letter name refused)", ! lynx::SimpleDock::renameKitForCheck (kitFile, "x")
  32502. && lynx::SimpleDock::renameKitForCheck (kitFile, "Renamed kit 190fo") && renamed.existsAsFile()
  32503. && ! kitFile.exists());
  32504. renamed.deleteFile();
  32505. }
  32506. kitFile.deleteFile();
  32507. // a beat on the pads (the track's pattern) and the .lynx round trip
  32508. offline.editSong ([track] (lynx::Song& s) {
  32509. const auto pattern = [&] {
  32510. for (const auto& c : s.playlist)
  32511. if (c.track == track && c.kind == lynx::ClipKind::pattern)
  32512. return c.pattern;
  32513. return -1;
  32514. }();
  32515. if (pattern < 0)
  32516. return;
  32517. for (int step = 0; step < 16; ++step)
  32518. {
  32519. const int pad = step % 4 == 0 ? 0 : step % 8 == 4 ? 1 : 2;
  32520. lynx::Note n;
  32521. n.channel = sp::padChannel (s, track, pad);
  32522. n.key = sp::padKey;
  32523. n.start = (std::int64_t) step * lynx::ticksPerStep;
  32524. n.length = lynx::ticksPerStep;
  32525. s.patterns[(std::size_t) pattern].notes.push_back (n);
  32526. }
  32527. });
  32528. {
  32529. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  32530. juce::String error;
  32531. const auto back = lynx::ProjectFile::fromJson (json, error);
  32532. bool same = back.has_value() && back->channels.size() == offline.getSong().channels.size() && st::kindOf (*back, track) == st::Kind::pads;
  32533. for (std::size_t c = 0; same && c < back->channels.size(); ++c)
  32534. {
  32535. const auto& a = back->channels[c];
  32536. const auto& b = offline.getSong().channels[c];
  32537. same = a.simplePad == b.simplePad && a.zones == b.zones && a.cutGroup == b.cutGroup && a.cutBy == b.cutBy && a.samplePath == b.samplePath
  32538. && a.sampler.regionStart == b.sampler.regionStart && a.sampler.release == b.sampler.release && a.sampler.cutoff == b.sampler.cutoff;
  32539. }
  32540. check ("pads, their modes, groups and loops survive .lynx", same);
  32541. lynx::Song plain = lynx::Song::makeDefault();
  32542. check ("a project without pads writes no pad field", ! lynx::ProjectFile::toJson (plain).contains ("simplePad"));
  32543. }
  32544. ui.getPlaylistForSnapshot().selectTrack (track);
  32545. // --- a folder of stems and MIDI files (the other app's "download stems" naming) --------------------------------------
  32546. const auto stems = dir.getChildFile ("My song stems");
  32547. writeWav (stems.getChildFile ("01_Drums.wav"), 96000, [&rnd] (int i) { return (i % 24000) < 2000 ? (rnd.nextFloat() - 0.5f) * 0.8f : 0.0f; });
  32548. writeWav (stems.getChildFile ("02_Bass.wav"), 96000, [pi] (int i) { return (float) (0.3 * std::sin (2.0 * pi * 55.0 * i / 48000.0)); });
  32549. 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)); });
  32550. {
  32551. juce::MidiMessageSequence seq;
  32552. for (int k = 0; k < 8; ++k)
  32553. {
  32554. seq.addEvent (juce::MidiMessage::noteOn (1, 36 + (k % 4) * 3, (juce::uint8) 100), k * 480.0);
  32555. seq.addEvent (juce::MidiMessage::noteOff (1, 36 + (k % 4) * 3), k * 480.0 + 400.0);
  32556. }
  32557. seq.updateMatchedPairs();
  32558. juce::MidiFile midi;
  32559. midi.setTicksPerQuarterNote (960);
  32560. midi.addTrack (seq);
  32561. for (const auto& name : { "02_Bass.mid", "03_Keys.mid" })
  32562. {
  32563. juce::FileOutputStream out (stems.getChildFile (name));
  32564. midi.writeTo (out);
  32565. }
  32566. }
  32567. const auto tracksBefore = [&] {
  32568. int n = 0;
  32569. for (int t = 0; t < (int) offline.getSong().playlistTracks.size(); ++t)
  32570. n += st::kindOf (offline.getSong(), t).has_value() ? 1 : 0;
  32571. return n;
  32572. }();
  32573. simple->addFilesForCheck ({ stems });
  32574. offline.dispatchPendingMessages();
  32575. {
  32576. const auto& s = offline.getSong();
  32577. juce::StringArray names;
  32578. int muted = 0, count = 0;
  32579. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  32580. if (st::kindOf (s, t).has_value())
  32581. {
  32582. ++count;
  32583. if (count > tracksBefore)
  32584. {
  32585. names.add (juce::String::fromUTF8 (s.playlistTracks[(std::size_t) t].name.c_str()) + (s.playlistTracks[(std::size_t) t].muted ? " (muted)" : ""));
  32586. muted += s.playlistTracks[(std::size_t) t].muted ? 1 : 0;
  32587. }
  32588. }
  32589. line ("folder tracks: " + names.joinIntoString (", "));
  32590. check ("the folder gave 5 tracks in number order, named without numbers, the Bass notes muted (its stem plays)",
  32591. names == juce::StringArray { "Drums", "Bass", "Lead Vox", "Bass 2 (muted)", "Keys" } && muted == 1);
  32592. bool atZero = true;
  32593. for (const auto& c : s.playlist)
  32594. if (c.track >= 0 && st::kindOf (s, c.track) == st::Kind::audio)
  32595. atZero = atZero && c.start == 0;
  32596. check ("every stem starts at the song's start", atZero);
  32597. }
  32598. simple->hideChooser();
  32599. whole ("folder-import");
  32600. dir.deleteRecursively();
  32601. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  32602. juce::File (prefix + "-report.txt").replaceWithText (report);
  32603. }
  32604. void runSimple190dsShot (const juce::String& prefix)
  32605. {
  32606. namespace st = lynx::simpletracks;
  32607. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32608. lynx::AudioEngine offline (false);
  32609. lynx::MainComponent ui (offline, false);
  32610. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  32611. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  32612. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  32613. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  32614. const auto file = juce::File (prefix + "-" + name + ".png");
  32615. file.deleteFile();
  32616. juce::FileOutputStream out (file);
  32617. juce::PNGImageFormat().writeImageToStream (image, out);
  32618. };
  32619. juce::String report;
  32620. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  32621. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  32622. ui.selectTabForSnapshot (2);
  32623. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  32624. offline.dispatchPendingMessages();
  32625. auto* simple = ui.getSimpleWorkflowForSnapshot();
  32626. if (simple == nullptr)
  32627. {
  32628. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  32629. return;
  32630. }
  32631. simple->hideChooser();
  32632. auto& playlist = ui.getPlaylistForSnapshot();
  32633. // --- three loops: two with their key in the name, one only in its sound ---------------------------------------
  32634. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190ds-loops");
  32635. dir.deleteRecursively();
  32636. dir.createDirectory();
  32637. // a chord loop (two bars at 120 BPM, 48 kHz): each chord's notes with six harmonics, a soft attack per beat
  32638. const auto writeLoop = [&dir] (const juce::String& name, std::vector<std::vector<int>> chords) {
  32639. const int frames = 192000;
  32640. juce::AudioBuffer<float> audio (1, frames);
  32641. audio.clear();
  32642. for (int i = 0; i < frames; ++i)
  32643. {
  32644. const auto& chord = chords[(std::size_t) (i / (frames / (int) chords.size()))];
  32645. const auto t = (double) i / 48000.0;
  32646. const auto beat = std::fmod (t, 0.5);
  32647. double v = 0.0;
  32648. for (const auto key : chord)
  32649. {
  32650. const auto f = 440.0 * std::pow (2.0, (key - 69) / 12.0);
  32651. for (int h = 1; h <= 6; ++h)
  32652. v += std::sin (2.0 * juce::MathConstants<double>::pi * f * h * t) / (h * h);
  32653. }
  32654. audio.setSample (0, i, (float) (0.08 * v * (1.0 - std::exp (-beat * 60.0)) * (0.6 + 0.4 * std::exp (-beat * 3.0))));
  32655. }
  32656. const auto wav = dir.getChildFile (name);
  32657. juce::WavAudioFormat format;
  32658. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  32659. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  32660. {
  32661. out.release();
  32662. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  32663. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  32664. }
  32665. return wav.getFullPathName();
  32666. };
  32667. const auto gMinor = writeLoop ("Night Pad 120 Gm.wav", { { 55, 58, 62 }, { 51, 55, 58 }, { 53, 57, 60 }, { 55, 58, 62 } });
  32668. const auto dMinor = writeLoop ("Pluck_120_D_minor.wav", { { 50, 53, 57 }, { 46, 50, 53 }, { 48, 52, 55 }, { 50, 53, 57 } });
  32669. 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 } });
  32670. lynx::SimpleWorkflow::answerForSnapshot = 1; // "Set the project key to G minor?" — yes
  32671. simple->dropFiles ({ gMinor, dMinor, eMinor }, 0);
  32672. lynx::SimpleWorkflow::answerForSnapshot = -1;
  32673. offline.dispatchPendingMessages();
  32674. simple->hideChooser();
  32675. line ("question: " + simple->lastKeyQuestionForCheck());
  32676. check ("the first keyed loop offered its key (G minor)", simple->lastKeyQuestionForCheck().contains ("G minor"));
  32677. {
  32678. const auto& song = offline.getSong();
  32679. const auto key = lynx::projectkey::get (song);
  32680. check ("the project key is G minor", key && key->root == 7 && lynx::projectkey::isMinor (*key));
  32681. std::vector<int> clips;
  32682. for (int i = 0; i < (int) song.playlist.size(); ++i)
  32683. if (song.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  32684. clips.push_back (i);
  32685. check ("three loop clips", clips.size() == 3);
  32686. const int expect[] { 0, 5, 3 }; // G minor, D minor (F -> Bb: +5), E minor detected (G -> Bb: +3)
  32687. const int roots[] { 7, 2, 4 };
  32688. const int sources[] { 1, 1, 2 };
  32689. for (std::size_t k = 0; k < clips.size() && k < 3; ++k)
  32690. {
  32691. const auto& c = song.playlist[(std::size_t) clips[k]];
  32692. const auto& sampler = song.channels[(std::size_t) c.channel].sampler;
  32693. line ("loop " + juce::String ((int) k + 1) + ": key " + juce::String (sampler.loopKeyRoot) + (sampler.loopKeyMinor ? "m" : "") + " source "
  32694. + juce::String ((int) sampler.loopKeySource) + " follow " + juce::String (c.followKey ? 1 : 0) + " shift " + juce::String ((int) c.keyShift)
  32695. + " pitch " + juce::String (c.pitch));
  32696. check ("loop " + juce::String ((int) k + 1) + " key, source and move", sampler.loopKeyRoot == roots[k] && sampler.loopKeyMinor
  32697. && sampler.loopKeySource == sources[k] && c.followKey
  32698. && c.keyShift == expect[k] && std::abs (c.pitch - (float) expect[k]) < 1.0e-4f);
  32699. }
  32700. }
  32701. // the key changes: every following loop moves with it (one undo step)
  32702. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, lynx::projectkey::Key { 9, lynx::projectkey::commonFirst()[1] }); });
  32703. offline.dispatchPendingMessages();
  32704. {
  32705. const auto& song = offline.getSong();
  32706. std::vector<int> shifts;
  32707. for (const auto& c : song.playlist)
  32708. if (c.kind == lynx::ClipKind::audio)
  32709. shifts.push_back (c.keyShift);
  32710. line ("after A minor: " + juce::String (shifts.size() > 2 ? shifts[0] : 99) + " " + juce::String (shifts.size() > 2 ? shifts[1] : 99) + " "
  32711. + juce::String (shifts.size() > 2 ? shifts[2] : 99));
  32712. check ("A minor: the loops move by +2, -5, +5", shifts == std::vector<int> { 2, -5, 5 });
  32713. }
  32714. // the loop tracks in the dock: the switch and what it does
  32715. int loopTrack = -1;
  32716. for (const auto& c : offline.getSong().playlist)
  32717. if (c.kind == lynx::ClipKind::audio && loopTrack < 0)
  32718. loopTrack = c.track;
  32719. playlist.selectTrack (loopTrack);
  32720. offline.dispatchPendingMessages();
  32721. auto* dock = simple->dockForSnapshot();
  32722. if (dock == nullptr)
  32723. {
  32724. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  32725. return;
  32726. }
  32727. simple->trackSelected (loopTrack);
  32728. offline.dispatchPendingMessages();
  32729. const auto shots = [&] (const juce::String& name) {
  32730. offline.dispatchPendingMessages();
  32731. for (float scale : { 1.0f, 2.0f })
  32732. {
  32733. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  32734. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  32735. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  32736. }
  32737. };
  32738. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  32739. juce::StringArray names { title };
  32740. std::vector<juce::PopupMenu> menus { menu };
  32741. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  32742. if (it.getItem().subMenu != nullptr && it.getItem().text.startsWith (subTitle))
  32743. {
  32744. names.add (subTitle);
  32745. menus.push_back (*it.getItem().subMenu);
  32746. }
  32747. saveMenus (names, menus, prefix + "-" + name + ".png");
  32748. };
  32749. check ("the dock shows the follow switch for the loop track", dock->followShownForCheck());
  32750. shots ("follow-on");
  32751. {
  32752. int clip = -1;
  32753. for (int i = 0; i < (int) offline.getSong().playlist.size() && clip < 0; ++i)
  32754. if (offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  32755. clip = i;
  32756. const auto menu = playlist.getClipMenuForSnapshot (clip);
  32757. bool follow = false, keyItem = false;
  32758. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  32759. {
  32760. follow = follow || (it.getItem().text.startsWith (lynx::tr ("Follow the project key")) && it.getItem().isTicked);
  32761. keyItem = keyItem || it.getItem().text.startsWith (lynx::tr ("Loop key"));
  32762. }
  32763. check ("the clip menu has Follow the project key (ticked) and Loop key", follow && keyItem);
  32764. menuShot (menu, lynx::tr ("Audio clip"), lynx::tr ("Loop key"), "menu-clip-key");
  32765. }
  32766. dock->clickFollowForCheck(); // off: back to its own key
  32767. offline.dispatchPendingMessages();
  32768. {
  32769. float pitch = 99.0f;
  32770. bool following = true;
  32771. for (const auto& c : offline.getSong().playlist)
  32772. if (c.kind == lynx::ClipKind::audio && c.track == loopTrack)
  32773. pitch = c.pitch, following = c.followKey;
  32774. check ("switched off: the loop plays in its own key (pitch 0)", ! following && std::abs (pitch) < 1.0e-6f);
  32775. }
  32776. shots ("follow-off");
  32777. dock->clickFollowForCheck();
  32778. offline.dispatchPendingMessages();
  32779. // --- an instrument track from the tile: a pattern to write into, the Editor tab ------------------------------
  32780. {
  32781. st::Request q;
  32782. q.kind = st::Kind::instrument;
  32783. q.name = "Keys";
  32784. lynx::ChannelDef synth;
  32785. synth.instrument = lynx::InstrumentKind::synth;
  32786. q.channel = synth;
  32787. q.emptyBars = 4;
  32788. st::Result r;
  32789. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  32790. offline.dispatchPendingMessages();
  32791. check ("the new Instrument track has an empty 4-bar pattern on it", r.ok() && r.pattern >= 0
  32792. && st::patternOf (offline.getSong(), r.track) == r.pattern
  32793. && offline.getSong().patterns[(std::size_t) r.pattern].notes.empty());
  32794. // a few notes, as the first clicks would write them (A minor: A C E, then G B D)
  32795. offline.editSong ([r] (lynx::Song& s) {
  32796. auto& p = s.patterns[(std::size_t) r.pattern];
  32797. const int keys[] { 57, 60, 64, 67, 71, 74, 69, 72 };
  32798. for (int i = 0; i < 8; ++i)
  32799. {
  32800. lynx::Note n;
  32801. n.channel = r.channels.front();
  32802. n.key = keys[i];
  32803. n.start = (std::int64_t) (i / 3) * lynx::ppq * 2 + (i % 3 == 0 ? 0 : 0);
  32804. n.length = lynx::ppq * 2;
  32805. n.velocity = 0.8f;
  32806. p.notes.push_back (n);
  32807. }
  32808. p.sortNotes();
  32809. });
  32810. offline.dispatchPendingMessages();
  32811. playlist.selectTrack (r.track);
  32812. simple->trackSelected (r.track);
  32813. offline.dispatchPendingMessages();
  32814. check ("the instrument track has the Keyboard and Editor tabs", dock->hasPlayTabsForCheck());
  32815. dock->setTab (lynx::SimpleDock::Tab::editor);
  32816. offline.dispatchPendingMessages();
  32817. check ("the Piano roll is docked in the Editor tab", dock->isEditorDocked());
  32818. check ("on the track's pattern", offline.getSong().currentPattern == r.pattern);
  32819. ui.getPianoRollForSnapshot().scrollToNotes(); // (done asynchronously when it docks)
  32820. shots ("editor");
  32821. dock->clickFoldForCheck (true); // "Only notes in key"
  32822. check ("Only notes in key folds the rows to A minor", ui.getPianoRollForSnapshot().isFoldedToScale());
  32823. ui.getPianoRollForSnapshot().scrollToNotes();
  32824. shots ("editor-in-key");
  32825. dock->clickFoldForCheck (false);
  32826. // --- the keyboard's modes ------------------------------------------------------------------------------
  32827. auto& keyboard = lynx::scalekeys::current();
  32828. const auto saved = keyboard;
  32829. keyboard = {};
  32830. keyboard.lockToKey = true;
  32831. dock->setTab (lynx::SimpleDock::Tab::keyboard);
  32832. if (auto* panel = dock->keyboardPanelForSnapshot())
  32833. {
  32834. lynx::refreshKeyboardPanel (*panel);
  32835. shots ("keys-locked");
  32836. keyboard.lockToKey = false;
  32837. keyboard.mode = lynx::scalekeys::Mode::scaleKeys;
  32838. lynx::refreshKeyboardPanel (*panel);
  32839. shots ("scale-keys");
  32840. keyboard.mode = lynx::scalekeys::Mode::chordPad;
  32841. keyboard.complexity = lynx::scalekeys::Complexity::seventh;
  32842. keyboard.strumMs = 40;
  32843. lynx::refreshKeyboardPanel (*panel);
  32844. shots ("chord-pad");
  32845. }
  32846. check ("the Keyboard tab shows the keyboard panel", dock->keyboardPanelForSnapshot() != nullptr);
  32847. // the same panel as the Touch keyboard window, each mode with a key / pad held
  32848. for (const auto& [mode, name, pressed] : { std::tuple { lynx::scalekeys::Mode::scaleKeys, juce::String ("window-scale-keys"), 4 },
  32849. std::tuple { lynx::scalekeys::Mode::chordPad, juce::String ("window-chord-pad"), 3 } })
  32850. {
  32851. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, mode, pressed, [ch = r.channels.front()] { return ch; });
  32852. panel->setSize (1100, 260);
  32853. for (float scale : { 1.0f, 2.0f })
  32854. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
  32855. if (mode == lynx::scalekeys::Mode::chordPad)
  32856. menuShot (lynx::chordPadMenuForSnapshot (*panel, 3), lynx::tr ("Edit chord"), lynx::tr ("Chord type"), "menu-chord-edit");
  32857. }
  32858. // the Chord pad on an FL Studio Mobile chord set (the default set's shape: C Dm Em F G Am B° C)
  32859. {
  32860. 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})");
  32861. check ("an FLM chord set reads as 8 chords (B diminished)", set.size() == 8 && set[6].quality == 3);
  32862. offline.editSong ([set] (lynx::Song& s) { s.keyboardChords = set; });
  32863. keyboard.projectChords = true;
  32864. keyboard.complexity = lynx::scalekeys::Complexity::triad;
  32865. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, lynx::scalekeys::Mode::chordPad, 5, [ch = r.channels.front()] { return ch; });
  32866. panel->setSize (1100, 260);
  32867. for (float scale : { 1.0f, 2.0f })
  32868. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), juce::String ("window-chord-set") + (scale > 1.0f ? "@2x" : ""));
  32869. }
  32870. // the typing keys in each mode (A minor; Z = the root)
  32871. {
  32872. const auto& song = offline.getSong();
  32873. lynx::scalekeys::Settings s;
  32874. s.mode = lynx::scalekeys::Mode::scaleKeys;
  32875. juce::String z;
  32876. for (const int typed : { 60, 62, 64, 65, 67, 69, 71, 72, 61 })
  32877. {
  32878. const auto n = lynx::scalekeys::typedNotes (song, s, typed, 60);
  32879. z << (n.empty() ? juce::String ("-") : juce::String (n.front())) << " ";
  32880. }
  32881. line ("Scale keys, typing C D E F G A B C C#: " + z);
  32882. check ("Scale keys: the white typing keys play A minor from A", z.trim() == "69 71 72 74 76 77 79 81 -");
  32883. s.mode = lynx::scalekeys::Mode::chordPad;
  32884. s.projectChords = false;
  32885. const auto pad = lynx::scalekeys::typedNotes (song, s, 60, 60);
  32886. check ("Chord pad: Z plays A minor (A C E)", pad == std::vector<int> { 69, 72, 76 });
  32887. }
  32888. keyboard = saved;
  32889. }
  32890. // --- the project round trip --------------------------------------------------------------------------------
  32891. {
  32892. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  32893. juce::String error;
  32894. const auto back = lynx::ProjectFile::fromJson (json, error);
  32895. bool same = back.has_value() && back->keyboardChords == offline.getSong().keyboardChords && back->playlist.size() == offline.getSong().playlist.size();
  32896. for (std::size_t i = 0; same && i < back->playlist.size(); ++i)
  32897. same = back->playlist[i].followKey == offline.getSong().playlist[i].followKey && back->playlist[i].keyShift == offline.getSong().playlist[i].keyShift
  32898. && back->playlist[i].pitch == offline.getSong().playlist[i].pitch;
  32899. for (std::size_t c = 0; same && c < back->channels.size(); ++c)
  32900. same = back->channels[c].sampler.loopKeyRoot == offline.getSong().channels[c].sampler.loopKeyRoot
  32901. && back->channels[c].sampler.loopKeySource == offline.getSong().channels[c].sampler.loopKeySource;
  32902. check ("follow, key moves, loop keys and the chord set survive .lynx", same);
  32903. }
  32904. dir.deleteRecursively();
  32905. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  32906. juce::File (prefix + "-report.txt").replaceWithText (report);
  32907. }
  32908. void runSimple190dgShot (const juce::String& prefix)
  32909. {
  32910. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32911. lynx::AudioEngine offline (false);
  32912. lynx::MainComponent ui (offline, false);
  32913. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  32914. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  32915. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  32916. const auto file = juce::File (prefix + "-" + name + ".png");
  32917. file.deleteFile();
  32918. juce::FileOutputStream out (file);
  32919. juce::PNGImageFormat().writeImageToStream (image, out);
  32920. };
  32921. juce::String report;
  32922. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  32923. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  32924. ui.selectTabForSnapshot (2);
  32925. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  32926. offline.dispatchPendingMessages();
  32927. auto* simple = ui.getSimpleWorkflowForSnapshot();
  32928. if (simple == nullptr)
  32929. {
  32930. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  32931. return;
  32932. }
  32933. simple->hideChooser();
  32934. offline.editSong ([] (lynx::Song& s) {
  32935. namespace st = lynx::simpletracks;
  32936. st::Request q;
  32937. q.kind = st::Kind::voice;
  32938. q.name = "Lead vocal";
  32939. st::addTrack (s, q);
  32940. q = {};
  32941. q.kind = st::Kind::instrument;
  32942. q.name = "Keys";
  32943. lynx::ChannelDef keys;
  32944. keys.instrument = lynx::InstrumentKind::synth;
  32945. q.channel = keys;
  32946. st::addTrack (s, q);
  32947. });
  32948. offline.dispatchPendingMessages();
  32949. simple->hideChooser();
  32950. auto& playlist = ui.getPlaylistForSnapshot();
  32951. int voiceTrack = -1, keysTrack = -1;
  32952. {
  32953. const auto& song = offline.getSong();
  32954. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  32955. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  32956. {
  32957. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  32958. voiceTrack = t;
  32959. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  32960. keysTrack = t;
  32961. }
  32962. }
  32963. check ("two Simple tracks (voice, keys)", voiceTrack >= 0 && keysTrack >= 0);
  32964. playlist.selectTrack (voiceTrack);
  32965. offline.dispatchPendingMessages();
  32966. auto* dock = simple->dockForSnapshot();
  32967. if (dock == nullptr)
  32968. {
  32969. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  32970. return;
  32971. }
  32972. const auto shots = [&] (const juce::String& name) {
  32973. offline.dispatchPendingMessages();
  32974. for (float scale : { 1.0f, 2.0f })
  32975. {
  32976. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  32977. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  32978. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  32979. }
  32980. };
  32981. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  32982. juce::StringArray names { title };
  32983. std::vector<juce::PopupMenu> menus { menu };
  32984. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  32985. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  32986. {
  32987. names.add (subTitle);
  32988. menus.push_back (*it.getItem().subMenu);
  32989. }
  32990. saveMenus (names, menus, prefix + "-" + name + ".png");
  32991. };
  32992. const auto insert = dock->insertForCheck();
  32993. // --- every one-knob effect as a card, each at a knob position of its own -------------------------------------
  32994. const float at[] { 0.0f, 0.55f, 0.40f, 0.70f, 0.30f, 0.60f, 0.45f, 0.35f, 0.80f };
  32995. for (int id = 1; id <= lynx::goals::count; ++id)
  32996. dock->addOneKnobForCheck (id);
  32997. offline.dispatchPendingMessages();
  32998. for (int id = 1; id <= lynx::goals::count; ++id)
  32999. dock->turnKnobForCheck (id - 1, at[id]);
  33000. offline.dispatchPendingMessages();
  33001. check ("eight one-knob cards on the insert", dock->cardCountForCheck() == 8 && dock->oneKnobCardsForCheck() == 8);
  33002. {
  33003. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  33004. bool turned = fx.size() == 8;
  33005. for (std::size_t i = 0; turned && i < fx.size(); ++i)
  33006. turned = lynx::goals::active (fx[i]) && std::abs (fx[i].goalAmount - at[i + 1]) < 1.0e-6f;
  33007. check ("each knob wrote its effect's parameters", turned);
  33008. }
  33009. shots ("effects-all");
  33010. offline.dispatchPendingMessages();
  33011. for (int card = 0; card < dock->cardCountForCheck(); ++card)
  33012. {
  33013. const auto area = dock->cardBoundsForSnapshot (card);
  33014. const auto name = juce::String (lynx::goals::name (card + 1)).toLowerCase();
  33015. check ("card " + juce::String (card + 1) + " (" + name + ") is on screen", ! area.isEmpty() && dock->getLocalBounds().contains (area));
  33016. for (float scale : { 1.0f, 2.0f })
  33017. writeImage (dock->createComponentSnapshot (area.expanded (4), true, scale), "card-" + name + (scale > 1.0f ? "@2x" : ""));
  33018. }
  33019. // --- a chain preset with Blend --------------------------------------------------------------------------------
  33020. if (const auto* preset = lynx::chains::find ("Canyon"))
  33021. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  33022. offline.dispatchPendingMessages();
  33023. dock->setBlendForCheck (0.6f);
  33024. offline.dispatchPendingMessages();
  33025. check ("preset Canyon with Blend 60 % (shown as edited)", offline.getSong().mixer[(std::size_t) insert].chainPreset == "Canyon"
  33026. && std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.6f) < 1.0e-6f
  33027. && ! lynx::chains::unchanged (offline.getSong(), insert));
  33028. shots ("effects-preset-blend");
  33029. // favourites: the track's preset starred; the menu lists it first
  33030. const auto favFile = lynx::SimpleDock::favouritesFile();
  33031. const auto hadFavourites = favFile.existsAsFile();
  33032. const auto oldFavourites = favFile.loadFileAsString();
  33033. lynx::SimpleDock::setFavouritePreset ("Canyon", true);
  33034. lynx::SimpleDock::setFavouritePreset ("Clear Voice", true);
  33035. lynx::SimpleDock::setFavouritePreset ("Canyon", true); // (twice: once in the list)
  33036. check ("two favourites kept, in order", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Canyon", "Clear Voice" });
  33037. {
  33038. bool first = false, toggle = false;
  33039. const auto menu = dock->presetMenuForSnapshot();
  33040. juce::PopupMenu::MenuItemIterator it (menu);
  33041. if (it.next())
  33042. first = it.getItem().subMenu != nullptr && it.getItem().text.contains (lynx::tr ("Favourites"));
  33043. for (juce::PopupMenu::MenuItemIterator all (menu); all.next();)
  33044. toggle = toggle || all.getItem().text == lynx::tr ("Remove \"{0}\" from favourites", { "Canyon" });
  33045. check ("the Preset menu starts with the favourites and offers to unstar the track's preset", first && toggle);
  33046. menuShot (menu, lynx::tr ("Preset"), juce::String::fromUTF8 ("\xe2\x98\x85 ") + lynx::tr ("Favourites"), "menu-preset-favourites");
  33047. }
  33048. lynx::SimpleDock::setFavouritePreset ("Canyon", false);
  33049. check ("unstarred", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Clear Voice" });
  33050. if (hadFavourites)
  33051. favFile.replaceWithText (oldFavourites);
  33052. else
  33053. favFile.deleteFile();
  33054. // --- the sound picker: a search, and the installed plugins -----------------------------------------------------
  33055. playlist.selectTrack (keysTrack);
  33056. offline.dispatchPendingMessages();
  33057. check ("the Keys track opens on its sound", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  33058. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::bass);
  33059. dock->setSearchForSnapshot ("sub");
  33060. offline.dispatchPendingMessages();
  33061. line ("search \"sub\" in Bass: " + juce::String (dock->soundRowsForCheck()) + " rows");
  33062. check ("a search narrows the category", dock->soundRowsForCheck() > 0 && dock->soundRowsForCheck() < (int) lynx::soundlib::filter (lynx::soundlib::builtIn(), lynx::soundlib::Category::bass).size());
  33063. shots ("picker-search");
  33064. dock->setSearchForSnapshot ({});
  33065. // a made-up list of installed plugins (nothing is scanned or loaded)
  33066. dock->setPluginsForSnapshot ({ { "VST3-demo-1", "Analog Mono", "Example Audio", "VST3", "Instrument|Synth" },
  33067. { "VST3-demo-2", "Grand Upright", "Example Audio", "VST3", "Instrument|Piano" },
  33068. { "VST3-demo-3", "Beat Kit 808", "Sample Lab", "VST3", "Instrument|Drum" },
  33069. { "CLAP-demo-4", "Orchestra Strings", "Sample Lab", "CLAP", "Instrument|Sampler" },
  33070. { "VST3-demo-5", "Wave Table One", "Example Audio", "VST3", "Instrument|Synth" },
  33071. { "VST-demo-6", "Sub Bass Machine", "Low End", "VST", "Synth" },
  33072. { "VST3-demo-7", "Sample Player", "Sample Lab", "VST3", "Instrument|Sampler" } });
  33073. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::synths);
  33074. offline.dispatchPendingMessages();
  33075. check ("My plugins: the generic synths and samplers in their own category (" + juce::String (dock->soundRowsForCheck()) + " of 7)", dock->soundRowsForCheck() == 3);
  33076. shots ("picker-plugins");
  33077. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  33078. juce::File (prefix + "-report.txt").replaceWithText (report);
  33079. }
  33080. // LYNX --simple190jcshot prefix (round 190jc, design190ia slices 5, 14, 15, 22, 24 + Large controls): the Simple
  33081. // layout's tracks (only real rows, the round "+", M S, type icons, the track-colour volume and clips; muted, soloed,
  33082. // selected), the drop lane idle and lit, the dock (close X, icon tabs, a lone tab, the sound picker, the keyboard's
  33083. // keycaps and octave capsule, effect cards), the pads in all 8 colours (label contrast measured), the chooser,
  33084. // starter beats, Finish, the tour card beside its ring with the beacon (Animations on / off), and Large controls;
  33085. // windows at 1x and 2x, and a text report of the checks
  33086. void runSimple190jcShot (const juce::String& prefix)
  33087. {
  33088. namespace st = lynx::simpletracks;
  33089. namespace sp = lynx::simplepads;
  33090. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33091. lynx::AudioEngine offline (false);
  33092. lynx::MainComponent ui (offline, false);
  33093. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  33094. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  33095. ui.setVisible (true);
  33096. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  33097. const auto file = juce::File (prefix + "-" + name + ".png");
  33098. file.deleteFile();
  33099. juce::FileOutputStream out (file);
  33100. juce::PNGImageFormat().writeImageToStream (image, out);
  33101. };
  33102. juce::String report;
  33103. const auto line = [&report, &prefix] (const juce::String& text) {
  33104. report << text << "\n";
  33105. juce::File (prefix + "-report.txt").replaceWithText (report);
  33106. };
  33107. const auto check = [&line] (const juce::String& what, bool ok) { line ((ok ? "OK " : "ERROR ") + what); };
  33108. const auto settle = [&] {
  33109. for (int k = 0; k < 3; ++k)
  33110. offline.dispatchPendingMessages();
  33111. };
  33112. const auto whole = [&] (const juce::String& name, bool twoX = true) {
  33113. settle();
  33114. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name);
  33115. if (twoX)
  33116. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 2.0f), name + "@2x");
  33117. };
  33118. ui.selectTabForSnapshot (2);
  33119. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  33120. settle();
  33121. auto* simple = ui.getSimpleWorkflowForSnapshot();
  33122. auto& playlist = ui.getPlaylistForSnapshot();
  33123. if (simple == nullptr)
  33124. {
  33125. line ("ERROR no Simple workflow");
  33126. return;
  33127. }
  33128. // an empty project: the drop lane alone, the round "+"
  33129. offline.setSong ([] {
  33130. lynx::Song s;
  33131. s.mixer = lynx::Song::defaultMixer();
  33132. return s;
  33133. }());
  33134. settle();
  33135. simple->hideChooser();
  33136. whole ("empty");
  33137. check ("an empty song shows one row (the drop lane), with the round +", st::rowsShown (offline.getSong(), 500) == 1 && ! playlist.simpleAddButtonForSnapshot().isEmpty());
  33138. // --- sounds ------------------------------------------------------------------------------------------------------
  33139. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190jc");
  33140. dir.deleteRecursively();
  33141. dir.createDirectory();
  33142. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  33143. wav.getParentDirectory().createDirectory();
  33144. juce::AudioBuffer<float> audio (1, frames);
  33145. for (int i = 0; i < frames; ++i)
  33146. audio.setSample (0, i, f (i));
  33147. juce::WavAudioFormat format;
  33148. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  33149. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  33150. {
  33151. out.release();
  33152. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  33153. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  33154. }
  33155. return wav;
  33156. };
  33157. const auto pi = juce::MathConstants<double>::pi;
  33158. juce::Random rnd (190);
  33159. const auto loop = writeWav (dir.getChildFile ("Vocal chop 100.wav"), 230400, [pi] (int i) {
  33160. const auto t = i / 48000.0, inBeat = std::fmod (t, 0.6);
  33161. 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)));
  33162. });
  33163. std::vector<juce::File> padSounds;
  33164. const char* padNames[] { "Kick", "Snare", "Hat", "Clap", "Chord stab", "Vox hey", "Perc", "Bass hit" };
  33165. for (int k = 0; k < 8; ++k)
  33166. padSounds.push_back (writeWav (dir.getChildFile (juce::String ("pads/") + padNames[k] + ".wav"), 12000 + 3000 * k, [&rnd, k] (int i) {
  33167. return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.6f * std::exp (-i / (600.0f + 500.0f * (float) k)));
  33168. }));
  33169. // --- tracks: a voice with a loop, keys with chords, drums, a bass take, a Sampler track --------------------------------
  33170. int vocal = -1, keys = -1, drums = -1, bass = -1;
  33171. offline.editSong ([&] (lynx::Song& s) {
  33172. st::Request q;
  33173. q.kind = st::Kind::audio;
  33174. q.name = "Vocal chop";
  33175. q.audioFile = loop.getFullPathName().toStdString();
  33176. q.audioLength = 8 * lynx::ppq;
  33177. q.audioBeats = 8.0f;
  33178. vocal = st::addTrack (s, q).track;
  33179. q = {};
  33180. q.kind = st::Kind::instrument;
  33181. q.name = "Keys";
  33182. lynx::ChannelDef synth;
  33183. synth.instrument = lynx::InstrumentKind::synth;
  33184. q.channel = synth;
  33185. lynx::Pattern chords;
  33186. for (int i = 0; i < 4; ++i)
  33187. for (int k : { 60, 64, 67 })
  33188. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  33189. q.pattern = chords;
  33190. const auto r = st::addTrack (s, q);
  33191. keys = r.track;
  33192. q = {};
  33193. q.kind = st::Kind::drums;
  33194. q.name = "Drums";
  33195. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  33196. {
  33197. lynx::ChannelDef c;
  33198. c.instrument = kind;
  33199. q.kit.push_back (c);
  33200. }
  33201. lynx::Pattern beat;
  33202. for (int step = 0; step < 16; step += 2)
  33203. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 2, 60 });
  33204. for (int step : { 0, 8 })
  33205. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 0, 60 });
  33206. q.pattern = beat;
  33207. q.fillBars = 4;
  33208. const auto d = st::addTrack (s, q);
  33209. drums = d.track;
  33210. q = {};
  33211. q.kind = st::Kind::bass;
  33212. q.name = "Bass";
  33213. bass = st::addTrack (s, q).track;
  33214. if (r.insert > 0)
  33215. {
  33216. s.mixer[(std::size_t) r.insert].volume = 0.55f;
  33217. s.mixer[(std::size_t) r.insert].pan = -0.4f;
  33218. s.mixer[(std::size_t) r.insert].solo = true;
  33219. }
  33220. if (d.insert > 0)
  33221. s.mixer[(std::size_t) d.insert].muted = true;
  33222. });
  33223. settle();
  33224. check ("the Sampler tile's track was added", simple->addPads());
  33225. settle();
  33226. const auto& song = offline.getSong();
  33227. int pads = -1;
  33228. for (int t = 0; t < (int) song.playlistTracks.size() && pads < 0; ++t)
  33229. if (st::kindOf (song, t) == st::Kind::pads)
  33230. pads = t;
  33231. lynx::ui::WaveformCache::getInstance()->find (loop.getFullPathName(), [&offline, &loop] { return offline.getSampleLibrary().load (loop.getFullPathName()); });
  33232. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  33233. simple->hideChooser();
  33234. playlist.selectTrack (keys);
  33235. settle();
  33236. const auto rows = st::rowsShown (song, 500);
  33237. line ("tracks: vocal " + juce::String (vocal) + " keys " + juce::String (keys) + " drums " + juce::String (drums) + " bass " + juce::String (bass)
  33238. + " pads " + juce::String (pads) + "; rows shown " + juce::String (rows));
  33239. check ("five tracks + the drop lane are the rows shown (no placeholder rows)", rows == 6);
  33240. whole ("tracks");
  33241. {
  33242. // the Simple Playlist's whole paint (its rows only, no placeholder rows): CPU ms per frame
  33243. juce::Image img (juce::Image::ARGB, juce::jmax (1, playlist.getWidth()), juce::jmax (1, playlist.getHeight()), true);
  33244. std::vector<double> ms;
  33245. for (int f = -3; f < 40; ++f)
  33246. {
  33247. const auto t0 = lynx::threadCpuSeconds();
  33248. {
  33249. juce::Graphics g (img);
  33250. playlist.paintEntireComponent (g, true);
  33251. }
  33252. if (f >= 0)
  33253. ms.push_back (1000.0 * (lynx::threadCpuSeconds() - t0));
  33254. }
  33255. std::sort (ms.begin(), ms.end());
  33256. line ("simple playlist " + juce::String (playlist.getWidth()) + "x" + juce::String (playlist.getHeight()) + " whole paint: median "
  33257. + juce::String (ms[ms.size() / 2], 3) + " ms, p90 " + juce::String (ms[ms.size() * 9 / 10], 3) + " ms");
  33258. }
  33259. playlist.setDropLaneHotForSnapshot (true);
  33260. whole ("droplane-hot", false);
  33261. playlist.setDropLaneHotForSnapshot (false);
  33262. // --- the dock ------------------------------------------------------------------------------------------------------
  33263. auto* dock = simple->dockForSnapshot();
  33264. if (dock == nullptr)
  33265. {
  33266. line ("ERROR no dock");
  33267. return;
  33268. }
  33269. const auto dockShots = [&] (const juce::String& name) {
  33270. settle();
  33271. for (float scale : { 1.0f, 2.0f })
  33272. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + (scale > 1.0f ? "@2x" : ""));
  33273. };
  33274. simple->trackSelected (keys);
  33275. dock->setTab (lynx::SimpleDock::Tab::instrument);
  33276. dockShots ("instrument");
  33277. whole ("window-dock-instrument", false);
  33278. dock->showKeyboard();
  33279. dockShots ("keyboard");
  33280. simple->trackSelected (vocal);
  33281. settle();
  33282. check ("an audio track's dock has one tab (drawn as a title)", dock->getTab() == lynx::SimpleDock::Tab::effects);
  33283. dockShots ("audio-lone-tab");
  33284. simple->showEffectsOfInsert (st::insertOf (offline.getSong(), keys));
  33285. dock->addOneKnobForCheck (1);
  33286. dock->addOneKnobForCheck (2);
  33287. dockShots ("effects");
  33288. // --- pads: 8 sounds in the 8 colours --------------------------------------------------------------------------------
  33289. if (pads >= 0)
  33290. {
  33291. simple->trackSelected (pads);
  33292. settle();
  33293. for (int p = 0; p < 8; ++p)
  33294. dock->padsLoadForCheck (p, padSounds[(std::size_t) p]);
  33295. offline.editSong ([pads] (lynx::Song& s) {
  33296. for (int p = 0; p < 8; ++p)
  33297. if (const auto c = sp::padChannel (s, pads, p); c >= 0)
  33298. s.channels[(std::size_t) c].simplePad.colour = (std::uint8_t) (p + 1);
  33299. });
  33300. dock->padsSelectForCheck (4);
  33301. dock->padsUpdateForCheck();
  33302. dockShots ("pads");
  33303. dock->padsHitForCheck (2);
  33304. dockShots ("pads-hit");
  33305. whole ("window-pads", false);
  33306. // the labels' contrast on the 8 colours, unlit and lit (the same colours the page draws)
  33307. static const juce::uint32 palette[] { 0xffe5383b, 0xffe8833a, 0xffe2c044, 0xff5fbf6a, 0xff3fb6b0, 0xff4f8ee0, 0xff9a6fe0, 0xffe06aa8 };
  33308. float worst = 99.0f;
  33309. for (auto argb : palette)
  33310. for (bool lit : { false, true })
  33311. {
  33312. const auto fill = juce::Colour (argb).withMultipliedBrightness (lit ? 1.0f : 0.55f).withMultipliedSaturation (lit ? 1.0f : 0.8f);
  33313. const auto ratio = lynx::ui::simplelook::contrast (lynx::ui::simplelook::inkOn (fill), fill);
  33314. worst = juce::jmin (worst, ratio);
  33315. line ("pad " + juce::String::toHexString ((int) argb).substring (2) + (lit ? " lit " : " unlit") + ": label " + juce::String (ratio, 2) + ":1");
  33316. }
  33317. check ("pad labels >= 4.5:1 on all 8 colours, lit and unlit (worst " + juce::String (worst, 2) + ":1)", worst >= 4.5f);
  33318. }
  33319. // --- chooser, starters, Finish ---------------------------------------------------------------------------------------
  33320. simple->showChooser();
  33321. whole ("chooser");
  33322. simple->showStarterPageForSnapshot();
  33323. whole ("starters");
  33324. simple->hideChooser();
  33325. simple->showFinish();
  33326. whole ("finish");
  33327. simple->hideFinish();
  33328. // --- the tour: the card beside its ring, the beacon with Animations on and off -----------------------------------------
  33329. if (auto* tour = simple->tourForSnapshot())
  33330. {
  33331. simple->showWelcome();
  33332. settle();
  33333. tour->clickForSnapshot ("welcome.tour");
  33334. settle();
  33335. const auto ring = tour->ringForSnapshot();
  33336. const auto card = tour->cardBoundsForSnapshot();
  33337. const auto distance = juce::jmax (0, juce::jmax (card.getY() - ring.getBottom(), ring.getY() - card.getBottom()))
  33338. + juce::jmax (0, juce::jmax (card.getX() - ring.getRight(), ring.getX() - card.getRight()));
  33339. line ("tour step 1: ring " + ring.toString() + " card " + card.toString() + " gap " + juce::String (distance) + " px");
  33340. check ("the card sits beside its ring (<= 24 px)", ! ring.isEmpty() && distance <= 24 && ! card.intersects (ring));
  33341. check ("the beacon pulses after a step change (Animations on)", tour->pulsingForCheck());
  33342. tour->setPulseForSnapshot (0.5f);
  33343. whole ("tour-pulse-on", false);
  33344. lynx::ui::motion::enabled() = false;
  33345. tour->clickForSnapshot ("next");
  33346. settle();
  33347. check ("no pulse timer with Animations off", ! tour->pulsingForCheck());
  33348. tour->setPulseForSnapshot (0.0f);
  33349. whole ("tour-pulse-off", false);
  33350. lynx::ui::motion::enabled() = true;
  33351. tour->clickForSnapshot ("skip");
  33352. settle();
  33353. }
  33354. // --- Large controls ---------------------------------------------------------------------------------------------------
  33355. ui.setSimpleLargeControls (true);
  33356. simple->hideChooser();
  33357. playlist.selectTrack (keys);
  33358. settle();
  33359. whole ("large-tracks", false);
  33360. if (pads >= 0)
  33361. {
  33362. simple->trackSelected (pads);
  33363. dockShots ("large-pads");
  33364. }
  33365. ui.setSimpleLargeControls (false);
  33366. line ("done");
  33367. }
  33368. void runSimpleShot (const juce::String& prefix)
  33369. {
  33370. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33371. lynx::AudioEngine offline (false);
  33372. lynx::MainComponent ui (offline, false);
  33373. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  33374. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  33375. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  33376. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33377. file.deleteFile();
  33378. juce::FileOutputStream out (file);
  33379. juce::PNGImageFormat().writeImageToStream (image, out);
  33380. };
  33381. const auto write = [&ui, &writeImage] (const char* name) { writeImage (lynx::shot::snapshot (ui), name); };
  33382. // View › Layout style, with its submenu, as it is with `style` chosen
  33383. const auto viewMenu = [&ui] {
  33384. const auto names = ui.getMenuNamesForSnapshot();
  33385. const auto view = names.indexOf (lynx::tr ("View"));
  33386. return ui.getMenuForSnapshot (juce::jmax (0, view));
  33387. };
  33388. const auto saveStyleMenus = [&] (const juce::String& suffix) {
  33389. const auto view = viewMenu();
  33390. juce::StringArray names { lynx::tr ("View") };
  33391. std::vector<juce::PopupMenu> menus { view };
  33392. for (juce::PopupMenu::MenuItemIterator it (view); it.next();)
  33393. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Layout style"))
  33394. {
  33395. names.add (lynx::tr ("Layout style"));
  33396. menus.push_back (*it.getItem().subMenu);
  33397. }
  33398. saveMenus (names, menus, prefix + "-menu-" + suffix + ".png");
  33399. };
  33400. // Settings › General with `style` selected, and its style list
  33401. const auto saveSettings = [&] (lynx::layoutstyle::Style style, const char* name) {
  33402. lynx::SettingsHooks hooks;
  33403. hooks.getGeneral = [style] {
  33404. lynx::GeneralOptions o;
  33405. o.language = lynx::i18n::current();
  33406. o.layoutStyle = (int) style;
  33407. return o;
  33408. };
  33409. auto page = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general, false, hooks);
  33410. const auto image = lynx::shot::paint (*page, lynx::theme::panel, -1, juce::jmin (page->getHeight(), 420));
  33411. writeImage (image, name);
  33412. std::function<juce::ComboBox* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ComboBox* {
  33413. if (c.getComponentID() == "layoutStyle")
  33414. return dynamic_cast<juce::ComboBox*> (&c);
  33415. for (auto* child : c.getChildren())
  33416. if (auto* box = find (*child))
  33417. return box;
  33418. return nullptr;
  33419. };
  33420. if (auto* box = find (*page); box != nullptr && box->getRootMenu() != nullptr)
  33421. saveMenus (juce::StringArray { lynx::tr ("Layout style") }, std::vector<juce::PopupMenu> { *box->getRootMenu() },
  33422. prefix + "-" + name + "-list.png");
  33423. };
  33424. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  33425. ui.selectTabForSnapshot (2); // the Playlist panel, maximized (as --gridshot)
  33426. write ("pattern");
  33427. saveStyleMenus ("pattern");
  33428. saveSettings (lynx::layoutstyle::Style::pattern, "settings-pattern");
  33429. const auto madePattern = lynx::SimpleWorkflow::instances.load();
  33430. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  33431. saveStyleMenus ("cliplaunch");
  33432. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  33433. offline.dispatchPendingMessages();
  33434. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  33435. simple->showChooser(); // (an empty project opens on it by itself; the offline project may hold the default song)
  33436. write ("simple"); // the New track chooser (slice S3)
  33437. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  33438. {
  33439. simple->showStarterPageForSnapshot();
  33440. write ("simple-starter");
  33441. simple->hideChooser();
  33442. write ("simple-closed");
  33443. // round 190p: a loop keeps time. Two files with the same 4.8 s of audio dropped on the empty Simple timeline:
  33444. // "Guitar loop 100.wav" (2 bars at 100 BPM) lasts 2 bars at the project's tempo, "Guitar take.wav" plays at
  33445. // its own speed. Both are undone again, so the shots after this one are as they were.
  33446. {
  33447. const auto folder = juce::File (prefix + "-loops");
  33448. folder.createDirectory();
  33449. juce::StringArray files;
  33450. for (const auto* name : { "Guitar loop 100.wav", "Guitar take.wav" })
  33451. {
  33452. const auto file = folder.getChildFile (name);
  33453. file.deleteFile();
  33454. const auto rate = 44100.0;
  33455. const auto frames = (int) (4.8 * rate);
  33456. juce::AudioBuffer<float> audio (1, frames);
  33457. for (int i = 0; i < frames; ++i)
  33458. {
  33459. const auto t = (double) i / rate, inBeat = std::fmod (t, 0.6); // a plucked note on every beat at 100 BPM
  33460. audio.setSample (0, i, (float) (0.7 * std::exp (-inBeat * 7.0) * std::sin (juce::MathConstants<double>::twoPi * 196.0 * t)));
  33461. }
  33462. if (auto out = file.createOutputStream())
  33463. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0)))
  33464. {
  33465. out.release();
  33466. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  33467. }
  33468. files.add (file.getFullPathName());
  33469. }
  33470. simple->dropFiles (files, 0);
  33471. offline.dispatchPendingMessages();
  33472. // the clips' waveforms are analysed in the background and drawn once ready (a live window repaints by
  33473. // itself; one off-screen paint came too early and showed empty clips)
  33474. for (const auto& path : files)
  33475. lynx::ui::WaveformCache::getInstance()->find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  33476. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  33477. offline.dispatchPendingMessages();
  33478. write ("simple-loop");
  33479. const auto& song = offline.getSong();
  33480. juce::String report;
  33481. for (const auto& clip : song.playlist)
  33482. if (clip.kind == lynx::ClipKind::audio)
  33483. report << song.channels[(std::size_t) clip.channel].name << ": " << juce::String ((double) clip.length / lynx::ppq, 3) << " beats, stretch "
  33484. << juce::String (song.channels[(std::size_t) clip.channel].sampler.stretchBeats, 2) << "\n";
  33485. juce::File (prefix + "-loop.txt").replaceWithText ("tempo " + juce::String (song.bpm, 1) + "\n" + report);
  33486. for (int i = 0; i < files.size() && offline.canUndo(); ++i) // (one undo step per dropped file)
  33487. offline.undo();
  33488. offline.dispatchPendingMessages();
  33489. simple->hideChooser();
  33490. }
  33491. // round 190t, slice A: one click on a starter beat adds it, placed for four bars (undone again)
  33492. {
  33493. const auto clipsBefore = offline.getSong().playlist.size();
  33494. const auto tempoBefore = offline.getSong().bpm;
  33495. simple->clickStarterForSnapshot (1);
  33496. offline.dispatchPendingMessages();
  33497. write ("simple-starter-added");
  33498. const auto& song = offline.getSong();
  33499. juce::String report ("tempo " + juce::String (tempoBefore, 1) + " -> " + juce::String (song.bpm, 1) + "\n");
  33500. for (auto i = clipsBefore; i < song.playlist.size(); ++i)
  33501. report << "clip at beat " << juce::String ((double) song.playlist[i].start / lynx::ppq, 2) << ", " << juce::String ((double) song.playlist[i].length / lynx::ppq, 2)
  33502. << " beats, pattern " << song.playlist[i].pattern << ", track " << song.playlist[i].track << "\n";
  33503. juce::File (prefix + "-starter.txt").replaceWithText (report);
  33504. if (song.playlist.size() > clipsBefore && offline.canUndo())
  33505. offline.undo();
  33506. offline.dispatchPendingMessages();
  33507. simple->hideChooser();
  33508. }
  33509. // slice S4: the Simple headers with a few tracks (voice, instrument, drums, an audio file), some levels moved
  33510. offline.editSong ([] (lynx::Song& s) {
  33511. namespace st = lynx::simpletracks;
  33512. st::Request q;
  33513. q.kind = st::Kind::voice;
  33514. q.name = "Lead vocal";
  33515. st::addTrack (s, q);
  33516. q = {};
  33517. q.kind = st::Kind::instrument;
  33518. q.name = "Keys";
  33519. lynx::ChannelDef keys;
  33520. keys.instrument = lynx::InstrumentKind::synth;
  33521. q.channel = keys;
  33522. lynx::Pattern chords;
  33523. for (int i = 0; i < 4; ++i)
  33524. for (int k : { 60, 64, 67 })
  33525. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  33526. q.pattern = chords;
  33527. const auto r = st::addTrack (s, q);
  33528. q = {};
  33529. q.kind = st::Kind::drums;
  33530. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  33531. {
  33532. lynx::ChannelDef c;
  33533. c.instrument = kind;
  33534. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  33535. q.kit.push_back (c);
  33536. }
  33537. lynx::Pattern beat;
  33538. const auto hit = [&beat] (int step, int row) { beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, row, 60 }); };
  33539. for (int step = 0; step < 16; step += 2)
  33540. hit (step, 2); // hats on the 8ths, kick on 1 and 3, snare on 2 and 4
  33541. for (int step : { 0, 8 })
  33542. hit (step, 0);
  33543. for (int step : { 4, 12 })
  33544. hit (step, 1);
  33545. q.pattern = beat;
  33546. q.bpm = 96.0;
  33547. st::addTrack (s, q);
  33548. if (r.insert > 0)
  33549. {
  33550. s.mixer[(std::size_t) r.insert].volume = 0.55f;
  33551. s.mixer[(std::size_t) r.insert].pan = -0.4f;
  33552. s.mixer[(std::size_t) r.insert].solo = true;
  33553. }
  33554. });
  33555. offline.dispatchPendingMessages();
  33556. ui.getPlaylistForSnapshot().selectTrack (1);
  33557. write ("simple-tracks");
  33558. // round 190t, slice E: the backup status beside the title tools, in each of its states
  33559. {
  33560. const auto now = juce::Time::currentTimeMillis();
  33561. juce::String states;
  33562. int n = 0;
  33563. for (const auto& text : { lynx::MainComponent::simpleSaveStatusText (true, false, 0, now), lynx::MainComponent::simpleSaveStatusText (true, false, now - 5000, now),
  33564. lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now), lynx::MainComponent::simpleSaveStatusText (false, true, 0, now),
  33565. lynx::MainComponent::simpleSaveStatusText (false, false, 0, now) })
  33566. {
  33567. simple->setStatusForSnapshot (text);
  33568. offline.dispatchPendingMessages();
  33569. states << n << ": " << text << "\n";
  33570. // (round 190oo, CS-32: the status is the top bar's since round 190iv: its rows 0..74, not the title band)
  33571. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 74))),
  33572. ("status-" + juce::String (n++)).toRawUTF8());
  33573. }
  33574. juce::File (prefix + "-status.txt").replaceWithText (states);
  33575. simple->setStatusForSnapshot (lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now));
  33576. offline.dispatchPendingMessages();
  33577. write ("simple-status");
  33578. }
  33579. // round 190oo (design review 2): the top bar while the transport plays (CS-35: Play shows BandLab's Pause,
  33580. // Back-to-start becomes Stop; the offline engine does not play, so the main window's states are driven), and
  33581. // the LYNX extra O-4 (the project's name centred at the top, "Untitled" while it has none) at this size and at
  33582. // 1280 px, then off again
  33583. {
  33584. const auto topBar = [&ui] { return ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 80)); };
  33585. const auto nameWas = std::exchange (lynx::ui::simplelook::projectNameShown(), false); // (round 190qk: on by default)
  33586. ui.resized();
  33587. ui.transportForSnapshot (true, false);
  33588. writeImage (lynx::shot::snapshot (ui, topBar()), "topbar-playing");
  33589. ui.transportForSnapshot (false, false);
  33590. writeImage (lynx::shot::snapshot (ui, topBar()), "topbar-stopped");
  33591. lynx::ui::simplelook::projectNameShown() = true;
  33592. ui.resized();
  33593. writeImage (lynx::shot::snapshot (ui, topBar()), "topbar-project-name");
  33594. const auto wide = ui.getWidth(), tall = ui.getHeight();
  33595. ui.setSize (1280, tall);
  33596. offline.dispatchPendingMessages();
  33597. writeImage (lynx::shot::snapshot (ui, topBar()), "topbar-project-name-1280");
  33598. ui.setSize (wide, tall);
  33599. lynx::ui::simplelook::projectNameShown() = nameWas;
  33600. ui.resized();
  33601. offline.dispatchPendingMessages();
  33602. }
  33603. // slice S8: the Finish dock, empty, then with a look on the Master (Balanced, Normal, a little Tone)
  33604. simple->showFinish();
  33605. offline.dispatchPendingMessages();
  33606. write ("simple-finish-empty");
  33607. offline.editSongStructural ([] (lynx::Song& s) { lynx::looks::apply (s, lynx::MasterLookSettings { lynx::looks::balanced, 0.5f, { 1.5f, 0.0f, 1.0f }, -3.0f }); });
  33608. offline.dispatchPendingMessages();
  33609. simple->showFinish();
  33610. write ("simple-finish");
  33611. simple->hideFinish();
  33612. }
  33613. saveStyleMenus ("simple");
  33614. saveSettings (lynx::layoutstyle::Style::simple, "settings-simple");
  33615. // round 184a S11: the Key panel (no key, then an A minor riff and its guesses) and its menu
  33616. const auto toolbarShot = [&] (const char* name) {
  33617. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 80))), name);
  33618. };
  33619. toolbarShot ("key-none");
  33620. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-empty.png");
  33621. offline.editSong ([] (lynx::Song& s) {
  33622. if (s.channels.empty())
  33623. s.channels.resize (1);
  33624. if (s.patterns.empty())
  33625. s.patterns.emplace_back();
  33626. int t = 0;
  33627. for (int k : { 57, 60, 64, 67, 69, 67, 64, 60, 57, 59, 60, 62, 64, 62, 60, 59, 57, 57, 64, 45 })
  33628. {
  33629. lynx::Note n;
  33630. n.channel = 0;
  33631. n.key = k;
  33632. n.start = t * lynx::ppq / 2;
  33633. n.length = k == 57 || k == 45 ? lynx::ppq : lynx::ppq / 2;
  33634. s.patterns[0].notes.push_back (n);
  33635. ++t;
  33636. }
  33637. });
  33638. offline.dispatchPendingMessages();
  33639. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-guess.png");
  33640. const auto guesses = lynx::keyguess::guess (offline.getSong(), 3);
  33641. if (! guesses.empty())
  33642. offline.editSong ([k = guesses[0].key] (lynx::Song& s) { lynx::projectkey::set (s, k); });
  33643. offline.dispatchPendingMessages();
  33644. toolbarShot ("key-set");
  33645. write ("simple-key");
  33646. juce::String keyCounts;
  33647. for (const auto& g : guesses)
  33648. keyCounts << "guess " << lynx::projectkey::name (g.key) << " " << g.notesInScale << "/" << g.notes << " score " << g.score << "\n";
  33649. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, std::nullopt); });
  33650. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  33651. offline.dispatchPendingMessages();
  33652. toolbarShot ("key-pattern-toolbar");
  33653. write ("pattern-after");
  33654. // round 184a S17: the setup wizard with its Workflow choice — a first start (Pattern selected), then reopened in Simple
  33655. for (int style : { 0, 2 })
  33656. {
  33657. auto wizard = lynx::makeSetupWizardContent (offline, {}, {}, style, {});
  33658. auto image = lynx::shot::paint (*wizard);
  33659. writeImage (image, style == 0 ? "wizard-pattern" : "wizard-simple");
  33660. }
  33661. juce::File (prefix + "-counts.txt").replaceWithText ("simple workflows before " + juce::String (madeBefore) + ", in pattern workflow "
  33662. + juce::String (madePattern) + ", after " + juce::String (lynx::SimpleWorkflow::instances.load())
  33663. + "\nstyle after " + lynx::layoutstyle::id (ui.getLayoutStyle()) + "\n" + keyCounts);
  33664. }
  33665. void runLiveRackShot190hr (const juce::String& prefix)
  33666. {
  33667. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33668. lynx::AudioEngine offline (false);
  33669. lynx::MainComponent ui (offline, false);
  33670. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  33671. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  33672. const auto write = [&prefix, &ui, &offline] (const char* name) {
  33673. offline.dispatchPendingMessages();
  33674. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33675. file.deleteFile();
  33676. juce::FileOutputStream out (file);
  33677. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  33678. };
  33679. const auto writeView = [&prefix] (juce::Component& c, const char* name) {
  33680. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33681. file.deleteFile();
  33682. juce::FileOutputStream out (file);
  33683. juce::PNGImageFormat().writeImageToStream (lynx::shot::paint (c, lynx::theme::panel), out);
  33684. };
  33685. juce::String checks;
  33686. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  33687. const auto itemEnabled = [] (const juce::PopupMenu& menu, const juce::String& start) {
  33688. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  33689. if (it.getItem().text.startsWith (start))
  33690. return it.getItem().isEnabled ? 1 : 0;
  33691. return -1;
  33692. };
  33693. ui.setVisible (true);
  33694. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  33695. ui.setClipLaunchWorkflow (true);
  33696. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  33697. offline.editSong ([] (lynx::Song& s) {
  33698. if (s.channels.size() < 1)
  33699. s.channels.resize (1);
  33700. s.channels[0].name = "Lead";
  33701. s.channels[0].instrument = lynx::InstrumentKind::synth;
  33702. s.channels[0].mixerTrack = 2;
  33703. if (s.mixer.size() < 4)
  33704. s.mixer.resize (4);
  33705. s.mixer[2].name = "Lead";
  33706. s.mixer[2].effects.clear();
  33707. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::delay })
  33708. s.mixer[2].effects.push_back (lynx::makeEffectSlot (kind));
  33709. while (s.patterns.size() < 1)
  33710. s.patterns.emplace_back();
  33711. lynx::Note note;
  33712. note.channel = 0;
  33713. note.key = 60;
  33714. s.patterns[0].notes = { note };
  33715. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  33716. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  33717. s.playlistTracks[1].name = "Lead";
  33718. lynx::Clip clip;
  33719. clip.pattern = 0;
  33720. clip.length = 4 * lynx::ppq;
  33721. lynx::launcher::setClip (s, 1, 0, clip);
  33722. }, false);
  33723. offline.dispatchPendingMessages();
  33724. auto* detail = ui.getDetailViewForSnapshot();
  33725. if (detail == nullptr)
  33726. {
  33727. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  33728. return;
  33729. }
  33730. detail->showSelection (1, 0);
  33731. detail->setPage (lynx::DetailView::Page::devices);
  33732. detail->selectCardForCheck (0); // the instrument
  33733. write ("01-devices");
  33734. auto menu = detail->cardMenuForSnapshot (0);
  33735. saveMenus (juce::StringArray { "Instrument" }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-instrument-menu.png");
  33736. check ("instrument menu: Group on, Ungroup off", itemEnabled (menu, lynx::tr ("Group")) == 1 && itemEnabled (menu, lynx::tr ("Ungroup")) == 0);
  33737. // Ctrl+G: the synth into an Instrument Rack (the card becomes the rack's)
  33738. check ("Ctrl+G groups the instrument into an Instrument Rack", detail->groupCardForCheck (0, false));
  33739. const auto& grouped = offline.getSong().channels[0];
  33740. check ("the channel keeps its insert and the rack holds the synth",
  33741. grouped.mixerTrack == 2 && lynx::rack::isRack (grouped) && lynx::rack::rackOf (grouped.patcher)->kind == lynx::RackDoc::Kind::instrument
  33742. && lynx::rack::devices (*lynx::rack::rackOf (grouped.patcher), 0).size() == 1);
  33743. detail->selectCardForCheck (0);
  33744. write ("03-grouped");
  33745. menu = detail->cardMenuForSnapshot (0);
  33746. saveMenus (juce::StringArray { "Instrument Rack" }, std::vector<juce::PopupMenu> { menu }, prefix + "-04-rack-menu.png");
  33747. check ("rack menu: Ungroup on, Save as Live rack preset", itemEnabled (menu, lynx::tr ("Ungroup")) == 1
  33748. && itemEnabled (menu, lynx::tr ("Save as Live rack preset (.adg)...")) == 1);
  33749. check ("Ctrl+Shift+G ungroups it", detail->groupCardForCheck (0, true) && offline.getSong().channels[0].instrument == lynx::InstrumentKind::synth);
  33750. write ("05-ungrouped");
  33751. // a rack's view: Live's Save Preset button at the foot of the strip, the drop area
  33752. offline.editSong ([] (lynx::Song& s) {
  33753. auto rack = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  33754. lynx::rack::rackOf (rack.patcher)->showDevices = true;
  33755. s.mixer[3].effects = { rack };
  33756. }, false);
  33757. offline.dispatchPendingMessages();
  33758. {
  33759. auto view = lynx::RackWindows::makeSlotView (offline, 3, 0, true);
  33760. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  33761. writeView (*view, "06-rack-empty");
  33762. lynx::PatchNode fx;
  33763. fx.effect = lynx::makeEffectSlot (lynx::EffectKind::delay);
  33764. const juce::Point<int> inDevices { view->getWidth() - 30, view->getHeight() / 2 };
  33765. check ("an effect dropped on the chain goes in", view->dropNodeForCheck (fx, inDevices));
  33766. lynx::PatchNode synth;
  33767. synth.generator = true;
  33768. synth.channel.instrument = lynx::InstrumentKind::synth;
  33769. check ("an instrument dropped on an Audio Effect Rack is refused", ! view->dropNodeForCheck (synth, inDevices));
  33770. const auto* r = lynx::rack::rackOf (offline.getSong().mixer[3].effects[0].patcher);
  33771. check ("the chain holds one device", r != nullptr && lynx::rack::devices (*r, 0).size() == 1);
  33772. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  33773. writeView (*view, "07-rack-after-drop");
  33774. // the rack as a Live preset and back
  33775. const auto out = lynx::exportLiveRackPreset (offline.getSong().mixer[3].effects[0].patcher, "Shot Rack");
  33776. check ("Save as .adg writes Live's preset form", out.xml.find ("<GroupDevicePreset>") != std::string::npos
  33777. && out.xml.find ("<AudioEffectBranchPreset ") != std::string::npos);
  33778. const auto back = lynx::importLiveDevicePreset (out.bytes);
  33779. check ("the .adg reads back as the rack", back.has_value() && lynx::rack::isRack (back->slot)
  33780. && lynx::rack::rackOf (back->slot.patcher)->chains.size() == 1);
  33781. }
  33782. // Live's own .adg (Core Library, read-only): before round 190hr it opened without chains
  33783. const juce::File live ("C:/ProgramData/Ableton/Live 12 Trial/Resources/Core Library/Racks/Audio Effect Racks/Distortion/Smokey Water.adg");
  33784. const juce::File liveWsl ("/mnt/c/ProgramData/Ableton/Live 12 Trial/Resources/Core Library/Racks/Audio Effect Racks/Distortion/Smokey Water.adg");
  33785. const auto adg = live.existsAsFile() ? live : liveWsl;
  33786. if (adg.existsAsFile())
  33787. {
  33788. juce::MemoryBlock data;
  33789. adg.loadFileAsData (data);
  33790. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  33791. auto p = lynx::importLiveDevicePreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()));
  33792. check ("Live's Smokey Water.adg opens with its chain and devices", p.has_value() && lynx::rack::isRack (p->slot)
  33793. && ! lynx::rack::rackOf (p->slot.patcher)->chains.empty()
  33794. && lynx::rack::devices (*lynx::rack::rackOf (p->slot.patcher), 0).size() >= 3);
  33795. if (p)
  33796. {
  33797. lynx::rack::rackOf (p->slot.patcher)->showDevices = true;
  33798. lynx::rack::rackOf (p->slot.patcher)->showChains = true;
  33799. offline.editSong ([slot = p->slot] (lynx::Song& s) { s.mixer[3].effects = { slot }; }, false);
  33800. offline.dispatchPendingMessages();
  33801. auto view = lynx::RackWindows::makeSlotView (offline, 3, 0, true);
  33802. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  33803. writeView (*view, "08-live-adg-smokey-water");
  33804. }
  33805. }
  33806. else
  33807. checks << "skip Live's Core Library is not on this machine\n";
  33808. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33809. }
  33810. void runHelixShot190ja (const juce::String& prefix, const juce::String& preset)
  33811. {
  33812. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33813. lynx::AudioEngine offline (false);
  33814. lynx::MainComponent ui (offline, false);
  33815. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  33816. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  33817. juce::String checks;
  33818. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  33819. const auto write = [&prefix, &ui, &offline] (const char* name) {
  33820. offline.dispatchPendingMessages();
  33821. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33822. file.deleteFile();
  33823. juce::FileOutputStream out (file);
  33824. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  33825. };
  33826. // the Helix channel: Helix's defaults, or a Live Wavetable preset's values through the .als import's own mapping
  33827. lynx::ChannelDef helix;
  33828. helix.instrument = lynx::InstrumentKind::helix;
  33829. helix.name = "Helix";
  33830. if (preset.isNotEmpty())
  33831. {
  33832. juce::MemoryBlock raw;
  33833. juce::File (preset).loadFileAsData (raw);
  33834. juce::MemoryInputStream in (raw, false);
  33835. juce::GZIPDecompressorInputStream gz (&in, false, juce::GZIPDecompressorInputStream::gzipFormat);
  33836. const auto text = juce::File (preset).getFileExtension() == ".adv" ? gz.readEntireStreamAsString() : juce::String();
  33837. lynx::xml::Document doc;
  33838. lynx::alsdev::Notes notes;
  33839. const auto parsed = doc.parse (text.toStdString());
  33840. auto device = parsed ? doc.root().child ("InstrumentVector") : lynx::xml::Element();
  33841. check ("preset read: " + preset, parsed && (bool) device && lynx::alsdev::wavetableToHelix (device, helix, notes));
  33842. helix.name = juce::File (preset).getFileNameWithoutExtension().toStdString();
  33843. }
  33844. ui.setVisible (true);
  33845. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  33846. ui.setClipLaunchWorkflow (true);
  33847. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  33848. offline.editSong ([&helix] (lynx::Song& s) {
  33849. if (s.channels.empty())
  33850. s.channels.resize (1);
  33851. helix.mixerTrack = s.channels[0].mixerTrack;
  33852. s.channels[0] = helix;
  33853. while (s.patterns.empty())
  33854. s.patterns.emplace_back();
  33855. lynx::Note note;
  33856. note.channel = 0;
  33857. note.key = 60;
  33858. s.patterns[0].name = "Chords";
  33859. s.patterns[0].notes = { note };
  33860. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  33861. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  33862. s.playlistTracks[0].name = helix.name;
  33863. lynx::Clip clip;
  33864. clip.pattern = 0;
  33865. clip.length = 4 * lynx::ppq;
  33866. lynx::launcher::setClip (s, 0, 0, clip);
  33867. }, false);
  33868. offline.dispatchPendingMessages();
  33869. auto* detail = ui.getDetailViewForSnapshot();
  33870. check ("detail view", detail != nullptr);
  33871. if (detail != nullptr)
  33872. {
  33873. detail->showSelection (0, 0);
  33874. detail->setPage (lynx::DetailView::Page::devices);
  33875. offline.dispatchPendingMessages();
  33876. write ("01-device");
  33877. struct View
  33878. {
  33879. const char* name;
  33880. int modTab, source, osc;
  33881. };
  33882. 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 },
  33883. View { "06-lfo1", 0, 3, 0 }, View { "07-osc2", 0, 0, 1 } })
  33884. {
  33885. check (juce::String ("Helix card shown for ") + v.name, lynx::helixcards::showView (*detail, v.modTab, v.source, v.osc) > 0);
  33886. write (v.name);
  33887. }
  33888. lynx::helixcards::showView (*detail, 0, 0, 0);
  33889. }
  33890. // the Pattern layout: the channel window's page alone
  33891. {
  33892. auto page = lynx::makeHelixEditor (offline, [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; }, 0);
  33893. const auto file = lynx::shot::file (juce::File (prefix + "-10-window.png"));
  33894. file.deleteFile();
  33895. juce::FileOutputStream out (file);
  33896. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*page), out);
  33897. check ("channel window page", page->getWidth() > 0);
  33898. }
  33899. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33900. }
  33901. void runHelixShot190oc (const juce::String& prefix)
  33902. {
  33903. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33904. lynx::AudioEngine offline (false);
  33905. juce::String checks;
  33906. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  33907. const auto& bank = lynx::banks::bankOf (lynx::InstrumentKind::helix);
  33908. const auto load = [&] (const juce::String& name) {
  33909. int index = -1;
  33910. for (int b = 0; b < (int) bank.size(); ++b)
  33911. if (juce::String (bank[(std::size_t) b].name) == name)
  33912. index = b;
  33913. check ("preset " + name, index >= 0);
  33914. offline.editSong ([index] (lynx::Song& s) {
  33915. if (s.channels.empty())
  33916. s.channels.resize (1);
  33917. lynx::ChannelDef c;
  33918. c.instrument = lynx::InstrumentKind::helix;
  33919. c.name = "Helix";
  33920. c.mixerTrack = s.channels[0].mixerTrack;
  33921. if (auto loaded = lynx::banks::withPreset (c, std::max (index, 0)))
  33922. c = *loaded;
  33923. s.channels[0] = c;
  33924. }, false);
  33925. offline.dispatchPendingMessages();
  33926. };
  33927. const auto locate = [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; };
  33928. const auto save = [&prefix, &offline] (juce::Component& c, const char* name) {
  33929. offline.dispatchPendingMessages();
  33930. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33931. file.deleteFile();
  33932. juce::FileOutputStream out (file);
  33933. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  33934. };
  33935. const auto paintCost = [&checks] (juce::Component& c, const char* what) {
  33936. double best = 1.0e9;
  33937. for (int run = 0; run < 3; ++run)
  33938. {
  33939. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  33940. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  33941. for (int f = 0; f < 30; ++f)
  33942. {
  33943. juce::Graphics g (image);
  33944. c.paintEntireComponent (g, false);
  33945. }
  33946. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 30.0);
  33947. }
  33948. checks << "paint " << what << " " << juce::String (best, 3) << " ms per frame (" << c.getWidth() << " x " << c.getHeight() << ")\n";
  33949. };
  33950. // each part of a window alone (the strip, the device), its paint cost
  33951. const auto parts = [&checks] (juce::Component& page) {
  33952. for (int i = 0; i < page.getNumChildComponents(); ++i)
  33953. {
  33954. auto* child = page.getChildComponent (i);
  33955. juce::Image image (juce::Image::ARGB, std::max (1, child->getWidth()), std::max (1, child->getHeight()), true);
  33956. double best = 1.0e9;
  33957. for (int run = 0; run < 3; ++run)
  33958. {
  33959. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  33960. for (int f = 0; f < 10; ++f)
  33961. {
  33962. juce::Graphics g (image);
  33963. child->paintEntireComponent (g, false);
  33964. }
  33965. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 10.0);
  33966. }
  33967. checks << " part " << juce::String (best, 3) << " ms " << typeid (*child).name() << " " << child->getBounds().toString() << "\n";
  33968. }
  33969. };
  33970. // the channel window (Pattern layout, LYNX's look): Helix+'s strip with round 4's row
  33971. load ("Grain Swarm");
  33972. {
  33973. auto page = lynx::makeHelixEditor (offline, locate, 0);
  33974. check ("window page holds the six strip rows", page->getHeight() >= lynx::helixDeviceHeight + 16 + 446);
  33975. save (*page, "01-window-grain-swarm");
  33976. paintCost (*page, "window (Grain Swarm)");
  33977. }
  33978. load ("Spectral Ensemble");
  33979. {
  33980. auto page = lynx::makeHelixEditor (offline, locate, 0);
  33981. save (*page, "02-window-spectral-ensemble");
  33982. paintCost (*page, "window (Spectral Ensemble)");
  33983. parts (*page);
  33984. }
  33985. load ("Frozen Choir");
  33986. {
  33987. auto page = lynx::makeHelixEditor (offline, locate, 0);
  33988. save (*page, "03-window-frozen-choir");
  33989. }
  33990. load ("Triple Stack");
  33991. {
  33992. auto page = lynx::makeHelixEditor (offline, locate, 0);
  33993. save (*page, "04-window-triple");
  33994. paintCost (*page, "window (Triple Stack)");
  33995. parts (*page);
  33996. }
  33997. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33998. }
  33999. void runHelixShot190mt (const juce::String& prefix)
  34000. {
  34001. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34002. lynx::AudioEngine offline (false);
  34003. juce::String checks;
  34004. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  34005. const auto& bank = lynx::banks::bankOf (lynx::InstrumentKind::helix);
  34006. const auto load = [&] (const juce::String& name) {
  34007. int index = -1;
  34008. for (int b = 0; b < (int) bank.size(); ++b)
  34009. if (juce::String (bank[(std::size_t) b].name) == name)
  34010. index = b;
  34011. check ("preset " + name, index >= 0);
  34012. offline.editSong ([index] (lynx::Song& s) {
  34013. if (s.channels.empty())
  34014. s.channels.resize (1);
  34015. lynx::ChannelDef c;
  34016. c.instrument = lynx::InstrumentKind::helix;
  34017. c.name = "Helix";
  34018. c.mixerTrack = s.channels[0].mixerTrack;
  34019. if (auto loaded = lynx::banks::withPreset (c, std::max (index, 0)))
  34020. c = *loaded;
  34021. s.channels[0] = c;
  34022. }, false);
  34023. offline.dispatchPendingMessages();
  34024. };
  34025. const auto locate = [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; };
  34026. const auto save = [&prefix, &offline] (juce::Component& c, const char* name) {
  34027. offline.dispatchPendingMessages();
  34028. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  34029. file.deleteFile();
  34030. juce::FileOutputStream out (file);
  34031. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  34032. };
  34033. const auto paintCost = [&checks] (juce::Component& c, const char* what) {
  34034. double best = 1.0e9;
  34035. for (int run = 0; run < 3; ++run)
  34036. {
  34037. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  34038. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  34039. for (int f = 0; f < 30; ++f)
  34040. {
  34041. juce::Graphics g (image);
  34042. c.paintEntireComponent (g, false);
  34043. }
  34044. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 30.0);
  34045. }
  34046. checks << "paint " << what << " " << juce::String (best, 3) << " ms per frame (" << c.getWidth() << " x " << c.getHeight() << ")\n";
  34047. };
  34048. // the channel window (Pattern layout, LYNX's look): Helix+'s strip with round 3's row
  34049. load ("Grain Cloud");
  34050. {
  34051. auto page = lynx::makeHelixEditor (offline, locate, 0);
  34052. check ("window page holds the five strip rows", page->getHeight() >= lynx::helixDeviceHeight + 16 + 370);
  34053. save (*page, "01-window-granular");
  34054. paintCost (*page, "window (Grain Cloud)");
  34055. check ("Matrix tab", lynx::helixcards::showView (*page, 1, 0, 0) == 1);
  34056. save (*page, "04-matrix-granular");
  34057. }
  34058. load ("Frozen Choir");
  34059. {
  34060. auto page = lynx::makeHelixEditor (offline, locate, 0);
  34061. save (*page, "02-window-spectral");
  34062. }
  34063. load ("Spectral Glass");
  34064. {
  34065. auto page = lynx::makeHelixEditor (offline, locate, 0);
  34066. save (*page, "03-window-glass");
  34067. }
  34068. // the same preset as 190ml's first picture (the side by side)
  34069. load ("Triple Stack");
  34070. {
  34071. auto page = lynx::makeHelixEditor (offline, locate, 0);
  34072. save (*page, "05-window-triple");
  34073. paintCost (*page, "window (Triple Stack)");
  34074. for (int i = 0; i < page->getNumChildComponents(); ++i) // (each part alone)
  34075. {
  34076. auto* child = page->getChildComponent (i);
  34077. juce::Image image (juce::Image::ARGB, std::max (1, child->getWidth()), std::max (1, child->getHeight()), true);
  34078. double best = 1.0e9;
  34079. for (int run = 0; run < 3; ++run)
  34080. {
  34081. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  34082. for (int f = 0; f < 10; ++f)
  34083. {
  34084. juce::Graphics g (image);
  34085. child->paintEntireComponent (g, false);
  34086. }
  34087. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 10.0);
  34088. }
  34089. checks << " part " << juce::String (best, 3) << " ms " << typeid (*child).name() << " " << child->getBounds().toString() << "\n";
  34090. }
  34091. }
  34092. // the Clip-launch layout's Device View card (Live's look) with its Helix+ panel (Granular / Spectral discs)
  34093. load ("Frozen Choir");
  34094. {
  34095. lynx::MainComponent ui (offline, false);
  34096. ui.setSize (2560, 1080);
  34097. ui.setVisible (true);
  34098. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  34099. ui.setClipLaunchWorkflow (true);
  34100. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  34101. offline.editSong ([] (lynx::Song& s) {
  34102. while (s.patterns.empty())
  34103. s.patterns.emplace_back();
  34104. lynx::Note note;
  34105. note.channel = 0;
  34106. note.key = 60;
  34107. s.patterns[0].name = "Choir";
  34108. s.patterns[0].notes = { note };
  34109. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  34110. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  34111. s.playlistTracks[0].name = "Helix";
  34112. lynx::Clip clip;
  34113. clip.pattern = 0;
  34114. clip.length = 4 * lynx::ppq;
  34115. lynx::launcher::setClip (s, 0, 0, clip);
  34116. }, false);
  34117. offline.dispatchPendingMessages();
  34118. auto* detail = ui.getDetailViewForSnapshot();
  34119. check ("detail view", detail != nullptr);
  34120. if (detail != nullptr)
  34121. {
  34122. detail->showSelection (0, 0);
  34123. detail->setPage (lynx::DetailView::Page::devices);
  34124. offline.dispatchPendingMessages();
  34125. check ("card's Helix+ panel", lynx::helixcards::showPlusInCard (*detail, true) == 1);
  34126. offline.dispatchPendingMessages();
  34127. save (ui, "06-card-plus");
  34128. checks << "detail " << detail->getScreenBounds().translated (-ui.getScreenX(), -ui.getScreenY()).toString() << "\n";
  34129. lynx::helixcards::showPlusInCard (*detail, false);
  34130. }
  34131. }
  34132. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  34133. }
  34134. void runHelixShot190ml (const juce::String& prefix)
  34135. {
  34136. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34137. lynx::AudioEngine offline (false);
  34138. juce::String checks;
  34139. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  34140. const auto& bank = lynx::banks::bankOf (lynx::InstrumentKind::helix);
  34141. const auto load = [&] (const juce::String& name) {
  34142. int index = -1;
  34143. for (int b = 0; b < (int) bank.size(); ++b)
  34144. if (juce::String (bank[(std::size_t) b].name) == name)
  34145. index = b;
  34146. check ("preset " + name, index >= 0);
  34147. offline.editSong ([index] (lynx::Song& s) {
  34148. if (s.channels.empty())
  34149. s.channels.resize (1);
  34150. lynx::ChannelDef c;
  34151. c.instrument = lynx::InstrumentKind::helix;
  34152. c.name = "Helix";
  34153. c.mixerTrack = s.channels[0].mixerTrack;
  34154. if (auto loaded = lynx::banks::withPreset (c, std::max (index, 0)))
  34155. c = *loaded;
  34156. s.channels[0] = c;
  34157. }, false);
  34158. offline.dispatchPendingMessages();
  34159. };
  34160. const auto locate = [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; };
  34161. const auto save = [&prefix, &offline] (juce::Component& c, const char* name) {
  34162. offline.dispatchPendingMessages();
  34163. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  34164. file.deleteFile();
  34165. juce::FileOutputStream out (file);
  34166. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  34167. };
  34168. const auto paintCost = [&checks] (juce::Component& c, const char* what) {
  34169. double best = 1.0e9;
  34170. for (int run = 0; run < 3; ++run)
  34171. {
  34172. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  34173. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  34174. for (int f = 0; f < 30; ++f)
  34175. {
  34176. juce::Graphics g (image);
  34177. c.paintEntireComponent (g, false);
  34178. }
  34179. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 30.0);
  34180. }
  34181. checks << "paint " << what << " " << juce::String (best, 3) << " ms per frame (" << c.getWidth() << " x " << c.getHeight() << ")\n";
  34182. };
  34183. // the channel window (Pattern layout, LYNX's look): Helix+'s strip with Helix+ 2's two rows
  34184. load ("Triple Stack");
  34185. {
  34186. auto page = lynx::makeHelixEditor (offline, locate, 0);
  34187. check ("window page holds the four strip rows", page->getHeight() >= lynx::helixDeviceHeight + 16 + 300);
  34188. save (*page, "01-window");
  34189. paintCost (*page, "window");
  34190. // (the slowest parts: each child of the page and of its children, alone)
  34191. std::vector<std::pair<double, juce::String>> parts;
  34192. std::function<void (juce::Component&, int)> walk = [&] (juce::Component& c, int depth) {
  34193. for (auto* child : c.getChildren())
  34194. {
  34195. if (child->getWidth() <= 0 || child->getHeight() <= 0)
  34196. continue;
  34197. juce::Image image (juce::Image::ARGB, child->getWidth(), child->getHeight(), true);
  34198. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  34199. for (int f = 0; f < 10; ++f)
  34200. {
  34201. juce::Graphics g (image);
  34202. child->paintEntireComponent (g, false);
  34203. }
  34204. parts.push_back ({ (juce::Time::getMillisecondCounterHiRes() - t0) / 10.0,
  34205. juce::String (depth) + " " + typeid (*child).name() + " " + child->getBounds().toString() });
  34206. if (depth < 2)
  34207. walk (*child, depth + 1);
  34208. }
  34209. };
  34210. walk (*page, 0);
  34211. for (int i = 0; i < page->getNumChildComponents(); ++i) // (the page with one child hidden)
  34212. {
  34213. auto* child = page->getChildComponent (i);
  34214. child->setVisible (false);
  34215. paintCost (*page, (juce::String ("window without child ") + juce::String (i)).toRawUTF8());
  34216. child->setVisible (true);
  34217. }
  34218. paintCost (*page, "window again");
  34219. std::sort (parts.begin(), parts.end(), [] (const auto& x, const auto& y) { return x.first > y.first; });
  34220. for (std::size_t i = 0; i < parts.size() && i < 12; ++i)
  34221. checks << " part " << juce::String (parts[i].first, 3) << " ms " << parts[i].second << "\n";
  34222. check ("Macros tab", lynx::helixcards::showView (*page, 4, 0, 0) == 1);
  34223. save (*page, "02-matrix-macros");
  34224. }
  34225. load ("Vowel Sync");
  34226. {
  34227. auto page = lynx::makeHelixEditor (offline, locate, 0);
  34228. save (*page, "03-window-sample");
  34229. }
  34230. // the table editor on a formula preset's table
  34231. load ("Formula Bell");
  34232. {
  34233. auto editor = lynx::helixcards::makeTableEditor (offline, locate, 0, 0, 0, 20);
  34234. save (*editor, "04-table-draw");
  34235. paintCost (*editor, "table editor (draw)");
  34236. auto harmonics = lynx::helixcards::makeTableEditor (offline, locate, 0, 0, 1, 20);
  34237. save (*harmonics, "05-table-harmonics");
  34238. }
  34239. // the Clip-launch layout's Device View card (Live's look), without and with its Helix+ panel
  34240. load ("Triple Stack");
  34241. {
  34242. lynx::MainComponent ui (offline, false);
  34243. ui.setSize (2560, 1080); // (wide: the card with its panel whole)
  34244. ui.setVisible (true);
  34245. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  34246. ui.setClipLaunchWorkflow (true);
  34247. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  34248. offline.editSong ([] (lynx::Song& s) {
  34249. while (s.patterns.empty())
  34250. s.patterns.emplace_back();
  34251. lynx::Note note;
  34252. note.channel = 0;
  34253. note.key = 60;
  34254. s.patterns[0].name = "Lead";
  34255. s.patterns[0].notes = { note };
  34256. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  34257. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  34258. s.playlistTracks[0].name = "Helix";
  34259. lynx::Clip clip;
  34260. clip.pattern = 0;
  34261. clip.length = 4 * lynx::ppq;
  34262. lynx::launcher::setClip (s, 0, 0, clip);
  34263. }, false);
  34264. offline.dispatchPendingMessages();
  34265. auto* detail = ui.getDetailViewForSnapshot();
  34266. check ("detail view", detail != nullptr);
  34267. if (detail != nullptr)
  34268. {
  34269. detail->showSelection (0, 0);
  34270. detail->setPage (lynx::DetailView::Page::devices);
  34271. offline.dispatchPendingMessages();
  34272. lynx::helixcards::showPlusInCard (*detail, false);
  34273. save (ui, "06-card");
  34274. check ("card's Helix+ panel", lynx::helixcards::showPlusInCard (*detail, true) == 1);
  34275. offline.dispatchPendingMessages();
  34276. save (ui, "07-card-plus");
  34277. // (where the Device View sits in the picture, for the crops)
  34278. checks << "detail " << detail->getScreenBounds().translated (-ui.getScreenX(), -ui.getScreenY()).toString() << "\n";
  34279. lynx::helixcards::showPlusInCard (*detail, false);
  34280. }
  34281. }
  34282. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  34283. }
  34284. void runHelixShot190mi (const juce::String& prefix, const juce::String& presetName)
  34285. {
  34286. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34287. lynx::AudioEngine offline (false);
  34288. juce::String checks;
  34289. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  34290. const auto& bank = lynx::banks::bankOf (lynx::InstrumentKind::helix);
  34291. int index = -1;
  34292. for (int b = 0; b < (int) bank.size(); ++b)
  34293. if (juce::String (bank[(std::size_t) b].name) == presetName)
  34294. index = b;
  34295. check ("preset " + presetName, index >= 0);
  34296. offline.editSong ([index] (lynx::Song& s) {
  34297. if (s.channels.empty())
  34298. s.channels.resize (1);
  34299. lynx::ChannelDef c;
  34300. c.instrument = lynx::InstrumentKind::helix;
  34301. c.mixerTrack = s.channels[0].mixerTrack;
  34302. if (auto loaded = lynx::banks::withPreset (c, std::max (index, 0)))
  34303. c = *loaded;
  34304. s.channels[0] = c;
  34305. }, false);
  34306. offline.dispatchPendingMessages();
  34307. auto page = lynx::makeHelixEditor (offline, [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; }, 0);
  34308. const auto write = [&prefix, &page, &offline] (const char* name) {
  34309. offline.dispatchPendingMessages();
  34310. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  34311. file.deleteFile();
  34312. juce::FileOutputStream out (file);
  34313. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*page), out);
  34314. };
  34315. check ("window page", page->getWidth() > 0 && page->getHeight() > lynx::helixDeviceHeight + 100);
  34316. check ("Helix panel inside", lynx::helixcards::showView (*page, 0, 0, 0) == 1);
  34317. write ("01-window");
  34318. lynx::helixcards::showView (*page, 0, 3, 0);
  34319. write ("02-lfo1-drawn");
  34320. lynx::helixcards::showView (*page, 1, 0, 0);
  34321. write ("03-matrix");
  34322. // the window's paint cost (device + strip, the Mod Sources page): 60 whole frames off screen, the best of 3 runs
  34323. lynx::helixcards::showView (*page, 0, 0, 0);
  34324. double best = 1.0e9;
  34325. for (int run = 0; run < 3; ++run)
  34326. {
  34327. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  34328. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  34329. for (int f = 0; f < 60; ++f)
  34330. {
  34331. juce::Graphics g (image);
  34332. page->paintEntireComponent (g, false);
  34333. }
  34334. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 60.0);
  34335. }
  34336. checks << "paint " << juce::String (best, 3) << " ms per frame (" << page->getWidth() << " x " << page->getHeight() << ")\n";
  34337. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  34338. }
  34339. void runLiveShot190ce (const juce::String& prefix)
  34340. {
  34341. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34342. lynx::AudioEngine offline (false);
  34343. lynx::MainComponent ui (offline, false);
  34344. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  34345. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  34346. const auto write = [&prefix, &ui, &offline] (const char* name) {
  34347. offline.dispatchPendingMessages();
  34348. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  34349. file.deleteFile();
  34350. juce::FileOutputStream out (file);
  34351. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  34352. };
  34353. juce::String checks;
  34354. const auto check = [&checks] (const char* what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  34355. // a small library of its own (empty files: only names are shown)
  34356. const auto lib = juce::File (prefix + "-library");
  34357. lib.deleteRecursively();
  34358. for (const auto* path : { "Drums/Kicks/Kick Hard.wav", "Drums/Kicks/Kick Soft.wav", "Drums/Snare Tight.wav", "Drums/Hat Closed.wav",
  34359. "Loops/Break 120.wav", "Loops/Shaker 98.wav", "Textures/Vinyl Noise.wav", "Textures/Rain.wav" })
  34360. lib.getChildFile (path).create();
  34361. auto& browser = ui.getBrowserForSnapshot();
  34362. auto& store = lynx::BrowserComponent::collectionStore();
  34363. store = {};
  34364. const auto item = [&lib] (const char* path) { return lib.getChildFile (path).getFullPathName().toStdString(); };
  34365. ui.setVisible (true);
  34366. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  34367. ui.setClipLaunchWorkflow (true);
  34368. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  34369. offline.editSong ([] (lynx::Song& s) {
  34370. if (s.channels.size() < 2)
  34371. s.channels.resize (2);
  34372. s.channels[0].name = "Bass synth";
  34373. s.channels[0].mixerTrack = 2;
  34374. s.channels[1].mixerTrack = 3;
  34375. if (s.mixer.size() < 4)
  34376. s.mixer.resize (4);
  34377. s.mixer[2].name = "Bass";
  34378. s.mixer[2].effects.clear();
  34379. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  34380. {
  34381. lynx::EffectSlot fx;
  34382. fx.kind = kind;
  34383. const auto& info = lynx::effectInfo (kind);
  34384. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  34385. fx.params[k] = info.params[k].defaultValue;
  34386. s.mixer[2].effects.push_back (fx);
  34387. }
  34388. s.mixer[2].effects[1].enabled = false; // the compressor: off, at half mix
  34389. s.mixer[2].effects[1].mix = 0.5f;
  34390. while (s.patterns.size() < 2)
  34391. s.patterns.emplace_back();
  34392. s.patterns[0].name = "Bass line";
  34393. lynx::Note note;
  34394. note.channel = 0;
  34395. note.key = 36;
  34396. s.patterns[0].notes = { note };
  34397. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  34398. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  34399. s.playlistTracks[1].name = "Bass";
  34400. lynx::Clip clip;
  34401. clip.pattern = 0;
  34402. clip.length = 4 * lynx::ppq;
  34403. lynx::launcher::setClip (s, 1, 0, clip);
  34404. }, false);
  34405. offline.dispatchPendingMessages();
  34406. auto* detail = ui.getDetailViewForSnapshot();
  34407. if (detail == nullptr)
  34408. {
  34409. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  34410. return;
  34411. }
  34412. detail->showSelection (1, 0);
  34413. detail->setPage (lynx::DetailView::Page::devices);
  34414. detail->selectCardForCheck (2); // the compressor (card 0 is the instrument)
  34415. write ("01-devices"); // the cards' title buttons: hot-swap, save, fold
  34416. saveMenus (juce::StringArray { "Device (effect card)" }, std::vector<juce::PopupMenu> { detail->cardMenuForSnapshot (2) }, prefix + "-02-device-menu.png");
  34417. // hot-swap on for the compressor: the Browser's bar, the Plugin database's effects, the card's button lit
  34418. const auto compressor = lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1);
  34419. browser.beginHotSwap (compressor);
  34420. write ("03-hotswap-effect");
  34421. check ("hot-swap links the compressor", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  34422. // a swap through the Browser itself (the row of LYNX's Reverb, then Enter): the slot keeps its place, its off
  34423. // state and its Mix; the link moves to the new device
  34424. {
  34425. browser.showPluginDatabase ("LYNX SHARE", 0); // (the folder of LYNX's own effects, opened as a click would)
  34426. browser.selectRowForSnapshot (lynx::tr (lynx::effectInfo (lynx::EffectKind::reverb).name));
  34427. write ("03a-hotswap-row"); // the candidate's row selected
  34428. check ("swap: Enter on the Reverb row is taken by hot-swap", browser.hotSwapLoadSelected());
  34429. offline.dispatchPendingMessages();
  34430. const auto& slot = offline.getSong().mixer[2].effects[1];
  34431. // (round 190cy: the device comes in with its own on / off state, on, as in Live 12.4.16; the Mix stays)
  34432. 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);
  34433. check ("swap: three effects as before", offline.getSong().mixer[2].effects.size() == 3);
  34434. check ("swap: the Browser is linked to the new device", browser.isHotSwapping() && browser.hotSwapTarget() == lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1)
  34435. && ! (browser.hotSwapTarget() == compressor));
  34436. write ("03b-hotswap-swapped");
  34437. offline.undo();
  34438. offline.dispatchPendingMessages();
  34439. const auto& back = offline.getSong().mixer[2].effects[1];
  34440. check ("undo: the compressor is back with its instance", back.kind == lynx::EffectKind::compressor && back.instance.id == compressor.instance);
  34441. check ("undo: the Browser is still linked to it", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  34442. }
  34443. // round 190cy (Live 12.4.16 live check 190cw shot 02a): hot-swap starts on the device's current preset. The
  34444. // compressor got its settings from a saved preset of LYNX's ("Glue bus", in this run's own settings folder)
  34445. {
  34446. browser.endHotSwap();
  34447. const auto folder = lynx::pluginheader::userFolder (lynx::EffectKind::compressor);
  34448. folder.createDirectory();
  34449. const auto& fx = offline.getSong().mixer[2].effects[1];
  34450. for (const auto* name : { "Glue bus", "Gentle", "Parallel smash" })
  34451. folder.getChildFile (juce::String (name) + ".lynxpreset").replaceWithText (lynx::presets::toText (lynx::EffectKind::compressor, name, fx.params));
  34452. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects[1].presetName = "Glue bus"; }, false);
  34453. offline.dispatchPendingMessages();
  34454. browser.beginHotSwap (compressor);
  34455. write ("03c-hotswap-current-preset");
  34456. check ("hot-swap starts on the current preset", browser.getSelectedFile() == folder.getChildFile ("Glue bus.lynxpreset"));
  34457. // a preset of the same effect swapped in comes in on (the compressor was off)
  34458. browser.selectRowForSnapshot ("Gentle.lynxpreset");
  34459. check ("swap: the preset row is taken by hot-swap", browser.hotSwapLoadSelected());
  34460. offline.dispatchPendingMessages();
  34461. const auto& now = offline.getSong().mixer[2].effects[1];
  34462. check ("swap: the preset's settings, the device on", now.kind == lynx::EffectKind::compressor && now.presetName == "Gentle" && now.enabled);
  34463. write ("03d-hotswap-preset-swapped");
  34464. offline.undo();
  34465. offline.dispatchPendingMessages();
  34466. check ("undo: the compressor off again", ! offline.getSong().mixer[2].effects[1].enabled);
  34467. browser.endHotSwap();
  34468. check ("hot-swap ended: the preset list goes", ! browser.isHotSwapping());
  34469. browser.beginHotSwap (compressor);
  34470. }
  34471. // linked to the instrument instead
  34472. const auto bass = lynx::hotswap::targetOfChannel (offline.getSong(), 0);
  34473. browser.beginHotSwap (bass);
  34474. detail->selectCardForCheck (0);
  34475. write ("04-hotswap-instrument");
  34476. check ("re-link to the instrument", browser.hotSwapTarget() == bass);
  34477. browser.endHotSwap();
  34478. check ("hot-swap ended", ! browser.isHotSwapping());
  34479. write ("05-hotswap-ended"); // the Browser as it was before
  34480. // the device is deleted while linked: the mode ends by itself
  34481. browser.beginHotSwap (lynx::hotswap::targetOfEffect (offline.getSong(), 2, 2));
  34482. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.pop_back(); });
  34483. offline.dispatchPendingMessages();
  34484. check ("deleting the linked device ends hot-swap", ! browser.isHotSwapping());
  34485. offline.undo();
  34486. offline.dispatchPendingMessages();
  34487. // Duplicate (Ctrl+D) of the EQ
  34488. check ("duplicate", detail->duplicateCardForCheck (1));
  34489. offline.dispatchPendingMessages();
  34490. check ("duplicate: four effects, EQ twice", offline.getSong().mixer[2].effects.size() == 4 && offline.getSong().mixer[2].effects[1].kind == lynx::EffectKind::eq
  34491. && offline.getSong().mixer[2].effects[0].instance.id != offline.getSong().mixer[2].effects[1].instance.id);
  34492. write ("06-duplicated");
  34493. // --- collections ---
  34494. browser.showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  34495. ui.waitForBrowserForSnapshot();
  34496. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 0, true);
  34497. browser.setInCollection (item ("Drums/Snare Tight.wav"), 0, true);
  34498. browser.setInCollection (item ("Loops"), 0, true);
  34499. browser.setTab (lynx::BrowserComponent::starredTab);
  34500. write ("07-starred-only"); // only Starred shown: the tab as it always was
  34501. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 4, true); // also Blue
  34502. browser.setInCollection (item ("Loops/Break 120.wav"), 4, true);
  34503. browser.setInCollection (item ("Textures/Vinyl Noise.wav"), 3, true);
  34504. browser.setInCollection (item ("Textures/Rain.wav"), 3, true);
  34505. browser.setInCollection (item ("Drums/Hat Closed.wav"), 1, true);
  34506. store.rename (3, "Textures");
  34507. browser.setCollectionShown (1, true);
  34508. browser.setCollectionShown (3, true);
  34509. browser.setCollectionShown (4, true);
  34510. write ("08-collections"); // a heading per collection shown
  34511. check ("collections: four shown", store.shown().size() == 4);
  34512. check ("collections: an item in two", store.mask (item ("Drums/Kicks/Kick Hard.wav")) == 0b10001);
  34513. // round 190cy: the Clip-launch workflow's row menu lists the collections flat, as Live's item menu (shot 05);
  34514. // the Pattern workflow keeps the "Collections" sub-menu
  34515. browser.setLiveItemMenus (false);
  34516. saveMenus (juce::StringArray { "Collections (Pattern workflow: a row's sub-menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  34517. prefix + "-09-collections-menu.png");
  34518. browser.setLiveItemMenus (true);
  34519. saveMenus (juce::StringArray { "Collections (Clip-launch workflow: a row's menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  34520. prefix + "-09b-collections-flat.png");
  34521. // the key of a hidden collection (6, Purple) labels the row and the collection appears
  34522. check ("hidden collection: not shown before", ! store.isShown (5));
  34523. browser.setInCollection (item ("Textures/Rain.wav"), 5, true);
  34524. check ("hidden collection: its key shows it", store.isShown (5) && store.has (item ("Textures/Rain.wav"), 5));
  34525. write ("08b-hidden-collection-shown");
  34526. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { browser.buildViewMenu() }, prefix + "-10-browser-options.png");
  34527. browser.setTab (lynx::BrowserComponent::allTab);
  34528. write ("11-all-tab-chips"); // the colour chips on the rows of the ALL tab
  34529. browser.setSearchForSnapshot ("textures");
  34530. ui.waitForBrowserForSnapshot();
  34531. write ("12-search-collection-name"); // found by the collection's name
  34532. browser.setSearchForSnapshot ({});
  34533. // the file round trip
  34534. {
  34535. const auto text = store.toText();
  34536. check ("collections: text round trip", lynx::collections::Store::fromText (text) == store);
  34537. }
  34538. store = {};
  34539. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  34540. lib.deleteRecursively();
  34541. }
  34542. void runLinkShot190gl (const juce::String& prefix)
  34543. {
  34544. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34545. lynx::AudioEngine offline (false);
  34546. lynx::MainComponent ui (offline, false);
  34547. ui.setSize (1600, 900);
  34548. ui.setVisible (true);
  34549. juce::String checks;
  34550. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  34551. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  34552. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  34553. file.deleteFile();
  34554. juce::FileOutputStream out (file);
  34555. juce::PNGImageFormat().writeImageToStream (image, out);
  34556. };
  34557. const auto toolbarShot = [&] (const char* name) {
  34558. ui.tickLinkForSnapshot();
  34559. writeImage (lynx::shot::snapshot (ui, ui.getToolbarBoundsForSnapshot()), name);
  34560. };
  34561. auto& link = offline.getLink();
  34562. auto& transport = offline.getTransport();
  34563. link.deviceStarted (44100.0);
  34564. // the audio callbacks the offline engine has none of: Link's per-block step, in real time
  34565. const auto pump = [&] (double seconds, std::function<bool()> until = {}) {
  34566. const auto end = juce::Time::getMillisecondCounterHiRes() + seconds * 1000.0;
  34567. while (juce::Time::getMillisecondCounterHiRes() < end)
  34568. {
  34569. const auto start = link.beginBlock (transport, 256, 0.0);
  34570. if (start >= 0)
  34571. transport.playing.store (true);
  34572. if (transport.playing.load())
  34573. transport.positionTicks.store (transport.positionTicks.load() + 256 * transport.ticksPerSample());
  34574. juce::Thread::sleep (6);
  34575. if (until && until())
  34576. return true;
  34577. }
  34578. return ! until || until();
  34579. };
  34580. auto peer = lynx::AbletonLink::makeTestPeer (97.0); // the other app in the session (it was there first)
  34581. juce::Thread::sleep (1500); // (a session that started at the same moment as LYNX's could take either tempo)
  34582. using lynx::toolbarlayout::Group;
  34583. // FL's Pattern layout: no Link toggle on a new install
  34584. check ("Pattern layout: the Link toggle is hidden by default", ! ui.getToolbarLayoutForSnapshot().isShown (Group::link));
  34585. toolbarShot ("toolbar-fl-default");
  34586. // shown by hand (Settings › Ableton Link › Show Link Toggle): "Link", off
  34587. auto layout = ui.getToolbarLayoutForSnapshot();
  34588. layout.setShown (Group::link, true);
  34589. ui.setToolbarLayoutForSnapshot (layout);
  34590. toolbarShot ("toolbar-fl-link-off");
  34591. check ("off: the toggle says Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: Link"));
  34592. // on: the session the other peer runs (its tempo, 97 BPM, wins over the project's)
  34593. link.setEnabled (true, offline.getSong().bpm);
  34594. // (a new peer is counted at once; its session's tempo is taken after Link measured it, a moment later)
  34595. const auto joined = pump (8.0, [&] { return link.peers() > 0 && link.startProgress() >= 0.0 && std::abs (link.sessionTempo() - 97.0) < 1e-3; });
  34596. check ("Link on: one peer found", joined && link.peers() == 1);
  34597. 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);
  34598. toolbarShot ("toolbar-fl-link-on");
  34599. check ("on with one peer: the toggle says 1 Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: {0} Link").replace ("{0}", "1"));
  34600. check ("stopped with a peer: the position display shows the session's progress", link.startProgress() >= 0.0);
  34601. // the Clip-launch layout: the toggle is shown by default (the reference DAW's "Show Link Toggle": Show)
  34602. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  34603. ui.setClipLaunchWorkflow (true);
  34604. check ("Clip-launch layout: the Link toggle is shown by default", ui.getToolbarLayoutForSnapshot().isShown (Group::link));
  34605. pump (0.4);
  34606. toolbarShot ("toolbar-cliplaunch-1link");
  34607. writeImage (lynx::shot::snapshot (ui), "window-cliplaunch");
  34608. // Play: it waits for the session's phase (the play button lit, the progress bar running), then starts
  34609. transport.playing.store (true);
  34610. pump (0.05);
  34611. const auto waited = offline.isLinkWaiting();
  34612. check ("Play with a peer waits for the session's phase", waited);
  34613. toolbarShot ("toolbar-cliplaunch-waiting");
  34614. const auto started = pump (4.0, [&] { return transport.playing.load() && ! offline.isLinkWaiting(); });
  34615. check ("then playback starts on the session's phase", started);
  34616. pump (0.5);
  34617. toolbarShot ("toolbar-cliplaunch-playing");
  34618. check ("playing: no progress bar", link.startProgress() < 0.0);
  34619. // the toggle's drop-down and the Options menu
  34620. saveMenus (juce::StringArray { lynx::trc ("@Ableton Link: Link") }, std::vector<juce::PopupMenu> { ui.getLinkToggleForSnapshot().makeMenu() },
  34621. prefix + "-menu-link.png");
  34622. {
  34623. const auto names = ui.getMenuNamesForSnapshot();
  34624. for (int m = 0; m < names.size(); ++m)
  34625. if (names[m] == lynx::tr ("Options"))
  34626. saveMenus (juce::StringArray { names[m] }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (m) }, prefix + "-menu-options.png");
  34627. }
  34628. // Settings › Ableton Link
  34629. {
  34630. lynx::SettingsHooks hooks;
  34631. hooks.linkToggleShown = [] { return true; };
  34632. auto panel = lynx::makeSettingsPanel (offline, lynx::SettingsPage::link, false, hooks);
  34633. panel->setSize (680, 620);
  34634. writeImage (lynx::shot::snapshot (*panel), "settings-link");
  34635. }
  34636. // off: the project's own tempo comes back on the display
  34637. transport.playing.store (false);
  34638. pump (0.1);
  34639. link.setEnabled (false, offline.getSong().bpm);
  34640. pump (0.1);
  34641. toolbarShot ("toolbar-cliplaunch-link-off");
  34642. check ("off: the tempo display shows the project's tempo again", std::abs (offline.shownTempo() - offline.getSong().bpm) < 1e-9);
  34643. const auto stats = link.stats();
  34644. checks << "audio-thread cost of the Link step: mean " << juce::String (stats.meanUs, 2) << " us, max " << juce::String (stats.maxUs, 1)
  34645. << " us over " << (juce::int64) stats.blocks << " blocks\n";
  34646. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  34647. }
  34648. // LYNX --communityshot190hp <prefix> (round 190hp): the three community slices off-screen, with checks in
  34649. // prefix-checks.txt — B9 the MIDI Map Mode's "In every project (LYNX)" (the row menu, the Mapping Browser with the
  34650. // global rows, a new project still playing on the mapped CC, Settings' list), B16 the Mixer menu's Mix snapshots
  34651. // (take, recall, Compare A/B, the .lynx round trip), B18 the audio clip menu's "Split at silence..." (the dialog and
  34652. // the Playlist before / after).
  34653. void runCommunityShot190hp (const juce::String& prefix)
  34654. {
  34655. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34656. lynx::AudioEngine offline (false);
  34657. lynx::MainComponent ui (offline, false);
  34658. ui.setSize (1600, 900);
  34659. const auto write = [&prefix] (juce::Component& c, const char* name) {
  34660. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  34661. file.deleteFile();
  34662. juce::FileOutputStream out (file);
  34663. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  34664. };
  34665. juce::String checks;
  34666. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  34667. const auto plain = [] (juce::String t) { return t.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&"); };
  34668. const auto find = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  34669. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  34670. if (plain (it.getItem().text) == plain (text))
  34671. return &it.getItem();
  34672. return nullptr;
  34673. };
  34674. const auto click = [&find] (const juce::PopupMenu& menu, const juce::String& text) {
  34675. const auto* item = find (menu, text);
  34676. if (item == nullptr || ! item->isEnabled || item->action == nullptr)
  34677. return false;
  34678. item->action();
  34679. return true;
  34680. };
  34681. using namespace lynx::remotemap;
  34682. ui.setVisible (true);
  34683. // ---- B9: the MIDI Map Mode's mappings for every project ---------------------------------------------------------
  34684. ui.setClipLaunchWorkflow (true);
  34685. offline.editSong ([] (lynx::Song& s) {
  34686. auto& grid = lynx::launcher::ensureGrid (s);
  34687. grid.scenes.resize (4);
  34688. assignMidi (s, Target::of (lynx::RemoteAction::play), { 0, 118, -1 });
  34689. assignMidi (s, Target::of (lynx::RemoteAction::stop), { 0, 117, -1 });
  34690. assignMidi (s, Target::sceneLaunch (0), { 0, lynx::linkNoteBase + 44, -1 });
  34691. assignMidi (s, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, -1 });
  34692. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }), { 0, 7, -1 });
  34693. }, false);
  34694. offline.dispatchPendingMessages();
  34695. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist, lynx::workspace::Panel::browser });
  34696. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  34697. ui.setMapMode (Mode::midi);
  34698. auto* list = ui.mappingBrowserForSnapshot();
  34699. if (list == nullptr)
  34700. {
  34701. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no Mapping Browser\n");
  34702. return;
  34703. }
  34704. list->setMode (Mode::midi);
  34705. ui.resized();
  34706. const auto rowOf = [&] (const Target& t) {
  34707. const auto rows = list->rowsShown();
  34708. for (int r = 0; r < (int) rows.size(); ++r)
  34709. if (rows[(std::size_t) r].target == t)
  34710. return r;
  34711. return -1;
  34712. };
  34713. const auto everyProject = lynx::tr ("In every project (LYNX)");
  34714. {
  34715. const auto slotMenu = list->rowMenu (rowOf (Target::slot (0, 0)));
  34716. const auto* item = find (slotMenu, everyProject);
  34717. check ("row menu: a clip slot cannot be for every project (greyed)", item != nullptr && ! item->isEnabled);
  34718. const auto playRow = rowOf (Target::of (lynx::RemoteAction::play));
  34719. list->selectRow (playRow);
  34720. const auto playMenu = list->rowMenu (playRow);
  34721. const auto* p = find (playMenu, everyProject);
  34722. check ("row menu: Play can, unticked", p != nullptr && p->isEnabled && ! p->isTicked);
  34723. saveMenus (juce::StringArray { "Row" }, std::vector<juce::PopupMenu> { playMenu }, prefix + "-b9-01-row-menu.png");
  34724. check ("Play goes to every project", click (playMenu, everyProject) && offline.getMidiPrefs().globalMappings.size() == 1);
  34725. }
  34726. check ("Stop goes too", click (list->rowMenu (rowOf (Target::of (lynx::RemoteAction::stop))), everyProject));
  34727. check ("the Master volume link goes too (FL's global links)",
  34728. click (list->rowMenu (rowOf (Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }))), everyProject)
  34729. && offline.getMidiPrefs().globalLinks.size() == 1 && offline.getSong().midiLinks.empty());
  34730. list->setMode (Mode::midi);
  34731. const auto shown = list->rowsShown();
  34732. check ("Mapping Browser: 2 project rows, then 3 global ones (" + juce::String ((int) shown.size()) + ")",
  34733. shown.size() == 5 && ! shown[0].global && ! shown[1].global && shown[2].global && shown[4].global);
  34734. {
  34735. const auto rowMenu = list->rowMenu (2); // (round 190rf: kept while its item is read; ASan, heap-use-after-free)
  34736. const auto* ticked = find (rowMenu, everyProject);
  34737. check ("a global row's item is ticked", ticked != nullptr && ticked->isTicked);
  34738. }
  34739. write (*list, "b9-02-mapping-browser-global");
  34740. // a new project: the global mappings are there and act (CC 118 plays, CC 117 stops)
  34741. offline.setSong (lynx::Song::makeDefault());
  34742. offline.dispatchPendingMessages();
  34743. list->setMode (Mode::midi);
  34744. const auto fresh = list->rowsShown();
  34745. check ("new project: the 3 global rows (" + juce::String ((int) fresh.size()) + ")", fresh.size() == 3 && fresh[0].global);
  34746. write (*list, "b9-03-new-project-browser");
  34747. ui.setMapMode (Mode::off);
  34748. offline.injectControllerForTest (118, 0, 127);
  34749. offline.dispatchPendingMessages();
  34750. check ("new project: CC 118 plays", offline.getTransport().playing.load());
  34751. offline.injectControllerForTest (118, 0, 0);
  34752. offline.injectControllerForTest (117, 0, 127);
  34753. offline.dispatchPendingMessages();
  34754. check ("new project: CC 117 stops", ! offline.getTransport().playing.load());
  34755. offline.injectControllerForTest (7, 0, 0);
  34756. offline.dispatchPendingMessages();
  34757. check ("new project: CC 7 moves the Master", offline.currentTargetValue ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }) < 0.01f);
  34758. // the Pattern layout: they act there too, and Settings › MIDI lists them
  34759. ui.setClipLaunchWorkflow (false);
  34760. offline.injectControllerForTest (117, 0, 0);
  34761. offline.injectControllerForTest (118, 0, 127);
  34762. offline.dispatchPendingMessages();
  34763. check ("Pattern layout: CC 118 plays", offline.getTransport().playing.load());
  34764. offline.stop();
  34765. // back into one project, then cleared (the settings of this test engine are never written)
  34766. ui.setClipLaunchWorkflow (true);
  34767. ui.setMapMode (Mode::midi);
  34768. list->setMode (Mode::midi);
  34769. check ("back into this project", click (list->rowMenu (rowOf (Target::of (lynx::RemoteAction::play))), everyProject)
  34770. && offline.getMidiPrefs().globalMappings.size() == 1 && offline.getSong().remoteMappings.size() == 1);
  34771. ui.setMapMode (Mode::off);
  34772. ui.setClipLaunchWorkflow (false);
  34773. // ---- B16: Mix snapshots ----------------------------------------------------------------------------------------
  34774. offline.setSong (lynx::Song::makeDefault());
  34775. offline.dispatchPendingMessages();
  34776. offline.editSong ([] (lynx::Song& s) {
  34777. const char* names[] { "Master", "Drums", "Bass", "Keys", "Vox", "Reverb" };
  34778. for (int i = 1; i < 6 && i < (int) s.mixer.size(); ++i)
  34779. s.mixer[(std::size_t) i].name = names[i];
  34780. s.mixer[1].volume = 0.7f;
  34781. s.mixer[4].pan = -0.3f;
  34782. s.setRoute (4, 5, true, 0.5f);
  34783. });
  34784. juce::PopupMenu mixerMenu;
  34785. lynx::mixeroptions::addItems (mixerMenu, offline, false);
  34786. const auto* snaps = find (mixerMenu, lynx::tr ("Mix snapshots (LYNX)"));
  34787. check ("Mixer menu: Mix snapshots (LYNX)", snaps != nullptr && snaps->subMenu != nullptr);
  34788. check ("Take snapshot", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Take snapshot")) && offline.getSong().mixSnapshots.size() == 1);
  34789. offline.editSong ([] (lynx::Song& s) {
  34790. s.mixer[1].volume = 0.4f;
  34791. s.mixer[4].pan = 0.6f;
  34792. s.mixer[3].muted = true;
  34793. s.setRoute (4, 5, false);
  34794. });
  34795. check ("Take snapshot again", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Take snapshot")) && offline.getSong().mixSnapshots.size() == 2);
  34796. {
  34797. const auto menu = lynx::mixeroptions::snapshotsMenu (offline);
  34798. const auto* first = find (menu, juce::String ("Snapshot 1 (B)"));
  34799. check ("snapshot 1 listed as B", first != nullptr && first->subMenu != nullptr && ! first->isTicked);
  34800. const auto* second = find (menu, juce::String ("Snapshot 2 (A)"));
  34801. check ("snapshot 2 ticked: the mix is it", second != nullptr && second->isTicked);
  34802. saveMenus (juce::StringArray { "Mixer", "Mix snapshots (LYNX)", "Snapshot 1" },
  34803. std::vector<juce::PopupMenu> { mixerMenu, menu, first != nullptr ? *first->subMenu : juce::PopupMenu() }, prefix + "-b16-01-menus.png");
  34804. check ("Recall snapshot 1", first != nullptr && click (*first->subMenu, lynx::tr ("Recall")));
  34805. }
  34806. const auto& m = offline.getSong().mixer;
  34807. check ("recalled: fader, pan, mute, send", m[1].volume == 0.7f && m[4].pan == -0.3f && ! m[3].muted && offline.getSong().routes (4, 5));
  34808. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  34809. ui.resized();
  34810. offline.dispatchPendingMessages();
  34811. write (ui, "b16-02-mixer-recalled");
  34812. check ("Compare A/B", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Compare A/B: back to \"{0}\"", { "Snapshot 2" }))
  34813. && m[1].volume == 0.4f && m[3].muted);
  34814. offline.undo();
  34815. check ("one undo step: back to snapshot 1", m[1].volume == 0.7f);
  34816. {
  34817. const auto file = juce::File (prefix + "-b16-snapshots.lynx");
  34818. juce::String error;
  34819. const auto saved = lynx::ProjectFile::save (offline.getSong(), file, error);
  34820. const auto back = lynx::ProjectFile::load (file, error);
  34821. check ("saved and loaded: the snapshots and A/B", saved && back && back->mixSnapshots == offline.getSong().mixSnapshots
  34822. && back->mixSnapshotCurrent == offline.getSong().mixSnapshotCurrent
  34823. && back->mixSnapshotPrevious == offline.getSong().mixSnapshotPrevious);
  34824. file.deleteFile();
  34825. }
  34826. // ---- B18: Split at silence -------------------------------------------------------------------------------------
  34827. {
  34828. // a "vocal take": 0.5 s silence, three phrases with pauses of 0.6 s and 0.15 s, quiet hiss in the gaps
  34829. const double rate = 44100.0;
  34830. juce::AudioBuffer<float> buffer (1, (int) (rate * 4.0));
  34831. buffer.clear();
  34832. juce::Random noise (190);
  34833. for (int i = 0; i < buffer.getNumSamples(); ++i)
  34834. {
  34835. const auto t = i / rate;
  34836. const auto phrase = (t >= 0.5 && t < 1.4) || (t >= 2.0 && t < 2.6) || (t >= 2.75 && t < 3.3);
  34837. 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)))
  34838. : (noise.nextFloat() - 0.5f) * 0.0004f);
  34839. }
  34840. const auto wav = juce::File (prefix + "-b18-take.wav");
  34841. wav.deleteFile();
  34842. juce::WavAudioFormat format;
  34843. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (format.createWriterFor (wav.createOutputStream().release(), rate, 1, 16, {}, 0)))
  34844. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  34845. auto song = lynx::Song::makeDefault();
  34846. song.channels.push_back ({});
  34847. song.channels.back().name = "Vocal take";
  34848. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  34849. song.channels.back().samplePath = wav.getFullPathName().toStdString();
  34850. lynx::Clip c;
  34851. c.kind = lynx::ClipKind::audio;
  34852. c.channel = (int) song.channels.size() - 1;
  34853. c.track = 1;
  34854. c.start = 4 * lynx::ppq;
  34855. c.length = (std::int64_t) std::llround (4.0 * song.bpm / 60.0 * lynx::ppq); // (the whole file at the song tempo)
  34856. song.playlist.push_back (c);
  34857. offline.setSong (std::move (song));
  34858. offline.dispatchPendingMessages();
  34859. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  34860. ui.resized();
  34861. auto& playlist = ui.getPlaylistForSnapshot();
  34862. const auto index = (int) offline.getSong().playlist.size() - 1;
  34863. const auto menu = playlist.getClipMenuForSnapshot (index);
  34864. const auto* item = find (menu, lynx::tr ("Split at silence..."));
  34865. const auto* splitHere = find (menu, lynx::tr ("Split here"));
  34866. check ("clip menu: Split at silence... in LYNX extras, enabled", item != nullptr && item->isEnabled && splitHere != nullptr);
  34867. savePng (columnMenuImage (menu), prefix + "-b18-01-clip-menu.png");
  34868. {
  34869. auto dialog = playlist.makeSplitSilenceDialogForSnapshot (index);
  34870. write (*dialog, "b18-02-dialog");
  34871. }
  34872. offline.dispatchPendingMessages();
  34873. write (ui, "b18-03-playlist-before");
  34874. juce::String why;
  34875. const auto made = playlist.splitClipsAtSilence ({ index }, lynx::PlaylistComponent::splitSilenceOptions(), &why);
  34876. offline.dispatchPendingMessages();
  34877. const auto& clips = offline.getSong().playlist;
  34878. std::vector<const lynx::Clip*> audio;
  34879. for (const auto& x : clips)
  34880. if (x.kind == lynx::ClipKind::audio)
  34881. audio.push_back (&x);
  34882. std::sort (audio.begin(), audio.end(), [] (const lynx::Clip* a, const lynx::Clip* b) { return a->start < b->start; });
  34883. const auto secondsAt = [&] (std::int64_t ticks) { return (double) (ticks - 4 * lynx::ppq) / lynx::ppq * 60.0 / offline.getSong().bpm; };
  34884. check ("split into 2 clips (the 0.15 s pause stays inside): " + juce::String (made) + ", " + why, made == 2 && audio.size() == 2);
  34885. if (audio.size() == 2)
  34886. check ("the clips start at the phrases less the pre-roll, end after them: " + juce::String (secondsAt (audio[0]->start), 3) + "-"
  34887. + juce::String (secondsAt (audio[0]->end()), 3) + ", " + juce::String (secondsAt (audio[1]->start), 3) + "-" + juce::String (secondsAt (audio[1]->end()), 3),
  34888. std::abs (secondsAt (audio[0]->start) - 0.49) < 0.02 && std::abs (secondsAt (audio[0]->end()) - 1.45) < 0.02
  34889. && std::abs (secondsAt (audio[1]->start) - 1.99) < 0.02 && std::abs (secondsAt (audio[1]->end()) - 3.35) < 0.02
  34890. && audio[1]->offset - audio[0]->offset == audio[1]->start - audio[0]->start);
  34891. write (ui, "b18-04-playlist-after");
  34892. offline.undo();
  34893. check ("one undo step", offline.getSong().playlist.size() == clips.size() && std::count_if (offline.getSong().playlist.begin(), offline.getSong().playlist.end(),
  34894. [] (const lynx::Clip& x) { return x.kind == lynx::ClipKind::audio; }) == 1);
  34895. lynx::stripsilence::Options loud;
  34896. loud.thresholdDb = -1.0f;
  34897. check ("all below the threshold: nothing split", playlist.splitClipsAtSilence ({ index }, loud, &why) == 0);
  34898. wav.deleteFile();
  34899. }
  34900. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  34901. }
  34902. void runMapShot190ef (const juce::String& prefix)
  34903. {
  34904. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34905. lynx::AudioEngine offline (false);
  34906. lynx::MainComponent ui (offline, false);
  34907. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  34908. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  34909. const auto write = [&prefix] (juce::Component& c, const char* name) {
  34910. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  34911. file.deleteFile();
  34912. juce::FileOutputStream out (file);
  34913. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  34914. };
  34915. juce::String checks;
  34916. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  34917. using namespace lynx::remotemap;
  34918. ui.setVisible (true);
  34919. // the Pattern layout first: Ctrl+M stays FL's metronome there and no map mode starts
  34920. {
  34921. const auto before = offline.getTransport().metronome.load();
  34922. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  34923. check ("Pattern layout: Ctrl+M is the metronome, no map mode", ui.getMapMode() == Mode::off && offline.getTransport().metronome.load() != before);
  34924. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  34925. ui.setMapMode (Mode::midi);
  34926. check ("Pattern layout: setMapMode stays off", ui.getMapMode() == Mode::off);
  34927. }
  34928. ui.setClipLaunchWorkflow (true);
  34929. offline.editSong ([] (lynx::Song& s) {
  34930. if (s.mixer.size() < 6)
  34931. s.mixer.resize (6);
  34932. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Reverb" };
  34933. for (int i = 1; i < 6; ++i)
  34934. s.mixer[(std::size_t) i].name = inserts[i];
  34935. const int channels = (int) s.channels.size();
  34936. s.channels.resize ((std::size_t) channels + 3);
  34937. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  34938. for (int k = 0; k < 3; ++k)
  34939. {
  34940. auto& ch = s.channels[(std::size_t) (channels + k)];
  34941. ch.name = names[k];
  34942. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  34943. ch.mixerTrack = k + 1;
  34944. }
  34945. s.mixer[2].effects.clear();
  34946. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  34947. {
  34948. lynx::EffectSlot fx;
  34949. fx.kind = kind;
  34950. const auto& info = lynx::effectInfo (kind);
  34951. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  34952. fx.params[k] = info.params[k].defaultValue;
  34953. s.mixer[2].effects.push_back (fx);
  34954. }
  34955. while (s.patterns.size() < 3)
  34956. s.patterns.emplace_back();
  34957. const char* patterns[] { "Beat", "Bassline", "Chords" };
  34958. for (int p = 0; p < 3; ++p)
  34959. {
  34960. auto& pattern = s.patterns[(std::size_t) p];
  34961. pattern.name = patterns[p];
  34962. lynx::Note n;
  34963. n.channel = channels + p;
  34964. n.key = 48 + p * 5;
  34965. pattern.notes = { n };
  34966. pattern.lengthTicks = 4 * lynx::ppq;
  34967. }
  34968. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  34969. const char* tracks[] { "Drums", "Bass", "Keys", "Vox" };
  34970. for (int t = 0; t < 4; ++t)
  34971. s.playlistTracks[(std::size_t) t].name = tracks[t];
  34972. for (int t = 0; t < 3; ++t)
  34973. for (int r = 0; r < 3; ++r)
  34974. {
  34975. lynx::Clip clip;
  34976. clip.pattern = t;
  34977. clip.length = 4 * lynx::ppq;
  34978. lynx::launcher::setClip (s, t, r, clip);
  34979. }
  34980. auto& grid = lynx::launcher::ensureGrid (s);
  34981. const char* scenes[] { "Intro", "Verse", "Drop" };
  34982. grid.scenes.resize (4);
  34983. for (int r = 0; r < 3; ++r)
  34984. grid.scenes[(std::size_t) r].name = scenes[r];
  34985. // some mappings, as the lesson's pictures show them (pads on slots and scenes, knobs on volume and pan)
  34986. assignMidi (s, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, -1 });
  34987. assignMidi (s, Target::slot (1, 0), { 0, lynx::linkNoteBase + 37, -1 });
  34988. assignMidi (s, Target::sceneLaunch (1), { 0, lynx::linkNoteBase + 44, -1 });
  34989. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }), { 0, 17, -1 });
  34990. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }), { 0, 16, -1 });
  34991. assignMidi (s, Target::of (lynx::RemoteAction::play), { 0, 118, -1 });
  34992. setRange (s, rows (s, Mode::midi)[0], 0.0f, 0.85f);
  34993. assignKey (s, Target::slot (0, 1), 'A');
  34994. assignKey (s, Target::slot (1, 1), 'S');
  34995. assignKey (s, Target::sceneLaunch (2), '3');
  34996. assignKey (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 }), 'V');
  34997. }, false);
  34998. offline.dispatchPendingMessages();
  34999. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist, lynx::workspace::Panel::browser }); // (no floating Channel Rack over the grid)
  35000. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  35001. offline.dispatchPendingMessages();
  35002. ui.resized();
  35003. if (auto* detail = ui.getDetailViewForSnapshot())
  35004. {
  35005. detail->showSelection (1, 0);
  35006. detail->setPage (lynx::DetailView::Page::devices);
  35007. }
  35008. ui.resized();
  35009. offline.dispatchPendingMessages();
  35010. write (ui, "00-clip-launch-before");
  35011. // Ctrl+M in the Clip-launch layout: MIDI Map Mode (the metronome stays as it was)
  35012. const auto metronome = offline.getTransport().metronome.load();
  35013. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  35014. check ("Clip-launch layout: Ctrl+M starts MIDI Map Mode", ui.getMapMode() == Mode::midi && offline.getTransport().metronome.load() == metronome);
  35015. auto* overlay = ui.mapOverlayForSnapshot();
  35016. auto* list = ui.mappingBrowserForSnapshot();
  35017. if (overlay == nullptr || list == nullptr)
  35018. {
  35019. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no overlay\n");
  35020. return;
  35021. }
  35022. overlay->refresh();
  35023. const auto& spots = overlay->spots();
  35024. 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; }); };
  35025. const auto params = [&] (lynx::AutomationTargetKind k) {
  35026. 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; });
  35027. };
  35028. check ("overlay: clip slots (" + juce::String (count (lynx::RemoteAction::clipSlot)) + ")", count (lynx::RemoteAction::clipSlot) >= 12);
  35029. check ("overlay: scene launch buttons (" + juce::String (count (lynx::RemoteAction::sceneLaunch)) + ")", count (lynx::RemoteAction::sceneLaunch) >= 4);
  35030. check ("overlay: track stop buttons", count (lynx::RemoteAction::trackStop) >= 4);
  35031. check ("overlay: Stop all clips, Session Record", count (lynx::RemoteAction::stopAllClips) == 1 && count (lynx::RemoteAction::sessionRecord) == 1);
  35032. check ("overlay: transport play / stop / record / metronome", count (lynx::RemoteAction::play) == 1 && count (lynx::RemoteAction::stop) == 1
  35033. && count (lynx::RemoteAction::record) == 1 && count (lynx::RemoteAction::metronome) == 1);
  35034. check ("overlay: tempo", params (lynx::AutomationTargetKind::tempo) == 1);
  35035. check ("overlay: mixer volume / pan (" + juce::String (params (lynx::AutomationTargetKind::mixerVolume)) + " / " + juce::String (params (lynx::AutomationTargetKind::mixerPan)) + ")",
  35036. params (lynx::AutomationTargetKind::mixerVolume) >= 3 && params (lynx::AutomationTargetKind::mixerPan) >= 3);
  35037. check ("overlay: device knobs (" + juce::String (params (lynx::AutomationTargetKind::effectParam)) + ")", params (lynx::AutomationTargetKind::effectParam) >= 2);
  35038. // a click on Keys' first slot selects it; a MIDI control assigns it (as the engine's catch would)
  35039. for (const auto& spot : spots)
  35040. if (spot.target == Target::slot (2, 0))
  35041. {
  35042. auto source = juce::Desktop::getInstance().getMainMouseSource();
  35043. const auto now = juce::Time::getCurrentTime();
  35044. const auto at = spot.area.getCentre().toFloat();
  35045. overlay->mouseDown (juce::MouseEvent (source, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
  35046. overlay, overlay, now, at, now, 1, false));
  35047. break;
  35048. }
  35049. if (spots.empty())
  35050. {
  35051. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no spots\n");
  35052. return;
  35053. }
  35054. check ("a click selects the slot", overlay->selection() == std::optional<Target> (Target::slot (2, 0)));
  35055. check ("the overlay takes clicks only on elements", overlay->hitTest (spots.front().area.getCentreX(), spots.front().area.getCentreY()) && ! overlay->hitTest (2, ui.getHeight() - 2));
  35056. check ("a pad assigns it", overlay->assignMidi ({ 0, lynx::linkNoteBase + 38, -1 }) && midiOf (offline.getSong(), Target::slot (2, 0)).number == lynx::linkNoteBase + 38);
  35057. check ("the same pad again on track 0 is refused", ! (overlay->select (Target::slot (0, 2)), overlay->assignMidi ({ 0, lynx::linkNoteBase + 36, -1 })));
  35058. overlay->select (Target::slot (2, 0));
  35059. list->setMode (Mode::midi);
  35060. list->selectRow (0);
  35061. ui.resized();
  35062. overlay->refresh();
  35063. write (ui, "01-midi-map-mode");
  35064. check ("Mapping Browser rows (MIDI): " + juce::String ((int) list->rowsShown().size()), list->rowsShown().size() == 7);
  35065. write (*list, "02-mapping-browser-midi");
  35066. saveMenus (juce::StringArray { "Row" }, std::vector<juce::PopupMenu> { list->rowMenu (0) }, prefix + "-03-row-menu.png");
  35067. // Ctrl+K: Key Map Mode; a key assigns the selected element
  35068. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  35069. check ("Ctrl+K switches to Key Map Mode", ui.getMapMode() == Mode::key && offline.getMapMode() == Mode::key);
  35070. overlay->select (Target::sceneLaunch (0));
  35071. ui.keyPressed (juce::KeyPress ('1', {}, '1'));
  35072. check ("a key assigns the selected scene", keyOf (offline.getSong(), Target::sceneLaunch (0)).key == '1');
  35073. overlay->select (Target::sceneLaunch (1));
  35074. ui.keyPressed (juce::KeyPress ('A', {}, 'a'));
  35075. check ("a key already on a slot is refused for a scene", ! keyOf (offline.getSong(), Target::sceneLaunch (1)).found);
  35076. overlay->refresh();
  35077. write (ui, "04-key-map-mode");
  35078. write (*list, "05-mapping-browser-key");
  35079. {
  35080. // round 190em: Min / Max in the parameter's unit, Path "<track> | Mixer", Name "Track Volume" / "Slot n"
  35081. const lynx::remotemap::Target volume = Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 });
  35082. const auto [path, name] = lynx::mapmode::describe (offline, volume);
  35083. check ("browser: volume row Path / Name = " + path + " / " + name, path == "Bass | Mixer" && name == "Track Volume");
  35084. check ("browser: volume Min / Max = " + lynx::mapmode::rangeText (offline, volume, 0.0f) + " / " + lynx::mapmode::rangeText (offline, volume, 1.0f),
  35085. lynx::mapmode::rangeText (offline, volume, 0.0f) == juce::String::fromUTF8 ("\xe2\x88\x92\xe2\x88\x9e dB")
  35086. && lynx::mapmode::rangeText (offline, volume, 1.0f).endsWith (" dB"));
  35087. const lynx::remotemap::Target pan = Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 });
  35088. check ("browser: pan Min / Max = " + lynx::mapmode::rangeText (offline, pan, 0.25f) + " / " + lynx::mapmode::rangeText (offline, pan, 0.5f),
  35089. lynx::mapmode::rangeText (offline, pan, 0.25f) == "50L" && lynx::mapmode::rangeText (offline, pan, 0.5f) == "C"
  35090. && lynx::mapmode::rangeText (offline, pan, 1.0f) == "100R");
  35091. const auto typed = lynx::mapmode::rangeValueOf (offline, volume, "0 dB");
  35092. check ("browser: typing 0 dB", typed.has_value() && std::abs (lynx::mapmode::rangeText (offline, volume, *typed).getDoubleValue()) < 0.15);
  35093. check ("browser: typing 50L", lynx::mapmode::rangeValueOf (offline, pan, "50L") == std::optional<float> (0.25f));
  35094. check ("browser: Key column = " + lynx::mapmode::listKeyText ('V') + ", " + lynx::mapmode::listKeyText ('3'),
  35095. lynx::mapmode::listKeyText ('V') == "Key v" && lynx::mapmode::listKeyText ('3') == "Key 3");
  35096. check ("browser: slot row Name = " + lynx::mapmode::describe (offline, Target::slot (0, 2)).second,
  35097. lynx::mapmode::describe (offline, Target::slot (0, 2)) == std::pair<juce::String, juce::String> ("Drums", "Slot 3"));
  35098. }
  35099. // off again: the key mapping on a parameter toggles it between Min and Max
  35100. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  35101. check ("Ctrl+K again ends it", ui.getMapMode() == Mode::off && ! overlay->isVisible() && ! list->isVisible());
  35102. const lynx::AutomationTarget keysVolume { lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 };
  35103. // (round 190em, Live 12.4.16: the first press goes to Min, then Max, then Min)
  35104. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  35105. check ("the mapped key V moves Bass's volume to Min first", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  35106. ui.keyStateChanged (false); // (V is not down any more: its release)
  35107. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  35108. check ("again: to Max", std::abs (offline.currentTargetValue (keysVolume) - 1.0f) < 0.01f);
  35109. ui.keyStateChanged (false);
  35110. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  35111. check ("again: to Min", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  35112. ui.keyStateChanged (false);
  35113. // the title bar switches
  35114. ui.setMapMode (Mode::midi);
  35115. write (ui, "06-switches-midi-on");
  35116. ui.setMapMode (Mode::off);
  35117. ui.setClipLaunchWorkflow (false);
  35118. check ("leaving the Clip-launch layout ends the map mode", ui.getMapMode() == Mode::off);
  35119. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  35120. }
  35121. void runSceneShot190ef (const juce::String& prefix)
  35122. {
  35123. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  35124. lynx::AudioEngine offline (false);
  35125. lynx::MainComponent ui (offline, false);
  35126. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  35127. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  35128. const auto write = [&prefix] (juce::Component& c, const char* name) {
  35129. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  35130. file.deleteFile();
  35131. juce::FileOutputStream out (file);
  35132. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  35133. };
  35134. juce::String checks;
  35135. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  35136. ui.setVisible (true);
  35137. lynx::DetailView::shownSetting = false;
  35138. ui.setClipLaunchWorkflow (true);
  35139. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  35140. offline.editSong ([] (lynx::Song& s) {
  35141. const int channels = (int) s.channels.size();
  35142. s.channels.resize ((std::size_t) channels + 3);
  35143. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  35144. for (int k = 0; k < 3; ++k)
  35145. {
  35146. auto& ch = s.channels[(std::size_t) (channels + k)];
  35147. ch.name = names[k];
  35148. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  35149. }
  35150. while (s.patterns.size() < 3)
  35151. s.patterns.emplace_back();
  35152. const char* patterns[] { "Beat", "Bassline", "Chords" };
  35153. for (int p = 0; p < 3; ++p)
  35154. {
  35155. auto& pattern = s.patterns[(std::size_t) p];
  35156. pattern.name = patterns[p];
  35157. lynx::Note n;
  35158. n.channel = channels + p;
  35159. n.key = 48 + p * 5;
  35160. pattern.notes = { n };
  35161. pattern.lengthTicks = 4 * lynx::ppq;
  35162. }
  35163. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  35164. const char* tracks[] { "Drums", "Bass", "Keys" };
  35165. const std::uint32_t colours[] { 0xFFE0533Bu, 0xFF3B8BE0u, 0xFF46C27Au };
  35166. for (int t = 0; t < 3; ++t)
  35167. {
  35168. s.playlistTracks[(std::size_t) t].name = tracks[t];
  35169. s.playlistTracks[(std::size_t) t].colour = colours[t];
  35170. }
  35171. for (int t = 0; t < 3; ++t)
  35172. for (int r = 0; r < 3; ++r)
  35173. if (! (t == 2 && r == 0))
  35174. {
  35175. lynx::Clip clip;
  35176. clip.pattern = t;
  35177. clip.length = 4 * lynx::ppq;
  35178. lynx::launcher::setClip (s, t, r, clip);
  35179. }
  35180. auto& grid = lynx::launcher::ensureGrid (s);
  35181. grid.scenes.resize (4);
  35182. const char* scenes[] { "Intro", "Verse", "Drop" };
  35183. for (int r = 0; r < 3; ++r)
  35184. grid.scenes[(std::size_t) r].name = scenes[r];
  35185. lynx::session::setSceneTempo (s, 1, 128.0);
  35186. lynx::session::setSceneSignature (s, 1, 3, 4); // (as the live check's "Verse": 3 / 4)
  35187. lynx::session::setSceneSignature (s, 2, 6, 8); // (round 190em: a denominator of its own)
  35188. grid.scenes[2].colour = 0xFF8E5BD6u;
  35189. }, false);
  35190. offline.dispatchPendingMessages();
  35191. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  35192. offline.dispatchPendingMessages();
  35193. ui.resized();
  35194. auto* gridView = ui.getClipGridForSnapshot();
  35195. if (gridView == nullptr)
  35196. {
  35197. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid\n");
  35198. return;
  35199. }
  35200. lynx::clipGridSceneTempoShown() = true;
  35201. lynx::refreshClipGrid (*gridView);
  35202. lynx::selectClipGridScene (*gridView, 1);
  35203. write (*gridView, "01-scene-fields");
  35204. {
  35205. // round 190em: a plain scene's launch triangle in Live's dark grey (#1E1E1E), scene 4 (row 3)
  35206. const auto image = lynx::shot::snapshot (*gridView);
  35207. int dark = 0;
  35208. for (int y = 0; y < image.getHeight(); ++y)
  35209. for (int x = image.getWidth() - 240; x < image.getWidth() - 180; ++x)
  35210. if (const auto p = image.getPixelAt (x, y); y > 3 * 24 + 26 && y < 4 * 24 + 26 && std::abs (p.getRed() - 0x1e) <= 2
  35211. && std::abs (p.getGreen() - 0x1e) <= 2 && std::abs (p.getBlue() - 0x1e) <= 2)
  35212. ++dark;
  35213. check ("plain scene triangle in Live's #1E1E1E (" + juce::String (dark) + " px)", dark >= 20);
  35214. }
  35215. saveMenus (juce::StringArray { "Scene menu (Verse)" }, std::vector<juce::PopupMenu> { lynx::clipGridSceneMenu (*gridView, 1) }, prefix + "-02-scene-menu.png");
  35216. saveMenus (juce::StringArray { "Scene tempo field", "Scene time signature field" },
  35217. std::vector<juce::PopupMenu> { lynx::clipGridSceneFieldMenu (*gridView, 1, 1), lynx::clipGridSceneFieldMenu (*gridView, 2, 2) },
  35218. prefix + "-03-field-menus.png");
  35219. saveMenus (juce::StringArray { "Column title (Bass)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*gridView, 1) }, prefix + "-04-title-menu.png");
  35220. const auto clipsIn = [&offline] (int row) {
  35221. int n = 0;
  35222. if (const auto& g = offline.getSong().clipGrid)
  35223. for (int t = 0; t < 8; ++t)
  35224. n += lynx::launcher::clipAt (*g, t, row) != nullptr ? 1 : 0;
  35225. return n;
  35226. };
  35227. const auto before = clipsIn (1);
  35228. const auto dup = lynx::duplicateClipGridScene (*gridView, 1);
  35229. offline.dispatchPendingMessages();
  35230. const auto& scenesNow = offline.getSong().clipGrid->scenes;
  35231. check ("duplicate: Verse's copy is row 2, with its clips and tempo", dup == 2 && clipsIn (2) == before && scenesNow.size() > 2
  35232. && scenesNow[2].name == "Verse" && scenesNow[2].tempo == 128.0);
  35233. write (*gridView, "05-scene-duplicated");
  35234. const auto cap = lynx::captureClipGridScene (*gridView, 3, { 0, 2, 1 }); // Drums row 0, Bass row 2, Keys row 1
  35235. offline.dispatchPendingMessages();
  35236. check ("capture: a new row 4 with the three playing clips", cap == 4 && clipsIn (4) == 3);
  35237. {
  35238. const auto& sc = offline.getSong().clipGrid->scenes;
  35239. check ("capture while playing: the new scene is plain (no name, fields off)", sc.size() > 4 && sc[4] == lynx::ClipGridScene {});
  35240. }
  35241. write (*gridView, "06-scene-captured");
  35242. // round 190em: nothing plays: an empty scene like the selected one (name, tempo, signature), selected
  35243. const auto empty = lynx::captureClipGridScene (*gridView, 1, { -1, -1 });
  35244. offline.dispatchPendingMessages();
  35245. {
  35246. const auto& sc = offline.getSong().clipGrid->scenes;
  35247. check ("capture with nothing playing: an empty row 2 named Verse, 128 BPM, 3 / 4", empty == 2 && clipsIn (2) == 0 && sc[2].name == "Verse"
  35248. && sc[2].tempo == 128.0 && sc[2].beatsPerBar == 3 && sc[2].beatUnit == 4);
  35249. }
  35250. write (*gridView, "06b-scene-captured-stopped");
  35251. // round 190em: Capture and Insert while clips play: playback moves to the new row (the runtime view shows what
  35252. // the player reports once the published song holds the moved slots)
  35253. {
  35254. const auto rowsBefore = offline.getSong().clipGrid->scenes.size();
  35255. lynx::selectClipGridScene (*gridView, 0);
  35256. const auto at = lynx::captureClipGridScene (*gridView, 0, { 0, 0, -1 });
  35257. offline.dispatchPendingMessages();
  35258. const auto& g = *offline.getSong().clipGrid;
  35259. check ("capture while playing: row 1 holds the moved playing slots", at == 1 && g.scenes.size() == rowsBefore + 1
  35260. && clipsIn (1) == 2 && clipsIn (0) == 2 && g.scenes[1] == lynx::ClipGridScene {});
  35261. if (auto* runtime = offline.launcherStateForSnapshot())
  35262. for (int t = 0; t < 2; ++t)
  35263. runtime->tracks[(std::size_t) t].playing.store (1);
  35264. lynx::refreshClipGrid (*gridView);
  35265. write (*gridView, "09-capture-playing-moves");
  35266. if (auto* runtime = offline.launcherStateForSnapshot())
  35267. for (int t = 0; t < 2; ++t)
  35268. runtime->tracks[(std::size_t) t].playing.store (-1);
  35269. }
  35270. // round 190em: the fields as "n / d", a selected field, Del = Return to Default
  35271. lynx::clipGridSceneTempoShown() = true;
  35272. lynx::refreshClipGrid (*gridView);
  35273. {
  35274. const auto& sc = offline.getSong().clipGrid->scenes;
  35275. int verse = -1;
  35276. for (int r = 0; r < (int) sc.size() && verse < 0; ++r)
  35277. if (sc[(std::size_t) r].name == "Verse" && sc[(std::size_t) r].tempo > 0.0)
  35278. verse = r;
  35279. lynx::selectClipGridSceneField (*gridView, verse, 1);
  35280. write (*gridView, "10-field-selected");
  35281. gridView->keyPressed (juce::KeyPress (juce::KeyPress::deleteKey));
  35282. offline.dispatchPendingMessages();
  35283. const auto& after = offline.getSong().clipGrid->scenes;
  35284. check ("Del on a selected tempo field returns it to default (scene kept)", verse >= 0 && after.size() == sc.size()
  35285. && after[(std::size_t) verse].tempo == 0.0 && after[(std::size_t) verse].beatsPerBar == 3);
  35286. write (*gridView, "11-field-returned-to-default");
  35287. }
  35288. // round 190em: Capture MIDI to the armed track (Bass), the selected scene's slot, the tempo from the phrase
  35289. {
  35290. offline.stop();
  35291. offline.setGridTrackArmed (1, true, true);
  35292. lynx::selectClipGridScene (*gridView, 0);
  35293. int empty = 0;
  35294. while (lynx::launcher::clipAt (*offline.getSong().clipGrid, 1, empty) != nullptr)
  35295. ++empty;
  35296. const auto now = juce::Time::getMillisecondCounterHiRes();
  35297. const auto beat = 60000.0 / 148.0;
  35298. for (int i = 0; i < 8; ++i)
  35299. {
  35300. const auto at = now - 9.0 * beat + i * beat;
  35301. offline.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  35302. offline.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  35303. }
  35304. int placed = -1;
  35305. bool into = true;
  35306. const auto r = offline.captureMidiToSlot (1, empty, placed, into);
  35307. offline.dispatchPendingMessages();
  35308. check ("Capture MIDI: 8 notes into Bass row " + juce::String (placed) + ", tempo " + juce::String (offline.getSong().bpm, 2),
  35309. r.notes == 8 && placed == empty && ! into && std::abs (offline.getSong().bpm - 148.0) < 0.5 && offline.getTransport().playing.load());
  35310. const auto& capturedGrid = *offline.getSong().clipGrid;
  35311. const auto* capturedClip = lynx::launcher::clipAt (capturedGrid, 1, placed);
  35312. const auto* slot = capturedClip != nullptr ? &capturedGrid.slots[(std::size_t) capturedClip->gridSlot] : nullptr;
  35313. check ("Capture MIDI: the clip has no name of its own (blank label, as Live)", slot != nullptr && slot->name.empty() && slot->blankName);
  35314. if (auto* runtime = offline.launcherStateForSnapshot())
  35315. runtime->tracks[1].playing.store (placed);
  35316. lynx::refreshClipGrid (*gridView);
  35317. write (*gridView, "12-capture-midi");
  35318. if (auto* runtime = offline.launcherStateForSnapshot())
  35319. runtime->tracks[1].playing.store (-1);
  35320. offline.stop();
  35321. }
  35322. write (ui, "07-window");
  35323. lynx::clipGridSceneTempoShown() = false;
  35324. lynx::refreshClipGrid (*gridView);
  35325. write (*gridView, "08-fields-off");
  35326. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  35327. }
  35328. void runDrawShot190ef (const juce::String& prefix)
  35329. {
  35330. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  35331. lynx::AudioEngine offline (false);
  35332. lynx::MainComponent ui (offline, false);
  35333. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  35334. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  35335. const auto write = [&prefix] (juce::Component& c, const char* name) {
  35336. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  35337. file.deleteFile();
  35338. juce::FileOutputStream out (file);
  35339. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  35340. };
  35341. juce::String checks;
  35342. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  35343. ui.setVisible (true);
  35344. ui.setClipLaunchWorkflow (true);
  35345. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  35346. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  35347. lynx::autolanes::setShown (true);
  35348. offline.editSong ([] (lynx::Song& s) {
  35349. if (s.mixer.size() < 4)
  35350. s.mixer.resize (4);
  35351. s.mixer[1].name = "Bass";
  35352. s.mixer[2].name = "Pad";
  35353. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  35354. s.playlistTracks[0].name = "Bass";
  35355. s.playlistTracks[0].mode = lynx::PlaylistTrackMode::audio;
  35356. s.playlistTracks[0].mixerTrack = 1;
  35357. s.playlistTracks[1].name = "Pad";
  35358. s.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  35359. s.playlistTracks[1].mixerTrack = 2;
  35360. }, false);
  35361. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0);
  35362. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerPan, 2, 0, 0 }, 1);
  35363. offline.editSong ([] (lynx::Song& s) {
  35364. for (int t = 0; t < 2; ++t)
  35365. if (! s.playlistTracks[(std::size_t) t].lanes.empty())
  35366. s.playlistTracks[(std::size_t) t].lanes[0].height = 110;
  35367. }, false);
  35368. offline.dispatchPendingMessages();
  35369. auto& playlist = ui.getPlaylistForSnapshot();
  35370. playlist.setViewForSnapshot (180.0, 0, 0);
  35371. ui.resized();
  35372. offline.dispatchPendingMessages();
  35373. const auto& song = offline.getSong();
  35374. const auto laneA = song.playlistTracks[0].lanes.empty() ? -1 : song.playlistTracks[0].lanes[0].automation;
  35375. const auto laneB = song.playlistTracks[1].lanes.empty() ? -1 : song.playlistTracks[1].lanes[0].automation;
  35376. check ("two lanes made", laneA >= 0 && laneB >= 0);
  35377. if (laneA < 0 || laneB < 0)
  35378. {
  35379. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  35380. return;
  35381. }
  35382. write (ui, "00-lanes-before");
  35383. const auto before = song.automations[(std::size_t) laneA].points;
  35384. // a drag through the Playlist's own handlers (the events a real mouse sends)
  35385. auto source = juce::Desktop::getInstance().getMainMouseSource();
  35386. const auto now = juce::Time::getCurrentTime();
  35387. const auto stroke = [&] (int track, const std::vector<juce::Point<float>>& path, juce::ModifierKeys extra) {
  35388. const juce::ModifierKeys mods (juce::ModifierKeys::leftButtonModifier | extra.getRawFlags());
  35389. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
  35390. return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, path.front(), now, 1, dragged);
  35391. };
  35392. juce::ignoreUnused (track);
  35393. // (the engine joins the edits of one press into one undo step while a button is down)
  35394. const auto held = juce::ModifierKeys::currentModifiers;
  35395. juce::ModifierKeys::currentModifiers = mods;
  35396. playlist.mouseDown (event (path.front(), mods, false));
  35397. for (std::size_t i = 1; i < path.size(); ++i)
  35398. playlist.mouseDrag (event (path[i], mods, true));
  35399. juce::ModifierKeys::currentModifiers = held;
  35400. playlist.mouseUp (event (path.back(), extra, true));
  35401. };
  35402. const auto bodyA = playlist.laneBodyForSnapshot (0, 0), bodyB = playlist.laneBodyForSnapshot (1, 0);
  35403. const auto bar = (double) (4 * lynx::ppq);
  35404. const auto x = [&] (double bars) { return (float) playlist.xOfTickForSnapshot (bars * bar); };
  35405. const auto y = [] (juce::Rectangle<float> body, float v) { return body.getBottom() - v * body.getHeight(); };
  35406. lynx::drawmode::set (true);
  35407. // steps: a rise over bar 1 and a fall over bar 2, at the Playlist's grid (Line, at this zoom)
  35408. std::vector<juce::Point<float>> steps;
  35409. for (int k = 0; k <= 16; ++k)
  35410. steps.push_back ({ x (1.0 + k / 16.0) + 2.0f, y (bodyA, 0.15f + 0.05f * (float) k) });
  35411. for (int k = 0; k <= 16; ++k)
  35412. steps.push_back ({ x (2.0 + k / 16.0) + 2.0f, y (bodyA, 0.95f - 0.05f * (float) k) });
  35413. stroke (0, steps, {});
  35414. const auto& afterSteps = offline.getSong().automations[(std::size_t) laneA].points;
  35415. check ("Draw Mode drag made steps (" + juce::String ((int) afterSteps.size()) + " points)", afterSteps.size() > before.size() + 4);
  35416. bool unchangedOutside = true;
  35417. for (double t = 0.0; t < 6.0 * bar; t += 37.0)
  35418. if ((t < bar - 1.0 || t > 3.1 * bar) && std::abs (lynx::automationCurveAt (before, t) - lynx::automationCurveAt (afterSteps, t)) > 1.0e-4f)
  35419. unchangedOutside = false;
  35420. check ("the curve outside the drawn bars is unchanged", unchangedOutside);
  35421. {
  35422. // flat inside each drawn cell: the values in a cell's first and last tick are the same
  35423. int flatCells = 0, cells = 0;
  35424. for (double t = bar; t < 3.0 * bar; t += lynx::ppq / 4.0)
  35425. {
  35426. ++cells;
  35427. if (std::abs (lynx::automationCurveAt (afterSteps, t + 1.0) - lynx::automationCurveAt (afterSteps, t + lynx::ppq / 4.0 - 1.0)) < 1.0e-5f)
  35428. ++flatCells;
  35429. }
  35430. check ("each sixteenth inside bars 2-3 is flat (" + juce::String (flatCells) + " / " + juce::String (cells) + ")", flatCells == cells);
  35431. }
  35432. // freehand: Alt (no grid) on the pad's pan lane, a wave over bars 1-4
  35433. const auto panBefore = offline.getSong().automations[(std::size_t) laneB].points;
  35434. // (off-screen every press has the same mouse-down time, which the undo history uses to join one press's edits:
  35435. // an edit with no button down in between separates the two strokes, as a real second press does)
  35436. offline.editSong ([] (lynx::Song&) {});
  35437. std::vector<juce::Point<float>> wave;
  35438. for (int k = 0; k <= 60; ++k)
  35439. wave.push_back ({ x (1.0 + 3.0 * k / 60.0), y (bodyB, 0.5f + 0.4f * std::sin ((float) k * 0.3f)) });
  35440. stroke (1, wave, juce::ModifierKeys (juce::ModifierKeys::altModifier));
  35441. const auto& pan = offline.getSong().automations[(std::size_t) laneB].points;
  35442. check ("Alt drag drew freehand (" + juce::String ((int) pan.size()) + " points)", pan.size() > 30);
  35443. playlist.repaint();
  35444. write (ui, "01-draw-mode-steps-and-freehand");
  35445. if (auto* parent = playlist.getParentComponent())
  35446. write (*parent, "01b-playlist");
  35447. // one stroke is one undo step
  35448. offline.undo();
  35449. check ("one undo takes the whole freehand stroke back", offline.getSong().automations[(std::size_t) laneB].points == panBefore);
  35450. // Draw Mode off: the same press adds one point, as before
  35451. lynx::drawmode::set (false);
  35452. const auto countOff = offline.getSong().automations[(std::size_t) laneA].points.size();
  35453. stroke (0, { { x (4.5), y (bodyA, 0.8f) } }, {});
  35454. check ("Draw Mode off: a press adds one point", offline.getSong().automations[(std::size_t) laneA].points.size() == countOff + 1);
  35455. // the Options menu (Clip-launch layout) with the switch
  35456. lynx::drawmode::set (true);
  35457. {
  35458. const auto names = ui.getMenuNamesForSnapshot();
  35459. const auto index = names.indexOf (TRANS ("Options"));
  35460. if (index >= 0)
  35461. saveMenus (juce::StringArray { "Options" }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-02-options-menu.png");
  35462. check ("Options menu found", index >= 0);
  35463. }
  35464. lynx::drawmode::set (false);
  35465. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  35466. }
  35467. void runClipEnvShot190gi (const juce::String& prefix)
  35468. {
  35469. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  35470. lynx::AudioEngine offline (false);
  35471. lynx::MainComponent ui (offline, false);
  35472. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  35473. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  35474. const auto write = [&prefix] (juce::Component& c, const char* name) {
  35475. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  35476. file.deleteFile();
  35477. juce::FileOutputStream out (file);
  35478. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  35479. };
  35480. juce::String checks;
  35481. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  35482. // two files: a sustained pad (4 s, a slow swell, for the envelope over its waveform) and a one-bar loop of clicks
  35483. const auto writeWav = [] (const juce::File& file, int seconds, const std::function<float (int, double)>& fn) {
  35484. const double rate = 48000.0;
  35485. juce::AudioBuffer<float> buffer (2, (int) (rate * seconds));
  35486. for (int ch = 0; ch < 2; ++ch)
  35487. for (int i = 0; i < buffer.getNumSamples(); ++i)
  35488. buffer.setSample (ch, i, fn (i, rate));
  35489. file.deleteFile();
  35490. if (auto out = std::unique_ptr<juce::FileOutputStream> (file.createOutputStream()))
  35491. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  35492. {
  35493. out.release();
  35494. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  35495. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  35496. }
  35497. return file;
  35498. };
  35499. const auto pad = writeWav (juce::File (prefix + "-pad.wav"), 4, [] (int i, double rate) {
  35500. const auto t = i / rate;
  35501. return (float) (0.45 * (std::sin (juce::MathConstants<double>::twoPi * 220.0 * t) + 0.5 * std::sin (juce::MathConstants<double>::twoPi * 331.0 * t))
  35502. * (0.7 + 0.3 * std::sin (juce::MathConstants<double>::twoPi * 1.5 * t)));
  35503. });
  35504. const auto loop = writeWav (juce::File (prefix + "-loop.wav"), 2, [] (int i, double) {
  35505. const auto k = i % 12000;
  35506. const auto hit = i / 12000;
  35507. return k < 3000 ? (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8) : 0.0f;
  35508. });
  35509. ui.setVisible (true);
  35510. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  35511. offline.editSong ([&] (lynx::Song& s) {
  35512. const auto add = [&s] (const char* name, const juce::File& file) {
  35513. lynx::ChannelDef ch;
  35514. ch.name = name;
  35515. ch.instrument = lynx::InstrumentKind::audioClip;
  35516. ch.samplePath = file.getFullPathName().toStdString();
  35517. s.channels.push_back (ch);
  35518. return (int) s.channels.size() - 1;
  35519. };
  35520. const auto padChannel = add ("Pad", pad), loopChannel = add ("Loop", loop);
  35521. s.playlist.clear();
  35522. lynx::Clip a;
  35523. a.kind = lynx::ClipKind::audio;
  35524. a.channel = padChannel;
  35525. a.length = 8 * lynx::ppq;
  35526. a.track = 0;
  35527. s.playlist.push_back (a);
  35528. a.track = 1;
  35529. s.playlist.push_back (a);
  35530. lynx::Clip b = a;
  35531. b.channel = loopChannel;
  35532. b.track = 2;
  35533. b.length = 4 * lynx::ppq;
  35534. s.playlist.push_back (b);
  35535. // the first clip: a volume envelope (a swell, a dip, FL's curve modes on two segments)
  35536. auto& e = lynx::clipenv::own (s, s.playlist[0]);
  35537. e.shown = lynx::clipenv::volumeLane;
  35538. e.volume = { { 0, 0.15f, 0.0f, 0 }, { lynx::ppq * 2, 1.0f, -0.6f, 0 }, { lynx::ppq * 4, 1.0f, 0.0f, 0 },
  35539. { lynx::ppq * 5, 0.45f, 0.0f, 2 }, { lynx::ppq * 6, 0.9f, 0.0f, 0 }, { lynx::ppq * 8, 0.9f, 0.0f, 0 } };
  35540. // the second: its pan lane shown (only pan made)
  35541. lynx::clipenv::show (s, s.playlist[1], lynx::clipenv::panLane);
  35542. auto& p = lynx::clipenv::own (s, s.playlist[1]);
  35543. 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 } };
  35544. if (s.playlistTracks.size() < 3)
  35545. s.playlistTracks.resize (3);
  35546. for (int t = 0; t < 3; ++t)
  35547. s.playlistTracks[(std::size_t) t].height = 96;
  35548. }, false);
  35549. offline.dispatchPendingMessages();
  35550. auto& playlist = ui.getPlaylistForSnapshot();
  35551. playlist.setViewForSnapshot (360.0, 0, 0);
  35552. ui.resized();
  35553. offline.dispatchPendingMessages();
  35554. (void) lynx::shot::snapshot (ui); // (a paint starts the waveform analyses; the shot waits for them)
  35555. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  35556. offline.dispatchPendingMessages();
  35557. write (ui, "01-playlist-envelopes");
  35558. // the clip menu: LYNX's extras with Clip envelope ›, Auto-warp, Quantize audio (Auto-warp run from it on the loop)
  35559. {
  35560. const auto menu = playlist.getClipMenuForSnapshot (2);
  35561. const juce::PopupMenu* envelopeMenu = nullptr;
  35562. bool autoWarp = false, quantize = false;
  35563. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  35564. {
  35565. if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
  35566. envelopeMenu = it.getItem().subMenu.get();
  35567. autoWarp = autoWarp || (it.getItem().text == lynx::tr ("Auto-warp") && it.getItem().isEnabled);
  35568. quantize = quantize || (it.getItem().text == lynx::tr ("Quantize audio") && it.getItem().isEnabled);
  35569. }
  35570. check ("clip menu: Clip envelope submenu, Auto-warp, Quantize audio", envelopeMenu != nullptr && autoWarp && quantize);
  35571. saveMenus (juce::StringArray { lynx::tr ("Audio clip"), lynx::tr ("Clip envelope") },
  35572. std::vector<juce::PopupMenu> { menu, envelopeMenu != nullptr ? *envelopeMenu : juce::PopupMenu() }, prefix + "-02-clip-menu.png");
  35573. check ("Auto-warp from the clip menu places markers", clickMenuItem (menu, lynx::tr ("Auto-warp")));
  35574. offline.dispatchPendingMessages();
  35575. const auto& s = offline.getSong();
  35576. const auto& loopClip = s.playlist[2];
  35577. check ("the loop's channel is warped", s.channels[(std::size_t) loopClip.channel].sampler.warp.size() >= 2
  35578. && s.channels[(std::size_t) loopClip.channel].sampler.keepPitch);
  35579. // the first clip's menu: Show volume envelope ticked
  35580. const auto first = playlist.getClipMenuForSnapshot (0);
  35581. bool ticked = false;
  35582. for (juce::PopupMenu::MenuItemIterator it (first); it.next();)
  35583. if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
  35584. for (juce::PopupMenu::MenuItemIterator sub (*it.getItem().subMenu); sub.next();)
  35585. ticked = ticked || (sub.getItem().text == lynx::tr ("Show volume envelope") && sub.getItem().isTicked);
  35586. check ("Show volume envelope is ticked on the first clip", ticked);
  35587. }
  35588. // gestures through the Playlist's own handlers
  35589. auto source = juce::Desktop::getInstance().getMainMouseSource();
  35590. const auto now = juce::Time::getCurrentTime();
  35591. const auto press = [&] (juce::Point<float> from, juce::Point<float> to, juce::ModifierKeys button, juce::ModifierKeys extra) {
  35592. const juce::ModifierKeys mods (button.getRawFlags() | extra.getRawFlags());
  35593. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
  35594. return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, from, now, 1, dragged);
  35595. };
  35596. const auto held = juce::ModifierKeys::currentModifiers;
  35597. juce::ModifierKeys::currentModifiers = mods;
  35598. playlist.mouseDown (event (from, mods, false));
  35599. if (to != from)
  35600. playlist.mouseDrag (event (to, mods, true));
  35601. juce::ModifierKeys::currentModifiers = held;
  35602. playlist.mouseUp (event (to, extra, to != from));
  35603. };
  35604. const auto x = [&] (double beats) { return (float) playlist.xOfTickForSnapshot (beats * lynx::ppq); };
  35605. {
  35606. const auto body = playlist.curveBodyForSnapshot (0);
  35607. const auto points = offline.getSong().clipEnvelopes[(std::size_t) offline.getSong().playlist[0].envelope].volume.size();
  35608. // [RMB] in the curve's area adds a point there (FL's in-Playlist automation editing, round 165)
  35609. press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.3f * body.getHeight() },
  35610. juce::ModifierKeys::rightButtonModifier, {});
  35611. offline.dispatchPendingMessages();
  35612. const auto& s = offline.getSong();
  35613. const auto* e = lynx::clipenv::of (s, s.playlist[0]);
  35614. check ("[RMB] on the clip's volume lane adds a point", e != nullptr && e->volume.size() == points + 1
  35615. && std::abs (lynx::automationCurveAt (e->volume, 7.0 * lynx::ppq) - 0.3f) < 0.05f);
  35616. // drag that point up with the Pencil
  35617. press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.7f * body.getHeight() },
  35618. juce::ModifierKeys::leftButtonModifier, {});
  35619. offline.dispatchPendingMessages();
  35620. const auto* moved = lynx::clipenv::of (offline.getSong(), offline.getSong().playlist[0]);
  35621. check ("dragging the point moves it", moved != nullptr && std::abs (lynx::automationCurveAt (moved->volume, 7.0 * lynx::ppq) - 0.7f) < 0.05f);
  35622. check ("the edits are undoable", offline.canUndo());
  35623. }
  35624. write (ui, "03-playlist-edited");
  35625. {
  35626. // warp: a double-click on the loop clip's flag strip adds a marker; Alt + drag on its line (mid clip) moves it
  35627. const auto bounds = playlist.clipBoundsForSnapshot (2);
  35628. const auto channelOf = [&] { return offline.getSong().playlist[2].channel; };
  35629. const auto markers = [&] { return offline.getSong().channels[(std::size_t) channelOf()].sampler.warp; };
  35630. const auto before = markers().size();
  35631. const juce::Point<float> strip { x (1.5), (float) bounds.getY() + 13.0f + 3.0f };
  35632. playlist.mouseDoubleClick (juce::MouseEvent (source, strip, juce::ModifierKeys::leftButtonModifier, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist,
  35633. now, strip, now, 2, false));
  35634. offline.dispatchPendingMessages();
  35635. check ("a double-click on the flag strip adds a warp marker", markers().size() == before + 1);
  35636. if (markers().size() != before + 1)
  35637. checks << " (strip seconds " << playlist.warpStripSecondsForSnapshot (2, strip.toInt()) << ", played markers "
  35638. << (int) playlist.warpMarkerCountForSnapshot (2) << ", file seconds " << playlist.clipFileSecondsForSnapshot (2)
  35639. << ", channel markers " << (int) before << ", clip at " << bounds.toString() << ", strip " << strip.toString() << ")\n";
  35640. int added = -1;
  35641. for (int k = 0; k < (int) markers().size(); ++k)
  35642. if (std::abs (markers()[(std::size_t) k].beats - 1.5) < 0.05)
  35643. added = k;
  35644. check ("the marker sits on the beat it was added on", added > 0);
  35645. if (added > 0)
  35646. {
  35647. const juce::Point<float> line { x (1.5), (float) bounds.getCentreY() + 10.0f };
  35648. press (line, line.translated (x (1.75) - x (1.5), 0.0f), juce::ModifierKeys::leftButtonModifier, juce::ModifierKeys::altModifier);
  35649. offline.dispatchPendingMessages();
  35650. 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);
  35651. }
  35652. }
  35653. write (ui, "04-playlist-warp");
  35654. // the Clip-launch layout: the Clip View's Envelopes tab of a grid audio clip
  35655. offline.editSong ([&] (lynx::Song& s) {
  35656. auto clip = s.playlist[0];
  35657. clip.start = 0;
  35658. lynx::launcher::setClip (s, 0, 0, clip);
  35659. lynx::launcher::ensureGrid (s).scenes.resize (std::max<std::size_t> (1, lynx::launcher::ensureGrid (s).scenes.size()));
  35660. }, false);
  35661. offline.dispatchPendingMessages();
  35662. const auto shootPanel = [&] (const char* name, bool envelopes, std::uint8_t lane) {
  35663. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  35664. if (panel == nullptr)
  35665. return false;
  35666. panel->setSize (1100, 300);
  35667. for (auto* child : panel->getChildren())
  35668. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (envelopes ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
  35669. if (b->onClick)
  35670. b->onClick();
  35671. if (lane != 0)
  35672. offline.editSong ([lane] (lynx::Song& s) {
  35673. if (s.clipGrid)
  35674. if (auto* c = const_cast<lynx::Clip*> (lynx::launcher::clipAt (*s.clipGrid, 0, 0)); c != nullptr)
  35675. lynx::clipenv::show (s, *c, lane);
  35676. }, false);
  35677. offline.dispatchPendingMessages();
  35678. write (*panel, name);
  35679. return true;
  35680. };
  35681. check ("Clip View: Sample tab", shootPanel ("05-clipview-sample", false, 0));
  35682. check ("Clip View: Envelopes tab, Clip > Gain", shootPanel ("06-clipview-envelopes-gain", true, lynx::clipenv::volumeLane));
  35683. check ("Clip View: Envelopes tab, Mixer > Track Panning", shootPanel ("07-clipview-envelopes-pan", true, lynx::clipenv::panLane));
  35684. {
  35685. const auto* c = offline.getSong().clipGrid ? lynx::launcher::clipAt (*offline.getSong().clipGrid, 0, 0) : nullptr;
  35686. check ("the grid clip keeps the volume envelope", c != nullptr && lynx::clipenv::activeOf (offline.getSong(), *c) != nullptr);
  35687. }
  35688. shootPanel ("08-clipview-sample-again", false, 0); // (the tab choice back to Sample for the next run)
  35689. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  35690. }
  35691. void runGapsShot190kf (const juce::String& prefix, const juce::String& wavPath)
  35692. {
  35693. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  35694. lynx::AudioEngine offline (false);
  35695. juce::String checks;
  35696. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  35697. // 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)
  35698. auto wav = juce::File (wavPath);
  35699. if (! wav.existsAsFile())
  35700. {
  35701. wav = juce::File (prefix + "-probe.wav");
  35702. wav.deleteFile();
  35703. const double rate = 44100.0;
  35704. juce::AudioBuffer<float> buffer (1, (int) (rate * 8.421));
  35705. for (int k = 0; k < buffer.getNumSamples(); ++k)
  35706. {
  35707. const auto t = std::fmod (k / rate, 0.5);
  35708. buffer.setSample (0, k, (float) (0.5 * std::exp (-t * 6.0) * std::sin (2.0 * juce::MathConstants<double>::pi * 220.0 * k / rate)));
  35709. }
  35710. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  35711. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  35712. {
  35713. out.release();
  35714. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  35715. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  35716. }
  35717. }
  35718. double seconds = 0.0;
  35719. {
  35720. juce::AudioFormatManager formats;
  35721. formats.registerBasicFormats();
  35722. if (std::unique_ptr<juce::AudioFormatReader> r (formats.createReaderFor (wav)); r != nullptr && r->sampleRate > 0.0)
  35723. seconds = (double) r->lengthInSamples / r->sampleRate;
  35724. }
  35725. check ("probe file " + wav.getFileName() + " " + juce::String (seconds, 3) + " s", seconds > 1.0);
  35726. const auto beats = seconds * 2.0; // (warped at 120 BPM, its own tempo)
  35727. offline.editSong ([&] (lynx::Song& s) {
  35728. s.bpm = 120.0;
  35729. lynx::ChannelDef ch;
  35730. ch.name = "warped";
  35731. ch.instrument = lynx::InstrumentKind::audioClip;
  35732. ch.samplePath = wav.getFullPathName().toStdString();
  35733. ch.sampler.keepPitch = true;
  35734. ch.sampler.stretchMethod = lynx::StretchMethod::complex;
  35735. ch.sampler.stretchBeats = (float) beats;
  35736. ch.sampler.warp = { { 0.0, 0.0 }, { seconds * 0.3, beats * 0.25 }, { seconds * 0.55, beats * 0.5 }, { seconds, beats } };
  35737. s.channels.push_back (ch);
  35738. const auto c = (int) s.channels.size() - 1;
  35739. lynx::Clip audio;
  35740. audio.kind = lynx::ClipKind::audio;
  35741. audio.channel = c;
  35742. audio.offset = 2 * lynx::ppq; // (Loop Position 1.3, Length 2.0.0 → 3.3, Start 1.4: the probe set's)
  35743. audio.length = 8 * lynx::ppq;
  35744. lynx::launcher::setClip (s, 0, 0, audio);
  35745. lynx::launcher::ensureGrid (s).scenes.resize (1);
  35746. auto& grid = *s.clipGrid;
  35747. for (auto& g : grid.clips)
  35748. if (g.gridSlot >= 0)
  35749. {
  35750. grid.slots[(std::size_t) g.gridSlot].loop = true;
  35751. grid.slots[(std::size_t) g.gridSlot].startMarker = lynx::ppq;
  35752. }
  35753. }, false);
  35754. offline.dispatchPendingMessages();
  35755. const auto editorOf = [] (juce::Component& panel) -> juce::Component* {
  35756. for (auto* child : panel.getChildren())
  35757. if (child->isVisible() && child->getWidth() > 400 && dynamic_cast<juce::Button*> (child) == nullptr)
  35758. return child;
  35759. return nullptr;
  35760. };
  35761. const auto write = [&] (juce::Component& panel, const char* name) {
  35762. offline.dispatchPendingMessages();
  35763. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  35764. file.deleteFile();
  35765. juce::FileOutputStream out (file);
  35766. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (panel), out);
  35767. };
  35768. const auto slotOf = [&] (auto&& fn) {
  35769. offline.editSong ([&] (lynx::Song& s) {
  35770. for (auto& g : s.clipGrid->clips)
  35771. if (g.gridSlot >= 0)
  35772. fn (g, s.clipGrid->slots[(std::size_t) g.gridSlot]);
  35773. }, false);
  35774. offline.dispatchPendingMessages();
  35775. };
  35776. {
  35777. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  35778. check ("the Clip View panel", panel != nullptr);
  35779. if (panel == nullptr)
  35780. return;
  35781. panel->setSize (1390, 670);
  35782. if (auto* e = editorOf (*panel)) // (the Clip-launch layout's beat-time view; off-screen there is no layout)
  35783. lynx::setAudioEditorBeatTimeForSnapshot (*e, 1);
  35784. write (*panel, "01-loop-on-start-marker");
  35785. // perf (round gaps190kf): the sample editor painted 40 times with the warp time line (a grid clip's editor)
  35786. // and without it (the same channel's editor panel, no grid clip) — ms per full paint
  35787. {
  35788. const auto timeIt = [] (juce::Component& c) {
  35789. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  35790. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  35791. for (int k = 0; k < 40; ++k)
  35792. {
  35793. juce::Graphics g (image);
  35794. c.paintEntireComponent (g, false);
  35795. }
  35796. return (juce::Time::getMillisecondCounterHiRes() - t0) / 40.0;
  35797. };
  35798. if (auto* withLane = editorOf (*panel))
  35799. {
  35800. auto plain = lynx::makeAudioEditorPanel (offline, (int) offline.getSong().channels.size() - 1, -1, true);
  35801. plain->setSize (withLane->getWidth(), withLane->getHeight());
  35802. lynx::setAudioEditorBeatTimeForSnapshot (*plain, 1);
  35803. offline.dispatchPendingMessages();
  35804. timeIt (*withLane);
  35805. timeIt (*plain);
  35806. double a = 0.0, b = 0.0;
  35807. for (int round = 0; round < 3; ++round)
  35808. {
  35809. a += timeIt (*withLane) / 3.0;
  35810. b += timeIt (*plain) / 3.0;
  35811. }
  35812. check ("paint ms: with the warp time line " + juce::String (a, 3) + ", without " + juce::String (b, 3), true);
  35813. }
  35814. }
  35815. auto* editor = editorOf (*panel);
  35816. check ("its sample editor", editor != nullptr);
  35817. if (editor != nullptr)
  35818. {
  35819. lynx::selectAudioEditorBraceForSnapshot (*editor, true);
  35820. write (*panel, "02-brace-selected");
  35821. lynx::selectAudioEditorBraceForSnapshot (*editor, false);
  35822. lynx::holdAudioEditorBraceForSnapshot (*editor, 2, 12 * lynx::ppq); // (the loop's end dragged to 4.1)
  35823. write (*panel, "03-loop-end-held-at-4.1");
  35824. lynx::holdAudioEditorBraceForSnapshot (*editor, 0, 0);
  35825. }
  35826. }
  35827. slotOf ([] (lynx::Clip& c, lynx::ClipGridSlot& slot) {
  35828. slot.loop = false;
  35829. slot.startMarker = 0;
  35830. c.offset = 0;
  35831. c.length = (std::int64_t) std::llround (10.0 * lynx::ppq);
  35832. });
  35833. {
  35834. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  35835. if (panel != nullptr)
  35836. {
  35837. panel->setSize (1390, 670);
  35838. if (auto* e = editorOf (*panel))
  35839. lynx::setAudioEditorBeatTimeForSnapshot (*e, 1);
  35840. write (*panel, "04-loop-off-start-end");
  35841. }
  35842. }
  35843. offline.editSong ([&] (lynx::Song& s) { lynx::clipsample::setWarp (s, (int) s.channels.size() - 1, false, seconds); }, false);
  35844. offline.dispatchPendingMessages();
  35845. {
  35846. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  35847. if (panel != nullptr)
  35848. {
  35849. panel->setSize (1390, 670);
  35850. if (auto* e = editorOf (*panel))
  35851. lynx::setAudioEditorBeatTimeForSnapshot (*e, 1);
  35852. write (*panel, "05-unwarped-seconds");
  35853. }
  35854. }
  35855. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  35856. }
  35857. void runLiveFactsShot190gx (const juce::String& prefix)
  35858. {
  35859. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  35860. lynx::AudioEngine offline (false);
  35861. juce::String checks;
  35862. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  35863. // a 1 kHz sine, 20 s at 48 kHz (Live's 190gu clip-envelope stimulus), −9 dBFS
  35864. const auto wav = juce::File (prefix + "-sine1k.wav");
  35865. wav.deleteFile();
  35866. {
  35867. const double rate = 48000.0;
  35868. juce::AudioBuffer<float> buffer (2, (int) (rate * 20.0));
  35869. for (int k = 0; k < buffer.getNumSamples(); ++k)
  35870. for (int ch = 0; ch < 2; ++ch)
  35871. buffer.setSample (ch, k, (float) (0.3535 * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * k / rate)));
  35872. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  35873. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  35874. {
  35875. out.release();
  35876. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  35877. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  35878. }
  35879. }
  35880. offline.editSong ([&wav] (lynx::Song& s) {
  35881. s.bpm = 120.0;
  35882. lynx::ChannelDef ch;
  35883. ch.name = "sine1k";
  35884. ch.instrument = lynx::InstrumentKind::audioClip;
  35885. ch.samplePath = wav.getFullPathName().toStdString();
  35886. s.channels.push_back (ch);
  35887. const auto c = (int) s.channels.size() - 1;
  35888. lynx::clipsample::setWarp (s, c, true, 20.0);
  35889. lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats);
  35890. lynx::Clip audio;
  35891. audio.kind = lynx::ClipKind::audio;
  35892. audio.channel = c;
  35893. audio.length = 40 * lynx::ppq;
  35894. // Live's Clip Gain staircase of the 190gu render (−1 … 1 in 0.1 steps, 2 beats each), as LYNX lane values
  35895. lynx::ClipEnvelope e;
  35896. for (int k = 0; k <= 20; ++k)
  35897. {
  35898. const auto v = lynx::clipenv::fromLive (lynx::clipenv::volumeLane, -1.0 + 0.1 * k);
  35899. for (const auto at : { 2 * k, 2 * k + 2 })
  35900. {
  35901. lynx::AutomationPoint p;
  35902. p.tick = (std::int64_t) at * lynx::ppq;
  35903. p.value = v;
  35904. e.volume.push_back (p);
  35905. }
  35906. }
  35907. e.shown = lynx::clipenv::volumeLane;
  35908. s.clipEnvelopes.push_back (e);
  35909. audio.envelope = (int) s.clipEnvelopes.size() - 1;
  35910. lynx::launcher::setClip (s, 0, 0, audio);
  35911. lynx::launcher::ensureGrid (s).scenes.resize (1);
  35912. }, false);
  35913. offline.dispatchPendingMessages();
  35914. const auto channelOf = [&] {
  35915. const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, 0);
  35916. return c != nullptr ? c->channel : -1;
  35917. };
  35918. const auto shoot = [&] (const char* name, int w, int h, int tab) {
  35919. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  35920. if (panel == nullptr)
  35921. return std::unique_ptr<juce::Component>();
  35922. panel->setSize (w, h);
  35923. if (tab != 0)
  35924. for (auto* child : panel->getChildren())
  35925. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (tab == 2 ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
  35926. if (b->onClick)
  35927. b->onClick();
  35928. offline.dispatchPendingMessages();
  35929. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  35930. file.deleteFile();
  35931. juce::FileOutputStream out (file);
  35932. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
  35933. return panel;
  35934. };
  35935. const auto visibleText = [] (juce::Component& panel, const juce::String& text) {
  35936. for (auto* child : panel.getChildren())
  35937. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == text)
  35938. return b->isVisible();
  35939. return false;
  35940. };
  35941. const auto setMode = [&] (int method) {
  35942. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf(), method); }, false);
  35943. offline.dispatchPendingMessages();
  35944. };
  35945. check ("01 Beats (Preserve label + chooser, loop icon + Transient Envelope)", shoot ("01-audio-beats", 900, 250, 1) != nullptr);
  35946. setMode ((int) lynx::StretchMethod::tones);
  35947. check ("02 Tones (Grain Size 30.00)", shoot ("02-audio-tones", 900, 250, 1) != nullptr);
  35948. setMode ((int) lynx::StretchMethod::texture);
  35949. check ("03 Texture (Grain Size 65.00, Flux only when it plays)", shoot ("03-audio-texture", 900, 250, 1) != nullptr);
  35950. { // (round 190ik: Complex Pro plays, its Formants and Envelope show)
  35951. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setComplexPro (s, channelOf()); }, false);
  35952. offline.dispatchPendingMessages();
  35953. check ("04 Complex Pro (Formants 100.00, Envelope 128)", shoot ("04-audio-complex-pro", 900, 250, 1) != nullptr);
  35954. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setWarpLaw (s, channelOf(), 0); }, false);
  35955. offline.dispatchPendingMessages();
  35956. check ("04b Complex Pro of a project saved before 0.1.30 (law chooser, no Formants / Envelope)",
  35957. shoot ("04b-audio-complex-pro-classic", 900, 250, 1) != nullptr);
  35958. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setWarpLaw (s, channelOf(), 1); }, false);
  35959. offline.dispatchPendingMessages();
  35960. }
  35961. setMode ((int) lynx::StretchMethod::beats);
  35962. {
  35963. auto panel = shoot ("05-envelopes-clip-gain-staircase", 1390, 420, 2);
  35964. check ("05 Envelopes tab shown on a warped clip", panel != nullptr && visibleText (*panel, lynx::tr ("Envelopes")));
  35965. }
  35966. offline.editSong ([&] (lynx::Song& s) { lynx::clipsample::setWarp (s, channelOf(), false, 20.0); }, false);
  35967. offline.dispatchPendingMessages();
  35968. {
  35969. auto panel = shoot ("06-unwarped-sample-only", 1390, 420, 2);
  35970. check ("06 an unwarped clip has no Envelopes tab (Live)", panel != nullptr && ! visibleText (*panel, lynx::tr ("Envelopes"))
  35971. && visibleText (*panel, lynx::tr ("Sample")));
  35972. }
  35973. // the law: Live's staircase values round trip through the lane values
  35974. bool law = true;
  35975. for (int k = 0; k <= 20; ++k)
  35976. {
  35977. const auto L = -1.0 + 0.1 * k;
  35978. law = law && std::abs (lynx::clipenv::toLive (lynx::clipenv::volumeLane, lynx::clipenv::fromLive (lynx::clipenv::volumeLane, L)) - L) < 2.0e-3;
  35979. }
  35980. check ("Clip Gain values round trip (Live → lane → Live)", law);
  35981. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  35982. }
  35983. void runDvShot190hr (const juce::String& prefix)
  35984. {
  35985. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  35986. lynx::AudioEngine offline (false);
  35987. lynx::MainComponent ui (offline, false);
  35988. ui.setSize (1600, 900);
  35989. juce::String checks;
  35990. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  35991. const auto write = [&prefix] (juce::Component& c, const char* name) {
  35992. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  35993. file.deleteFile();
  35994. juce::FileOutputStream out (file);
  35995. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  35996. };
  35997. ui.setVisible (true);
  35998. lynx::DetailView::shownSetting = true;
  35999. ui.selectTabForSnapshot (2);
  36000. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  36001. offline.editSong ([] (lynx::Song& s) {
  36002. const int ch = (int) s.channels.size();
  36003. s.channels.resize ((std::size_t) ch + 1);
  36004. s.channels[(std::size_t) ch].name = "Keys";
  36005. s.channels[(std::size_t) ch].instrument = lynx::InstrumentKind::synth;
  36006. while (s.patterns.empty())
  36007. s.patterns.emplace_back();
  36008. auto& p = s.patterns[0];
  36009. p.name = "Riff";
  36010. p.notes.clear();
  36011. const int keys[] { 62, 65, 69, 72, 64, 67 };
  36012. for (int i = 0; i < 6; ++i)
  36013. {
  36014. lynx::Note n;
  36015. n.channel = ch;
  36016. n.key = keys[i];
  36017. n.start = i * lynx::ppq / 2 + (i % 2 ? 37 : -0) + 11; // a little off the 1/16 grid
  36018. n.length = lynx::ppq / 3;
  36019. p.notes.push_back (n);
  36020. }
  36021. p.lengthTicks = 4 * lynx::ppq;
  36022. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  36023. s.playlistTracks[0].name = "Keys";
  36024. lynx::Clip clip;
  36025. clip.pattern = 0;
  36026. clip.length = 4 * lynx::ppq;
  36027. const auto id = lynx::launcher::setClip (s, 0, 0, clip);
  36028. lynx::launcher::setClip (s, 0, 1, clip);
  36029. auto& grid = lynx::launcher::ensureGrid (s);
  36030. grid.scenes.resize (3);
  36031. if (id >= 0)
  36032. {
  36033. auto& slot = grid.slots[(std::size_t) id];
  36034. slot.name = "Riff";
  36035. slot.startMarker = 2 * lynx::ppq; // Start 1. 3. 1 inside the loop 1. 1. 1 + 1 bar
  36036. slot.ownScale = true;
  36037. slot.scaleRoot = 2; // D, the scale list's first (Major)
  36038. slot.scaleIndex = (std::int16_t) lynx::projectkey::commonFirst().front();
  36039. slot.follow.enabled = true;
  36040. slot.follow.a = lynx::FollowKind::next;
  36041. slot.follow.b = lynx::FollowKind::jump;
  36042. slot.follow.jumpB = 1;
  36043. slot.follow.chanceA = 70;
  36044. slot.follow.chanceB = 30;
  36045. slot.follow.linked = true;
  36046. slot.follow.iterations = 2;
  36047. }
  36048. }, false);
  36049. offline.dispatchPendingMessages();
  36050. ui.resized();
  36051. auto* detail = ui.getDetailViewForSnapshot();
  36052. if (detail == nullptr)
  36053. {
  36054. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  36055. return;
  36056. }
  36057. detail->showSelection (0, 0);
  36058. detail->setPage (lynx::DetailView::Page::clip);
  36059. offline.dispatchPendingMessages();
  36060. ui.resized();
  36061. write (ui, "01-clip-view-midi");
  36062. write (*detail, "01b-detail-alone");
  36063. auto& roll = ui.getPianoRollForSnapshot();
  36064. check ("the docked editor uses the reference's grid (" + roll.liveGridTextForCheck() + ")", roll.liveGridOn() && roll.liveGridTextForCheck().isNotEmpty());
  36065. 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);
  36066. {
  36067. std::vector<juce::PopupMenu> menus { roll.liveGridMenu() };
  36068. saveMenus (juce::StringArray { "Grid" }, menus, prefix + "-02-grid-menu.png");
  36069. }
  36070. roll.liveGrid.fixed = true;
  36071. roll.liveGrid.fixedIndex = lynx::livegrid::defaultFixed;
  36072. roll.resized();
  36073. const auto sixteenth = roll.gridStepForCheck();
  36074. roll.runAction ("pianoRoll.liveGridNarrower");
  36075. const auto narrower = roll.gridStepForCheck();
  36076. roll.runAction ("pianoRoll.liveGridTriplet");
  36077. const auto triplet = roll.gridStepForCheck();
  36078. 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) + ")",
  36079. sixteenth == lynx::ppq / 4 && narrower == lynx::ppq / 8 && triplet == lynx::ppq / 12);
  36080. write (roll, "03-editor-grid-1-32T");
  36081. roll.runAction ("pianoRoll.liveGridTriplet");
  36082. roll.runAction ("pianoRoll.liveGridWider");
  36083. const auto before = offline.getSong().patterns[0].notes;
  36084. roll.runAction ("pianoRoll.liveQuantize"); // (Live 12: Edit › Quantize, the Quantize tool's settings: Grid = 1/16 here)
  36085. offline.dispatchPendingMessages();
  36086. {
  36087. const auto& after = offline.getSong().patterns[0].notes;
  36088. bool onGrid = ! after.empty();
  36089. for (const auto& n : after)
  36090. onGrid = onGrid && n.start % (lynx::ppq / 4) == 0;
  36091. check ("Ctrl+U quantized every note start onto the editor's 1/16 grid", onGrid && after.size() == before.size() && after != before);
  36092. }
  36093. roll.runAction ("pianoRoll.liveQuantizeSettings"); // (Live 12: Quantize Settings… opens the MIDI Tools' Quantize tool)
  36094. offline.dispatchPendingMessages();
  36095. check ("Ctrl+Shift+U shows the MIDI Tools' Quantize tool", detail->midiToolsForSnapshot().getTool() == lynx::MidiToolsPanel::quantize
  36096. && detail->midiToolsForSnapshot().isVisible());
  36097. ui.resized();
  36098. write (*detail, "04-after-quantize-tool");
  36099. // an audio clip transposed +30 st 25 ct (Live's ±48 st)
  36100. const auto wav = juce::File (prefix + "-tone.wav");
  36101. wav.deleteFile();
  36102. {
  36103. const double rate = 48000.0;
  36104. juce::AudioBuffer<float> buffer (1, (int) (rate * 2.0));
  36105. for (int k = 0; k < buffer.getNumSamples(); ++k)
  36106. buffer.setSample (0, k, (float) (0.5 * std::sin (k * 0.05)));
  36107. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  36108. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  36109. {
  36110. out.release();
  36111. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  36112. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  36113. }
  36114. }
  36115. offline.editSong ([&wav] (lynx::Song& s) {
  36116. lynx::ChannelDef ch;
  36117. ch.name = "Tone";
  36118. ch.instrument = lynx::InstrumentKind::audioClip;
  36119. ch.samplePath = wav.getFullPathName().toStdString();
  36120. s.channels.push_back (ch);
  36121. lynx::Clip audio;
  36122. audio.kind = lynx::ClipKind::audio;
  36123. audio.channel = (int) s.channels.size() - 1;
  36124. audio.length = 4 * lynx::ppq;
  36125. audio.pitch = 30.25f;
  36126. lynx::launcher::setClip (s, 1, 0, audio);
  36127. }, false);
  36128. offline.dispatchPendingMessages();
  36129. if (auto panel = lynx::makeClipAudioPanel (offline, 1, 0))
  36130. {
  36131. panel->setSize (900, 250);
  36132. write (*panel, "06-audio-transpose-30");
  36133. check ("audio clip transpose +30.25 st kept", std::abs (lynx::launcher::clipAt (*offline.getSong().clipGrid, 1, 0)->pitch - 30.25f) < 1e-4f);
  36134. }
  36135. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  36136. }
  36137. void runWarpShot190fm (const juce::String& prefix)
  36138. {
  36139. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  36140. lynx::AudioEngine offline (false);
  36141. juce::String checks;
  36142. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  36143. // a one-bar loop of clicks (2 s at 48 kHz) for the audio clips
  36144. const auto wav = juce::File (prefix + "-loop.wav");
  36145. wav.deleteFile();
  36146. {
  36147. const double rate = 48000.0;
  36148. juce::AudioBuffer<float> buffer (2, (int) (rate * 2.0));
  36149. buffer.clear();
  36150. for (int hit = 0; hit < 8; ++hit)
  36151. for (int k = 0; k < 3000; ++k)
  36152. for (int ch = 0; ch < 2; ++ch)
  36153. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
  36154. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  36155. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  36156. {
  36157. out.release();
  36158. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  36159. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  36160. }
  36161. }
  36162. offline.editSong ([&wav] (lynx::Song& s) {
  36163. lynx::ChannelDef ch;
  36164. ch.name = "Loop";
  36165. ch.instrument = lynx::InstrumentKind::audioClip;
  36166. ch.samplePath = wav.getFullPathName().toStdString();
  36167. s.channels.push_back (ch);
  36168. const auto c = (int) s.channels.size() - 1;
  36169. lynx::clipsample::setWarp (s, c, true, 2.0);
  36170. lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats); // (keeps the pitch: Beats, not Re-Pitch)
  36171. lynx::Clip audio;
  36172. audio.kind = lynx::ClipKind::audio;
  36173. audio.channel = c;
  36174. audio.length = 4 * lynx::ppq;
  36175. lynx::launcher::setClip (s, 0, 0, audio);
  36176. lynx::launcher::setClip (s, 0, 1, audio); // (a second clip on the same channel: O16)
  36177. lynx::launcher::ensureGrid (s).scenes.resize (2);
  36178. }, false);
  36179. offline.dispatchPendingMessages();
  36180. const auto shoot = [&] (const char* name) {
  36181. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  36182. if (panel == nullptr)
  36183. return false;
  36184. panel->setSize (900, 250);
  36185. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  36186. file.deleteFile();
  36187. juce::FileOutputStream out (file);
  36188. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
  36189. return true;
  36190. };
  36191. const auto channelOf = [&] (int scene) {
  36192. const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, scene);
  36193. return c != nullptr ? c->channel : -1;
  36194. };
  36195. const auto beatsOn = [&] { const auto& sm = offline.getSong().channels[(std::size_t) channelOf (0)].sampler; return sm.keepPitch && sm.stretchMethod == lynx::StretchMethod::beats; };
  36196. check ("01 Beats panel (defaults: Transients, Back-and-Forth, 100)", beatsOn() && shoot ("01-beats-defaults"));
  36197. offline.editSong ([&] (lynx::Song& s) {
  36198. const auto c = lynx::warpmodes::ownChannelForGridClip (s, 0, 0);
  36199. lynx::warpmodes::setPreserve (s, c, 3);
  36200. lynx::warpmodes::setLoopMode (s, c, 0);
  36201. lynx::warpmodes::setEnvelope (s, c, 40.0);
  36202. }, false);
  36203. offline.dispatchPendingMessages();
  36204. 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);
  36205. check ("02 Beats panel (1/8, Loop Off, 40)", beatsOn() && shoot ("02-beats-set"));
  36206. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::tones); }, false);
  36207. offline.dispatchPendingMessages();
  36208. check ("03 Tones panel (Grain Size 30)", shoot ("03-tones"));
  36209. offline.editSong ([&] (lynx::Song& s) {
  36210. lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::texture);
  36211. lynx::warpmodes::setGrain (s, channelOf (0), 120.0);
  36212. }, false);
  36213. offline.dispatchPendingMessages();
  36214. check ("04 Texture panel (Grain Size 120)", shoot ("04-texture"));
  36215. check ("Texture grain kept 120, Tones grain still 30", offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.textureGrain == 120.0f
  36216. && offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.tonesGrain == 30.0f);
  36217. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::complex); }, false);
  36218. offline.dispatchPendingMessages();
  36219. check ("05 Complex panel (no settings row)", shoot ("05-complex"));
  36220. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  36221. }
  36222. // LYNX --livelook190jnshot prefix [set.als]: round 190jn off screen (design190ia slices 13 CL-D, 17 CL-E, 18 CL-H,
  36223. // 19 CL-F, 25 CL-I: the Clip-launch layout in Ableton Live's look) — the Session mixer (selected, armed, muted,
  36224. // soloed, I/O on and off, peak pills), the Device View (cards, a card off and one folded, the hot-swap link, a Drum
  36225. // Rack's pads, an Instrument Rack's macros), the Clip View (MIDI and audio, three detail heights), the Info View with a
  36226. // hovered control and the status strip; with a Live set: its Arrangement in 19 px lanes, the 38 px option and a tall
  36227. // audio lane; every view once more in the classic LYNX look (View › Classic LYNX look). prefix-checks.txt
  36228. void runLiveLook190jnShot (const juce::String& prefix, const juce::String& set)
  36229. {
  36230. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  36231. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  36232. juce::String checks;
  36233. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  36234. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  36235. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  36236. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  36237. const auto area = [&prefix] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) { saveArea (c, r, prefix + "-" + name + ".png"); };
  36238. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  36239. const auto w = juce::jlimit (800, 3840, size[0].getIntValue()), h = juce::jlimit (450, 2160, size[1].getIntValue());
  36240. const auto classicBefore = lynx::clipGridClassicLook();
  36241. const auto tallBefore = lynx::playlistTallLiveLanes();
  36242. lynx::clipGridClassicLook() = false;
  36243. lynx::playlistTallLiveLanes() = false;
  36244. lynx::DetailView::infoViewShown = true;
  36245. // ---- A. a synthetic set (round 190dr's, with a Drum Rack and an audio loop) -----------------------------------
  36246. const auto wav = juce::File (prefix + "-loop.wav");
  36247. wav.deleteFile();
  36248. {
  36249. const double rate = 48000.0;
  36250. juce::AudioBuffer<float> buffer (2, (int) (rate * 4.0));
  36251. buffer.clear();
  36252. for (int hit = 0; hit < 16; ++hit)
  36253. for (int k = 0; k < 9000 && hit * 12000 + k < buffer.getNumSamples(); ++k)
  36254. for (int ch = 0; ch < 2; ++ch)
  36255. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 2500.0) * 0.8));
  36256. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  36257. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  36258. {
  36259. out.release();
  36260. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  36261. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  36262. }
  36263. }
  36264. {
  36265. lynx::AudioEngine offline (false);
  36266. lynx::MainComponent ui (offline, false);
  36267. ui.setSize (w, h);
  36268. const auto settle = [&] {
  36269. for (int k = 0; k < 3; ++k)
  36270. offline.dispatchPendingMessages();
  36271. };
  36272. ui.setVisible (true);
  36273. lynx::DetailView::shownSetting = true;
  36274. lynx::DetailView::devicesPage = true;
  36275. lynx::DetailView::preferredHeight = 228;
  36276. ui.setClipLaunchWorkflow (true);
  36277. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  36278. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  36279. settle();
  36280. int audioChannel = -1;
  36281. const auto selectedChannel = offline.getSelectedChannel();
  36282. offline.editSong ([&audioChannel, selectedChannel] (lynx::Song& s) {
  36283. lynx::Clip audio;
  36284. if (! s.playlist.empty())
  36285. {
  36286. audio = s.playlist.front();
  36287. audioChannel = audio.channel;
  36288. s.playlist.clear();
  36289. }
  36290. const int channels = (int) s.channels.size();
  36291. s.channels.resize ((std::size_t) channels + 3);
  36292. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  36293. for (int k = 0; k < 3; ++k)
  36294. {
  36295. auto& ch = s.channels[(std::size_t) (channels + k)];
  36296. ch.name = names[k];
  36297. ch.instrument = k == 0 ? lynx::InstrumentKind::patcher : lynx::InstrumentKind::synth;
  36298. ch.mixerTrack = k + 1;
  36299. }
  36300. // the Drum kit: a Drum Rack with Live's 909 pad names, its two first macros mapped
  36301. {
  36302. auto& kit = s.channels[(std::size_t) channels].patcher;
  36303. kit = lynx::rack::makeDrumRack();
  36304. const char* pads[] { "Bass Drum", "Rim Shot", "Snare Drum", "Hand Clap", "Snare Drum", "Closed Hi Hat", "Snare Drum", "Bass Drum",
  36305. "Low Tom", "Mid Tom", "Open Hi Hat", "Hi Tom", "Crash", "Crash", "Ride", "Ride" };
  36306. for (int p = 0; p < 16; ++p)
  36307. {
  36308. lynx::PatchNode n;
  36309. n.generator = true;
  36310. n.channel.instrument = lynx::InstrumentKind::sampler;
  36311. n.channel.name = pads[p];
  36312. lynx::rack::addPad (kit, 36 + p, pads[p], n);
  36313. }
  36314. if (auto* r = lynx::rack::rackOf (kit))
  36315. {
  36316. r->name = "909 Core Kit";
  36317. r->showMacros = true;
  36318. r->showPads = true;
  36319. r->shownMacros = 8;
  36320. r->macros[0].name = "Low Gain";
  36321. r->macros[1].name = "Mid Gain";
  36322. }
  36323. for (int m = 0; m < 2; ++m)
  36324. {
  36325. lynx::RackMapping map;
  36326. map.target = lynx::RackMapping::Target::chainVolume;
  36327. map.chain = m;
  36328. lynx::rack::map (kit, m, map);
  36329. }
  36330. lynx::rack::compile (kit);
  36331. }
  36332. if (audioChannel >= 0)
  36333. s.channels[(std::size_t) audioChannel].mixerTrack = 5;
  36334. if (s.mixer.size() < 8)
  36335. s.mixer.resize (8);
  36336. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Loop", "Reverb", "Delay" };
  36337. for (int i = 1; i < 8; ++i)
  36338. s.mixer[(std::size_t) i].name = inserts[i];
  36339. s.mixer[1].volume = lynx::sessionmixer::positionForDb (-3.0);
  36340. s.mixer[2].pan = 0.3f;
  36341. s.mixer[2].effects.clear();
  36342. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay, lynx::EffectKind::reverb })
  36343. {
  36344. lynx::EffectSlot fx;
  36345. fx.kind = kind;
  36346. const auto& info = lynx::effectInfo (kind);
  36347. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  36348. fx.params[k] = info.params[k].defaultValue;
  36349. s.mixer[2].effects.push_back (fx);
  36350. }
  36351. s.mixer[2].effects[2].enabled = false; // (the Delay off: Live dims a device that is off)
  36352. s.mixer[3].muted = true; // the Keys' activator off
  36353. s.mixer[4].inputChannel = 0;
  36354. s.mixer[4].inputStereo = true;
  36355. s.mixer[4].monitor = lynx::InputMonitor::automatic;
  36356. s.mixer[5].solo = false; // (soloed later: Live greys every activator while a track is soloed)
  36357. 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 } })
  36358. {
  36359. lynx::MixerSend send;
  36360. send.target = to;
  36361. send.level = lynx::faderGain (level);
  36362. s.mixer[(std::size_t) from].sends.push_back (send);
  36363. }
  36364. while (s.patterns.size() < 3)
  36365. s.patterns.emplace_back();
  36366. const char* patterns[] { "Beat", "Bassline", "Chords" };
  36367. for (int p = 0; p < 3; ++p)
  36368. {
  36369. auto& pattern = s.patterns[(std::size_t) p];
  36370. pattern.name = patterns[p];
  36371. pattern.notes.clear();
  36372. for (int k = 0; k < 6; ++k)
  36373. {
  36374. lynx::Note n;
  36375. n.channel = channels + p;
  36376. n.key = (p == 0 ? 36 : 48) + (k * 5) % 12 + p * 2;
  36377. n.start = (std::int64_t) k * lynx::ppq / 2;
  36378. n.length = lynx::ppq / 2;
  36379. n.velocity = 0.55f + 0.07f * (float) k;
  36380. pattern.notes.push_back (n);
  36381. }
  36382. pattern.lengthTicks = 4 * lynx::ppq;
  36383. }
  36384. // a "Lead" clip on the FX track for the Clip View's MIDI shot: notes of the rack's selected channel (the docked
  36385. // Piano roll edits its notes) in the Piano roll's opening rows
  36386. {
  36387. const auto kick = juce::jlimit (0, channels - 1, selectedChannel); // (the docked Piano roll edits the selected channel's notes)
  36388. lynx::Pattern lead;
  36389. lead.name = "Lead";
  36390. for (int k = 0; k < 6; ++k)
  36391. {
  36392. lynx::Note n;
  36393. n.channel = kick;
  36394. n.key = 79 + (k * 5) % 6; // (G6 .. C7 in FL's names, C5 = 60: the rows the docked Piano roll opens on)
  36395. n.start = (std::int64_t) k * lynx::ppq / 2;
  36396. n.length = lynx::ppq / 2;
  36397. n.velocity = 0.55f + 0.07f * (float) k;
  36398. lead.notes.push_back (n);
  36399. }
  36400. lead.lengthTicks = 4 * lynx::ppq;
  36401. s.patterns.push_back (lead);
  36402. }
  36403. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  36404. const char* tracks[] { "Drums", "Bass", "Keys", "Vox", "Loop", "FX" };
  36405. const std::uint32_t colours[] { 0xff9bc48d, 0xffd2e498, 0xffa595b5, 0xffcdf1f8, 0xfff7f47c, 0xffc6928b }; // (Live's palette)
  36406. for (int t = 0; t < 6; ++t)
  36407. {
  36408. s.playlistTracks[(std::size_t) t].name = tracks[t];
  36409. s.playlistTracks[(std::size_t) t].colour = colours[t];
  36410. }
  36411. s.playlistTracks[3].mode = lynx::PlaylistTrackMode::audio;
  36412. s.playlistTracks[3].mixerTrack = 4;
  36413. for (int t = 0; t < 3; ++t)
  36414. for (int r = 0; r < 3; ++r)
  36415. if (! (t == 2 && r == 0))
  36416. {
  36417. lynx::Clip clip;
  36418. clip.pattern = t;
  36419. clip.length = 4 * lynx::ppq;
  36420. lynx::launcher::setClip (s, t, r, clip);
  36421. }
  36422. {
  36423. lynx::Clip lead;
  36424. lead.pattern = (int) s.patterns.size() - 1;
  36425. lead.length = 4 * lynx::ppq;
  36426. lynx::launcher::setClip (s, 5, 0, lead);
  36427. }
  36428. if (audioChannel >= 0)
  36429. {
  36430. lynx::clipsample::setWarp (s, audioChannel, true, 4.0);
  36431. audio.track = 4;
  36432. audio.start = 0;
  36433. lynx::launcher::setClip (s, 4, 0, audio);
  36434. lynx::launcher::setClip (s, 4, 1, audio);
  36435. }
  36436. auto& grid = lynx::launcher::ensureGrid (s);
  36437. const char* scenes[] { "Intro", "Verse", "Drop" };
  36438. grid.scenes.resize (5);
  36439. for (int r = 0; r < 3; ++r)
  36440. grid.scenes[(std::size_t) r].name = scenes[r];
  36441. }, false);
  36442. settle();
  36443. offline.setGridTrackArmed (3, true);
  36444. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  36445. settle();
  36446. ui.resized();
  36447. auto* gridView = ui.getClipGridForSnapshot();
  36448. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  36449. auto* detail = ui.getDetailViewForSnapshot();
  36450. if (gridView == nullptr || mixer == nullptr || detail == nullptr)
  36451. {
  36452. check ("a grid, a Session mixer and a detail view", false);
  36453. return;
  36454. }
  36455. check ("the Live look is on (Clip-launch, classic off)", lynx::theme::livelook::active());
  36456. const auto meters = [&] {
  36457. mixer->tick();
  36458. const float peaks[] { 0.9f, 0.5f, 0.7f, 0.0f, 0.3f, 0.45f, 0.2f, 0.12f };
  36459. for (int i = 0; i < 8; ++i)
  36460. mixer->setMeterForSnapshot (i, peaks[i], peaks[i] * 0.85f, peaks[i] * 1.1f, peaks[i], i == 1 ? 1.2f : peaks[i] * 1.15f);
  36461. };
  36462. if (auto* runtime = offline.launcherStateForSnapshot())
  36463. {
  36464. runtime->tracks[0].playing.store (1);
  36465. runtime->tracks[0].progress.store (0.3f);
  36466. runtime->tracks[1].playing.store (1);
  36467. runtime->tracks[1].progress.store (0.3f);
  36468. runtime->tracks[4].playing.store (0);
  36469. runtime->tracks[4].progress.store (0.5f);
  36470. runtime->running.store (true);
  36471. }
  36472. lynx::selectClipGridSlotForSnapshot (*gridView, 1, 1); // (the Bass track selected: its strip #464646)
  36473. settle();
  36474. meters();
  36475. gridView->resized();
  36476. write (ui, "13-window");
  36477. write (*gridView, "13-grid-mixer");
  36478. area (*gridView, mixer->getBoundsInParent(), "13-mixer");
  36479. using Part = lynx::SessionMixerComponent::Part;
  36480. check ("mixer: the Drums strip has a peak pill in Live's look", ! mixer->partBounds (0, Part::peak).isEmpty());
  36481. check ("mixer: the Drums peak pill reads the clipped peak", mixer->loudestPeak (1) >= 1.0f);
  36482. line ("mixer: activator " + mixer->partBounds (0, Part::activator).toString() + ", solo " + mixer->partBounds (0, Part::solo).toString()
  36483. + ", arm " + mixer->partBounds (0, Part::arm).toString() + ", pan " + mixer->partBounds (0, Part::pan).toString()
  36484. + ", volume " + mixer->partBounds (0, Part::volume).toString() + ", peak " + mixer->partBounds (0, Part::peak).toString());
  36485. 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());
  36486. mixer->setHoverForSnapshot ({ 1, Part::solo, 0 });
  36487. area (*gridView, mixer->getBoundsInParent(), "13-mixer-hover-solo");
  36488. mixer->setHoverForSnapshot ({});
  36489. // the I/O section off (View › Mixer › I/O)
  36490. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.io = false; }, false);
  36491. settle();
  36492. gridView->resized();
  36493. meters();
  36494. area (*gridView, mixer->getBoundsInParent(), "13-mixer-io-off");
  36495. // a track soloed: Live greys every active activator (#757575, captured in shots/ref/live-mixer-solo-deactivated.png)
  36496. offline.editSong ([] (lynx::Song& s) { s.mixer[5].solo = true; }, false);
  36497. settle();
  36498. meters();
  36499. area (*gridView, mixer->getBoundsInParent(), "13-mixer-soloing");
  36500. offline.editSong ([] (lynx::Song& s) { s.mixer[5].solo = false; }, false);
  36501. settle();
  36502. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.io = true; }, false);
  36503. settle();
  36504. gridView->resized();
  36505. // ---- 19 + 25: the Device View of the Bass track (EQ, Compressor, Delay off, Reverb folded), the Info View ----
  36506. detail->showSelection (1, 1);
  36507. detail->setPage (lynx::DetailView::Page::devices);
  36508. settle();
  36509. ui.resized();
  36510. settle();
  36511. const auto cards = detail->cardCountForCheck();
  36512. line ("device view: " + juce::String (cards) + " cards, insert " + juce::String (detail->chainInsertForCheck()));
  36513. if (cards >= 5)
  36514. detail->toggleFoldForCheck (4);
  36515. detail->selectCardForCheck (1);
  36516. meters();
  36517. // the Info View with a hovered control: the Bass strip's activator, as the hint timer would give it
  36518. {
  36519. lynx::ui::Hint hint; // (the mixer's hint is its tooltip, read at the mouse: off screen its text for the part)
  36520. hint.text = mixer->tipForSnapshot ({ 1, Part::activator, 0 });
  36521. detail->setInfoHint (hint);
  36522. line ("info view: title '" + detail->infoViewForSnapshot().getTitleText() + "', body '" + detail->infoViewForSnapshot().getBodyText() + "'");
  36523. check ("info view: the hovered activator's hint shows", detail->infoViewForSnapshot().getBodyText().isNotEmpty());
  36524. }
  36525. write (ui, "19-window-devices");
  36526. write (*detail, "19-detail-devices");
  36527. area (*detail, detail->getLocalBounds().withTrimmedTop (detail->getHeight() - lynx::DetailView::stripHeight), "25-status-strip");
  36528. area (*detail, detail->getLocalBounds().withWidth (260), "25-info-view");
  36529. check ("device view: four effect cards and the instrument", cards >= 5);
  36530. check ("device view: the folded card stays folded", cards < 5 || detail->isFoldedForCheck (4));
  36531. // the hot-swap link on the selected card (Q)
  36532. ui.runActionForSnapshot ("view.hotSwap");
  36533. settle();
  36534. write (*detail, "19-detail-hotswap");
  36535. ui.runActionForSnapshot ("view.hotSwap");
  36536. settle();
  36537. // the Drum Rack (the Drums track's instrument)
  36538. detail->showSelection (0, 1);
  36539. settle();
  36540. detail->selectCardForCheck (0);
  36541. write (*detail, "19-detail-drumrack");
  36542. // an Instrument Rack (Keys grouped: Ctrl+G on the instrument card)
  36543. detail->showSelection (2, 1);
  36544. settle();
  36545. check ("device view: the Keys instrument grouped into an Instrument Rack", detail->groupCardForCheck (0, false));
  36546. settle();
  36547. write (*detail, "19-detail-instrumentrack");
  36548. // the Info View off (its (i) button), then back
  36549. detail->toggleInfoView();
  36550. write (*detail, "25-detail-info-off");
  36551. detail->toggleInfoView();
  36552. // ---- 17: the Clip View: a MIDI clip, then the audio clip at three detail heights --------------------------
  36553. detail->showSelection (5, 0); // (the FX track's Lead clip)
  36554. detail->setPage (lynx::DetailView::Page::clip);
  36555. settle();
  36556. ui.resized();
  36557. settle();
  36558. write (ui, "17-window-clip-midi");
  36559. write (*detail, "17-detail-clip-midi");
  36560. // Launch (folded at first, as Live shows it) and Pitch & Time open, the column scrolled to them
  36561. detail->clipSectionsForSnapshot (true, true, true, 0);
  36562. write (*detail, "17-detail-clip-midi-launch-open");
  36563. detail->clipSectionsForSnapshot (true, true, true, 160);
  36564. write (*detail, "17-detail-clip-midi-scrolled");
  36565. detail->clipSectionsForSnapshot (true, false, true, 0);
  36566. detail->showSelection (4, 0);
  36567. settle();
  36568. for (const auto height : { 190, 260, 350 })
  36569. {
  36570. lynx::DetailView::preferredHeight = height;
  36571. ui.resized();
  36572. if (auto* parent = detail->getParentComponent()) // (the Playlist area lays its docked detail view out)
  36573. parent->resized();
  36574. settle();
  36575. write (*detail, "17-detail-clip-audio-" + juce::String (height));
  36576. check ("audio box at " + juce::String (height) + " px: the detail view is that high", detail->getHeight() == height);
  36577. }
  36578. lynx::DetailView::preferredHeight = 228;
  36579. ui.resized();
  36580. if (auto* parent = detail->getParentComponent())
  36581. parent->resized();
  36582. settle();
  36583. write (ui, "17-window-clip-audio");
  36584. // ---- the same views in the classic LYNX look (View › Classic LYNX look in the Clip-launch layout) --------
  36585. lynx::clipGridClassicLook() = true;
  36586. lynx::refreshClipGrid (*gridView);
  36587. ui.getPlaylistForSnapshot().liveLanesChanged();
  36588. ui.resized();
  36589. detail->resized();
  36590. settle();
  36591. check ("classic look: the Live look is off", ! lynx::theme::livelook::active());
  36592. write (ui, "classic-window-clip-audio");
  36593. detail->setPage (lynx::DetailView::Page::devices);
  36594. detail->showSelection (1, 1);
  36595. settle();
  36596. meters();
  36597. write (ui, "classic-window-devices");
  36598. lynx::clipGridClassicLook() = false;
  36599. lynx::refreshClipGrid (*gridView);
  36600. ui.getPlaylistForSnapshot().liveLanesChanged();
  36601. ui.resized();
  36602. settle();
  36603. // ---- 18: the synthetic set's Arrangement (Song view) ------------------------------------------------------
  36604. offline.editSong ([audioChannel] (lynx::Song& s) {
  36605. for (int t = 0; t < 3; ++t)
  36606. for (int bar = 0; bar < 8; bar += 2)
  36607. {
  36608. lynx::Clip clip;
  36609. clip.pattern = t;
  36610. clip.track = t;
  36611. clip.start = (std::int64_t) bar * 4 * lynx::ppq + (t == 2 ? 4 * lynx::ppq : 0);
  36612. clip.length = 4 * lynx::ppq * (t == 1 ? 2 : 1);
  36613. if (! (t == 1 && bar % 4 != 0))
  36614. s.playlist.push_back (clip);
  36615. }
  36616. if (audioChannel >= 0)
  36617. for (int bar = 0; bar < 8; bar += 2)
  36618. {
  36619. lynx::Clip audio;
  36620. audio.channel = audioChannel;
  36621. audio.track = 4;
  36622. audio.start = (std::int64_t) bar * 4 * lynx::ppq;
  36623. audio.length = 8 * lynx::ppq;
  36624. audio.kind = lynx::ClipKind::audio;
  36625. s.playlist.push_back (audio);
  36626. }
  36627. }, false);
  36628. settle();
  36629. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  36630. settle();
  36631. ui.resized();
  36632. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  36633. settle();
  36634. ui.getPlaylistForSnapshot().repaint();
  36635. write (ui, "18-synthetic-arrangement-19");
  36636. lynx::playlistTallLiveLanes() = true;
  36637. ui.getPlaylistForSnapshot().liveLanesChanged();
  36638. settle();
  36639. write (ui, "18-synthetic-arrangement-38");
  36640. lynx::playlistTallLiveLanes() = false;
  36641. ui.getPlaylistForSnapshot().liveLanesChanged();
  36642. settle();
  36643. }
  36644. // ---- B. the Live set (its Arrangement with real audio) ----------------------------------------------------------
  36645. if (set.isNotEmpty() && juce::File (set).existsAsFile())
  36646. {
  36647. lynx::AudioEngine offline (false);
  36648. lynx::MainComponent ui (offline, false);
  36649. ui.setSize (w, h);
  36650. const auto settle = [&] {
  36651. for (int k = 0; k < 3; ++k)
  36652. offline.dispatchPendingMessages();
  36653. };
  36654. ui.setVisible (true);
  36655. lynx::DetailView::shownSetting = true;
  36656. lynx::DetailView::devicesPage = true;
  36657. ui.selectTabForSnapshot (2);
  36658. ui.setClipLaunchWorkflow (true); // (first: the import takes Live's colour table in this layout, CL-6)
  36659. settle();
  36660. ui.openFile (juce::File (set));
  36661. settle();
  36662. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  36663. settle();
  36664. ui.resized();
  36665. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  36666. settle();
  36667. const auto& song = offline.getSong();
  36668. line ("set: " + juce::String ((int) song.playlist.size()) + " Arrangement clips, " + juce::String ((int) song.playlistTracks.size()) + " tracks");
  36669. int drums = -1;
  36670. for (int t = 0; t < (int) song.playlistTracks.size() && drums < 0; ++t)
  36671. if (juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str()).containsIgnoreCase ("drum"))
  36672. drums = t;
  36673. if (drums >= 0)
  36674. line ("set: Drums track colour #" + juce::String::toHexString ((int) (song.playlistTracks[(std::size_t) drums].colour & 0xffffff)).paddedLeft ('0', 6));
  36675. check ("set: the Drums track has Live's colour #9BC48D (CL-6)", drums >= 0 && (song.playlistTracks[(std::size_t) drums].colour & 0xffffff) == 0x9bc48d);
  36676. write (ui, "18-als-arrangement-19");
  36677. // the set's Session mixer (the coordinator's 190jn follow-up: every Patience track has its strip)
  36678. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  36679. settle();
  36680. ui.resized();
  36681. settle();
  36682. if (auto* gridView = ui.getClipGridForSnapshot())
  36683. if (auto* mixer = lynx::clipGridMixer (*gridView))
  36684. {
  36685. int strips = 0;
  36686. for (int t = 0; t < 64; ++t)
  36687. strips += mixer->partBounds (t, lynx::SessionMixerComponent::Part::volume).isEmpty() ? 0 : 1;
  36688. line ("set: Session mixer strips with a volume: " + juce::String (strips) + ", mixer " + mixer->getBounds().toString()
  36689. + ", grid " + gridView->getBounds().toString());
  36690. write (ui, "13-als-window");
  36691. area (*gridView, mixer->getBoundsInParent(), "13-als-mixer");
  36692. }
  36693. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  36694. settle();
  36695. write (ui.getPlaylistForSnapshot(), "18-als-playlist-19");
  36696. lynx::playlistTallLiveLanes() = true;
  36697. ui.getPlaylistForSnapshot().liveLanesChanged();
  36698. settle();
  36699. write (ui, "18-als-arrangement-38");
  36700. // a tall audio lane (live-arrangement-audiolane.png: Vocal Main at ~250 px)
  36701. int vocal = -1;
  36702. for (int t = 0; t < (int) song.playlistTracks.size() && vocal < 0; ++t)
  36703. if (juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str()).containsIgnoreCase ("vocal"))
  36704. vocal = t;
  36705. if (vocal >= 0)
  36706. {
  36707. offline.editSong ([vocal] (lynx::Song& s) { s.playlistTracks[(std::size_t) vocal].height = 250; }, false);
  36708. lynx::playlistTallLiveLanes() = false;
  36709. ui.getPlaylistForSnapshot().liveLanesChanged();
  36710. settle();
  36711. write (ui, "18-als-audiolane");
  36712. }
  36713. line ("set: Vocal track " + juce::String (vocal));
  36714. lynx::clipGridClassicLook() = true;
  36715. ui.getPlaylistForSnapshot().liveLanesChanged();
  36716. settle();
  36717. write (ui, "classic-als-arrangement");
  36718. lynx::clipGridClassicLook() = false;
  36719. }
  36720. lynx::clipGridClassicLook() = classicBefore;
  36721. lynx::playlistTallLiveLanes() = tallBefore;
  36722. wav.deleteFile();
  36723. line ("done");
  36724. }
  36725. // LYNX --fllook190joshot prefix project.flp: round 190jo off screen (design190ia slices 12 FM-S6, 21 FM-S4, 23 FW-S4)
  36726. void runFllook190joShot (const juce::String& prefix, const juce::String& project)
  36727. {
  36728. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  36729. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  36730. lynx::ui::motion::enabled() = false; // (hover states drawn at once, no fade)
  36731. juce::String checks;
  36732. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  36733. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  36734. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  36735. lynx::AudioEngine offline (false);
  36736. lynx::MainComponent ui (offline, false);
  36737. ui.setSize (1920, 1080);
  36738. const auto settle = [&] {
  36739. for (int k = 0; k < 3; ++k)
  36740. offline.dispatchPendingMessages();
  36741. };
  36742. const auto area = [&] (juce::Rectangle<int> r, const juce::String& name) { saveArea (ui, r, prefix + "-" + name + ".png"); };
  36743. ui.selectTabForSnapshot (2);
  36744. if (project.isNotEmpty())
  36745. {
  36746. ui.openFile (juce::File (project));
  36747. settle();
  36748. }
  36749. check ("the project opened", ! offline.getSong().channels.empty());
  36750. const auto bar = [&ui] { return ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 90)); };
  36751. const std::pair<int, int> sizes[] { { 1920, 1080 }, { 1600, 900 }, { 1366, 768 }, { 1280, 800 } };
  36752. // ---- slice 12: the Pattern toolbar ------------------------------------------------------------------------------
  36753. for (const auto& [w, h] : sizes)
  36754. {
  36755. ui.setSize (w, h);
  36756. settle();
  36757. area (bar(), "tb-" + juce::String (w));
  36758. int tiles = 0;
  36759. for (auto* c : ui.getChildren())
  36760. if (auto* b = dynamic_cast<lynx::IconButton*> (c); b != nullptr && b->isVisible() && b->getLook() == lynx::IconButton::Look::flTile)
  36761. ++tiles;
  36762. line ("toolbar " + juce::String (w) + ": " + juce::String (tiles) + " tiled buttons");
  36763. }
  36764. ui.setSize (1920, 1080);
  36765. settle();
  36766. std::vector<lynx::IconButton*> tiled;
  36767. for (auto* c : ui.getChildren())
  36768. if (auto* b = dynamic_cast<lynx::IconButton*> (c); b != nullptr && b->isVisible() && b->getLook() == lynx::IconButton::Look::flTile)
  36769. tiled.push_back (b);
  36770. check ("the Pattern toolbar's buttons are FL tiles (" + juce::String ((int) tiled.size()) + ")", tiled.size() >= 25);
  36771. std::vector<bool> lit;
  36772. for (auto* b : tiled)
  36773. lit.push_back (b->getToggleState());
  36774. area (bar(), "tb-states-idle");
  36775. for (const auto& [state, name] : { std::pair<juce::Button::ButtonState, const char*> { juce::Button::buttonOver, "hover" }, { juce::Button::buttonDown, "pressed" } })
  36776. {
  36777. for (auto* b : tiled)
  36778. b->setState (state);
  36779. area (bar(), juce::String ("tb-states-") + name);
  36780. for (auto* b : tiled)
  36781. b->setState (juce::Button::buttonNormal);
  36782. }
  36783. for (auto* b : tiled)
  36784. b->setToggleState (true, juce::dontSendNotification);
  36785. area (bar(), "tb-states-on");
  36786. for (auto* b : tiled)
  36787. b->setState (juce::Button::buttonOver);
  36788. area (bar(), "tb-states-on-hover");
  36789. for (std::size_t k = 0; k < tiled.size(); ++k)
  36790. {
  36791. tiled[k]->setState (juce::Button::buttonNormal);
  36792. tiled[k]->setToggleState (lit[k], juce::dontSendNotification);
  36793. tiled[k]->setEnabled (false);
  36794. }
  36795. area (bar(), "tb-states-disabled");
  36796. for (auto* b : tiled)
  36797. b->setEnabled (true);
  36798. // one switch and one plain button under the mouse, as FL's capture (its audio editor button lit)
  36799. if (auto* metronome = dynamic_cast<lynx::IconButton*> (ui.toolbarPartForSnapshot ("metronome")))
  36800. {
  36801. metronome->setState (juce::Button::buttonOver);
  36802. area (bar(), "tb-hover-switch");
  36803. metronome->setState (juce::Button::buttonNormal);
  36804. }
  36805. // the time panel in B:S:T at bar 3, step 05, tick 12 (FL: "3:05:12"), the tempo, and the hint bar
  36806. {
  36807. auto& transport = offline.getTransport();
  36808. const auto& song = offline.getSong();
  36809. transport.positionTicks.store ((double) (2 * song.barTicks()) + 4.0 * lynx::ticksPerStep + lynx::ticksPerStep / 2.0);
  36810. ui.transportTickForSnapshot();
  36811. auto* time = ui.toolbarPartForSnapshot ("position");
  36812. auto* tempo = ui.toolbarPartForSnapshot ("tempo");
  36813. if (time != nullptr && tempo != nullptr)
  36814. {
  36815. area (time->getBounds().getUnion (tempo->getBounds()).expanded (8, 6), "tb-time");
  36816. if (auto* hs = dynamic_cast<lynx::ui::HintSource*> (time))
  36817. line ("time panel: " + hs->hintAt ({}).value);
  36818. check ("the time panel reads FL's B:S:T (3:05:12)", dynamic_cast<lynx::ui::HintSource*> (time) != nullptr
  36819. && dynamic_cast<lynx::ui::HintSource*> (time)->hintAt ({}).value == "3:05:12");
  36820. }
  36821. transport.positionTicks.store (0.0);
  36822. ui.transportTickForSnapshot();
  36823. }
  36824. const auto hintColumn = juce::Rectangle<int> (0, 0, 360, 80);
  36825. if (auto* knob = dynamic_cast<lynx::ui::HintSource*> (ui.toolbarPartForSnapshot ("masterVolume")))
  36826. {
  36827. ui.setHintForSnapshot (knob->hintAt ({}));
  36828. area (hintColumn, "tb-hint-knob");
  36829. }
  36830. if (auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record")))
  36831. {
  36832. ui.setHintForSnapshot ({ rec->getTooltip().upToFirstOccurrenceOf ("\n", false, false), {}, false, true });
  36833. area (hintColumn, "tb-hint-button");
  36834. }
  36835. ui.setHintForSnapshot ({});
  36836. area (hintColumn, "tb-menu");
  36837. // ---- slice 21: the Piano roll ----------------------------------------------------------------------------------
  36838. ui.selectTabForSnapshot (1);
  36839. settle();
  36840. saveSnapshot (ui, prefix + "-pr.png");
  36841. auto& roll = ui.getPianoRollForSnapshot();
  36842. line ("piano roll rows: " + juce::String (roll.rowHeight) + " px");
  36843. check ("FL's 18 px rows by default", roll.rowHeight == 18);
  36844. const auto keysBefore = lynx::PianoRollComponent::keyStyle; // (round 190oo: FL's keys are the default)
  36845. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::piano;
  36846. roll.repaint();
  36847. saveSnapshot (ui, prefix + "-pr-pianokeys.png");
  36848. lynx::PianoRollComponent::keyStyle = keysBefore;
  36849. lynx::notenames::everyKey.store (true);
  36850. roll.repaint();
  36851. saveSnapshot (ui, prefix + "-pr-allnames.png");
  36852. lynx::notenames::everyKey.store (false);
  36853. roll.repaint();
  36854. ui.setHintForSnapshot (roll.hoverForSnapshot());
  36855. saveSnapshot (ui, prefix + "-pr-hover.png");
  36856. ui.setHintForSnapshot ({});
  36857. {
  36858. // FL's ghost capture: "Synth Bass" (no notes of its own in this pattern) over the other channels' notes
  36859. const auto& song = offline.getSong();
  36860. int bass = -1;
  36861. for (int c = 0; c < (int) song.channels.size() && bass < 0; ++c)
  36862. if (juce::String (song.channels[(std::size_t) c].name).equalsIgnoreCase ("Synth Bass"))
  36863. bass = c;
  36864. const auto kept = offline.getSelectedChannel();
  36865. if (bass >= 0)
  36866. {
  36867. offline.setSelectedChannel (bass);
  36868. settle();
  36869. roll.rowHeight = 18;
  36870. roll.repaint();
  36871. saveSnapshot (ui, prefix + "-pr-ghosts.png");
  36872. offline.setSelectedChannel (kept);
  36873. settle();
  36874. }
  36875. check ("Synth Bass found for the ghosts", bass >= 0);
  36876. }
  36877. {
  36878. // the note label against the note over the velocity range of each note colour group (WCAG)
  36879. float worst = 99.0f;
  36880. for (int group = 0; group < 16; ++group)
  36881. for (float v = 0.0f; v <= 1.0001f; v += 0.05f)
  36882. {
  36883. const auto fill = lynx::theme::noteGroupColour (group, v);
  36884. const auto label = fill.getPerceivedBrightness() > 0.5f ? lynx::theme::colour::bg0 : lynx::theme::colour::textPrimary;
  36885. worst = juce::jmin (worst, lynx::theme::contrast (label, fill));
  36886. }
  36887. line ("note label contrast, worst of 16 colour groups x velocity 0..1: " + juce::String (worst, 2) + ":1");
  36888. const auto red = lynx::theme::noteGroupColour (0, 0.78f);
  36889. line ("default note " + red.toDisplayString (false) + " label " + juce::String (lynx::theme::contrast (lynx::theme::colour::bg0, red), 2) + ":1");
  36890. check ("note labels >= 4.5:1 on the default red notes", lynx::theme::contrast (lynx::theme::colour::bg0, red) >= 4.5f);
  36891. }
  36892. ui.selectTabForSnapshot (2);
  36893. settle();
  36894. // ---- slice 23: the audio editor in Edison's layout -------------------------------------------------------------
  36895. {
  36896. const juce::File breaker ("C:\\Program Files\\Image-Line\\FL Studio 2026\\Data\\Patches\\Packs\\Loops\\DL Breaker.wav");
  36897. const auto wav = breaker.existsAsFile() ? breaker : juce::File (juce::SystemStats::getEnvironmentVariable ("LYNX_190JO_WAV", ""));
  36898. check ("FL's DL Breaker.wav", wav.existsAsFile());
  36899. if (wav.existsAsFile())
  36900. if (auto editor = lynx::makeAudioEditorForFileSnapshot (offline, wav))
  36901. {
  36902. for (const auto& [w, h] : { std::pair { 1120, 600 }, std::pair { 960, 520 } })
  36903. {
  36904. editor->setSize (w, h);
  36905. saveSnapshot (*editor, prefix + "-ed-breaker-" + juce::String (w) + ".png");
  36906. }
  36907. editor->setSize (760, 320); // (the compact form: a short dock)
  36908. saveSnapshot (*editor, prefix + "-ed-compact.png");
  36909. }
  36910. const auto at = lynx::addEdisonSlot (offline, 1);
  36911. settle();
  36912. if (at >= 0)
  36913. if (auto slot = lynx::makeEdisonSlotEditor (offline, 1, at))
  36914. {
  36915. slot->setSize (1120, 630);
  36916. saveSnapshot (*slot, prefix + "-ed-slot.png");
  36917. }
  36918. check ("an Edison slot editor", at >= 0);
  36919. const auto& song = offline.getSong();
  36920. int sampled = -1;
  36921. for (int c = 0; c < (int) song.channels.size() && sampled < 0; ++c)
  36922. if (! song.channels[(std::size_t) c].samplePath.empty())
  36923. sampled = c;
  36924. if (sampled >= 0)
  36925. if (auto panel = lynx::makeAudioEditorPanel (offline, sampled, -1))
  36926. {
  36927. panel->setSize (1100, 300);
  36928. saveSnapshot (*panel, prefix + "-ed-panel.png");
  36929. }
  36930. }
  36931. lynx::ui::motion::enabled() = true;
  36932. }
  36933. // Round 190kc (see --cliplaunch190kcshot above): the Patience set in the Clip-launch layout
  36934. void runClipLaunch190kcShot (const juce::String& prefix, const juce::String& set)
  36935. {
  36936. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  36937. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  36938. juce::String checks;
  36939. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  36940. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  36941. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  36942. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  36943. const auto area = [&prefix] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) { saveArea (c, r, prefix + "-" + name + ".png"); };
  36944. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  36945. const auto w = juce::jlimit (800, 3840, size[0].getIntValue()), h = juce::jlimit (450, 2160, size[1].getIntValue());
  36946. const auto classicBefore = lynx::clipGridClassicLook();
  36947. lynx::clipGridClassicLook() = false;
  36948. if (set.isEmpty() || ! juce::File (set).existsAsFile())
  36949. {
  36950. check ("the Live set given", false);
  36951. return;
  36952. }
  36953. using Part = lynx::SessionMixerComponent::Part;
  36954. lynx::AudioEngine offline (false);
  36955. lynx::MainComponent ui (offline, false);
  36956. ui.setSize (w, h);
  36957. const auto settle = [&] {
  36958. for (int k = 0; k < 3; ++k)
  36959. offline.dispatchPendingMessages();
  36960. };
  36961. ui.setVisible (true);
  36962. lynx::DetailView::shownSetting = true;
  36963. lynx::DetailView::devicesPage = true;
  36964. ui.selectTabForSnapshot (2);
  36965. ui.setClipLaunchWorkflow (true);
  36966. settle();
  36967. ui.openFile (juce::File (set));
  36968. settle();
  36969. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  36970. settle();
  36971. ui.resized();
  36972. settle();
  36973. auto* gridView = ui.getClipGridForSnapshot();
  36974. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  36975. if (gridView == nullptr || mixer == nullptr)
  36976. {
  36977. check ("a clip grid with its Session mixer", false);
  36978. return;
  36979. }
  36980. const auto& song = offline.getSong();
  36981. const auto returns = lynx::sessionmixer::returnsOf (song);
  36982. line ("returns: " + juce::String ((int) returns.size()) + ", return strips " + juce::String (mixer->returnColumnCount()));
  36983. check ("the set's two returns are Live return tracks (A Reverb, B Delay)",
  36984. returns.size() == 2 && lynx::sessionmixer::returnTitle (song, returns[0]) == "A Reverb" && lynx::sessionmixer::returnTitle (song, returns[1]) == "B Delay");
  36985. check ("two return strips beside the tracks", mixer->returnColumnCount() == 2);
  36986. check ("every track shows a Sends row per return (the sends at -inf)",
  36987. mixer->sendTargets() == returns && ! mixer->partBounds (0, Part::send, 1).isEmpty());
  36988. const auto retA = lynx::SessionMixerComponent::returnColumn (0);
  36989. check ("a return strip: Sends, volume, activator, Solo, no Arm",
  36990. ! mixer->partBounds (retA, Part::send, 1).isEmpty() && ! mixer->partBounds (retA, Part::activator).isEmpty()
  36991. && ! mixer->partBounds (retA, Part::solo).isEmpty() && mixer->partBounds (retA, Part::arm).isEmpty());
  36992. check ("the Main strip: a Pre / Post toggle per return", ! mixer->partBounds (-2, Part::post, 0).isEmpty() && ! mixer->partBounds (-2, Part::post, 1).isEmpty());
  36993. line ("Post A " + mixer->partBounds (-2, Part::post, 0).toString() + ", Post B " + mixer->partBounds (-2, Part::post, 1).toString()
  36994. + ", return A activator " + mixer->partBounds (retA, Part::activator).toString());
  36995. write (ui, "window");
  36996. area (*gridView, mixer->getBoundsInParent(), "mixer");
  36997. area (*gridView, { 0, 0, gridView->getWidth(), 240 }, "grid-top");
  36998. area (*gridView, mixer->getBoundsInParent().withTrimmedLeft (mixer->getWidth() - 260), "mixer-returns");
  36999. // a return's send to the other one, switched on; Pre on return B
  37000. offline.editSong ([&returns] (lynx::Song& s) {
  37001. lynx::sessionmixer::setSendEnabled (s, returns[0], returns[1], true);
  37002. lynx::sessionmixer::setPre (s, returns[1], true);
  37003. });
  37004. settle();
  37005. area (*gridView, mixer->getBoundsInParent(), "mixer-sendon-pre");
  37006. area (*gridView, mixer->getBoundsInParent().withTrimmedLeft (mixer->getWidth() - 260), "mixer-returns-sendon-pre");
  37007. 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]));
  37008. saveMenus (juce::StringArray { "Return send" }, std::vector<juce::PopupMenu> { mixer->sendMenu ({ lynx::SessionMixerComponent::returnColumn (1), Part::send, 0 }) },
  37009. prefix + "-menu-send.png");
  37010. offline.editSong ([&returns] (lynx::Song& s) {
  37011. lynx::sessionmixer::setSendEnabled (s, returns[0], returns[1], false);
  37012. lynx::sessionmixer::setPre (s, returns[1], false);
  37013. });
  37014. // the crossfader section: track 1 on A, track 2 on B, the crossfader a little towards A
  37015. const auto i0 = lynx::sessionmixer::stripOf (song, 0).insert, i1 = lynx::sessionmixer::stripOf (song, 1).insert;
  37016. offline.editSong ([i0, i1] (lynx::Song& s) {
  37017. lynx::launcher::ensureGrid (s).mixerView.crossfader = true;
  37018. if (i0 > 0)
  37019. s.mixer[(std::size_t) i0].crossfade = lynx::CrossfadeAssign::a;
  37020. if (i1 > 0)
  37021. s.mixer[(std::size_t) i1].crossfade = lynx::CrossfadeAssign::b;
  37022. s.crossfader = -0.3f;
  37023. });
  37024. settle();
  37025. gridView->resized(); // (the menu item does this: the grid gives the mixer its new height)
  37026. settle();
  37027. check ("the Crossfader section: A / B on a track, the crossfader on Main",
  37028. ! mixer->partBounds (0, Part::xfadeA).isEmpty() && ! mixer->partBounds (0, Part::xfadeB).isEmpty() && ! mixer->partBounds (-2, Part::crossfader).isEmpty());
  37029. line ("A " + mixer->partBounds (0, Part::xfadeA).toString() + ", B " + mixer->partBounds (0, Part::xfadeB).toString() + ", crossfader "
  37030. + mixer->partBounds (-2, Part::crossfader).toString());
  37031. area (*gridView, mixer->getBoundsInParent(), "mixer-crossfader");
  37032. area (*gridView, mixer->getBoundsInParent().withTrimmedLeft (mixer->getWidth() - 260), "mixer-returns-crossfader");
  37033. saveMenus (juce::StringArray { "Crossfader" }, std::vector<juce::PopupMenu> { mixer->crossfaderMenu() }, prefix + "-menu-curve.png");
  37034. lynx::clipGridClassicLook() = true;
  37035. lynx::refreshClipGrid (*gridView);
  37036. ui.resized();
  37037. settle();
  37038. area (*gridView, mixer->getBoundsInParent(), "classic-mixer-crossfader");
  37039. write (ui, "classic-window");
  37040. lynx::clipGridClassicLook() = false;
  37041. lynx::refreshClipGrid (*gridView);
  37042. ui.resized();
  37043. settle();
  37044. // the map modes: a key on a slot, a scene, Scene Down, the crossfader's left position
  37045. using namespace lynx::remotemap;
  37046. offline.editSong ([] (lynx::Song& s) {
  37047. assignKey (s, Target::slot (0, 0), 'Q');
  37048. assignKey (s, Target::sceneLaunch (0), 'W');
  37049. assignKey (s, Target::of (lynx::RemoteAction::sceneDown), 'J');
  37050. assignKey (s, Target::of (lynx::RemoteAction::crossfaderLeft), 'Z');
  37051. });
  37052. for (const auto mode : { Mode::key, Mode::midi })
  37053. {
  37054. ui.setMapMode (mode);
  37055. settle();
  37056. if (auto* overlay = ui.mapOverlayForSnapshot())
  37057. {
  37058. overlay->refresh();
  37059. const auto& spots = overlay->spots();
  37060. 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; }); };
  37061. line (juce::String (mode == Mode::key ? "key" : "midi") + " map: " + juce::String ((int) spots.size()) + " spots; relative strip "
  37062. + juce::String (count (lynx::RemoteAction::sceneUp) + count (lynx::RemoteAction::sceneDown) + count (lynx::RemoteAction::launchSelectedScene)
  37063. + count (lynx::RemoteAction::cancelLaunch))
  37064. + ", per-track launch " + juce::String (count (lynx::RemoteAction::launchSelectedClip)) + ", crossfader positions "
  37065. + juce::String (count (lynx::RemoteAction::crossfaderLeft) + count (lynx::RemoteAction::crossfaderCentre) + count (lynx::RemoteAction::crossfaderRight)));
  37066. check (juce::String (mode == Mode::key ? "Key" : "MIDI") + " Map Mode: the relative strip and the crossfader's three positions are mappable",
  37067. count (lynx::RemoteAction::sceneUp) == 1 && count (lynx::RemoteAction::sceneDown) == 1 && count (lynx::RemoteAction::launchSelectedScene) == 1
  37068. && count (lynx::RemoteAction::cancelLaunch) == 1 && count (lynx::RemoteAction::launchSelectedClip) >= 4
  37069. && count (lynx::RemoteAction::crossfaderLeft) == 1 && count (lynx::RemoteAction::crossfaderRight) == 1);
  37070. }
  37071. write (ui, mode == Mode::key ? "keymap" : "midimap");
  37072. }
  37073. ui.setMapMode (Mode::off);
  37074. settle();
  37075. // grooves on clips: a groove of LYNX's bank on the first MIDI clip and on an audio clip; the Clip View's Commit
  37076. int midiTrack = -1, midiScene = -1, audioTrack = -1, audioScene = -1;
  37077. if (song.clipGrid)
  37078. for (const auto& c : song.clipGrid->clips)
  37079. {
  37080. const auto scene = c.gridSlot >= 0 && c.gridSlot < (int) song.clipGrid->slots.size() ? song.clipGrid->slots[(std::size_t) c.gridSlot].scene : -1;
  37081. if (c.kind == lynx::ClipKind::pattern && midiTrack < 0)
  37082. midiTrack = c.track, midiScene = scene;
  37083. if (c.kind == lynx::ClipKind::audio && audioTrack < 0)
  37084. audioTrack = c.track, audioScene = scene;
  37085. }
  37086. line ("MIDI clip " + juce::String (midiTrack) + "/" + juce::String (midiScene) + ", audio clip " + juce::String (audioTrack) + "/" + juce::String (audioScene));
  37087. std::uint32_t grooveId = 0;
  37088. offline.editSong ([&grooveId, midiTrack, midiScene, audioTrack, audioScene] (lynx::Song& s) {
  37089. auto g = lynx::groove::factoryBank().front().groove;
  37090. g.timing = 1.0f;
  37091. grooveId = lynx::groove::add (s.grooves, g);
  37092. lynx::groove::setClipGroove (s, midiTrack, midiScene, grooveId);
  37093. lynx::groove::setClipGroove (s, audioTrack, audioScene, grooveId);
  37094. });
  37095. settle();
  37096. if (auto* detail = ui.getDetailViewForSnapshot(); detail != nullptr && midiTrack >= 0 && audioTrack >= 0)
  37097. {
  37098. detail->showSelection (midiTrack, midiScene);
  37099. detail->setPage (lynx::DetailView::Page::clip);
  37100. settle();
  37101. write (*detail, "clip-midi-groove");
  37102. detail->showSelection (audioTrack, audioScene);
  37103. detail->setPage (lynx::DetailView::Page::clip);
  37104. settle();
  37105. write (*detail, "clip-audio-groove");
  37106. const auto* audio = lynx::launcher::clipAt (*song.clipGrid, audioTrack, audioScene);
  37107. const auto sample = audio != nullptr && audio->channel >= 0 ? offline.getSampleLibrary().load (juce::String::fromUTF8 (song.channels[(std::size_t) audio->channel].samplePath.c_str()))
  37108. : nullptr;
  37109. check ("the audio clip's file loads", sample != nullptr);
  37110. if (sample != nullptr && audio != nullptr)
  37111. {
  37112. const auto hits = lynx::grooveaudio::hitsOf (song, *audio, *sample);
  37113. {
  37114. const auto all = lynx::clipwarp::attacks (*sample);
  37115. const auto& sm = song.channels[(std::size_t) audio->channel].sampler;
  37116. line ("audio file: " + juce::String ((int) sample->frames()) + " frames at " + juce::String (sample->sampleRate) + " Hz, "
  37117. + juce::String ((int) all.size()) + " attacks (first " + juce::String (all.empty() ? -1.0 : all.front(), 3) + " s); clip offset "
  37118. + juce::String (audio->offset) + " length " + juce::String (audio->length) + " stretch " + juce::String (audio->stretch, 3)
  37119. + "; warp " + juce::String ((int) sm.warp.size()) + " markers, keepPitch " + juce::String ((int) sm.keepPitch)
  37120. + ", first content beat " + juce::String (all.empty() ? 0.0 : lynx::grooveaudio::contentBeat (sm, all.front(), song.bpm), 3));
  37121. }
  37122. const auto pool = song.grooves.grooves.size();
  37123. offline.editSong ([&] (lynx::Song& s) {
  37124. if (const auto* c = lynx::launcher::clipAt (*s.clipGrid, audioTrack, audioScene))
  37125. if (auto g = lynx::grooveaudio::extract (s, *c, *sample, lynx::GrooveBase::sixteenth, "Vocal groove"); ! g.points.empty())
  37126. lynx::groove::add (s.grooves, std::move (g));
  37127. });
  37128. line ("audio clip: " + juce::String ((int) hits.size()) + " attacks; pool " + juce::String ((int) pool) + " -> " + juce::String ((int) song.grooves.grooves.size()));
  37129. check ("Extract Groove from the audio clip adds a groove", song.grooves.grooves.size() == pool + 1);
  37130. int placed = -1;
  37131. offline.editSong ([&] (lynx::Song& s) { placed = lynx::grooveaudio::commit (s, audioTrack, audioScene, *sample); });
  37132. auto gridCopy = *song.clipGrid;
  37133. const auto* slot = lynx::launcher::settingsAt (gridCopy, audioTrack, audioScene);
  37134. line ("commit on audio: " + juce::String (placed) + " warp markers");
  37135. check ("Commit on the audio clip writes warp markers and sets its groove to None", placed > 0 && slot != nullptr && slot->groove == 0);
  37136. }
  37137. }
  37138. lynx::clipGridClassicLook() = classicBefore;
  37139. line ("done");
  37140. }
  37141. // LYNX --capfix190jjshot prefix project.flp set.als: round 190jj off screen (capture190ji's "Change in LYNX" lines) —
  37142. // the Simple capsule idle / playing / count-in / recording with the master meter, the pads at rest and pressed, the
  37143. // keys held in the track's colour, the drop lane's ghosts; Live's control bar idle / playing / recording / punch;
  37144. // FL's C-11 picker drop ghost with the drag image, the drop, and the picker's playing mark; prefix-checks.txt
  37145. void runCapfix190jjShot (const juce::String& prefix, const juce::String& project, const juce::String& set)
  37146. {
  37147. namespace st = lynx::simpletracks;
  37148. namespace sp = lynx::simplepads;
  37149. using Look = lynx::toolbarlayout::Look;
  37150. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37151. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  37152. juce::String checks;
  37153. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  37154. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  37155. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  37156. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  37157. const auto area = [&prefix] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) { saveArea (c, r, prefix + "-" + name + ".png"); };
  37158. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  37159. const auto w = juce::jlimit (800, 3840, size[0].getIntValue()), h = juce::jlimit (450, 2160, size[1].getIntValue());
  37160. // ---- A. Simple ----------------------------------------------------------------------------------------------------
  37161. {
  37162. lynx::AudioEngine offline (false);
  37163. lynx::MainComponent ui (offline, false);
  37164. ui.setSize (w, h);
  37165. const auto settle = [&] {
  37166. for (int k = 0; k < 3; ++k)
  37167. offline.dispatchPendingMessages();
  37168. };
  37169. ui.selectTabForSnapshot (2);
  37170. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  37171. settle();
  37172. auto* simple = ui.getSimpleWorkflowForSnapshot();
  37173. auto& playlist = ui.getPlaylistForSnapshot();
  37174. if (simple == nullptr)
  37175. {
  37176. check ("a Simple workflow", false);
  37177. return;
  37178. }
  37179. offline.setSong ([] {
  37180. lynx::Song s;
  37181. s.mixer = lynx::Song::defaultMixer();
  37182. s.bpm = 120.0;
  37183. return s;
  37184. }());
  37185. settle();
  37186. simple->hideChooser();
  37187. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190jj");
  37188. dir.deleteRecursively();
  37189. dir.createDirectory();
  37190. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  37191. wav.getParentDirectory().createDirectory();
  37192. juce::AudioBuffer<float> audio (1, frames);
  37193. for (int i = 0; i < frames; ++i)
  37194. audio.setSample (0, i, f (i));
  37195. juce::WavAudioFormat format;
  37196. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  37197. if (auto* wr = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  37198. {
  37199. out.release();
  37200. std::unique_ptr<juce::AudioFormatWriter> writer (wr);
  37201. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  37202. }
  37203. return wav;
  37204. };
  37205. const auto pi = juce::MathConstants<double>::pi;
  37206. juce::Random rnd (190);
  37207. // a 4-bar loop at 120 bpm (8 s), as BandLab's "TRAP_160_Piano1_Bm_4bars" is four bars
  37208. const auto loop = writeWav (dir.getChildFile ("TRAP_120_Piano1_Bm_4bars.wav"), 384000, [pi] (int i) {
  37209. const auto t = i / 48000.0, inBeat = std::fmod (t, 0.5);
  37210. return (float) (0.6 * std::exp (-inBeat * 6.0) * std::sin (2.0 * pi * 247.0 * t));
  37211. });
  37212. std::vector<juce::File> padSounds;
  37213. const char* padNames[] { "Kick", "Snare", "Hat", "Clap", "Stab", "Vox", "Perc", "Bass" };
  37214. for (int k = 0; k < 8; ++k)
  37215. padSounds.push_back (writeWav (dir.getChildFile (juce::String ("pads/") + padNames[k] + ".wav"), 12000 + 3000 * k, [&rnd, k] (int i) {
  37216. return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.6f * std::exp (-i / (600.0f + 500.0f * (float) k)));
  37217. }));
  37218. int vocal = -1, keys = -1;
  37219. offline.editSong ([&] (lynx::Song& s) {
  37220. st::Request q;
  37221. q.kind = st::Kind::audio;
  37222. q.name = "Piano loop";
  37223. q.audioFile = loop.getFullPathName().toStdString();
  37224. q.audioLength = 16 * lynx::ppq;
  37225. q.audioBeats = 16.0f;
  37226. vocal = st::addTrack (s, q).track;
  37227. q = {};
  37228. q.kind = st::Kind::instrument;
  37229. q.name = "Instrument";
  37230. lynx::ChannelDef synth;
  37231. synth.instrument = lynx::InstrumentKind::synth;
  37232. q.channel = synth;
  37233. keys = st::addTrack (s, q).track;
  37234. });
  37235. settle();
  37236. check ("the Sampler (pads) track was added", simple->addPads());
  37237. settle();
  37238. const auto& song = offline.getSong();
  37239. int pads = -1;
  37240. for (int t = 0; t < (int) song.playlistTracks.size() && pads < 0; ++t)
  37241. if (st::kindOf (song, t) == st::Kind::pads)
  37242. pads = t;
  37243. simple->hideChooser();
  37244. playlist.selectTrack (keys);
  37245. settle();
  37246. // 1. the transport capsule (+ tempo, key, master) in its four states
  37247. const auto bar = [&ui] {
  37248. juce::Rectangle<int> r;
  37249. for (const auto* name : { "play", "stop", "record", "position", "metronome", "tempo", "signature", "key", "masterVolume", "masterPitch" })
  37250. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible())
  37251. r = r.isEmpty() ? c->getBounds() : r.getUnion (c->getBounds());
  37252. return r.expanded (8, 6);
  37253. };
  37254. auto& transport = offline.getTransport();
  37255. auto* tempo = ui.toolbarPartForSnapshot ("tempo");
  37256. auto* stopButton = dynamic_cast<lynx::IconButton*> (ui.toolbarPartForSnapshot ("stop"));
  37257. auto* playButton = dynamic_cast<lynx::IconButton*> (ui.toolbarPartForSnapshot ("play"));
  37258. auto* master = dynamic_cast<lynx::toolbar::MasterKnob*> (ui.toolbarPartForSnapshot ("masterVolume"));
  37259. ui.transportTickForSnapshot();
  37260. area (ui, bar(), "simple-bar-idle");
  37261. check ("idle: Play shows Play, the second button Back-to-start", playButton != nullptr && playButton->getIcon() == lynx::Icon::play
  37262. && stopButton != nullptr && stopButton->getIcon() == lynx::Icon::toStart);
  37263. transport.positionTicks.store ((double) (2 * song.barTicks()) + 0.3 * lynx::ppq);
  37264. transport.playing.store (true);
  37265. if (master != nullptr)
  37266. master->meterForSnapshot ({ 0.62f, 0.57f });
  37267. ui.transportTickForSnapshot();
  37268. area (ui, bar(), "simple-bar-playing");
  37269. check ("playing: Pause and Stop (BandLab)", playButton != nullptr && playButton->getIcon() == lynx::Icon::pause && stopButton->getIcon() == lynx::Icon::stop);
  37270. transport.playing.store (false);
  37271. transport.positionTicks.store (0.0);
  37272. offline.setRecording (true);
  37273. transport.countIn.store (0.85 * (double) song.barTicks()); // (-1.7 s of a 2 s bar at 120 bpm)
  37274. ui.transportTickForSnapshot();
  37275. area (ui, bar(), "simple-bar-countin");
  37276. check ("count-in: tempo greyed, Pause shown", tempo != nullptr && ! tempo->isEnabled() && playButton->getIcon() == lynx::Icon::pause);
  37277. transport.countIn.store (0.0);
  37278. transport.playing.store (true);
  37279. transport.positionTicks.store (0.45 * (double) song.barTicks());
  37280. ui.transportTickForSnapshot();
  37281. area (ui, bar(), "simple-bar-recording");
  37282. line ("record start kept: " + juce::String (ui.simpleRecordStartForCheck(), 1) + " ticks");
  37283. check ("recording: the take's start is kept (the count-in's target, 0)", ui.simpleRecordStartForCheck() == 0.0);
  37284. auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record"));
  37285. const auto litA = rec != nullptr && rec->getToggleState();
  37286. juce::Thread::sleep (260);
  37287. ui.transportTickForSnapshot();
  37288. const auto litB = rec != nullptr && rec->getToggleState();
  37289. check ("recording: Record steady (lit 260 ms apart, no blink in Simple)", litA && litB);
  37290. transport.seekRequest.store (-1.0);
  37291. ui.stopForCheck();
  37292. line ("seek after Stop: " + juce::String (transport.seekRequest.load(), 1));
  37293. check ("Stop after a take goes back to where it started", transport.seekRequest.load() == 0.0);
  37294. offline.setRecording (false);
  37295. transport.playing.store (false);
  37296. ui.transportTickForSnapshot();
  37297. check ("stopped: tempo enabled again", tempo != nullptr && tempo->isEnabled());
  37298. if (master != nullptr)
  37299. {
  37300. area (ui, master->getBounds().expanded (6, 4), "simple-master-idle");
  37301. master->meterForSnapshot ({ 0.62f, 0.57f });
  37302. area (ui, master->getBounds().expanded (6, 4), "simple-master-playing");
  37303. master->meterForSnapshot ({ 0.0f, 0.0f });
  37304. }
  37305. // 2. the dock: pads at rest and pressed, keys held
  37306. if (auto* dock = simple->dockForSnapshot(); dock != nullptr && pads >= 0)
  37307. {
  37308. simple->trackSelected (pads);
  37309. settle();
  37310. for (int p = 0; p < 8; ++p)
  37311. dock->padsLoadForCheck (p, padSounds[(std::size_t) p]);
  37312. offline.editSong ([pads] (lynx::Song& s) {
  37313. for (int p = 0; p < 8; ++p)
  37314. if (const auto c = sp::padChannel (s, pads, p); c >= 0)
  37315. s.channels[(std::size_t) c].simplePad.colour = (std::uint8_t) (p + 1);
  37316. });
  37317. dock->padsSelectForCheck (0);
  37318. dock->padsUpdateForCheck();
  37319. settle();
  37320. write (*dock, "dock-pads-rest");
  37321. dock->padsPressForSnapshot (3, 1.0f);
  37322. dock->padsPressForSnapshot (5, 0.5f);
  37323. write (*dock, "dock-pads-pressed");
  37324. dock->padsPressForSnapshot (3, 0.0f);
  37325. dock->padsPressForSnapshot (5, 0.0f);
  37326. simple->trackSelected (keys);
  37327. settle();
  37328. dock->showKeyboard();
  37329. settle();
  37330. if (auto* kb = dock->keyboardForSnapshot())
  37331. {
  37332. lynx::keyboardPressForSnapshot (*kb);
  37333. write (*dock, "dock-keys-held");
  37334. }
  37335. }
  37336. // 3. the drop lane while the loop is dragged (the Browser's file drag)
  37337. simple->hideChooser();
  37338. playlist.selectTrack (vocal);
  37339. settle();
  37340. const auto lane = st::nextEmptyTrack (offline.getSong());
  37341. const juce::var drag (juce::String ("lynx-arquivo|") + loop.getFullPathName());
  37342. const auto x = (int) playlist.xOfTickForSnapshot (9.0 * (double) song.barTicks()) + 6;
  37343. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (lane).getCentreY() });
  37344. write (playlist, "simple-drop-lane");
  37345. check ("over the lane: a ghost, no reason", ! playlist.dropGhostAreaForCheck().isEmpty() && playlist.dropGhostReasonForCheck().isEmpty());
  37346. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (vocal).getCentreY() });
  37347. write (playlist, "simple-drop-audio-track");
  37348. check ("over an audio track: no reason", playlist.dropGhostReasonForCheck().isEmpty());
  37349. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (pads).getCentreY() });
  37350. write (playlist, "simple-drop-refused");
  37351. check ("over the Sampler track: red, with the reason", playlist.dropGhostReasonForCheck().isNotEmpty());
  37352. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (keys).getCentreY() });
  37353. check ("over an instrument track: red, with the reason", playlist.dropGhostReasonForCheck().isNotEmpty());
  37354. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (lane).getBottom() + 60 });
  37355. write (playlist, "simple-drop-below");
  37356. check ("below the lane: only the tag", playlist.dropGhostTagOnlyForCheck());
  37357. playlist.dragOverForSnapshot ({}, {});
  37358. check ("after the drag: nothing left to paint", playlist.dropGhostAreaForCheck().isEmpty());
  37359. const auto clipsBefore = offline.getSong().playlist.size();
  37360. playlist.filesDropped ({ loop.getFullPathName() }, x, playlist.trackRowForSnapshot (pads).getCentreY());
  37361. settle();
  37362. check ("a loop dropped on the Sampler track is refused", offline.getSong().playlist.size() == clipsBefore);
  37363. write (ui, "simple-window");
  37364. dir.deleteRecursively();
  37365. }
  37366. // ---- B. Clip-launch: Live's control bar ----------------------------------------------------------------------------
  37367. if (set.isNotEmpty())
  37368. {
  37369. lynx::AudioEngine offline (false);
  37370. lynx::MainComponent ui (offline, false);
  37371. ui.setSize (w, h);
  37372. ui.openFile (juce::File (set));
  37373. offline.dispatchPendingMessages();
  37374. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch, false);
  37375. offline.dispatchPendingMessages();
  37376. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  37377. offline.dispatchPendingMessages();
  37378. const auto centre = [&ui] {
  37379. juce::Rectangle<int> r;
  37380. for (const auto* name : { "backToArrangement", "position", "play", "stop", "record", "overdub", "capture", "sessionRecord", "punch" })
  37381. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible())
  37382. r = r.isEmpty() ? c->getBounds() : r.getUnion (c->getBounds());
  37383. return r.expanded (8, 8);
  37384. };
  37385. auto& transport = offline.getTransport();
  37386. ui.transportTickForSnapshot();
  37387. area (ui, centre(), "live-bar-idle");
  37388. transport.playing.store (true);
  37389. ui.transportTickForSnapshot();
  37390. area (ui, centre(), "live-bar-playing");
  37391. offline.setRecording (true);
  37392. ui.transportTickForSnapshot();
  37393. area (ui, centre(), "live-bar-recording");
  37394. auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record"));
  37395. const auto litA = rec != nullptr && rec->getToggleState();
  37396. juce::Thread::sleep (260);
  37397. ui.transportTickForSnapshot();
  37398. check ("Live look: Record steady while recording (no blink)", litA && rec->getToggleState());
  37399. if (auto* punch = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("punch")))
  37400. {
  37401. punch->setToggleState (true, juce::dontSendNotification);
  37402. area (ui, centre(), "live-bar-punch-lit");
  37403. punch->setToggleState (false, juce::dontSendNotification);
  37404. }
  37405. offline.setRecording (false);
  37406. transport.playing.store (false);
  37407. ui.transportTickForSnapshot();
  37408. }
  37409. // ---- C. Pattern (FL): C-11 drop ghost + drag image, the drop, the picker's playing mark ----------------------------------
  37410. if (project.isNotEmpty())
  37411. {
  37412. lynx::layoutstyle::setCurrent (lynx::layoutstyle::Style::pattern); // (the style is global: A and B changed it)
  37413. lynx::AudioEngine offline (false);
  37414. lynx::MainComponent ui (offline, false);
  37415. ui.setSize (w, h);
  37416. ui.openFile (juce::File (project));
  37417. offline.dispatchPendingMessages();
  37418. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern, false);
  37419. ui.selectTabForSnapshot (2);
  37420. offline.dispatchPendingMessages();
  37421. auto& playlist = ui.getPlaylistForSnapshot();
  37422. auto& picker = ui.getPickerForSnapshot();
  37423. const auto& song = offline.getSong();
  37424. write (playlist, "warmup");
  37425. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  37426. offline.dispatchPendingMessages();
  37427. juce::File (lynx::shot::file (juce::File (prefix + "-warmup.png"))).deleteFile();
  37428. int synthBass = 0;
  37429. for (int p = 0; p < (int) song.patterns.size(); ++p)
  37430. if (juce::String::fromUTF8 (song.patterns[(std::size_t) p].name.c_str()).equalsIgnoreCase ("Synth Bass"))
  37431. {
  37432. synthBass = p;
  37433. break;
  37434. }
  37435. // an empty track low in the view (FL's capture: Track 43 / 47, past the song's tracks)
  37436. // (an unnamed track past the song's own, as FL's Track 43 / 47)
  37437. const auto target = (int) song.playlistTracks.size() + 2;
  37438. for (int first = juce::jmax (0, target - 30); first <= target; ++first) // (the row in the lower part of the view)
  37439. {
  37440. playlist.setViewForSnapshot (15.6, 0, first);
  37441. if (playlist.trackRowForSnapshot (target).getBottom() < playlist.getHeight() - 40)
  37442. break;
  37443. }
  37444. offline.dispatchPendingMessages();
  37445. const auto row = playlist.trackRowForSnapshot (target);
  37446. const auto mouse = juce::Point<int> ((int) playlist.xOfTickForSnapshot (9.1 * (double) song.barTicks()), row.getCentreY());
  37447. const juce::var drag (lynx::PlaylistComponent::pickerDragDescription (lynx::ClipKind::pattern, { synthBass }));
  37448. playlist.dragOverForSnapshot (drag, mouse);
  37449. {
  37450. // the window as the drag shows it: the ghost in the row, the entry's picture below right of the mouse
  37451. auto image = lynx::shot::snapshot (ui);
  37452. const auto scale = (float) image.getWidth() / (float) juce::jmax (1, ui.getWidth());
  37453. const auto listRow = picker.listRowOfPattern (synthBass);
  37454. if (listRow >= 0)
  37455. {
  37456. const auto entry = picker.dragImageOf (listRow);
  37457. const auto at = ui.getLocalPoint (&playlist, mouse) + lynx::PatternPicker::dragImageOffset();
  37458. juce::Graphics g (image);
  37459. g.addTransform (juce::AffineTransform::scale (scale));
  37460. g.drawImageAt (entry, at.x, at.y);
  37461. g.setColour (juce::Colours::white);
  37462. juce::Path arrow; // (the mouse pointer, so the pair reads as FL's film still)
  37463. arrow.startNewSubPath ((float) ui.getLocalPoint (&playlist, mouse).x, (float) ui.getLocalPoint (&playlist, mouse).y);
  37464. arrow.lineTo (arrow.getCurrentPosition() + juce::Point<float> (0.0f, 16.0f));
  37465. arrow.lineTo (arrow.getCurrentPosition() + juce::Point<float> (4.0f, -4.0f));
  37466. arrow.lineTo (arrow.getCurrentPosition() + juce::Point<float> (7.0f, 0.0f));
  37467. arrow.closeSubPath();
  37468. g.fillPath (arrow);
  37469. g.setColour (juce::Colours::black);
  37470. g.strokePath (arrow, juce::PathStrokeType (1.0f));
  37471. }
  37472. savePng (image, prefix + "-fl-c11-drag.png");
  37473. }
  37474. const auto ghost = playlist.dropGhostAreaForCheck();
  37475. line ("ghost " + ghost.toString() + ", row " + row.toString() + ", mouse " + mouse.toString());
  37476. check ("C-11: the ghost lies in the row under the mouse", ! ghost.isEmpty() && ghost.getY() >= row.getY() - 2 && ghost.getBottom() <= row.getBottom() + 2);
  37477. const auto first = (int) offline.getSong().playlist.size();
  37478. playlist.dropForSnapshot (drag, mouse);
  37479. offline.dispatchPendingMessages();
  37480. const auto& dropped = offline.getSong(); // (an edit publishes a new Song: read it again; the Playlist sorts its clips)
  37481. int onRow = 0, at = -1;
  37482. for (int c = 0; c < (int) dropped.playlist.size(); ++c)
  37483. if (dropped.playlist[(std::size_t) c].track == target)
  37484. {
  37485. ++onRow;
  37486. at = c;
  37487. }
  37488. line ("clips " + juce::String (first) + " -> " + juce::String ((int) dropped.playlist.size()) + ", on the row " + juce::String (onRow));
  37489. check ("C-11: the drop places one clip on the row", (int) dropped.playlist.size() == first + 1 && onRow == 1);
  37490. check ("C-11: the dropped clip is selected", at >= 0 && playlist.isClipSelectedForCheck (at));
  37491. check ("C-11: nothing of the ghost is left", playlist.dropGhostAreaForCheck().isEmpty());
  37492. write (ui, "fl-c11-dropped");
  37493. // the picker's playing mark: Synth Bass plays in the first bars; then another pattern selected
  37494. offline.getTransport().positionTicks.store (0.5 * (double) offline.getSong().barTicks());
  37495. offline.getTransport().playing.store (true);
  37496. offline.getTransport().songMode = true;
  37497. playlist.frameStepForSnapshot();
  37498. playlist.frameStepForSnapshot();
  37499. write (picker, "fl-picker-playing");
  37500. line ("playing patterns: " + juce::String ((int) picker.playingForCheck().size()));
  37501. const auto other = juce::jmin ((int) offline.getSong().patterns.size() - 1, 7);
  37502. offline.editSong ([other] (lynx::Song& s) { s.currentPattern = other; }, false);
  37503. offline.dispatchPendingMessages();
  37504. playlist.frameStepForSnapshot();
  37505. write (picker, "fl-picker-playing-other-selected");
  37506. check ("DC-3: the mark follows what plays, not the selection",
  37507. std::find (picker.playingForCheck().begin(), picker.playingForCheck().end(), other) == picker.playingForCheck().end()
  37508. || std::count_if (offline.getSong().playlist.begin(), offline.getSong().playlist.end(), [&] (const lynx::Clip& c) {
  37509. return c.kind == lynx::ClipKind::pattern && c.pattern == other && (double) c.start <= 0.5 * (double) offline.getSong().barTicks()
  37510. && (double) c.end() > 0.5 * (double) offline.getSong().barTicks();
  37511. }) > 0);
  37512. offline.getTransport().playing.store (false);
  37513. playlist.frameStepForSnapshot();
  37514. write (picker, "fl-picker-stopped");
  37515. check ("DC-3: no mark once stopped", picker.playingForCheck().empty());
  37516. }
  37517. line ("done");
  37518. }
  37519. void runDetails190imShot (const juce::String& prefix, const juce::String& project, const juce::String& set)
  37520. {
  37521. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37522. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true); // (the live frame steps run off-screen)
  37523. juce::String checks;
  37524. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  37525. const auto line = [&checks] (const juce::String& what) { checks << " " << what << "\n"; };
  37526. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  37527. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  37528. {
  37529. // ---- Pattern layout, the FL demo
  37530. lynx::AudioEngine offline (false);
  37531. lynx::MainComponent ui (offline, false);
  37532. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  37533. if (project.isNotEmpty())
  37534. ui.openFile (juce::File (project));
  37535. offline.dispatchPendingMessages();
  37536. ui.selectTabForSnapshot (2);
  37537. auto& playlist = ui.getPlaylistForSnapshot();
  37538. offline.dispatchPendingMessages();
  37539. const auto settle = [&] {
  37540. write (playlist, "warmup");
  37541. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  37542. offline.dispatchPendingMessages();
  37543. juce::File (prefix + "-warmup.png").deleteFile();
  37544. };
  37545. const auto& song = offline.getSong();
  37546. offline.editSong ([] (lynx::Song& s) { for (auto& t : s.playlistTracks) t.height = 50; }, false);
  37547. offline.dispatchPendingMessages();
  37548. const auto toolbar = ui.getToolbarBoundsForSnapshot();
  37549. // R1: the automation clip with the most points in view, its second point dragged, its first segment bent
  37550. int autoClip = -1;
  37551. for (int c = 0; c < (int) song.playlist.size(); ++c)
  37552. if (const auto& clip = song.playlist[(std::size_t) c]; clip.kind == lynx::ClipKind::automation && clip.automation >= 0
  37553. && clip.automation < (int) song.automations.size() && song.automations[(std::size_t) clip.automation].points.size() >= 3
  37554. && (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()))
  37555. autoClip = c;
  37556. check ("R1: an automation clip with points in the project", autoClip >= 0);
  37557. if (autoClip >= 0)
  37558. {
  37559. const auto& clip = song.playlist[(std::size_t) autoClip];
  37560. const auto bar = (int) (clip.start / song.barTicks());
  37561. playlist.setViewForSnapshot (39.75, juce::jmax (0, bar - 2), juce::jmax (0, clip.track - 3));
  37562. settle();
  37563. const auto point = playlist.dragHintForSnapshot (autoClip, 1, false);
  37564. line ("point drag hint: " + point.text + " | " + point.value);
  37565. check ("R1: a dragged automation-clip point shows its value (DE-117)", point.value.isNotEmpty());
  37566. ui.setHintForSnapshot (point);
  37567. saveArea (ui, toolbar, prefix + "-r1-hint-point.png");
  37568. write (ui, "r1-window-point");
  37569. int bent = 0; // (a segment that is bent, when the clip has one)
  37570. const auto& points = song.automations[(std::size_t) clip.automation].points;
  37571. for (int k = 0; k + 1 < (int) points.size(); ++k)
  37572. if (points[(std::size_t) k].tension != 0.0f)
  37573. {
  37574. bent = k;
  37575. break;
  37576. }
  37577. const auto tension = playlist.dragHintForSnapshot (autoClip, bent, true);
  37578. line ("tension drag hint: " + tension.text + " | " + tension.value);
  37579. check ("R1: a bent segment shows its tension (DE-118)", tension.value.startsWith (lynx::tr ("Tension: {0}", { "" }).upToFirstOccurrenceOf (" ", false, false).trimEnd()));
  37580. ui.setHintForSnapshot (tension);
  37581. saveArea (ui, toolbar, prefix + "-r1-hint-tension.png");
  37582. const auto body = playlist.curveBodyForSnapshot (autoClip);
  37583. const auto hoverX = juce::jlimit (playlist.headerWidthForSnapshot() + 20, playlist.getWidth() - 40, (int) body.getX() + 80);
  37584. const auto hover = playlist.hintAt ({ hoverX, (int) body.getCentreY() });
  37585. line ("hover hint: " + hover.text + " | " + hover.value);
  37586. check ("R1: hovering the curve shows the value at the mouse (DE-119)", hover.value.contains (" "));
  37587. ui.setHintForSnapshot (hover);
  37588. saveArea (ui, toolbar, prefix + "-r1-hint-hover.png");
  37589. }
  37590. // R5: playing at bar 33 (FL's fl-playing.png), the meters fed so the activity strips show their steps
  37591. playlist.setViewForSnapshot (39.75, 20, 24);
  37592. settle();
  37593. offline.getTransport().positionTicks.store ((double) (32 * song.barTicks()));
  37594. offline.getTransport().playing.store (true);
  37595. const auto feed = [&offline] {
  37596. const float levels[] { 1.0f, 0.3f, 0.08f, 0.02f };
  37597. for (int k = 1; k < lynx::maxMixerTracks; ++k)
  37598. offline.getMeters().accumulate (k, levels[k % 4], levels[k % 4]);
  37599. };
  37600. feed();
  37601. playlist.frameStepForSnapshot();
  37602. feed();
  37603. playlist.frameStepForSnapshot();
  37604. write (ui, "r5-playing");
  37605. write (ui.getPickerForSnapshot(), "r5-picker-playing");
  37606. const auto px = (int) playlist.xOfTickForSnapshot (32.0 * (double) song.barTicks());
  37607. saveArea (playlist, { px - 40, lynx::PlaylistComponent::headerHeight, 60, 120 }, prefix + "-r5-playhead.png");
  37608. saveArea (playlist, { 0, lynx::PlaylistComponent::toolbarHeight, playlist.getWidth(), lynx::PlaylistComponent::overviewHeight }, prefix + "-r5-overview.png");
  37609. saveArea (playlist, { 0, lynx::PlaylistComponent::headerHeight, playlist.headerWidthForSnapshot() + 4, playlist.getHeight() - lynx::PlaylistComponent::headerHeight }, prefix + "-r5-headers.png");
  37610. lynx::ui::motion::enabled() = false;
  37611. playlist.frameStepForSnapshot();
  37612. saveArea (playlist, { px - 40, lynx::PlaylistComponent::headerHeight, 60, 120 }, prefix + "-r5-playhead-noanim.png");
  37613. lynx::ui::motion::enabled() = true;
  37614. playlist.frameStepForSnapshot();
  37615. // a drop preview: two patterns dragged from the Picker (issue #177's description) over track 4, bar 36
  37616. const auto row = playlist.trackRowForSnapshot (27);
  37617. playlist.dragOverForSnapshot (juce::var ("lynx-picker|0|0,1"), { (int) playlist.xOfTickForSnapshot (35.6 * (double) song.barTicks()), row.getCentreY() });
  37618. write (ui, "r5-drop-preview");
  37619. playlist.dragOverForSnapshot ({}, {});
  37620. offline.getTransport().playing.store (false);
  37621. playlist.frameStepForSnapshot();
  37622. write (ui, "r5-stopped");
  37623. write (ui.getPickerForSnapshot(), "r5-picker-stopped");
  37624. saveArea (playlist, { 0, lynx::PlaylistComponent::toolbarHeight, playlist.getWidth(), lynx::PlaylistComponent::overviewHeight }, prefix + "-r5-overview-stopped.png");
  37625. // R15: a scroll by hand while playing — Pattern layout: Follow goes on (off by default); the option on: it pauses
  37626. auto& globals = lynx::EditorGlobals::get();
  37627. const auto scrollWhilePlaying = [&] {
  37628. offline.getTransport().playing.store (true);
  37629. playlist.frameStepForSnapshot();
  37630. playlist.setScrollTickForSnapshot (playlist.scrollTicksForSnapshot() + 4.0 * (double) song.barTicks());
  37631. playlist.frameStepForSnapshot();
  37632. const auto paused = playlist.followPausedForSnapshot();
  37633. offline.getTransport().playing.store (false);
  37634. playlist.frameStepForSnapshot();
  37635. return paused;
  37636. };
  37637. check ("R15: Pattern layout (option off by default): no pause", ! globals.followPausing() && ! scrollWhilePlaying());
  37638. globals.followPausesOnEdit = 1;
  37639. check ("R15: option on: a scroll while playing pauses Follow", scrollWhilePlaying());
  37640. check ("R15: a stop lifts the pause", ! playlist.followPausedForSnapshot());
  37641. globals.followPausesOnEdit = -1;
  37642. }
  37643. {
  37644. // ---- R11: the Sampler's handles (a 1 s tone, loop points on)
  37645. lynx::AudioEngine engine (false);
  37646. const auto tone = juce::File (prefix).getParentDirectory().getChildFile ("details190im-tone.wav");
  37647. {
  37648. juce::AudioBuffer<float> buffer (1, 44100);
  37649. for (int i = 0; i < buffer.getNumSamples(); ++i)
  37650. buffer.setSample (0, i, (float) (0.6 * std::sin (juce::MathConstants<double>::twoPi * 110.0 * i / 44100.0) * (1.0 - i / 44100.0)));
  37651. tone.deleteFile();
  37652. juce::WavAudioFormat wav;
  37653. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (tone.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  37654. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  37655. }
  37656. engine.editSong ([&] (lynx::Song& s) {
  37657. if (s.channels.empty())
  37658. s.channels.resize (1);
  37659. lynx::audioclips::loadSampleInto (s.channels[0], tone.getFullPathName().toStdString(), "Tone");
  37660. });
  37661. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  37662. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  37663. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  37664. frame->createComponentSnapshot (frame->getLocalBounds());
  37665. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  37666. auto& f = *frame;
  37667. lynx::samplerPageTurn (f, "useLoops", 1.0);
  37668. lynx::samplerPageTurn (f, "loopStart", 11025.0);
  37669. lynx::samplerPageTurn (f, "loopEnd", 22050.0);
  37670. lynx::samplerPageTurn (f, "smpStart", 0.0);
  37671. savePng (f.createComponentSnapshot (f.getLocalBounds()), prefix + "-r11-sampler-before.png");
  37672. for (const auto* h : { "Start", "LoopStart", "LoopEnd" })
  37673. line (juce::String ("press on the drawn ") + h + " handle takes: " + lynx::samplerPageQuery (f, juce::String ("handleAt") + h));
  37674. check ("R11: a press on the loop start line takes the loop start", lynx::samplerPageQuery (f, "handleAtLoopStart") == "loopStart");
  37675. check ("R11: a press on the loop end line takes the loop end", lynx::samplerPageQuery (f, "handleAtLoopEnd") == "loopEnd");
  37676. check ("R11: a press on the Start marker takes the start", lynx::samplerPageQuery (f, "handleAtStart") == "start");
  37677. lynx::samplerPageTurn (f, "dragLoopEnd", 0.75);
  37678. check ("R11: the loop end dragged to 3/4", std::abs ((double) sampler().loopEnd - 0.75 * 44099.0) < 2.0);
  37679. lynx::samplerPageTurn (f, "dragLoopStart", 0.375, true);
  37680. check ("R11: Shift drags the whole loop", sampler().loopStart > 16000 && sampler().loopEnd - sampler().loopStart > 22000);
  37681. line ("loop after the drags: " + juce::String (sampler().loopStart) + " - " + juce::String (sampler().loopEnd));
  37682. lynx::samplerPageTurn (f, "dragStart", 0.2);
  37683. check ("R11: the Start marker dragged to 20 %", std::abs (sampler().startOffset - 0.2f) < 0.01f);
  37684. savePng (f.createComponentSnapshot (f.getLocalBounds()), prefix + "-r11-sampler-after.png");
  37685. tone.deleteFile();
  37686. }
  37687. if (set.isNotEmpty())
  37688. {
  37689. // ---- Clip-launch layout, the Live set
  37690. lynx::AudioEngine offline (false);
  37691. lynx::MainComponent ui (offline, false);
  37692. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  37693. ui.setVisible (true);
  37694. ui.selectTabForSnapshot (2);
  37695. ui.setClipLaunchWorkflow (true);
  37696. offline.dispatchPendingMessages();
  37697. ui.openFile (juce::File (set));
  37698. offline.dispatchPendingMessages();
  37699. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  37700. offline.dispatchPendingMessages();
  37701. ui.resized();
  37702. auto* gridView = ui.getClipGridForSnapshot();
  37703. auto* runtime = offline.launcherStateForSnapshot();
  37704. const auto& song = offline.getSong();
  37705. check ("grid and launcher", gridView != nullptr && runtime != nullptr && song.clipGrid.has_value());
  37706. if (gridView == nullptr || runtime == nullptr || ! song.clipGrid.has_value())
  37707. {
  37708. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  37709. return;
  37710. }
  37711. auto& grid = *gridView;
  37712. gridView->resized();
  37713. const auto firstClip = [&song] (int track, lynx::ClipKind kind) {
  37714. for (int r = 0; r < 64; ++r)
  37715. if (const auto* c = lynx::launcher::clipAt (*song.clipGrid, track, r); c != nullptr && c->kind == kind)
  37716. return r;
  37717. return -1;
  37718. };
  37719. const auto bigCrop = [&] (const juce::String& name, juce::Rectangle<int> area) { saveArea (grid, area, prefix + "-" + name + ".png"); };
  37720. // R6: track 0 plays a one-shot (Loop off), track 1 loops in its 2nd pass, track 2's clip has a follow action
  37721. int rows[3] { -1, -1, -1 };
  37722. for (int t = 0; t < 3; ++t)
  37723. for (const auto kind : { lynx::ClipKind::audio, lynx::ClipKind::pattern })
  37724. if (rows[t] < 0)
  37725. rows[t] = firstClip (t, kind);
  37726. offline.editSong ([&rows] (lynx::Song& s) {
  37727. if (rows[0] >= 0)
  37728. lynx::launcher::settingsAt (*s.clipGrid, 0, rows[0])->loop = false;
  37729. if (rows[2] >= 0)
  37730. {
  37731. auto& f = lynx::launcher::settingsAt (*s.clipGrid, 2, rows[2])->follow;
  37732. f.enabled = true;
  37733. f.a = lynx::FollowKind::next;
  37734. }
  37735. }, false);
  37736. offline.dispatchPendingMessages();
  37737. runtime->running.store (true);
  37738. for (int t = 0; t < 2; ++t)
  37739. if (rows[t] >= 0)
  37740. {
  37741. const auto length = (double) lynx::launcher::clipAt (*song.clipGrid, t, rows[t])->length;
  37742. runtime->tracks[(std::size_t) t].playing.store (rows[t]);
  37743. runtime->tracks[(std::size_t) t].progress.store (0.4f);
  37744. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  37745. runtime->clockNow.store (length * 1.4);
  37746. }
  37747. lynx::tickClipGridForSnapshot (grid);
  37748. grid.repaint();
  37749. write (grid, "r6-grid-playing");
  37750. bigCrop ("r6-status-oneshot", lynx::clipGridCellForSnapshot (grid, 1, 0, 0).getUnion (lynx::clipGridCellForSnapshot (grid, 1, 1, 0)));
  37751. if (rows[2] >= 0)
  37752. {
  37753. const auto cell = lynx::clipGridCellForSnapshot (grid, 0, 2, rows[2]);
  37754. bigCrop ("r6-follow-stripes", cell);
  37755. }
  37756. // the queued scene's pulse, both phases, then the next scene selected
  37757. const auto scene = juce::jmax (0, rows[1]);
  37758. lynx::setClipGridBlinkPhaseForSnapshot (1);
  37759. lynx::launchClipGridSceneForSnapshot (grid, scene);
  37760. grid.repaint();
  37761. bigCrop ("r6-scene-queued-lit", lynx::clipGridCellForSnapshot (grid, 2, 0, scene));
  37762. lynx::setClipGridBlinkPhaseForSnapshot (0);
  37763. grid.repaint();
  37764. bigCrop ("r6-scene-queued-dark", lynx::clipGridCellForSnapshot (grid, 2, 0, scene));
  37765. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  37766. const auto [selected, sceneSelected] = lynx::clipGridSceneSelectionForSnapshot (grid);
  37767. 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);
  37768. write (grid, "r6-grid-scene-launched");
  37769. // the hints of each part
  37770. const auto hintAt = [&] (const juce::String& what, juce::Point<int> p) {
  37771. const auto [text, value] = lynx::clipGridHintForSnapshot (grid, p);
  37772. line ("hint " + what + ": " + text + " | " + value);
  37773. return text;
  37774. };
  37775. const auto slot = lynx::clipGridCellForSnapshot (grid, 0, 1, juce::jmax (0, rows[1]));
  37776. const auto launchHint = hintAt ("clip launch button", { slot.getX() + 7, slot.getCentreY() });
  37777. hintAt ("clip", { slot.getCentreX(), slot.getCentreY() });
  37778. hintAt ("stop button", { lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getX() + 7, lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getCentreY() });
  37779. hintAt ("status", { lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getCentreX(), lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getCentreY() });
  37780. const auto sceneCell = lynx::clipGridCellForSnapshot (grid, 2, 0, 0);
  37781. hintAt ("scene launch button", { sceneCell.getX() + 6, sceneCell.getCentreY() });
  37782. hintAt ("scene", { sceneCell.getCentreX(), sceneCell.getCentreY() });
  37783. check ("R6: the grid's parts have hints (DL-21)", launchHint.isNotEmpty());
  37784. ui.setHintForSnapshot ({ launchHint, {}, false, false });
  37785. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-r6-hint-launch.png");
  37786. // R12: 0 on the selected clip deactivates it (greyed), again activates it; the scene column's font
  37787. lynx::selectClipGridSlotForSnapshot (grid, 1, juce::jmax (0, rows[1]));
  37788. grid.grabKeyboardFocus();
  37789. 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; };
  37790. check ("R12: 0 is taken by the grid", lynx::clipGridKeyForSnapshot (grid, juce::KeyPress ('0')));
  37791. offline.dispatchPendingMessages();
  37792. check ("R12: 0 deactivates the selected clip", ! activeNow());
  37793. for (auto& v : runtime->tracks)
  37794. v.playing.store (-1);
  37795. grid.repaint();
  37796. write (grid, "r12-clip-deactivated");
  37797. bigCrop ("r12-clip-deactivated-cell", slot);
  37798. lynx::clipGridKeyForSnapshot (grid, juce::KeyPress ('0'));
  37799. offline.dispatchPendingMessages();
  37800. check ("R12: 0 again activates it", activeNow());
  37801. 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))));
  37802. // R13: the Clip View of a launched MIDI clip: the Piano roll's playhead at the clip's position
  37803. int midiTrack = -1, midiRow = -1;
  37804. for (int t = 0; t < 16 && midiTrack < 0; ++t)
  37805. if (const auto r = firstClip (t, lynx::ClipKind::pattern); r >= 0)
  37806. {
  37807. midiTrack = t;
  37808. midiRow = r;
  37809. }
  37810. check ("R13: the set has a MIDI clip", midiTrack >= 0);
  37811. if (auto* detail = ui.getDetailViewForSnapshot(); detail != nullptr && midiTrack >= 0)
  37812. {
  37813. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  37814. lynx::DetailView::shownSetting = true;
  37815. detail->showSelection (midiTrack, midiRow);
  37816. detail->setPage (lynx::DetailView::Page::clip);
  37817. offline.dispatchPendingMessages();
  37818. ui.resized();
  37819. const auto& clip = *lynx::launcher::clipAt (*song.clipGrid, midiTrack, midiRow);
  37820. runtime->running.store (true);
  37821. runtime->tracks[(std::size_t) midiTrack].playing.store (midiRow);
  37822. runtime->tracks[(std::size_t) midiTrack].anchor.store (0.0);
  37823. runtime->clockNow.store ((double) clip.length * 2.3);
  37824. offline.getTransport().playing.store (true);
  37825. auto& roll = ui.getPianoRollForSnapshot();
  37826. roll.frameStepForSnapshot();
  37827. const auto expect = (double) clip.offset + 0.3 * (double) clip.length;
  37828. line ("piano roll playhead " + juce::String (roll.playheadForSnapshot(), 1) + ", the launched clip at " + juce::String (expect, 1));
  37829. check ("R13: the docked Piano roll shows the launched clip's position (DL-74)", std::abs (roll.playheadForSnapshot() - expect) < (double) lynx::ppq);
  37830. write (ui, "r13-clipview-midi");
  37831. offline.getTransport().playing.store (false);
  37832. runtime->tracks[(std::size_t) midiTrack].playing.store (-1);
  37833. roll.frameStepForSnapshot();
  37834. }
  37835. }
  37836. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  37837. }
  37838. void runDesign190igShot (const juce::String& prefix, const juce::String& project)
  37839. {
  37840. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37841. lynx::AudioEngine offline (false);
  37842. lynx::MainComponent ui (offline, false);
  37843. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  37844. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  37845. const auto write = [&prefix] (juce::Component& c, const char* name) {
  37846. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  37847. };
  37848. if (project.isNotEmpty())
  37849. ui.openFile (juce::File (project));
  37850. offline.dispatchPendingMessages();
  37851. ui.selectTabForSnapshot (2); // the Playlist, maximized
  37852. auto& playlist = ui.getPlaylistForSnapshot();
  37853. offline.dispatchPendingMessages();
  37854. const auto settle = [&] { // (the waveforms are analysed in the background on the first paint)
  37855. write (playlist, "warmup");
  37856. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  37857. offline.dispatchPendingMessages();
  37858. juce::File (prefix + "-warmup.png").deleteFile();
  37859. };
  37860. const auto heights = [&] (int h) {
  37861. offline.editSong ([h] (lynx::Song& s) {
  37862. for (auto& t : s.playlistTracks)
  37863. t.height = h;
  37864. }, false);
  37865. offline.dispatchPendingMessages();
  37866. };
  37867. // 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
  37868. heights (26);
  37869. playlist.setViewForSnapshot (15.6, 20, 0);
  37870. playlist.setScrollYForSnapshot (19 * 26);
  37871. settle();
  37872. write (ui, "01-default");
  37873. write (playlist, "01-default-playlist");
  37874. // 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
  37875. heights (50);
  37876. playlist.setViewForSnapshot (39.75, 20, 0);
  37877. playlist.setScrollYForSnapshot (24 * 50 + 4);
  37878. settle();
  37879. write (ui, "02-zoom17");
  37880. write (playlist, "02-zoom17-playlist");
  37881. // playing (shots/ref/fl-playing.png): the playhead at bar 33, the activity column lit for the tracks that sound
  37882. offline.getTransport().positionTicks.store ((double) (32 * offline.getSong().barTicks()));
  37883. offline.getTransport().playing.store (true);
  37884. playlist.frameStepForSnapshot();
  37885. playlist.frameStepForSnapshot();
  37886. write (ui, "03-playing");
  37887. offline.getTransport().playing.store (false);
  37888. playlist.frameStepForSnapshot();
  37889. heights (26);
  37890. playlist.setViewForSnapshot (15.6, 0, 0);
  37891. playlist.setScrollYForSnapshot (0);
  37892. write (ui, "04-default-start");
  37893. // round 190jd (live check 190iw Q4): FL's grid levels at its Ctrl+wheel steps — bars only at 9.9 px a beat, beat
  37894. // 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
  37895. heights (32);
  37896. for (const auto beat : { 9.9, 11.5, 18.4, 21.5 })
  37897. {
  37898. playlist.setViewForSnapshot (beat * 4.0, 8, 0);
  37899. playlist.setScrollYForSnapshot (0);
  37900. write (playlist, ("05-grid-" + juce::String (beat, 1) + "px-beat").toRawUTF8());
  37901. }
  37902. // round 190jd: NEW automation clips from the first channel's volume and pan knobs take FL's colours by parameter
  37903. // (#8C5F5F, #7F8C5E; shots/q4-fl-new-automation-clip-zoom2.png); the editor windows they open are closed again
  37904. if (! offline.getSong().channels.empty())
  37905. {
  37906. // (the channels of FL's capture: Synth Bass pan + volume, Grv Kick 27 volume + pan; else the first channel)
  37907. const auto channelNamed = [&offline] (const char* name) {
  37908. const auto& channels = offline.getSong().channels;
  37909. for (int c = 0; c < (int) channels.size(); ++c)
  37910. if (juce::String (channels[(std::size_t) c].name).startsWithIgnoreCase (name))
  37911. return c;
  37912. return 0;
  37913. };
  37914. juce::String report;
  37915. offline.editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  37916. offline.getTransport().positionTicks.store (0.0);
  37917. const auto before = offline.getSong().automations.size();
  37918. for (const auto& [name, kind] : { std::pair { "Synth Bass", lynx::AutomationTargetKind::channelPan },
  37919. std::pair { "Grv Kick", lynx::AutomationTargetKind::channelVolume },
  37920. std::pair { "Synth Bass", lynx::AutomationTargetKind::channelVolume },
  37921. std::pair { "Grv Kick", lynx::AutomationTargetKind::channelPan } })
  37922. {
  37923. lynx::AutomationTarget t;
  37924. t.kind = kind;
  37925. t.index = channelNamed (name);
  37926. lynx::createAutomationClip (offline, t);
  37927. offline.dispatchPendingMessages();
  37928. }
  37929. lynx::closeAutomationEditors();
  37930. offline.dispatchPendingMessages();
  37931. int first = -1;
  37932. for (std::size_t a = before; a < offline.getSong().automations.size(); ++a)
  37933. {
  37934. const auto& au = offline.getSong().automations[a];
  37935. for (const auto& c : offline.getSong().playlist)
  37936. if (c.kind == lynx::ClipKind::automation && c.automation == (int) a)
  37937. {
  37938. first = first < 0 ? c.track : std::min (first, c.track);
  37939. report << "new clip '" << au.name << "' track " << (c.track + 1) << " colour #"
  37940. << juce::String::toHexString ((int) (au.colour & 0xFFFFFF)).paddedLeft ('0', 6).toUpperCase() << "\n";
  37941. }
  37942. }
  37943. report << "automations " << (int) before << " -> " << (int) offline.getSong().automations.size() << "\n";
  37944. juce::File (prefix + "-190jd-automation.txt").replaceWithText (report);
  37945. heights (50);
  37946. playlist.setViewForSnapshot (39.75, 0, 0);
  37947. playlist.setScrollYForSnapshot (std::max (0, first - 1) * 50);
  37948. write (playlist, "06-new-automation-clips");
  37949. }
  37950. // round 190jd (live check 190iw Q7, shots/q7-fl-countin-sheet.png): a 1-bar count-in — the time display reads
  37951. // "REC IN 4" on its first beat and "REC IN 1" on its last, Play shows its Pause glyph, Record stays lit
  37952. for (const auto beatsLeft : { 4, 1 })
  37953. {
  37954. offline.getTransport().countIn.store ((double) beatsLeft * lynx::ppq - 1.0);
  37955. ui.tickLinkForSnapshot();
  37956. ui.transportForSnapshot (true, true);
  37957. write (ui, ("07-countin-" + juce::String (beatsLeft)).toRawUTF8());
  37958. }
  37959. offline.getTransport().countIn.store (0.0);
  37960. }
  37961. void runDesign190igS4Shot (const juce::String& prefix, const juce::String& projectPath)
  37962. {
  37963. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  37964. lynx::AudioEngine offline (false);
  37965. lynx::MainComponent ui (offline, false);
  37966. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  37967. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  37968. juce::String checks;
  37969. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  37970. const auto write = [&prefix] (juce::Component& c, const juce::String& name) {
  37971. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  37972. file.deleteFile();
  37973. juce::FileOutputStream out (file);
  37974. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  37975. };
  37976. ui.setVisible (true);
  37977. ui.selectTabForSnapshot (2);
  37978. ui.setClipLaunchWorkflow (true); // (first: an .als opened in the Clip-launch layout takes Live's own colours)
  37979. offline.dispatchPendingMessages();
  37980. if (projectPath.isNotEmpty())
  37981. {
  37982. ui.openFile (juce::File (projectPath));
  37983. offline.dispatchPendingMessages();
  37984. }
  37985. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  37986. offline.dispatchPendingMessages();
  37987. ui.resized();
  37988. auto* gridView = ui.getClipGridForSnapshot();
  37989. auto* runtime = offline.launcherStateForSnapshot();
  37990. const auto& song = offline.getSong();
  37991. if (gridView == nullptr || ! song.clipGrid)
  37992. {
  37993. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid\n");
  37994. return;
  37995. }
  37996. if (! song.mixer.empty())
  37997. checks << "first mixer colours:";
  37998. for (std::size_t m = 1; m < std::min<std::size_t> (song.mixer.size(), 6); ++m)
  37999. checks << " " << juce::String::toHexString ((int) (song.mixer[m].colour & 0xffffff)).paddedLeft ('0', 6);
  38000. checks << "\n";
  38001. gridView->resized();
  38002. write (ui, "01-window-idle");
  38003. write (*gridView, "02-grid-idle");
  38004. if (runtime == nullptr)
  38005. {
  38006. check ("a launcher runtime exists", false);
  38007. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  38008. return;
  38009. }
  38010. // the frame strip: the first five tracks; the scene each plays or waits for, by the clips the set has
  38011. const auto& grid = *song.clipGrid;
  38012. const auto rowWithClip = [&grid] (int track, int from) {
  38013. for (int r = from; r < 64; ++r)
  38014. if (lynx::launcher::clipAt (grid, track, r) != nullptr)
  38015. return r;
  38016. return -1;
  38017. };
  38018. const auto reset = [&] {
  38019. for (auto& v : runtime->tracks)
  38020. {
  38021. v.playing.store (-1);
  38022. v.pending.store (-1);
  38023. v.stopping.store (false);
  38024. v.recording.store (-1);
  38025. v.recordPending.store (-1);
  38026. v.progress.store (0.0f);
  38027. }
  38028. runtime->running.store (true);
  38029. };
  38030. const auto bar = (double) song.barTicks();
  38031. const auto state = [&] (const juce::String& name) {
  38032. gridView->repaint();
  38033. write (*gridView, name);
  38034. };
  38035. // playing (Live frame 1): tracks 0..3 play their first clip, a third of the way into its second loop
  38036. reset();
  38037. for (int t = 0; t < 4; ++t)
  38038. if (const auto r = rowWithClip (t, 0); r >= 0)
  38039. {
  38040. runtime->tracks[(std::size_t) t].playing.store (r);
  38041. runtime->tracks[(std::size_t) t].progress.store (0.33f);
  38042. const auto length = (double) lynx::launcher::clipAt (grid, t, r)->length;
  38043. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  38044. runtime->clockNow.store (length * 1.33);
  38045. }
  38046. state ("10-playing");
  38047. // queued (Live frames 2 and 3): the same, and each track's next clip waits for its start; both blink phases
  38048. for (int t = 0; t < 4; ++t)
  38049. if (const auto r = runtime->tracks[(std::size_t) t].playing.load(); r >= 0)
  38050. if (const auto next = rowWithClip (t, r + 1); next >= 0)
  38051. runtime->tracks[(std::size_t) t].pending.store (next);
  38052. lynx::setClipGridBlinkPhaseForSnapshot (0);
  38053. state ("11-queued-dark");
  38054. lynx::setClipGridBlinkPhaseForSnapshot (1);
  38055. state ("12-queued-lit");
  38056. // Animations off: the lit green, steady
  38057. lynx::ui::motion::enabled() = false;
  38058. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  38059. state ("13-queued-animations-off");
  38060. lynx::ui::motion::enabled() = true;
  38061. // a stop waiting (both phases)
  38062. reset();
  38063. for (int t = 0; t < 4; ++t)
  38064. if (const auto r = rowWithClip (t, 0); r >= 0)
  38065. {
  38066. runtime->tracks[(std::size_t) t].playing.store (r);
  38067. runtime->tracks[(std::size_t) t].progress.store (0.5f);
  38068. runtime->tracks[(std::size_t) t].stopping.store (t % 2 == 0);
  38069. }
  38070. lynx::setClipGridBlinkPhaseForSnapshot (0);
  38071. state ("14-stopping-dark");
  38072. lynx::setClipGridBlinkPhaseForSnapshot (1);
  38073. state ("15-stopping-lit");
  38074. // recording into an empty slot of track 1 (the counter one beat in) and a launch waiting on an empty slot (a stop)
  38075. reset();
  38076. {
  38077. int empty = -1;
  38078. for (int r = 0; r < 16 && empty < 0; ++r)
  38079. if (lynx::launcher::clipAt (grid, 1, r) == nullptr)
  38080. empty = r;
  38081. if (empty >= 0)
  38082. {
  38083. runtime->tracks[1].recording.store (empty);
  38084. runtime->tracks[1].recordFrom.store (0.0);
  38085. runtime->clockNow.store ((double) lynx::ppq);
  38086. }
  38087. check ("recording: an empty slot on track 2", empty >= 0);
  38088. }
  38089. state ("16-recording");
  38090. // the status pie at 25 / 50 / 75 % in the second loop
  38091. 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) })
  38092. {
  38093. reset();
  38094. for (int t = 0; t < 4; ++t)
  38095. if (const auto r = rowWithClip (t, 0); r >= 0)
  38096. {
  38097. const auto length = (double) lynx::launcher::clipAt (grid, t, r)->length;
  38098. runtime->tracks[(std::size_t) t].playing.store (r);
  38099. runtime->tracks[(std::size_t) t].progress.store (p);
  38100. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  38101. runtime->clockNow.store (length * (1.0 + (double) p));
  38102. }
  38103. state (name);
  38104. }
  38105. juce::ignoreUnused (bar);
  38106. // round 181a's look, the option (View › Classic LYNX look for the clip grid)
  38107. reset();
  38108. for (int t = 0; t < 4; ++t)
  38109. if (const auto r = rowWithClip (t, 0); r >= 0)
  38110. runtime->tracks[(std::size_t) t].playing.store (r);
  38111. lynx::clipGridClassicLook() = true;
  38112. lynx::refreshClipGrid (*gridView);
  38113. state ("20-classic-look-option");
  38114. lynx::clipGridClassicLook() = false;
  38115. lynx::refreshClipGrid (*gridView);
  38116. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  38117. reset();
  38118. runtime->running.store (false);
  38119. write (ui, "21-window-after");
  38120. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  38121. ui.setClipLaunchWorkflow (false);
  38122. }
  38123. void runLiveShot190dr (const juce::String& prefix)
  38124. {
  38125. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  38126. lynx::AudioEngine offline (false);
  38127. lynx::MainComponent ui (offline, false);
  38128. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  38129. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  38130. const auto write = [&prefix] (juce::Component& c, const char* name) {
  38131. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  38132. file.deleteFile();
  38133. juce::FileOutputStream out (file);
  38134. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  38135. };
  38136. juce::String checks;
  38137. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  38138. // a two-bar loop of clicks for the audio clip
  38139. const auto wav = juce::File (prefix + "-loop.wav");
  38140. wav.deleteFile();
  38141. {
  38142. const double rate = 48000.0;
  38143. juce::AudioBuffer<float> buffer (2, (int) (rate * 4.0));
  38144. buffer.clear();
  38145. for (int hit = 0; hit < 16; ++hit)
  38146. for (int k = 0; k < 3000 && hit * 12000 + k < buffer.getNumSamples(); ++k)
  38147. for (int ch = 0; ch < 2; ++ch)
  38148. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
  38149. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  38150. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  38151. {
  38152. out.release();
  38153. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  38154. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  38155. }
  38156. }
  38157. ui.setVisible (true);
  38158. lynx::DetailView::shownSetting = true;
  38159. lynx::DetailView::devicesPage = false;
  38160. ui.setClipLaunchWorkflow (true);
  38161. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  38162. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  38163. offline.dispatchPendingMessages();
  38164. int audioChannel = -1;
  38165. offline.editSong ([&audioChannel] (lynx::Song& s) {
  38166. lynx::Clip audio;
  38167. if (! s.playlist.empty())
  38168. {
  38169. audio = s.playlist.front();
  38170. audioChannel = audio.channel;
  38171. s.playlist.clear();
  38172. }
  38173. const int channels = (int) s.channels.size();
  38174. s.channels.resize ((std::size_t) channels + 3);
  38175. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  38176. for (int k = 0; k < 3; ++k)
  38177. {
  38178. auto& ch = s.channels[(std::size_t) (channels + k)];
  38179. ch.name = names[k];
  38180. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  38181. ch.mixerTrack = k + 1;
  38182. }
  38183. if (audioChannel >= 0)
  38184. s.channels[(std::size_t) audioChannel].mixerTrack = 5;
  38185. if (s.mixer.size() < 8)
  38186. s.mixer.resize (8);
  38187. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Loop", "Reverb", "Delay" };
  38188. for (int i = 1; i < 8; ++i)
  38189. s.mixer[(std::size_t) i].name = inserts[i];
  38190. s.mixer[1].volume = lynx::sessionmixer::positionForDb (-3.0);
  38191. s.mixer[2].pan = 0.3f;
  38192. s.mixer[2].effects.clear();
  38193. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  38194. {
  38195. lynx::EffectSlot fx;
  38196. fx.kind = kind;
  38197. const auto& info = lynx::effectInfo (kind);
  38198. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  38199. fx.params[k] = info.params[k].defaultValue;
  38200. s.mixer[2].effects.push_back (fx);
  38201. }
  38202. s.mixer[3].muted = true; // the Keys' activator off
  38203. s.mixer[4].inputChannel = 0;
  38204. s.mixer[4].inputStereo = true;
  38205. s.mixer[4].monitor = lynx::InputMonitor::automatic;
  38206. s.mixer[4].effects.clear();
  38207. {
  38208. lynx::EffectSlot fx;
  38209. fx.kind = lynx::EffectKind::reverb;
  38210. s.mixer[4].effects.push_back (fx);
  38211. }
  38212. s.mixer[5].solo = true;
  38213. 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 } })
  38214. {
  38215. lynx::MixerSend send;
  38216. send.target = to;
  38217. send.level = lynx::faderGain (level);
  38218. s.mixer[(std::size_t) from].sends.push_back (send);
  38219. }
  38220. while (s.patterns.size() < 3)
  38221. s.patterns.emplace_back();
  38222. const char* patterns[] { "Beat", "Bassline", "Chords" };
  38223. for (int p = 0; p < 3; ++p)
  38224. {
  38225. auto& pattern = s.patterns[(std::size_t) p];
  38226. pattern.name = patterns[p];
  38227. lynx::Note n;
  38228. n.channel = channels + p;
  38229. n.key = 48 + p * 5;
  38230. pattern.notes = { n };
  38231. pattern.lengthTicks = 4 * lynx::ppq;
  38232. }
  38233. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  38234. const char* tracks[] { "Drums", "Bass", "Keys", "Vox", "Loop", "FX" };
  38235. for (int t = 0; t < 6; ++t)
  38236. s.playlistTracks[(std::size_t) t].name = tracks[t];
  38237. s.playlistTracks[3].mode = lynx::PlaylistTrackMode::audio;
  38238. s.playlistTracks[3].mixerTrack = 4;
  38239. for (int t = 0; t < 3; ++t)
  38240. for (int r = 0; r < 3; ++r)
  38241. if (! (t == 2 && r == 0))
  38242. {
  38243. lynx::Clip clip;
  38244. clip.pattern = t;
  38245. clip.length = 4 * lynx::ppq;
  38246. lynx::launcher::setClip (s, t, r, clip);
  38247. }
  38248. if (audioChannel >= 0)
  38249. {
  38250. lynx::clipsample::setWarp (s, audioChannel, true, 4.0); // (Warp on, as a dropped loop in Live)
  38251. audio.track = 4;
  38252. audio.start = 0;
  38253. lynx::launcher::setClip (s, 4, 0, audio);
  38254. lynx::launcher::setClip (s, 4, 1, audio);
  38255. }
  38256. auto& grid = lynx::launcher::ensureGrid (s);
  38257. const char* scenes[] { "Intro", "Verse", "Drop" };
  38258. grid.scenes.resize (5);
  38259. for (int r = 0; r < 3; ++r)
  38260. grid.scenes[(std::size_t) r].name = scenes[r];
  38261. }, false);
  38262. offline.dispatchPendingMessages();
  38263. offline.setGridTrackArmed (3, true);
  38264. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  38265. offline.dispatchPendingMessages();
  38266. ui.resized();
  38267. auto* gridView = ui.getClipGridForSnapshot();
  38268. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  38269. auto* detail = ui.getDetailViewForSnapshot();
  38270. if (gridView == nullptr || mixer == nullptr || detail == nullptr)
  38271. {
  38272. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid, mixer or detail view\n");
  38273. return;
  38274. }
  38275. // the meters: a level per insert, as a playing song leaves them (offscreen nothing plays), two ticks
  38276. const auto levels = [&] {
  38277. for (int k = 0; k < 2; ++k)
  38278. {
  38279. const float peaks[] { 0.9f, 0.5f, 0.7f, 0.0f, 0.3f, 0.45f, 0.2f, 0.12f };
  38280. for (int i = 0; i < 8; ++i)
  38281. offline.getMeters().accumulate (i, peaks[i], peaks[i] * 0.85f);
  38282. mixer->tick();
  38283. }
  38284. };
  38285. if (auto* runtime = offline.launcherStateForSnapshot())
  38286. {
  38287. runtime->tracks[0].playing.store (1);
  38288. runtime->tracks[0].progress.store (0.3f);
  38289. runtime->tracks[1].playing.store (1);
  38290. runtime->tracks[1].progress.store (0.3f);
  38291. runtime->tracks[4].playing.store (0);
  38292. runtime->tracks[4].progress.store (0.5f);
  38293. runtime->running.store (true);
  38294. }
  38295. levels();
  38296. gridView->resized();
  38297. write (ui, "01-session-mixer");
  38298. write (*gridView, "01b-grid-alone");
  38299. using Part = lynx::SessionMixerComponent::Part;
  38300. check ("mixer: Sends rows are the two buses (Reverb 6, Delay 7)", mixer->sendTargets() == std::vector<int> { 6, 7 });
  38301. check ("mixer: the arm buttons moved into the Volume section", mixer->armsShown());
  38302. check ("mixer: Drums strip has activator, solo, arm, pan, volume", ! mixer->partBounds (0, Part::activator).isEmpty() && ! mixer->partBounds (0, Part::solo).isEmpty()
  38303. && ! mixer->partBounds (0, Part::arm).isEmpty() && ! mixer->partBounds (0, Part::pan).isEmpty()
  38304. && ! mixer->partBounds (0, Part::volume).isEmpty());
  38305. check ("mixer: Vox strip (audio track) has Audio From, its channel, Monitor and Audio To", ! mixer->partBounds (3, Part::inType).isEmpty()
  38306. && ! mixer->partBounds (3, Part::inChannel).isEmpty()
  38307. && ! mixer->partBounds (3, Part::monAuto).isEmpty()
  38308. && ! mixer->partBounds (3, Part::output).isEmpty());
  38309. check ("mixer: Bass strip (instrument) shows MIDI From, no Monitor", mixer->partBounds (1, Part::monIn).isEmpty() && ! mixer->partBounds (1, Part::output).isEmpty());
  38310. check ("mixer: FX strip (no clips) has no activator but an arm", mixer->partBounds (5, Part::activator).isEmpty() && ! mixer->partBounds (5, Part::arm).isEmpty());
  38311. check ("mixer: Main strip has volume and pan, no activator", ! mixer->partBounds (-2, Part::volume).isEmpty() && mixer->partBounds (-2, Part::activator).isEmpty());
  38312. {
  38313. const auto hit = mixer->hitAt (mixer->partBounds (2, Part::solo).getCentre());
  38314. check ("mixer: a click on the Keys' S is its solo", hit.column == 2 && hit.part == Part::solo);
  38315. const auto send = mixer->hitAt (mixer->partBounds (1, Part::send, 1).getCentre());
  38316. check ("mixer: the Bass' second knob is its send to Delay", send.column == 1 && send.part == Part::send && send.row == 1);
  38317. }
  38318. {
  38319. juce::PopupMenu menu;
  38320. mixer->addViewItems (menu);
  38321. saveMenus (juce::StringArray { "Mixer (footer button)" }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-mixer-view-menu.png");
  38322. }
  38323. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.trackOptions = true; }, false);
  38324. offline.dispatchPendingMessages();
  38325. gridView->resized();
  38326. levels();
  38327. write (*gridView, "03-mixer-track-options");
  38328. offline.editSong ([] (lynx::Song& s) {
  38329. auto& v = lynx::launcher::ensureGrid (s).mixerView;
  38330. v.trackOptions = v.io = v.sends = false;
  38331. }, false);
  38332. offline.dispatchPendingMessages();
  38333. gridView->resized();
  38334. levels();
  38335. write (*gridView, "04-mixer-volume-only");
  38336. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.shown = false; }, false);
  38337. offline.dispatchPendingMessages();
  38338. gridView->resized();
  38339. write (*gridView, "05-mixer-hidden");
  38340. check ("mixer hidden: the arm buttons are back in the status row", ! mixer->armsShown() && mixer->getHeight() == 0);
  38341. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView = {}; }, false);
  38342. offline.dispatchPendingMessages();
  38343. gridView->resized();
  38344. // the Clip page of the Loop clip (track 4, scene 0) while it plays: Warp on, the Set buttons lit, the title
  38345. detail->showSelection (4, 0);
  38346. detail->setPage (lynx::DetailView::Page::clip);
  38347. offline.editSong ([] (lynx::Song&) {}, false); // (a change message: the Clip panel reads the playing state)
  38348. offline.dispatchPendingMessages();
  38349. write (ui, "06-clip-audio-warp-on");
  38350. // round 190ig (round 190ia CL-20a, the BPM row bug): the Audio box at Live's 190 px, 260 px and 350 px detail
  38351. // heights, in Re-Pitch (no settings rows) and in Beats (three rows: the most a mode shows)
  38352. if (audioChannel >= 0)
  38353. {
  38354. const auto heightBefore = lynx::DetailView::preferredHeight;
  38355. for (const auto beats : { false, true })
  38356. {
  38357. offline.editSong ([audioChannel, beats] (lynx::Song& s) {
  38358. auto& sampler = s.channels[(std::size_t) audioChannel].sampler;
  38359. sampler.keepPitch = beats;
  38360. sampler.stretchMethod = beats ? lynx::StretchMethod::beats : sampler.stretchMethod;
  38361. }, false);
  38362. offline.dispatchPendingMessages();
  38363. for (const auto h : { 190, 260, 350 })
  38364. {
  38365. lynx::DetailView::preferredHeight = h;
  38366. ui.resized();
  38367. if (auto* area = detail->getParentComponent()) // (the Playlist area lays its docked detail view out)
  38368. area->resized();
  38369. offline.dispatchPendingMessages();
  38370. write (ui, (juce::String ("06h-audio-box-") + (beats ? "beats-" : "repitch-") + juce::String (h)).toRawUTF8());
  38371. check ("audio box at " + juce::String (h) + " px: the detail view is that high", detail->getHeight() == h);
  38372. }
  38373. }
  38374. offline.editSong ([audioChannel] (lynx::Song& s) { s.channels[(std::size_t) audioChannel].sampler.keepPitch = false; }, false);
  38375. offline.dispatchPendingMessages();
  38376. lynx::DetailView::preferredHeight = heightBefore;
  38377. ui.resized();
  38378. if (auto* area = detail->getParentComponent())
  38379. area->resized();
  38380. offline.dispatchPendingMessages();
  38381. }
  38382. if (audioChannel >= 0)
  38383. {
  38384. const auto beforeLength = lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length;
  38385. offline.editSong ([audioChannel] (lynx::Song& s) { lynx::clipsample::setWarp (s, audioChannel, false, 4.0); });
  38386. offline.dispatchPendingMessages();
  38387. write (ui, "07-clip-audio-warp-off");
  38388. check ("warp off: the channel plays at its own speed", ! lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  38389. offline.undo();
  38390. offline.dispatchPendingMessages();
  38391. check ("warp: undo gives the clip back as it was", lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length == beforeLength
  38392. && lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  38393. // Set (start) at the play position, half way: one undo step
  38394. const auto clipBefore = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  38395. offline.editSong ([] (lynx::Song& s) {
  38396. for (auto& c : s.clipGrid->clips)
  38397. if (c.track == 4 && c.gridSlot >= 0 && s.clipGrid->slots[(std::size_t) c.gridSlot].scene == 0)
  38398. lynx::clipsample::setStartAt (c, lynx::clipsample::playPosition (c, 0.5f));
  38399. });
  38400. const auto& after = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  38401. check ("set start: the clip starts half way and ends where it did", after.offset == clipBefore.offset + clipBefore.length / 2
  38402. && after.offset + after.length == clipBefore.offset + clipBefore.length);
  38403. offline.undo();
  38404. offline.dispatchPendingMessages();
  38405. }
  38406. // a MIDI clip's Clip page too (the Set buttons are there for every clip), playing through a groove of the pool
  38407. offline.editSong ([] (lynx::Song& s) {
  38408. const auto& bank = lynx::groove::factoryBank();
  38409. if (bank.size() > 9)
  38410. lynx::groove::setClipGroove (s, 0, 1, lynx::groove::add (s.grooves, bank[9].groove));
  38411. }, false);
  38412. detail->showSelection (0, 1);
  38413. offline.editSong ([] (lynx::Song&) {}, false);
  38414. offline.dispatchPendingMessages();
  38415. write (ui, "08-clip-midi-set-buttons");
  38416. // the Device View of Bass (insert 2): its compressor dragged onto Keys (insert 3), then Ctrl-dragged onto Vox
  38417. detail->showSelection (1, 0);
  38418. detail->setPage (lynx::DetailView::Page::devices);
  38419. offline.dispatchPendingMessages();
  38420. write (ui, "09-devices-bass-before");
  38421. lynx::setClipGridDeviceDropForSnapshot (*gridView, 2);
  38422. write (ui, "10-device-dragged-over-keys");
  38423. lynx::setClipGridDeviceDropForSnapshot (*gridView, -1);
  38424. int fromId = 0;
  38425. {
  38426. const auto& s = offline.getSong();
  38427. fromId = (int) (s.mixer[2].effects[1].instance.id & 0x7fffffff);
  38428. }
  38429. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  38430. offline.dispatchPendingMessages();
  38431. check ("drag to Keys: the compressor moved (same device)", offline.getSong().mixer[2].effects.size() == 2 && offline.getSong().mixer[3].effects.size() == 1
  38432. && (int) (offline.getSong().mixer[3].effects[0].instance.id & 0x7fffffff) == fromId);
  38433. detail->showSelection (2, 1);
  38434. offline.dispatchPendingMessages();
  38435. write (ui, "11-devices-keys-after-move");
  38436. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 0, 4, true); });
  38437. offline.dispatchPendingMessages();
  38438. check ("Ctrl-drag to Vox: a copy of the EQ after its reverb, Bass keeps its own", offline.getSong().mixer[4].effects.size() == 2
  38439. && offline.getSong().mixer[4].effects[1].kind == lynx::EffectKind::eq
  38440. && offline.getSong().mixer[2].effects[0].kind == lynx::EffectKind::eq);
  38441. offline.undo();
  38442. offline.undo();
  38443. offline.dispatchPendingMessages();
  38444. check ("undo twice: Bass has its three devices again, Keys none", offline.getSong().mixer[2].effects.size() == 3 && offline.getSong().mixer[3].effects.empty()
  38445. && offline.getSong().mixer[4].effects.size() == 1);
  38446. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  38447. wav.deleteFile();
  38448. }
  38449. void runWarpShot (const juce::String& prefix)
  38450. {
  38451. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  38452. lynx::AudioEngine offline (false);
  38453. lynx::MainComponent ui (offline, false);
  38454. ui.setSize (1600, 900);
  38455. const auto write = [&prefix] (juce::Component& c, const char* name) {
  38456. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  38457. file.deleteFile();
  38458. juce::FileOutputStream out (file);
  38459. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  38460. };
  38461. // a two-bar loop of clicks, a little off the grid (what Quantize is for)
  38462. const auto wav = juce::File (prefix + "-loop.wav");
  38463. wav.deleteFile();
  38464. {
  38465. const double rate = 44100.0;
  38466. juce::AudioBuffer<float> buffer (1, (int) (rate * 4.0));
  38467. buffer.clear();
  38468. for (int hit = 0; hit < 8; ++hit)
  38469. {
  38470. const auto at = (int) ((hit * 0.5 + (hit % 3) * 0.035) * rate);
  38471. for (int k = 0; k < 4000 && at + k < buffer.getNumSamples(); ++k)
  38472. buffer.setSample (0, at + k, (float) (std::sin (k * (hit % 2 ? 0.25 : 0.06)) * std::exp (-k / 700.0) * 0.8));
  38473. }
  38474. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  38475. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  38476. {
  38477. out.release();
  38478. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  38479. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  38480. }
  38481. }
  38482. ui.setVisible (true);
  38483. lynx::DetailView::shownSetting = true;
  38484. ui.selectTabForSnapshot (2);
  38485. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  38486. lynx::autolanes::setShown (true);
  38487. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  38488. offline.dispatchPendingMessages();
  38489. int channel = -1;
  38490. offline.editSong ([&channel] (lynx::Song& s) {
  38491. if (s.playlist.empty())
  38492. return;
  38493. auto audio = s.playlist.front();
  38494. channel = audio.channel;
  38495. audio.track = 1;
  38496. s.playlist.front() = audio;
  38497. for (int k = 1; k < 3; ++k)
  38498. {
  38499. auto more = audio;
  38500. more.start = audio.start + k * 8 * lynx::ppq;
  38501. s.playlist.push_back (more);
  38502. }
  38503. while (s.patterns.size() < 1)
  38504. s.patterns.emplace_back();
  38505. for (int t = 2; t < 5; ++t)
  38506. for (int k = 0; k < 4; ++k)
  38507. {
  38508. lynx::Clip c;
  38509. c.pattern = 0;
  38510. c.track = t;
  38511. c.start = k * 4 * lynx::ppq;
  38512. c.length = 4 * lynx::ppq;
  38513. s.playlist.push_back (c);
  38514. }
  38515. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  38516. s.playlistTracks[1].name = "Loop";
  38517. s.playlistTracks[2].name = "Drums";
  38518. s.playlistTracks[3].name = "Kick";
  38519. s.playlistTracks[4].name = "Hats";
  38520. s.playlistTracks[4].folded = true;
  38521. lynx::noteedit::groupWithAbove (s, 3);
  38522. lynx::noteedit::groupWithAbove (s, 4);
  38523. lynx::arrange::makeGroupBus (s, 3);
  38524. lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::tempo, 0, 0, 0 }, "Tempo", lynx::valueFromTempo (s.bpm));
  38525. if (! s.automations.empty())
  38526. s.automations.back().points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { 8 * lynx::ppq, lynx::valueFromTempo (120.0), 0.0f },
  38527. { 12 * lynx::ppq, lynx::valueFromTempo (180.0), 0.0f }, { 16 * lynx::ppq, lynx::valueFromTempo (140.0), 0.0f } };
  38528. s.addMarker ({ 4 * lynx::ppq, "Verse", 0, 0 });
  38529. s.addMarker ({ 8 * lynx::ppq, {}, 3, 4 });
  38530. s.addMarker ({ 14 * lynx::ppq, {}, 4, 4 });
  38531. s.loopStart = 4 * lynx::ppq;
  38532. s.loopEnd = 12 * lynx::ppq;
  38533. s.loopOff = true;
  38534. s.tempoViewLow = 60.0; // the tempo lane's range
  38535. s.tempoViewHigh = 200.0;
  38536. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& a, const lynx::Clip& b) { return a.start < b.start; });
  38537. // the same audio in the clip grid, for the Clip page
  38538. lynx::Clip slot = audio;
  38539. slot.start = 0;
  38540. slot.pitch = -2.25f;
  38541. slot.gain = 0.7f;
  38542. lynx::launcher::setClip (s, 1, 0, slot);
  38543. // a few warp markers, as Quantize leaves them
  38544. if (channel >= 0 && channel < (int) s.channels.size())
  38545. {
  38546. auto& sampler = s.channels[(std::size_t) channel].sampler;
  38547. lynx::warpedit::ensureMarkers (sampler, 4.0, s.bpm);
  38548. std::vector<double> attacks;
  38549. for (int hit = 1; hit < 8; ++hit)
  38550. attacks.push_back (hit * 0.5 + (hit % 3) * 0.035);
  38551. lynx::warptools::quantize (sampler, attacks, 0.0, 4.0, 0.5, 1.0);
  38552. lynx::warpedit::syncLength (sampler, 4.0);
  38553. }
  38554. }, false);
  38555. offline.dispatchPendingMessages();
  38556. ui.resized();
  38557. write (ui, "arrangement-loop-off");
  38558. offline.editSong ([] (lynx::Song& s) { s.loopOff = false; }, false);
  38559. offline.dispatchPendingMessages();
  38560. write (ui, "arrangement-loop-on");
  38561. juce::String facts;
  38562. {
  38563. const auto& s = offline.getSong();
  38564. facts << "channel " << channel << ", warp markers " << (channel >= 0 ? (int) s.channels[(std::size_t) channel].sampler.warp.size() : -1)
  38565. << ", group bus insert " << lynx::arrange::groupBus (s, 3) << ", folded track 4: " << (lynx::arrange::isFolded (s, 4) ? 1 : 0) << "\n";
  38566. }
  38567. if (auto* detail = ui.getDetailViewForSnapshot())
  38568. {
  38569. detail->showSelection (1, 0);
  38570. detail->setPage (lynx::DetailView::Page::clip);
  38571. offline.dispatchPendingMessages();
  38572. write (ui, "clip-audio");
  38573. }
  38574. if (channel >= 0)
  38575. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  38576. {
  38577. editor->setSize (1120, 600);
  38578. write (*editor, "audio-editor-warp");
  38579. // round 190cy (Live 12.4.16 live check 190cw shot 09): a plain drag of marker 3 holds it two sixteenths
  38580. // later (its audio goes there); Shift + drag slides the audio under it. Round 190db: the Clip-launch
  38581. // workflow draws the warped clip in beats, so the held drag shows the audio stretched around the marker
  38582. // (plain) or slid under it, its attack later (Shift, to the right as in Live's shot)
  38583. const auto& w = offline.getSong().channels[(std::size_t) channel].sampler.warp;
  38584. if (w.size() > 4)
  38585. {
  38586. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].beats + 0.5, false);
  38587. write (*editor, "audio-editor-drag-stretch");
  38588. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].seconds - 0.12, true);
  38589. write (*editor, "audio-editor-drag-slide");
  38590. }
  38591. // the same clip in file time (the Pattern workflow's view, or "Show the audio in beats" off)
  38592. if (auto inFileTime = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  38593. {
  38594. inFileTime->setSize (1120, 600);
  38595. lynx::setAudioEditorBeatTimeForSnapshot (*inFileTime, 0);
  38596. write (*inFileTime, "audio-editor-file-time");
  38597. if (w.size() > 4)
  38598. {
  38599. lynx::holdAudioEditorWarpDragForSnapshot (*inFileTime, 3, w[3].beats + 0.5, false);
  38600. write (*inFileTime, "audio-editor-file-time-drag");
  38601. }
  38602. }
  38603. }
  38604. // round 190cy (Live 12.4.16 live check 190cw shot 02): ÷2 from the editor of the first Playlist clip halves that
  38605. // clip's length with the markers' beats; ÷2 on the grid clip's Clip page halves the grid clip
  38606. {
  38607. const auto lengthOf = [&offline] (int index) { return index < (int) offline.getSong().playlist.size() ? offline.getSong().playlist[(std::size_t) index].length : -1; };
  38608. const auto gridLength = [&offline] {
  38609. const auto& s = offline.getSong();
  38610. const auto* c = s.clipGrid ? lynx::launcher::clipAt (*s.clipGrid, 1, 0) : nullptr;
  38611. return c != nullptr ? c->length : (std::int64_t) -1;
  38612. };
  38613. const auto first = [&offline] {
  38614. const auto& s = offline.getSong();
  38615. for (int i = 0; i < (int) s.playlist.size(); ++i)
  38616. if (s.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  38617. return i;
  38618. return -1;
  38619. }();
  38620. facts << "halve: playlist clip " << first << " length " << lengthOf (first);
  38621. if (first >= 0)
  38622. if (auto editor = lynx::makeAudioEditorPanel (offline, offline.getSong().playlist[(std::size_t) first].channel, first, true))
  38623. {
  38624. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  38625. offline.dispatchPendingMessages();
  38626. }
  38627. facts << " -> " << lengthOf (first) << "; grid clip length " << gridLength();
  38628. if (channel >= 0)
  38629. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, -1, true))
  38630. {
  38631. lynx::setAudioEditorGridClip (*editor, 1, 0);
  38632. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  38633. offline.dispatchPendingMessages();
  38634. }
  38635. facts << " -> " << gridLength() << "\n";
  38636. ui.resized();
  38637. write (ui, "arrangement-halved");
  38638. // Duplicate Time over beats 4-8 holding the locator "Verse" (beat 4): a second "Verse" at beat 8
  38639. offline.editSong ([] (lynx::Song& s) { lynx::arrange::duplicateTime (s, 4 * lynx::ppq, 8 * lynx::ppq); });
  38640. offline.dispatchPendingMessages();
  38641. int verses = 0;
  38642. for (const auto& m : offline.getSong().markers())
  38643. verses += m.name == "Verse" ? 1 : 0;
  38644. facts << "duplicate time: locators named Verse " << verses << "\n";
  38645. write (ui, "arrangement-duplicated-time");
  38646. }
  38647. juce::File (prefix + "-facts.txt").replaceWithText (facts);
  38648. lynx::autolanes::setShown (false);
  38649. }
  38650. void runMtShot190fm (const juce::String& prefix)
  38651. {
  38652. lynx::AudioEngine offline (false);
  38653. offline.editSong ([] (lynx::Song& s) {
  38654. if (s.patterns.empty())
  38655. s.patterns.emplace_back();
  38656. s.patterns[0].notes.clear();
  38657. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  38658. s.currentPattern = 0;
  38659. }, false);
  38660. lynx::MidiToolsPanel panel (offline, [] {
  38661. lynx::MidiToolsPanel::Target t;
  38662. t.pattern = 0;
  38663. t.grid = lynx::ppq / 4;
  38664. t.channel = 0;
  38665. t.length = 4 * lynx::ppq; // one bar, no time selection
  38666. return t;
  38667. });
  38668. panel.setSize (lynx::MidiToolsPanel::panelWidth, lynx::MidiToolsPanel::panelHeight);
  38669. panel.setSection (lynx::MidiToolsPanel::generateSection);
  38670. panel.setGenerateShotSettingsForSnapshot();
  38671. const auto write = [&prefix] (const juce::Image& image, const juce::String& name) {
  38672. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  38673. file.deleteFile();
  38674. juce::FileOutputStream out (file);
  38675. juce::PNGImageFormat().writeImageToStream (image, out);
  38676. };
  38677. std::vector<juce::Image> images;
  38678. juce::String checks;
  38679. for (int g = 0; g < lynx::midigen::Settings::toolCount; ++g)
  38680. {
  38681. panel.setGenerator (g);
  38682. const auto name = juce::String (lynx::midigen::toolName (g)).toLowerCase();
  38683. images.push_back (lynx::shot::paint (panel, lynx::theme::colour::bg2));
  38684. write (images.back(), "generate-" + name);
  38685. panel.generateNow();
  38686. offline.dispatchPendingMessages();
  38687. const auto made = (int) offline.getSong().patterns[0].notes.size();
  38688. offline.undo();
  38689. offline.dispatchPendingMessages();
  38690. const auto after = (int) offline.getSong().patterns[0].notes.size();
  38691. checks << name << ": generated " << made << " notes, after undo " << after << (made > 0 && after == 0 ? " OK" : " FAIL") << "\n";
  38692. }
  38693. // the five side by side (6 px apart, on the window's background)
  38694. const auto gap = juce::roundToInt (6.0f * lynx::shot::scale());
  38695. int width = gap, height = 0;
  38696. for (const auto& image : images)
  38697. {
  38698. width += image.getWidth() + gap;
  38699. height = std::max (height, image.getHeight());
  38700. }
  38701. juce::Image strip (juce::Image::RGB, width, height + 2 * gap, true);
  38702. {
  38703. juce::Graphics g (strip);
  38704. g.fillAll (lynx::theme::colour::bg0);
  38705. int x = gap;
  38706. for (const auto& image : images)
  38707. {
  38708. g.drawImageAt (image, x, gap);
  38709. x += image.getWidth() + gap;
  38710. }
  38711. }
  38712. write (strip, "generate-panels");
  38713. checks << "settings saved with the project: " << (offline.getSong().midiGenerate.stacksOptions.sequence.size() == 2 ? "OK" : "FAIL") << "\n";
  38714. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  38715. }
  38716. // Round 190hy: see --mpeshot190hy
  38717. void runMpeShot190hy (const juce::String& prefix)
  38718. {
  38719. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  38720. lynx::AudioEngine offline (false);
  38721. lynx::MainComponent ui (offline, false);
  38722. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  38723. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  38724. const auto write = [&prefix, &ui] (const char* name) {
  38725. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  38726. file.deleteFile();
  38727. juce::FileOutputStream out (file);
  38728. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  38729. };
  38730. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  38731. offline.editSong ([] (lynx::Song& s) {
  38732. if (s.channels.empty())
  38733. s.channels.resize (1);
  38734. s.channels[0].name = "MPE lead";
  38735. s.channels[0].mixerTrack = 1;
  38736. if (s.mixer.size() < 2)
  38737. s.mixer.resize (2);
  38738. while (s.patterns.empty())
  38739. s.patterns.emplace_back();
  38740. auto& p = s.patterns[0];
  38741. p.name = "MPE take";
  38742. p.notes.clear();
  38743. // four notes as an MPE controller plays them: a slide up an octave, a vibrato, a fall, a held chord tone
  38744. const auto note = [&p] (std::int64_t start, std::int64_t length, int key, lynx::NoteCurves c, float modX = 0.5f) {
  38745. lynx::Note n;
  38746. n.channel = 0;
  38747. n.start = start;
  38748. n.length = length;
  38749. n.key = key;
  38750. n.modX = modX;
  38751. n.curves = std::move (c);
  38752. p.notes.push_back (n);
  38753. };
  38754. const auto beat = (float) lynx::ppq;
  38755. lynx::NoteCurves glide;
  38756. glide.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { beat * 0.5f, 0.0f }, { beat * 1.5f, 1200.0f }, { beat * 2.0f, 1200.0f } };
  38757. glide.lane (lynx::NoteCurveLane::timbre) = { { 0.0f, 0.3f }, { beat * 2.0f, 0.85f } };
  38758. glide.lane (lynx::NoteCurveLane::pressure) = { { 0.0f, 0.2f }, { beat * 0.4f, 0.9f }, { beat * 1.6f, 0.7f }, { beat * 2.0f, 0.0f } };
  38759. note (0, 2 * lynx::ppq, 60, glide, 0.3f);
  38760. lynx::NoteCurves vibrato;
  38761. for (int k = 0; k <= 24; ++k)
  38762. vibrato.lane (lynx::NoteCurveLane::pitch).push_back ({ beat * 0.0833f * (float) k, k < 4 ? 0.0f : 40.0f * std::sin ((float) k * 1.5708f) });
  38763. vibrato.lane (lynx::NoteCurveLane::pressure) = { { 0.0f, 0.5f }, { beat * 1.0f, 0.95f }, { beat * 2.0f, 0.4f } };
  38764. note (2 * lynx::ppq, 2 * lynx::ppq, 67, vibrato);
  38765. lynx::NoteCurves fall;
  38766. fall.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { beat * 0.75f, 0.0f }, { beat * 1.0f, -500.0f } };
  38767. fall.lane (lynx::NoteCurveLane::timbre) = { { 0.0f, 0.6f }, { beat * 1.0f, 0.2f } };
  38768. note (4 * lynx::ppq, lynx::ppq, 72, fall, 0.6f);
  38769. note (5 * lynx::ppq, 3 * lynx::ppq, 64, {}); // (a note without curves: its own values, dashed)
  38770. p.lengthTicks = 8 * lynx::ppq;
  38771. }, false);
  38772. offline.dispatchPendingMessages();
  38773. juce::String checks;
  38774. auto& roll = ui.getPianoRollForSnapshot();
  38775. ui.selectTabForSnapshot (1);
  38776. roll.selectMidiToolResult ({ 0 });
  38777. roll.scrollToNotes();
  38778. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneMpePitch, "pitch" },
  38779. { lynx::PianoRollComponent::laneMpeSlide, "slide" },
  38780. { lynx::PianoRollComponent::laneMpePressure, "pressure" } })
  38781. {
  38782. roll.setLaneForSnapshot (lane);
  38783. offline.dispatchPendingMessages();
  38784. write (name);
  38785. checks << "lane " << name << ": areas " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  38786. }
  38787. roll.setLaneForSnapshot (lynx::PianoRollComponent::laneVelocity);
  38788. int curved = 0;
  38789. for (const auto& n : offline.getSong().patterns[0].notes)
  38790. curved += n.curves.has() ? 1 : 0;
  38791. checks << "notes with curves: " << curved << " of " << (int) offline.getSong().patterns[0].notes.size() << "\n";
  38792. // the Clip-launch layout: the clip's Notes tab, then its MPE tab (Live 11+'s note expression lanes)
  38793. ui.selectTabForSnapshot (2);
  38794. lynx::DetailView::shownSetting = true;
  38795. lynx::DetailView::devicesPage = false;
  38796. ui.setClipLaunchWorkflow (true);
  38797. offline.editSong ([] (lynx::Song& s) {
  38798. lynx::Clip clip;
  38799. clip.pattern = 0;
  38800. clip.length = 8 * lynx::ppq;
  38801. lynx::launcher::setClip (s, 0, 0, clip);
  38802. }, false);
  38803. offline.dispatchPendingMessages();
  38804. if (auto* detail = ui.getDetailViewForSnapshot())
  38805. {
  38806. detail->showSelection (0, 0);
  38807. detail->setPage (lynx::DetailView::Page::clip);
  38808. detail->setClipTab (false);
  38809. offline.dispatchPendingMessages();
  38810. roll.scrollToNotes();
  38811. write ("clip-notes");
  38812. checks << "clip notes tab: mpe view " << (roll.isMpeView() ? 1 : 0) << "\n";
  38813. detail->setMpeTab();
  38814. offline.dispatchPendingMessages();
  38815. roll.selectMidiToolResult ({ 0 });
  38816. roll.scrollToNotes();
  38817. write ("clip-mpe");
  38818. checks << "clip MPE tab: mpe view " << (roll.isMpeView() ? 1 : 0) << ", lanes " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  38819. // round 190jd (Live 12.4's MPE tab): the value ghost point on note 1's Pressure line, the "Show Lane:" menu,
  38820. // then all four lanes shown (Slide, Pressure, Velocity, Release Velocity)
  38821. checks << "ghost on the Pressure line: '" << roll.hoverMpeLineForSnapshot (lynx::PianoRollComponent::laneMpePressure, (double) lynx::ppq) << "'\n";
  38822. write ("clip-mpe-ghost190jd");
  38823. roll.hoverMpeLineForSnapshot (0, 0.0);
  38824. saveMenus (juce::StringArray { "MPE tab: Show Lane" }, std::vector<juce::PopupMenu> { roll.getMpeLaneMenuForSnapshot() },
  38825. prefix + "-clip-mpe-showlane190jd.png");
  38826. roll.setMpeLanesForSnapshot (lynx::mpetab::allLanes);
  38827. offline.dispatchPendingMessages();
  38828. write ("clip-mpe-lanes4-190jd");
  38829. checks << "four lanes: " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  38830. roll.setMpeLanesForSnapshot (lynx::mpetab::defaultLanes);
  38831. detail->setClipTab (false);
  38832. offline.dispatchPendingMessages();
  38833. checks << "back to Notes: mpe view " << (roll.isMpeView() ? 1 : 0) << "\n";
  38834. }
  38835. else
  38836. checks << "no detail view\n";
  38837. lynx::shot::file (juce::File (prefix + "-checks.txt")).replaceWithText (checks);
  38838. }
  38839. // round 190kk: Live's Erosion / Vinyl Distortion / Corpus imported, their LYNX engines on the Device View
  38840. void runMeldShot190ko (const juce::String& prefix, const juce::String& meld, const juce::String& time, const juce::String& resonator)
  38841. {
  38842. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  38843. lynx::AudioEngine offline (false);
  38844. lynx::MainComponent ui (offline, false);
  38845. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  38846. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  38847. juce::String checks;
  38848. // a Live device preset (.adv, gzip) → its device element's text
  38849. const auto deviceOf = [] (const juce::String& path, lynx::xml::Document& doc) {
  38850. juce::MemoryBlock raw;
  38851. juce::File (path).loadFileAsData (raw);
  38852. juce::MemoryInputStream in (raw, false);
  38853. juce::GZIPDecompressorInputStream gz (&in, false, juce::GZIPDecompressorInputStream::gzipFormat);
  38854. const auto text = gz.readEntireStreamAsString();
  38855. if (! doc.parse (text.toStdString()))
  38856. return lynx::xml::Element();
  38857. const auto kids = doc.root().children();
  38858. return kids.empty() ? lynx::xml::Element() : kids.front();
  38859. };
  38860. lynx::ChannelDef braid;
  38861. braid.instrument = lynx::InstrumentKind::braid;
  38862. braid.name = "Meld";
  38863. {
  38864. lynx::xml::Document doc;
  38865. lynx::alsdev::Notes notes;
  38866. const auto d = deviceOf (meld, doc);
  38867. const auto ok = (bool) d && lynx::alsdev::meldToBraid (d, braid, notes);
  38868. checks << (ok ? "ok " : "FAIL ") << "Meld -> Braid: " << meld << "\n";
  38869. braid.name = juce::File (meld).getFileNameWithoutExtension().toStdString();
  38870. }
  38871. std::vector<lynx::EffectSlot> slots;
  38872. for (const auto& path : { time, resonator })
  38873. {
  38874. lynx::xml::Document doc;
  38875. const auto d = deviceOf (path, doc);
  38876. if (const auto t = d ? lynx::alsdev::effectFromLiveDevice (d) : std::nullopt)
  38877. {
  38878. slots.push_back (t->slot);
  38879. checks << "ok " << t->from << " -> " << t->to << ": " << path << "\n";
  38880. }
  38881. else
  38882. checks << "FAIL NOT TRANSLATED: " << path << "\n";
  38883. }
  38884. offline.editSong ([&slots, &braid] (lynx::Song& s) {
  38885. if (s.channels.empty())
  38886. s.channels.resize (1);
  38887. braid.mixerTrack = 2;
  38888. s.channels[0] = braid;
  38889. if (s.mixer.size() < 3)
  38890. s.mixer.resize (3);
  38891. s.mixer[2].name = braid.name;
  38892. s.mixer[2].effects = slots;
  38893. while (s.patterns.empty())
  38894. s.patterns.emplace_back();
  38895. s.patterns[0].name = "Chords";
  38896. s.patterns[0].notes.clear();
  38897. for (const int key : { 48, 52, 55 })
  38898. {
  38899. lynx::Note note;
  38900. note.channel = 0;
  38901. note.start = 0;
  38902. note.length = 2 * lynx::ppq;
  38903. note.key = key;
  38904. s.patterns[0].notes.push_back (note);
  38905. }
  38906. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  38907. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  38908. s.playlistTracks[1].name = braid.name;
  38909. }, false);
  38910. offline.dispatchPendingMessages();
  38911. ui.setVisible (true);
  38912. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  38913. ui.selectTabForSnapshot (2);
  38914. ui.setClipLaunchWorkflow (true);
  38915. offline.editSong ([] (lynx::Song& s) {
  38916. lynx::Clip clip;
  38917. clip.pattern = 0;
  38918. clip.length = 4 * lynx::ppq;
  38919. lynx::launcher::setClip (s, 1, 0, clip);
  38920. }, false);
  38921. offline.dispatchPendingMessages();
  38922. if (auto* detail = ui.getDetailViewForSnapshot())
  38923. {
  38924. detail->showSelection (1, 0);
  38925. detail->setPage (lynx::DetailView::Page::devices);
  38926. offline.dispatchPendingMessages();
  38927. const auto file = lynx::shot::file (juce::File (prefix + "-devices.png"));
  38928. file.deleteFile();
  38929. juce::FileOutputStream out (file);
  38930. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  38931. checks << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << "\n";
  38932. }
  38933. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  38934. }
  38935. void runLiveDevShot190kk (const juce::String& prefix)
  38936. {
  38937. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  38938. lynx::AudioEngine offline (false);
  38939. lynx::MainComponent ui (offline, false);
  38940. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  38941. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  38942. const auto par = [] (const char* name, double v) { return juce::String ("<") + name + "><Manual Value=\"" + juce::String (v) + "\" /></" + name + ">"; };
  38943. // the Core Library presets' values (Erosion "Fizzle", Vinyl Distortion "Crack" with Tracing on, Corpus "Pipe Resonator" closed)
  38944. const juce::String erosion = "<Erosion2 Id=\"1\"><On><Manual Value=\"true\" /></On>" + par ("Amount", 0.9) + par ("Frequency", 16000) +
  38945. par ("FilterWidth", 1.734) + par ("NoiseBlend", 1) + par ("StereoWidth", 1) + "</Erosion2>";
  38946. const juce::String vinyl = "<Vinyl Id=\"1\"><On><Manual Value=\"true\" /></On><Band1On><Manual Value=\"true\" /></Band1On>" + par ("Gain1", 0.5) +
  38947. par ("BandFreq1", 7500) + par ("BandQ1", 3) + "<Band2On><Manual Value=\"false\" /></Band2On>" + par ("Gain2", 0.35) +
  38948. par ("BandFreq2", 5366) + par ("BandQ2", 0.32) + par ("Drive", 1) + par ("SoftHard", 0) + par ("NormalMono", 0) +
  38949. par ("CracleDensity", 50) + par ("CracleVolume", 1) + "</Vinyl>";
  38950. juce::String corpus = "<Corpus Id=\"1\"><On><Manual Value=\"true\" /></On><FilterOn><Manual Value=\"false\" /></FilterOn>";
  38951. for (const auto& [k, v] : std::initializer_list<std::pair<const char*, double>> { { "ResonanceType", 5 }, { "ResonatorQuality", 3 },
  38952. { "Frequency", 0.4603 }, { "Decay", 0.6032 }, { "FreqDamping", 0 }, { "AmpFreq", 0 }, { "Inharmonics", 0 }, { "Radius", 0.8642 },
  38953. { "TubeOpening", 1 }, { "Ratio", 0.5 }, { "ExcitationX", 0.5 }, { "ListeningXL", 0.1 }, { "ListeningXR", 0.9 }, { "Detune", 0.047 },
  38954. { "Drive", 0.405 }, { "Bleed", 0 }, { "DryWet", 0.696 }, { "StereoWidth", 1 }, { "FilterMidFreq", 1000 }, { "FilterBandWidth", 4 } })
  38955. corpus += par (k, v);
  38956. corpus += "</Corpus>";
  38957. std::vector<lynx::EffectSlot> slots;
  38958. juce::String checks;
  38959. for (const auto& text : { erosion, vinyl, corpus })
  38960. {
  38961. lynx::xml::Document doc;
  38962. doc.parse (text.toStdString());
  38963. if (const auto t = lynx::alsdev::effectFromLiveDevice (doc.root()))
  38964. {
  38965. slots.push_back (t->slot);
  38966. checks << t->from << " -> " << t->to << "\n";
  38967. }
  38968. else
  38969. checks << "NOT TRANSLATED\n";
  38970. }
  38971. offline.editSong ([&slots] (lynx::Song& s) {
  38972. if (s.channels.empty())
  38973. s.channels.resize (1);
  38974. s.channels[0].name = "Drums";
  38975. s.channels[0].mixerTrack = 2;
  38976. if (s.mixer.size() < 3)
  38977. s.mixer.resize (3);
  38978. s.mixer[2].name = "Drums";
  38979. s.mixer[2].effects = slots;
  38980. while (s.patterns.empty())
  38981. s.patterns.emplace_back();
  38982. s.patterns[0].name = "Beat";
  38983. s.patterns[0].notes.clear();
  38984. for (int n = 0; n < 4; ++n)
  38985. {
  38986. lynx::Note note;
  38987. note.channel = 0;
  38988. note.start = n * lynx::ppq;
  38989. note.key = 36;
  38990. s.patterns[0].notes.push_back (note);
  38991. }
  38992. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  38993. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  38994. s.playlistTracks[1].name = "Drums";
  38995. }, false);
  38996. offline.dispatchPendingMessages();
  38997. ui.setVisible (true);
  38998. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  38999. ui.selectTabForSnapshot (2);
  39000. ui.setClipLaunchWorkflow (true);
  39001. offline.editSong ([] (lynx::Song& s) {
  39002. lynx::Clip clip;
  39003. clip.pattern = 0;
  39004. clip.length = 4 * lynx::ppq;
  39005. lynx::launcher::setClip (s, 1, 0, clip);
  39006. }, false);
  39007. offline.dispatchPendingMessages();
  39008. if (auto* detail = ui.getDetailViewForSnapshot())
  39009. {
  39010. detail->showSelection (1, 0);
  39011. detail->setPage (lynx::DetailView::Page::devices);
  39012. const auto file = lynx::shot::file (juce::File (prefix + "-devices.png"));
  39013. file.deleteFile();
  39014. juce::FileOutputStream out (file);
  39015. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  39016. checks << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << "\n";
  39017. }
  39018. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  39019. }
  39020. void runDetailShot (const juce::String& prefix)
  39021. {
  39022. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  39023. lynx::AudioEngine offline (false);
  39024. lynx::MainComponent ui (offline, false);
  39025. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  39026. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  39027. const auto write = [&prefix, &ui] (const char* name) {
  39028. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  39029. file.deleteFile();
  39030. juce::FileOutputStream out (file);
  39031. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  39032. };
  39033. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  39034. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  39035. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  39036. offline.editSong ([] (lynx::Song& s) {
  39037. if (s.channels.size() < 2)
  39038. s.channels.resize (2);
  39039. s.channels[0].name = "Bass synth";
  39040. s.channels[0].mixerTrack = 2;
  39041. s.channels[1].mixerTrack = 3;
  39042. if (s.mixer.size() < 4)
  39043. s.mixer.resize (4);
  39044. s.mixer[2].name = "Bass";
  39045. s.mixer[2].effects.clear();
  39046. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::reverb, lynx::EffectKind::delay })
  39047. {
  39048. lynx::EffectSlot fx;
  39049. fx.kind = kind;
  39050. const auto& info = lynx::effectInfo (kind);
  39051. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  39052. fx.params[k] = info.params[k].defaultValue;
  39053. fx.enabled = kind != lynx::EffectKind::compressor; // one switched off
  39054. s.mixer[2].effects.push_back (fx);
  39055. }
  39056. while (s.patterns.size() < 2)
  39057. s.patterns.emplace_back();
  39058. s.patterns[0].name = "Bass line";
  39059. s.patterns[0].notes.clear();
  39060. for (int n = 0; n < 4; ++n)
  39061. {
  39062. lynx::Note note;
  39063. note.channel = 0;
  39064. note.start = n * lynx::ppq;
  39065. note.key = 36 + (n % 2) * 7;
  39066. s.patterns[0].notes.push_back (note);
  39067. }
  39068. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  39069. lynx::PatternEvents lane; // a volume swell for the Envelopes tab (slice 3)
  39070. lane.target = lynx::AutomationTarget { lynx::AutomationTargetKind::channelVolume, 0 };
  39071. for (int e = 0; e < 16; ++e)
  39072. lane.events.push_back ({ e * lynx::ppq / 4, 0.3f + 0.6f * (float) e / 15.0f });
  39073. s.patterns[0].events = { lane };
  39074. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  39075. s.playlistTracks[1].name = "Bass";
  39076. }, false);
  39077. offline.dispatchPendingMessages();
  39078. write ("pattern"); // Pattern workflow: no detail view exists
  39079. ui.setClipLaunchWorkflow (true);
  39080. offline.editSong ([] (lynx::Song& s) {
  39081. lynx::Clip clip;
  39082. clip.pattern = 0;
  39083. clip.length = 4 * lynx::ppq;
  39084. lynx::launcher::setClip (s, 1, 0, clip);
  39085. }, false);
  39086. offline.dispatchPendingMessages();
  39087. juce::String counts;
  39088. if (auto* detail = ui.getDetailViewForSnapshot())
  39089. {
  39090. detail->showSelection (1, 0);
  39091. detail->setPage (lynx::DetailView::Page::devices);
  39092. write ("devices");
  39093. counts << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << ", channel " << detail->chainChannelForCheck() << "\n";
  39094. detail->toggleFoldForCheck (3); // the reverb (card 0 is the instrument)
  39095. write ("folded");
  39096. counts << "folded card 3: " << (detail->isFoldedForCheck (3) ? 1 : 0) << "\n";
  39097. detail->showSelection (2, 0); // an empty track
  39098. write ("empty-track");
  39099. detail->showSelection (1, 0);
  39100. detail->setPage (lynx::DetailView::Page::clip);
  39101. offline.dispatchPendingMessages();
  39102. ui.getPianoRollForSnapshot().scrollToNotes(); // (the app does it on the message loop, which this shot doesn't run)
  39103. write ("clip"); // slice 2: the Piano roll docked here
  39104. {
  39105. // round 190s: the Transform panel with each MIDI tool, then Arpeggiate applied (and undone again)
  39106. auto& tools = detail->midiToolsForSnapshot();
  39107. for (int t = 0; t < lynx::MidiToolsPanel::toolCount; ++t)
  39108. {
  39109. tools.setTool (t);
  39110. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase()).toRawUTF8());
  39111. }
  39112. // round 190aa: the pages again with the settings of the Live shots they are compared with
  39113. tools.setAuto (false);
  39114. tools.setLiveShotSettingsForSnapshot();
  39115. for (int t : { (int) lynx::MidiToolsPanel::chop, (int) lynx::MidiToolsPanel::quantize, (int) lynx::MidiToolsPanel::timeWarp })
  39116. {
  39117. tools.setTool (t);
  39118. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase() + "-set").toRawUTF8());
  39119. }
  39120. tools.setAuto (true);
  39121. tools.setTool (lynx::MidiToolsPanel::arpeggiate);
  39122. tools.transformNow();
  39123. offline.dispatchPendingMessages();
  39124. write ("clip-mt-applied");
  39125. counts << "midi tools: arpeggiate made " << (int) offline.getSong().patterns[0].notes.size() << " notes of 4\n";
  39126. offline.undo();
  39127. offline.dispatchPendingMessages();
  39128. counts << "midi tools: undo gives " << (int) offline.getSong().patterns[0].notes.size() << " notes\n";
  39129. }
  39130. counts << "piano roll docked: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  39131. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() == detail ? 1 : 0) << "\n";
  39132. detail->setClipTab (true); // slice 3: the pattern's events in the Envelopes tab
  39133. offline.dispatchPendingMessages();
  39134. write ("envelopes");
  39135. detail->setClipTab (false);
  39136. detail->setPage (lynx::DetailView::Page::devices);
  39137. // round 183c-card: an Audio Effect Rack in the chain draws as its own card (the rack's view, Rand / Map in its
  39138. // title bar), as Live's Device View shows a rack
  39139. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.insert (s.mixer[2].effects.begin() + 1, shotRack()); }, false);
  39140. offline.dispatchPendingMessages();
  39141. detail->showSelection (2, 0);
  39142. detail->showSelection (1, 0);
  39143. write ("devices-rack");
  39144. counts << "rack card: cards " << detail->cardCountForCheck() << "\n";
  39145. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.erase (s.mixer[2].effects.begin() + 1); }, false);
  39146. offline.dispatchPendingMessages();
  39147. counts << "piano roll back in its panel: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  39148. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() != detail ? 1 : 0) << "\n";
  39149. }
  39150. else
  39151. counts << "no detail view\n";
  39152. ui.setClipLaunchWorkflow (false);
  39153. offline.dispatchPendingMessages();
  39154. write ("pattern-after");
  39155. juce::File (prefix + "-counts.txt").replaceWithText (counts);
  39156. }
  39157. void runPerfShot (const juce::String& prefix, const juce::String& projectPath)
  39158. {
  39159. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  39160. lynx::AudioEngine offline (false);
  39161. {
  39162. lynx::MainComponent ui (offline, false);
  39163. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  39164. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  39165. if (projectPath.isNotEmpty())
  39166. ui.openFile (juce::File (projectPath));
  39167. offline.dispatchPendingMessages();
  39168. // LYNX_PERFSHOT_PREPARE=1: Tools › Macros › Prepare for performance mode first (16 one-bar columns)
  39169. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PERFSHOT_PREPARE", {}) == "1")
  39170. offline.editSong ([] (lynx::Song& s) { lynx::perf::prepareForPerformance (s, 16, 4 * lynx::ppq); }, false);
  39171. offline.editSong ([] (lynx::Song& s) { s.performanceMode = true; s.mode = lynx::PlayMode::song; }, false);
  39172. offline.dispatchPendingMessages();
  39173. // what the Player would publish: on each of the first tracks with zone clips, one clip playing (part way)
  39174. // and on every other one the next clip waiting for its sync point
  39175. const auto& song = offline.getSong();
  39176. auto& live = offline.performanceStateForSnapshot();
  39177. const auto zone = lynx::perf::zoneClips (song);
  39178. int lastTrack = -1, launched = 0;
  39179. for (const auto index : zone)
  39180. {
  39181. const auto& c = song.playlist[(std::size_t) index];
  39182. if (c.track == lastTrack || c.track >= lynx::perf::maxTracks)
  39183. continue;
  39184. lastTrack = c.track;
  39185. std::int64_t clips[64];
  39186. const auto n = lynx::perf::trackZoneClips (song, zone, c.track, clips, 64);
  39187. auto& view = live.tracks[(std::size_t) c.track];
  39188. view.playing.store (clips[(std::size_t) ((launched % 3) % n)]);
  39189. view.progress.store (0.2f + 0.15f * (float) (launched % 5));
  39190. if (launched % 2 == 1 && n > 1)
  39191. view.pending.store (clips[(std::size_t) ((launched % 3 + 1) % n)]);
  39192. ++launched;
  39193. }
  39194. live.anyPlaying.store (launched > 0);
  39195. ui.selectTabForSnapshot (2);
  39196. offline.dispatchPendingMessages();
  39197. auto& playlist = ui.getPlaylistForSnapshot();
  39198. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-song.png");
  39199. playlist.runAction ("playlist.zoomPerformance"); // as FL opens these demos: the zone fills the view
  39200. offline.dispatchPendingMessages();
  39201. saveSnapshot (ui, prefix + "-playlist.png");
  39202. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-only.png");
  39203. // patcherize: the first insert with effects (all of them) and the first channel that can be
  39204. auto patched = offline.getSong();
  39205. for (int t = 0; t < (int) patched.mixer.size(); ++t)
  39206. if (lynx::patcherize::slotsForAll (patched, t).size() > 1)
  39207. {
  39208. lynx::patcherize::patcherizeSlots (patched, t, 0, true);
  39209. break;
  39210. }
  39211. for (int c = 0; c < (int) patched.channels.size(); ++c)
  39212. if (lynx::patcherize::patcherizeChannel (patched, c))
  39213. break;
  39214. juce::String error;
  39215. lynx::ProjectFile::save (patched, juce::File (prefix + "-patcherized.lynx"), error);
  39216. }
  39217. }
  39218. void runPatcherShot (const juce::String& prefix, const juce::String& projectPath)
  39219. {
  39220. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  39221. lynx::AudioEngine offline (false);
  39222. {
  39223. lynx::MainComponent ui (offline, false);
  39224. ui.setSize (1280, 720);
  39225. if (projectPath.isNotEmpty())
  39226. ui.openFile (juce::File (projectPath));
  39227. else
  39228. {
  39229. auto song = lynx::Song::makeDefault();
  39230. song.mixer.resize (4);
  39231. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  39232. slot.patcher.wires.clear();
  39233. for (auto [kind, x, y] : { std::tuple { lynx::EffectKind::frequencySplitter, 200.0f, 60.0f }, { lynx::EffectKind::reverb, 420.0f, 0.0f },
  39234. { lynx::EffectKind::fruityDelay3, 420.0f, 120.0f }, { lynx::EffectKind::peakController, 200.0f, 260.0f } })
  39235. {
  39236. lynx::PatchNode n;
  39237. n.effect = lynx::makeEffectSlot (kind);
  39238. n.x = x;
  39239. n.y = y;
  39240. slot.patcher.nodes.push_back (n);
  39241. }
  39242. { // round 165c: a Hardware Insert node (its editor opens from the node)
  39243. lynx::PatchNode n;
  39244. n.effect = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  39245. n.x = 420.0f, n.y = 260.0f;
  39246. slot.patcher.nodes.push_back (n);
  39247. }
  39248. auto wire = [&] (int from, int fromPort, int to, int toPort, float gain = 1.0f, lynx::PatchWire::Kind kind = lynx::PatchWire::Kind::audio) {
  39249. lynx::PatchWire w;
  39250. w.kind = kind;
  39251. w.from = from, w.fromPort = fromPort, w.to = to, w.toPort = toPort, w.gain = gain;
  39252. slot.patcher.wires.push_back (w);
  39253. };
  39254. wire (lynx::patchFromHost, 0, 0, 0);
  39255. wire (0, 1, 1, 0);
  39256. wire (0, 3, 2, 0, 0.5f);
  39257. wire (1, 0, lynx::patchToHost, 0);
  39258. wire (2, 0, lynx::patchToHost, 0);
  39259. wire (lynx::patchFromHost, 1, 3, 0);
  39260. wire (3, 1, 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  39261. wire (0, 2, lynx::patchToHost, 1, 0.7f);
  39262. // round 171b (issue #65): a Surface knob on the reverb's parameter input 1, the reverb's parameter 0 out to
  39263. // the delay's parameter input 2 (FL's Inputs / Outputs › Parameters)
  39264. {
  39265. lynx::SurfaceControl knob;
  39266. knob.name = "Knob 1";
  39267. knob.value = 0.6f;
  39268. slot.patcher.surface = { knob };
  39269. slot.patcher.surfaceX = 200.0f, slot.patcher.surfaceY = 380.0f;
  39270. lynx::patcher::setParamInput (slot.patcher, 1, 1, true, "Reverb - 2");
  39271. lynx::patcher::setParamOutput (slot.patcher, 1, 0, true);
  39272. lynx::patcher::setParamInput (slot.patcher, 2, 2, true, "Delay - 3");
  39273. wire (lynx::patchSurface, 0, 1, 1, 1.0f, lynx::PatchWire::Kind::control);
  39274. wire (1, lynx::patchParamOutput (0), 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  39275. }
  39276. slot.patcher.outputTracks = { 3 };
  39277. slot.patcher.inputX = -20.0f;
  39278. slot.patcher.outputX = 660.0f;
  39279. song.mixer[1].effects = { slot };
  39280. lynx::ChannelDef ch;
  39281. ch.name = "Patcher";
  39282. ch.instrument = lynx::InstrumentKind::patcher;
  39283. lynx::PatchNode synth, chorus;
  39284. synth.generator = true;
  39285. synth.channel.instrument = lynx::InstrumentKind::synth;
  39286. synth.channel.name = "Synth";
  39287. synth.x = 220.0f;
  39288. chorus.effect = lynx::makeEffectSlot (lynx::EffectKind::chorus);
  39289. chorus.x = 420.0f;
  39290. // round 162: a MIDI Out node between the "MIDI port 5" pin and "To LYNX" MIDI port 3, an Envelope Controller
  39291. // on the notes moving the chorus
  39292. lynx::PatchNode midiOut, envelope;
  39293. midiOut.generator = envelope.generator = true;
  39294. midiOut.channel.instrument = lynx::InstrumentKind::midiOut;
  39295. midiOut.channel.name = "MIDI Out";
  39296. lynx::midictl::writeMidiOut (midiOut.channel.pluginState.edit(), { 3, 0, 0, -1, -1 });
  39297. midiOut.x = 220.0f, midiOut.y = 160.0f;
  39298. envelope.channel.instrument = lynx::InstrumentKind::controller;
  39299. envelope.channel.name = "Envelope Controller";
  39300. envelope.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  39301. envelope.x = 220.0f, envelope.y = 260.0f;
  39302. lynx::PatchNode osc; // round 164f: an FL engine node (its editor opens from the node)
  39303. osc.generator = true;
  39304. osc.channel = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  39305. osc.channel.instrument = lynx::InstrumentKind::threeosc;
  39306. osc.channel.name = "3x Osc";
  39307. osc.x = 420.0f, osc.y = 260.0f;
  39308. // round 165c: Keyboard Controller, SoundFont player, Granulizer and Dashboard nodes (their editors open from the node)
  39309. lynx::PatchNode keys, soundfont, granulizer, dashboard;
  39310. keys.generator = soundfont.generator = granulizer.generator = dashboard.generator = true;
  39311. keys.channel.instrument = lynx::InstrumentKind::controller;
  39312. keys.channel.name = "Keyboard Controller";
  39313. {
  39314. lynx::KeyboardControllerData ramp;
  39315. for (std::size_t k = 0; k < ramp.keys.size(); ++k)
  39316. ramp.keys[k] = (float) k / (float) (ramp.keys.size() - 1);
  39317. lynx::writeKeyboardController (ramp, keys.channel.controllerState);
  39318. }
  39319. soundfont.channel = lynx::sf::makeChannel();
  39320. granulizer.channel = lynx::natives::makeChannel (lynx::InstrumentKind::granulizer, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  39321. granulizer.channel.instrument = lynx::InstrumentKind::granulizer;
  39322. granulizer.channel.name = "Fruity Granulizer";
  39323. dashboard.channel.instrument = lynx::InstrumentKind::dashboard;
  39324. dashboard.channel.name = "Dashboard";
  39325. dashboard.channel.patcher.surface = lynx::surface::starterControls();
  39326. keys.x = 20.0f, keys.y = 440.0f;
  39327. soundfont.x = 220.0f, soundfont.y = 440.0f;
  39328. granulizer.x = 420.0f, granulizer.y = 440.0f;
  39329. dashboard.x = 20.0f, dashboard.y = 540.0f;
  39330. // and a Layer node playing the SoundFont and Granulizer nodes on its Children pin (crossfaded)
  39331. lynx::PatchNode layerNode;
  39332. layerNode.generator = true;
  39333. layerNode.channel.instrument = lynx::InstrumentKind::layer;
  39334. layerNode.channel.name = "Layer";
  39335. layerNode.channel.layer.crossfade = true;
  39336. layerNode.channel.layer.fade = 0.35f;
  39337. layerNode.x = 220.0f, layerNode.y = 540.0f;
  39338. ch.patcher.nodes = { synth, chorus, midiOut, envelope, osc, keys, soundfont, granulizer, dashboard, layerNode };
  39339. lynx::PatchWire notes, a, b, portIn, portOut, envNotes, envControl;
  39340. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  39341. a.from = 0, a.to = 1;
  39342. b.from = 1;
  39343. portIn.kind = lynx::PatchWire::Kind::midi, portIn.fromPort = lynx::patchMidiPortPin (5), portIn.to = 2;
  39344. portOut.kind = lynx::PatchWire::Kind::midi, portOut.from = 2, portOut.to = lynx::patchToHost, portOut.toPort = 3;
  39345. envNotes.kind = lynx::PatchWire::Kind::midi, envNotes.to = 3;
  39346. envControl.kind = lynx::PatchWire::Kind::control, envControl.from = 3, envControl.to = 1, envControl.toPort = 0;
  39347. lynx::PatchWire oscNotes, oscOut;
  39348. oscNotes.kind = lynx::PatchWire::Kind::midi, oscNotes.to = 4;
  39349. oscOut.from = 4;
  39350. lynx::PatchWire layerNotes, layerToFont, layerToGrains, fontOut, grainsOut;
  39351. layerNotes.kind = layerToFont.kind = layerToGrains.kind = lynx::PatchWire::Kind::midi;
  39352. layerNotes.to = 9;
  39353. layerToFont.from = 9, layerToFont.to = 6;
  39354. layerToGrains.from = 9, layerToGrains.to = 7;
  39355. fontOut.from = 6;
  39356. grainsOut.from = 7;
  39357. ch.patcher.wires = { notes, a, b, portIn, portOut, envNotes, envControl, oscNotes, oscOut, layerNotes, layerToFont, layerToGrains, fontOut, grainsOut };
  39358. ch.patcher.fromMidiPorts = { 1, 5 };
  39359. ch.patcher.toMidiPorts = { 3 };
  39360. ch.patcher.outputX = 640.0f;
  39361. song.channels.push_back (ch);
  39362. // LYNX_PATCHERSHOT_SAVE=file.lynx: the demo as a project (a GUI check of the same Patchers, round 164f)
  39363. if (const auto save = juce::SystemStats::getEnvironmentVariable ("LYNX_PATCHERSHOT_SAVE", {}); save.isNotEmpty())
  39364. {
  39365. if (! song.patterns.empty())
  39366. for (int k = 0; k < 4; ++k)
  39367. 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 });
  39368. juce::String error;
  39369. lynx::ProjectFile::save (song, juce::File (save), error);
  39370. // round 171b: the saved Patchers come back the same (parameter ports, event cables, published)
  39371. juce::String report;
  39372. if (const auto loaded = lynx::ProjectFile::load (juce::File (save), error))
  39373. {
  39374. const auto same = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  39375. && loaded->mixer[1].effects[0].patcher == song.mixer[1].effects[0].patcher;
  39376. const auto& d = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty() ? loaded->mixer[1].effects[0].patcher : lynx::PatcherDoc {};
  39377. report << "patcher round trip: " << (same ? "OK" : "DIFFERENT") << "\n";
  39378. if (! same && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty())
  39379. {
  39380. const auto& a = song.mixer[1].effects[0].patcher;
  39381. report << "wires " << (a.wires == d.wires ? "same" : "differ") << ", published " << (a.published == d.published ? "same" : "differ")
  39382. << ", surface " << (a.surface == d.surface ? "same" : "differ") << "\n";
  39383. for (std::size_t n = 0; n < std::min (a.nodes.size(), d.nodes.size()); ++n)
  39384. if (! (a.nodes[n] == d.nodes[n]))
  39385. report << "node " << (int) n << " differs: ports " << (a.nodes[n].paramIns == d.nodes[n].paramIns && a.nodes[n].paramOuts == d.nodes[n].paramOuts ? "same" : "differ")
  39386. << ", effect " << (a.nodes[n].effect == d.nodes[n].effect ? "same" : "differ") << ", xy "
  39387. << (a.nodes[n].x == d.nodes[n].x && a.nodes[n].y == d.nodes[n].y ? "same" : "differ") << "\n";
  39388. }
  39389. for (int n = 0; n < (int) d.nodes.size(); ++n)
  39390. report << "node " << n << " paramIns " << (int) d.nodes[(std::size_t) n].paramIns.size() << " paramOuts "
  39391. << (int) d.nodes[(std::size_t) n].paramOuts.size() << "\n";
  39392. for (const auto& w : d.wires)
  39393. if (w.kind == lynx::PatchWire::Kind::control)
  39394. report << "control " << w.from << ":" << w.fromPort << " -> " << w.to << ":" << w.toPort << "\n";
  39395. for (const auto& p : d.published)
  39396. report << "published " << p.node << ":" << p.param << " " << juce::String::fromUTF8 (p.name.c_str()) << "\n";
  39397. }
  39398. else
  39399. report << "patcher round trip: load failed: " << error << "\n";
  39400. juce::File (prefix + "-roundtrip.txt").replaceWithText (report);
  39401. }
  39402. offline.setSong (std::move (song));
  39403. }
  39404. offline.dispatchPendingMessages();
  39405. const auto& song = offline.getSong();
  39406. auto shootOpen = [&] (const juce::String& name) {
  39407. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  39408. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  39409. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  39410. {
  39411. auto* c = w->getContentComponent();
  39412. savePng (lynx::shot::snapshot (*c), prefix + name);
  39413. delete w;
  39414. return;
  39415. }
  39416. };
  39417. int shots = 0;
  39418. for (int t = 0; t < (int) song.mixer.size() && shots < 12; ++t)
  39419. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  39420. if (song.mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::patcher)
  39421. {
  39422. lynx::PatcherWindows::openSlot (offline, t, s);
  39423. shootOpen ("-insert" + juce::String (t) + "-slot" + juce::String (s) + ".png");
  39424. // each built-in node's editor, as a double-click opens it (round 165c)
  39425. lynx::PatcherWindows::shootNodeEditors (offline, false, t, s, [&] (const juce::Image& image, int n) {
  39426. savePng (image, prefix + "-insert" + juce::String (t) + "-slot" + juce::String (s) + "-node" + juce::String (n) + ".png");
  39427. });
  39428. ++shots;
  39429. if (shots == 1) // its menus (round 162)
  39430. lynx::PatcherWindows::shootMenus (offline, false, t, s, [&] (const juce::Image& image, const juce::String& name) {
  39431. savePng (image, prefix + "-menu-" + name + ".png");
  39432. });
  39433. }
  39434. for (int c = 0; c < (int) song.channels.size(); ++c)
  39435. if (song.channels[(std::size_t) c].instrument == lynx::InstrumentKind::patcher)
  39436. {
  39437. lynx::PatcherWindows::openChannel (offline, c);
  39438. shootOpen ("-channel" + juce::String (c) + ".png");
  39439. // each node's editor, as a double-click opens it (round 164f; every built-in node since round 165c)
  39440. lynx::PatcherWindows::shootNodeEditors (offline, true, c, 0, [&] (const juce::Image& image, int n) {
  39441. savePng (image, prefix + "-channel" + juce::String (c) + "-node" + juce::String (n) + ".png");
  39442. });
  39443. lynx::PatcherWindows::shootMenus (offline, true, c, 0, [&] (const juce::Image& image, const juce::String& name) {
  39444. savePng (image, prefix + "-channel" + juce::String (c) + "-menu-" + name + ".png");
  39445. });
  39446. }
  39447. }
  39448. }
  39449. // Issue #64: FL's letter keys in a plugin menu (quickpick::showMenu), checked on the real menu windows
  39450. struct TypeAheadTest final : private juce::Timer
  39451. {
  39452. juce::File out;
  39453. juce::StringArray log;
  39454. int step = 0, picked = 0;
  39455. bool ok = true, menuShown = false;
  39456. std::unique_ptr<juce::DocumentWindow> owner;
  39457. juce::PopupMenu pending;
  39458. static juce::String highlighted()
  39459. {
  39460. if (auto* window = juce::Component::getCurrentlyModalComponent())
  39461. for (auto* child : window->getChildren())
  39462. if (auto* h = child->getAccessibilityHandler(); h != nullptr && h->hasFocus (false))
  39463. return h->getTitle();
  39464. return "(none)";
  39465. }
  39466. static void press (const juce::KeyPress& key)
  39467. {
  39468. if (auto* window = juce::Component::getCurrentlyModalComponent())
  39469. if (auto* peer = window->getPeer())
  39470. peer->handleKeyPress (key);
  39471. }
  39472. void expect (const juce::String& what, const juce::String& got, const juce::String& wanted)
  39473. {
  39474. const auto good = got == wanted;
  39475. ok = ok && good;
  39476. log.add ((good ? "ok " : "FAIL ") + what + ": " + got + (good ? juce::String() : " (wanted " + wanted + ")"));
  39477. }
  39478. void start()
  39479. {
  39480. juce::PopupMenu menu, sub;
  39481. auto item = [this] (juce::PopupMenu& m, int id, const char* text, bool enabled = true) {
  39482. m.addItem (text, enabled, false, [this, id] { picked = id; });
  39483. };
  39484. menu.addSectionHeader ("LYNX SHARE");
  39485. item (menu, 1, "Echoform");
  39486. item (menu, 2, "EQ");
  39487. item (menu, 3, "Halo");
  39488. menu.addSectionHeader ("Misc");
  39489. item (menu, 4, "Effector");
  39490. item (menu, 5, "Exciter (unavailable)", false);
  39491. item (sub, 10, "Delay");
  39492. item (sub, 11, "Edison");
  39493. item (sub, 12, "Eventide");
  39494. menu.addSubMenu ("Tree", sub);
  39495. // the menu belongs to a window in the foreground, as when the user right-clicks a mixer slot (JUCE closes a
  39496. // menu of a background process at once)
  39497. owner = std::make_unique<juce::DocumentWindow> ("LYNX type-ahead test", juce::Colours::black, 0);
  39498. owner->setBounds (200, 200, 300, 200);
  39499. owner->setVisible (true);
  39500. lynx::forceForegroundForTest (*owner);
  39501. pending = menu; // shown once the window is up and active (X11 maps and activates it asynchronously)
  39502. startTimer (300);
  39503. }
  39504. void timerCallback() override
  39505. {
  39506. const auto e = juce::KeyPress ('e', {}, 'e');
  39507. if (step == 0 && owner != nullptr && ! menuShown)
  39508. {
  39509. menuShown = true;
  39510. lynx::forceForegroundForTest (*owner);
  39511. lynx::quickpick::showMenu (pending, juce::PopupMenu::Options().withTargetComponent (owner.get()), {});
  39512. return;
  39513. }
  39514. switch (step++)
  39515. {
  39516. case 0: expect ("menu open", juce::String ((int) (juce::Component::getCurrentlyModalComponent() != nullptr)), "1"); break;
  39517. case 1: press (e); expect ("e", highlighted(), "Echoform"); break;
  39518. case 2: press (e); expect ("e again", highlighted(), "EQ"); break;
  39519. case 3: press (juce::KeyPress ('E', juce::ModifierKeys::shiftModifier, 'E')); expect ("E (shift)", highlighted(), "Effector"); break;
  39520. case 4: press (e); expect ("e wraps (skips the disabled one)", highlighted(), "Echoform"); break;
  39521. case 5: press (juce::KeyPress ('m', {}, 'm')); expect ("m (only a heading starts with it: no move)", highlighted(), "Echoform"); break;
  39522. case 6: press (juce::KeyPress (juce::KeyPress::downKey)); expect ("down arrow", highlighted(), "EQ"); break;
  39523. case 7: press (e); expect ("e after the arrow", highlighted(), "Effector"); break;
  39524. case 8: press (juce::KeyPress ('t', {}, 't')); expect ("t", highlighted(), "Tree"); break;
  39525. case 9: press (juce::KeyPress (juce::KeyPress::rightKey)); break; // opens the submenu (it takes the keys)
  39526. case 10: press (e); expect ("e in the submenu", highlighted(), "Edison"); break;
  39527. case 11: press (e); expect ("e again in the submenu", highlighted(), "Eventide"); break;
  39528. case 12: expect ("nothing picked by the letters", juce::String (picked), "0"); press (juce::KeyPress (juce::KeyPress::returnKey)); break;
  39529. case 13: break;
  39530. default:
  39531. expect ("Enter closed the menu", juce::String ((int) (juce::Component::getCurrentlyModalComponent() == nullptr)), "1");
  39532. expect ("Enter picked", juce::String (picked), "12");
  39533. stopTimer();
  39534. owner.reset();
  39535. log.add (ok ? "result=OK" : "result=FAIL");
  39536. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  39537. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  39538. juce::JUCEApplication::quit();
  39539. return;
  39540. }
  39541. }
  39542. };
  39543. std::unique_ptr<TypeAheadTest> typeAheadTest;
  39544. struct ChooserTest final : private juce::Timer
  39545. {
  39546. juce::File out, file;
  39547. juce::StringArray log;
  39548. std::unique_ptr<juce::FileChooser> chooser;
  39549. double started = 0;
  39550. bool shot = false, done = false;
  39551. void start()
  39552. {
  39553. log.add ("LYNX_FILE_DIALOG=" + juce::SystemStats::getEnvironmentVariable ("LYNX_FILE_DIALOG", {}));
  39554. log.add ("native=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  39555. chooser = lynx::ui::makeFileChooser ("Open audio file", file.getParentDirectory(), "*.wav;*.flac");
  39556. started = juce::Time::getMillisecondCounterHiRes();
  39557. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  39558. [this] (const juce::FileChooser& fc) { finish (fc.getResult()); });
  39559. startTimer (200);
  39560. }
  39561. static juce::FileChooserDialogBox* builtInDialog()
  39562. {
  39563. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i)
  39564. if (auto* box = dynamic_cast<juce::FileChooserDialogBox*> (juce::Desktop::getInstance().getComponent (i)); box != nullptr && box->isShowing())
  39565. return box;
  39566. return nullptr;
  39567. }
  39568. static juce::FileBrowserComponent* findBrowser (juce::Component& c)
  39569. {
  39570. if (auto* b = dynamic_cast<juce::FileBrowserComponent*> (&c))
  39571. return b;
  39572. for (auto* child : c.getChildren())
  39573. if (auto* b = findBrowser (*child))
  39574. return b;
  39575. return nullptr;
  39576. }
  39577. void timerCallback() override
  39578. {
  39579. if (done)
  39580. return;
  39581. if (auto* box = builtInDialog(); box != nullptr && ! shot)
  39582. {
  39583. shot = true;
  39584. log.add ("built-in dialog shown after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms");
  39585. const auto image = lynx::shot::snapshot (*box);
  39586. juce::FileOutputStream png (out.getSiblingFile (out.getFileName() + ".png"));
  39587. if (png.openedOk())
  39588. {
  39589. png.setPosition (0), png.truncate();
  39590. juce::PNGImageFormat().writeImageToStream (image, png);
  39591. }
  39592. if (auto* browser = findBrowser (*box))
  39593. {
  39594. browser->setRoot (file.getParentDirectory());
  39595. browser->setFileName (file.getFileName());
  39596. log.add ("typed " + file.getFileName());
  39597. box->exitModalState (1);
  39598. }
  39599. else
  39600. log.add ("no file browser in the dialog");
  39601. }
  39602. if (juce::Time::getMillisecondCounterHiRes() - started > 30000.0)
  39603. finish ({}, "timeout");
  39604. }
  39605. void finish (const juce::File& result, const juce::String& why = {})
  39606. {
  39607. if (done)
  39608. return;
  39609. done = true;
  39610. stopTimer();
  39611. log.add ("callback after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms: "
  39612. + (why.isNotEmpty() ? why : result.getFullPathName().isEmpty() ? juce::String ("(no file)") : result.getFullPathName()));
  39613. log.add ("native now=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  39614. const auto ok = result == file && result.existsAsFile();
  39615. log.add (ok ? "result=OK" : "result=FAIL");
  39616. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  39617. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  39618. juce::MessageManager::callAsync ([] { juce::JUCEApplication::quit(); });
  39619. }
  39620. };
  39621. std::unique_ptr<ChooserTest> chooserTest;
  39622. void runChooserTest (const juce::File& out, const juce::File& file)
  39623. {
  39624. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  39625. chooserTest = std::make_unique<ChooserTest>();
  39626. chooserTest->out = out;
  39627. chooserTest->file = file;
  39628. chooserTest->start();
  39629. }
  39630. void runTypeAheadTest (const juce::File& out)
  39631. {
  39632. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  39633. typeAheadTest = std::make_unique<TypeAheadTest>();
  39634. typeAheadTest->out = out;
  39635. typeAheadTest->start();
  39636. }
  39637. void runStabilityShot (const juce::String& folder)
  39638. {
  39639. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  39640. const juce::File dir (folder);
  39641. dir.createDirectory();
  39642. {
  39643. lynx::AudioEngine offline (false);
  39644. const auto save = [&dir] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  39645. juce::Component frame;
  39646. frame.setSize (c->getWidth(), c->getHeight());
  39647. frame.setOpaque (true);
  39648. if (c->isOnDesktop()) // (an AlertWindow: never shown, so it takes no foreground)
  39649. c->removeFromDesktop();
  39650. frame.addAndMakeVisible (*c);
  39651. c->setTopLeftPosition (0, 0);
  39652. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  39653. const auto file = dir.getChildFile (name);
  39654. file.deleteFile();
  39655. juce::PNGImageFormat png;
  39656. if (auto out = file.createOutputStream())
  39657. png.writeImageToStream (image, *out);
  39658. };
  39659. save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "crash-prompt.png");
  39660. save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", true), "crash-prompt-onload.png");
  39661. save (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "crash-notice.png");
  39662. save (lynx::makePluginManagerPanel (offline, false), "plugin-manager.png");
  39663. save (lynx::makePluginMonitorPanel (offline), "plugin-monitor.png");
  39664. }
  39665. setApplicationReturnValue (0);
  39666. quit();
  39667. }
  39668. void runDetails190ihShot (const juce::String& prefix)
  39669. {
  39670. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  39671. juce::String report;
  39672. auto line = [&report] (const juce::String& t) { report << t << "\n"; };
  39673. {
  39674. // R2: Gross Beat on Insert 1 — the first time slot and a half-beat volume gate, as in FL's capture ("Empty",
  39675. // "1/2 Bt Gate")
  39676. lynx::AudioEngine offline (false);
  39677. lynx::Song song;
  39678. song.mixer = lynx::Song::defaultMixer (2);
  39679. song.bpm = 150.0;
  39680. auto gb = lynx::makeEffectSlot (lynx::EffectKind::grossBeat);
  39681. const auto names = lynx::grossbeat::slotNames (gb.state, true);
  39682. int gate = 0;
  39683. for (int k = 0; k < (int) names.size(); ++k)
  39684. if (names[(std::size_t) k] == "Gate 1/2 beat") // (LYNX's factory slot for FL's "1/2 Bt Gate")
  39685. gate = k;
  39686. gb.params[0] = lynx::grossbeat::paramFromRaw (0, 0);
  39687. gb.params[1] = lynx::grossbeat::paramFromRaw (1, gate);
  39688. song.mixer[1].effects.push_back (gb);
  39689. offline.setSong (std::move (song));
  39690. offline.dispatchPendingMessages();
  39691. // the real effect played to beat 2.9 of its bar: its published outputs go where the rack writes them
  39692. auto run = lynx::makeEffect (gb);
  39693. run->prepare (48000.0);
  39694. const auto tps = 150.0 / 60.0 * lynx::ppq / 48000.0;
  39695. std::vector<float> l (480, 0.3f), r (480, 0.3f);
  39696. std::size_t done = 0;
  39697. auto block = [&] (lynx::EffectParams& params) {
  39698. run->setSongPosition ((double) done * tps);
  39699. run->process (l.data(), r.data(), 480, params, 150.0);
  39700. done += 480;
  39701. };
  39702. auto publish = [&] (bool playing) {
  39703. const auto key = (std::size_t) (1 * lynx::maxEffectSlots + 0) * lynx::ProcessTimes::meterOutputs;
  39704. if (auto* times = offline.getProcessTimes())
  39705. for (int k = 0; k < lynx::ProcessTimes::meterOutputs; ++k)
  39706. times->effectMeters[key + (std::size_t) k].store (run->controlOutput (k), std::memory_order_relaxed);
  39707. else
  39708. line ("no process times: the editor shows nothing live");
  39709. offline.getTransport().playing.store (playing);
  39710. juce::String values;
  39711. for (int k = 0; k < 7; ++k)
  39712. values << " " << juce::String (run->controlOutput (k), 3);
  39713. line ("gross beat outputs:" + values);
  39714. };
  39715. while ((double) done * tps / lynx::ppq < 2.9)
  39716. block (gb.params);
  39717. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f);
  39718. editor->setSize (editor->getWidth(), editor->getHeight());
  39719. for (const int view : { 1, 0 })
  39720. {
  39721. lynx::showGrossBeatEnvelopeForSnapshot (*editor, view);
  39722. publish (true);
  39723. lynx::tickNativeEffectEditor (*editor);
  39724. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-playing-" + (view == 1 ? "volume" : "time") + ".png");
  39725. }
  39726. lynx::ui::motion::enabled() = false;
  39727. lynx::tickNativeEffectEditor (*editor);
  39728. editor->repaint();
  39729. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-playing-noanim.png");
  39730. lynx::ui::motion::enabled() = true;
  39731. // a click on another time slot: queued until the next 4 beats
  39732. auto queued = gb.params;
  39733. queued[0] = lynx::grossbeat::paramFromRaw (0, 5);
  39734. block (queued);
  39735. publish (true);
  39736. lynx::tickNativeEffectEditor (*editor);
  39737. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-queued.png");
  39738. publish (false); // stopped: no locator, no fill
  39739. lynx::tickNativeEffectEditor (*editor);
  39740. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-stopped.png");
  39741. // round 190jd (live check 190iw Q7): the locator in FL's colours (the editor's Options menu) on the beat (cream,
  39742. // 3 px trail), a third into it (orange) and near its end (dusty red); LYNX's playhead colour stays the default
  39743. lynx::gblocator::setFlStyle (true);
  39744. lynx::showGrossBeatEnvelopeForSnapshot (*editor, 1);
  39745. for (const auto at : { 4.02, 4.35, 4.9 })
  39746. {
  39747. while ((double) done * tps / lynx::ppq < at)
  39748. block (queued);
  39749. publish (true);
  39750. juce::Thread::sleep (60); // (the editor's frame budget: ~21 frames a second in this style)
  39751. lynx::tickNativeEffectEditor (*editor);
  39752. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-fl-colours-" + juce::String (at - 4.0, 2) + ".png");
  39753. }
  39754. lynx::gblocator::setFlStyle (false);
  39755. offline.getTransport().playing.store (false);
  39756. }
  39757. {
  39758. // R7: the Envelope Controller's Keyboard / Velocity mapping pages after a note (key 64, velocity 0.8)
  39759. lynx::AudioEngine offline (false);
  39760. lynx::Song song;
  39761. lynx::ChannelDef env;
  39762. env.name = "Envelope Controller";
  39763. env.instrument = lynx::InstrumentKind::controller;
  39764. auto ec = lynx::defaultEnvelopeController();
  39765. ec[0].maps[lynx::mapKeyboard].count = 2;
  39766. ec[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  39767. ec[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  39768. ec[0].maps[lynx::mapVelocity] = ec[0].maps[lynx::mapKeyboard];
  39769. env.controllerState = lynx::writeEnvelopeController (ec);
  39770. song.channels.push_back (env);
  39771. song.patterns.emplace_back();
  39772. offline.setSong (std::move (song));
  39773. offline.dispatchPendingMessages();
  39774. auto editor = lynx::makeEnvelopeControllerEditor (
  39775. offline, [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; }, 0,
  39776. [] (int k) { return k == 8 ? 64.0f : k == 9 ? 0.8f : 0.5f; });
  39777. for (const int part : { 2, 3 })
  39778. {
  39779. for (auto* child : editor->getChildren())
  39780. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  39781. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  39782. savePng (lynx::shot::snapshot (*editor), prefix + "-r7-ec-" + (part == 2 ? "keyboard" : "velocity") + "-line.png");
  39783. }
  39784. }
  39785. {
  39786. lynx::AudioEngine offline (false);
  39787. lynx::MainComponent ui (offline, false);
  39788. ui.setSize (1920, 1080);
  39789. lynx::Song song;
  39790. song.mixer = lynx::Song::defaultMixer (4);
  39791. for (const auto* name : { "Grv Kick 27", "Snare", "Hat", "Bass (locked)" })
  39792. {
  39793. lynx::ChannelDef c;
  39794. c.name = name;
  39795. c.instrument = lynx::InstrumentKind::sampler;
  39796. song.channels.push_back (c);
  39797. }
  39798. song.channels[3].receiveFrom = "MIDI keyboard";
  39799. song.patterns.emplace_back();
  39800. offline.setSong (std::move (song));
  39801. offline.dispatchPendingMessages();
  39802. ui.showDesktopForSnapshot (false);
  39803. offline.dispatchPendingMessages();
  39804. // R4: the rack's activity light — before, at note-on, held, after the release; a locked channel lit (orange)
  39805. auto& rack = ui.getRackForSnapshot();
  39806. const std::pair<const char*, float> states[] { { "before", 0.0f }, { "noteon", 1.0f }, { "held", lynx::activity::held }, { "after", 0.0f } };
  39807. for (const auto& [name, level] : states)
  39808. {
  39809. rack.setActivityForSnapshot (0, level);
  39810. rack.setActivityForSnapshot (3, level);
  39811. savePng (lynx::shot::snapshot (rack), prefix + "-r4-rack-" + name + ".png");
  39812. }
  39813. rack.setActivityForSnapshot (0, 0.0f);
  39814. rack.setActivityForSnapshot (3, 0.0f);
  39815. // R3: the transport stopped, playing, recording (both blink phases), armed and stopped; the hint bar
  39816. const auto toolbar = ui.getToolbarBoundsForSnapshot();
  39817. auto& transport = offline.getTransport();
  39818. ui.transportForSnapshot (false, true);
  39819. saveArea (ui, toolbar, prefix + "-r3-toolbar-stopped.png");
  39820. transport.playing.store (true);
  39821. ui.transportForSnapshot (true, true);
  39822. saveArea (ui, toolbar, prefix + "-r3-toolbar-playing.png");
  39823. transport.recording.store (true);
  39824. ui.transportForSnapshot (true, true);
  39825. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-lit.png");
  39826. ui.transportForSnapshot (true, false);
  39827. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-dark.png");
  39828. lynx::ui::motion::enabled() = false;
  39829. ui.transportForSnapshot (true, false);
  39830. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-noanim.png");
  39831. lynx::ui::motion::enabled() = true;
  39832. transport.playing.store (false);
  39833. ui.transportForSnapshot (false, false);
  39834. saveArea (ui, toolbar, prefix + "-r3-toolbar-armed-stopped.png");
  39835. transport.recording.store (false);
  39836. ui.transportForSnapshot (false, true);
  39837. for (const bool on : { true, false })
  39838. {
  39839. offline.markLiveNote (60, 100, on);
  39840. const auto hint = ui.liveNoteHintForSnapshot();
  39841. line ("hint: " + hint);
  39842. ui.setHintForSnapshot ({ hint, {}, false, false });
  39843. saveArea (ui, toolbar, prefix + "-r3-hint-note" + (on ? "on" : "off") + ".png");
  39844. }
  39845. offline.editSong ([] (lynx::Song& s) { s.bpm = 128.0; }); // (a change: the project is modified)
  39846. offline.dispatchPendingMessages();
  39847. const auto reminder = ui.saveReminderForSnapshot();
  39848. line ("reminder: " + reminder);
  39849. ui.setHintForSnapshot ({ reminder, {}, false, false });
  39850. saveArea (ui, toolbar, prefix + "-r3-save-reminder.png");
  39851. // R14: the Simple dock's input level
  39852. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  39853. offline.dispatchPendingMessages();
  39854. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  39855. if (auto* dock = simple->dockForSnapshot())
  39856. {
  39857. dock->inputLevelForSnapshot (0.72f);
  39858. offline.dispatchPendingMessages();
  39859. savePng (lynx::shot::snapshot (*dock), prefix + "-r14-dock-input-level.png");
  39860. line ("dock: " + juce::String (dock->getWidth()) + "x" + juce::String (dock->getHeight()));
  39861. }
  39862. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  39863. offline.dispatchPendingMessages();
  39864. }
  39865. juce::File (prefix + "-report.txt").replaceWithText (report);
  39866. }
  39867. void runJsfxShots (const juce::String& folderPath)
  39868. {
  39869. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  39870. const juce::File folder (folderPath);
  39871. folder.createDirectory();
  39872. lynx::jsfx::installPack();
  39873. juce::StringArray made;
  39874. {
  39875. lynx::AudioEngine offline (false);
  39876. lynx::JsfxPluginFormat format;
  39877. auto& known = offline.getPluginHost().getKnownPlugins();
  39878. for (const auto& f : format.searchPathsForPlugins (juce::FileSearchPath (lynx::jsfx::packFolder().getFullPathName()), true, false))
  39879. {
  39880. juce::OwnedArray<juce::PluginDescription> found;
  39881. format.findAllTypesForFile (found, f);
  39882. for (auto* d : found)
  39883. known.addType (*d);
  39884. }
  39885. // the slider panels (the plugin window's editor) of four bundled scripts
  39886. for (const auto* rel : { "chokehold/Clipper/soft_clipper.jsfx", "chokehold/Generator/test_signals.jsfx",
  39887. "chokehold/Instrument FX/mic_combiner.jsfx", "chokehold/MIDI/midi_chord_trigger.jsfx" })
  39888. {
  39889. const auto file = lynx::jsfx::packFolder().getChildFile (rel);
  39890. juce::OwnedArray<juce::PluginDescription> found;
  39891. format.findAllTypesForFile (found, file.getFullPathName());
  39892. if (found.isEmpty())
  39893. continue;
  39894. juce::String error;
  39895. auto instance = format.createInstanceFromDescription (*found[0], 48000.0, 512, error);
  39896. if (instance == nullptr)
  39897. {
  39898. made.add (juce::String (rel) + ": " + error);
  39899. continue;
  39900. }
  39901. lynx::preparePlugin (*instance, 48000.0, 512);
  39902. juce::AudioBuffer<float> buffer (2, 512);
  39903. juce::MidiBuffer midi;
  39904. for (int b = 0; b < 8; ++b)
  39905. {
  39906. buffer.clear();
  39907. instance->processBlock (buffer, midi);
  39908. }
  39909. offline.dispatchPendingMessages(); // (the latency it reported)
  39910. std::unique_ptr<juce::AudioProcessorEditor> editor (instance->createEditor());
  39911. const auto name = "jsfx-panel-" + file.getFileNameWithoutExtension() + ".png";
  39912. saveSnapshot (*editor, folder.getChildFile (name).getFullPathName());
  39913. made.add (name);
  39914. editor = nullptr;
  39915. }
  39916. // the Browser's Plugin database with its JSFX categories open, in the default desktop
  39917. lynx::MainComponent ui (offline, false);
  39918. ui.setSize (1280, 720);
  39919. offline.dispatchPendingMessages();
  39920. ui.waitForBrowserForSnapshot();
  39921. ui.getBrowserForSnapshot().showJsfxForSnapshot();
  39922. offline.dispatchPendingMessages();
  39923. saveSnapshot (ui, folder.getChildFile ("jsfx-browser.png").getFullPathName());
  39924. saveArea (ui, ui.getBrowserForSnapshot().getBoundsInParent(), folder.getChildFile ("jsfx-browser-panel.png").getFullPathName());
  39925. made.add ("jsfx-browser.png");
  39926. // Settings › File with the JSFX folders list
  39927. auto settings = lynx::makeSettingsPanel (offline, lynx::SettingsPage::files);
  39928. if (settings->getWidth() < 200 || settings->getHeight() < 200)
  39929. settings->setSize (720, 640);
  39930. offline.dispatchPendingMessages();
  39931. saveSnapshot (*settings, folder.getChildFile ("jsfx-settings-files.png").getFullPathName());
  39932. made.add ("jsfx-settings-files.png");
  39933. }
  39934. folder.getChildFile ("jsfxshots.txt").replaceWithText (made.joinIntoString ("\n") + "\n");
  39935. setApplicationReturnValue (0);
  39936. quit();
  39937. }
  39938. void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
  39939. {
  39940. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  39941. // LYNX_SNAPSHOT_THEME=file.lynxtheme: the pictures in that theme (round 162d)
  39942. if (const auto themeFile = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_THEME", {}); themeFile.isNotEmpty())
  39943. if (const auto spec = lynx::themeui::loadFile (juce::File (themeFile)))
  39944. lynx::themeui::apply (*spec, false);
  39945. {
  39946. lynx::AudioEngine offline (false);
  39947. lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
  39948. // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
  39949. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
  39950. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  39951. if (projectPath.isNotEmpty())
  39952. ui.openFile (juce::File (projectPath));
  39953. offline.dispatchPendingMessages(); // change notifications are asynchronous
  39954. ui.waitForBrowserForSnapshot();
  39955. // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
  39956. // (and a sample hint in the status strip, as when hovering a knob)
  39957. ui.showDesktopForSnapshot (false);
  39958. ui.setMetersForSnapshot (0.23, (std::int64_t) 412 << 20, 6);
  39959. offline.dispatchPendingMessages();
  39960. saveSnapshot (ui, prefix + "-desktop.png");
  39961. // the first start: the setup wizard over the main window (round 140), also on a small screen (it scrolls)
  39962. {
  39963. const auto size = ui.getBounds();
  39964. ui.showSetupWizard();
  39965. offline.dispatchPendingMessages();
  39966. saveSnapshot (ui, prefix + "-desktop-setup.png");
  39967. ui.setSize (1024, 600);
  39968. offline.dispatchPendingMessages();
  39969. saveSnapshot (ui, prefix + "-desktop-setup-small.png");
  39970. ui.closeSetupWizardForSnapshot();
  39971. ui.setBounds (size);
  39972. offline.dispatchPendingMessages();
  39973. }
  39974. // the start-up desktop and the toolbar at the usual window sizes: the untouched default layout
  39975. // follows the window (default rects, not scaled ones); panels drop from the toolbar by priority
  39976. {
  39977. const auto size = ui.getBounds();
  39978. for (const auto& [w, h] : std::vector<std::pair<int, int>> { { 1280, 720 }, { 1366, 768 }, { 1600, 900 }, { 1920, 1080 }, { 2560, 1440 }, { 3840, 2160 } })
  39979. {
  39980. ui.setSize (w, h);
  39981. offline.dispatchPendingMessages();
  39982. saveSnapshot (ui, prefix + "-desktop-" + juce::String (w) + ".png");
  39983. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + juce::String (w) + ".png");
  39984. if (w == 1920) // the rack scrolled to its last steps: the controls column stays in view (round 90)
  39985. {
  39986. ui.scrollRackForSnapshot (100000);
  39987. offline.dispatchPendingMessages();
  39988. saveSnapshot (ui, prefix + "-desktop-rack-scrolled.png");
  39989. ui.scrollRackForSnapshot (0);
  39990. }
  39991. }
  39992. // the toolbar with small and large icons, and a customized one (groups hidden and reordered)
  39993. ui.setSize (1600, 900);
  39994. for (auto [iconSize, name] : { std::pair { lynx::toolbarlayout::IconSize::small, "small" }, { lynx::toolbarlayout::IconSize::large, "large" } })
  39995. {
  39996. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  39997. layout.iconSize = iconSize;
  39998. ui.setToolbarLayoutForSnapshot (layout);
  39999. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + name + "-1600.png");
  40000. }
  40001. {
  40002. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  40003. layout.move (lynx::toolbarlayout::Group::windows, -3);
  40004. layout.setShown (lynx::toolbarlayout::Group::record, false);
  40005. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  40006. ui.setToolbarLayoutForSnapshot (layout);
  40007. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-custom-1600.png");
  40008. }
  40009. {
  40010. // round 170e: the toolbar after a knob was moved: the last tweaked read-out (its caption) and the snap magnet
  40011. ui.setSize (1920, 1080); // the read-out needs room beside the hint bar
  40012. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  40013. lynx::AutomationTarget t;
  40014. t.kind = lynx::AutomationTargetKind::mixerVolume;
  40015. t.index = 0;
  40016. offline.noteTweaked (t);
  40017. ui.refreshTweakReadoutForSnapshot();
  40018. offline.dispatchPendingMessages();
  40019. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-tweak-1920.png");
  40020. ui.setSize (1600, 900);
  40021. }
  40022. {
  40023. // the toolbar's edit mode (round 115): outlined panels and the tray of panels under it
  40024. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  40025. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  40026. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  40027. ui.setToolbarLayoutForSnapshot (layout);
  40028. ui.setToolbarEditingForSnapshot (true);
  40029. offline.dispatchPendingMessages();
  40030. saveArea (ui, ui.getToolbarBoundsForSnapshot().withHeight (ui.getToolbarAndTrayHeightForSnapshot()), prefix + "-toolbar-edit-1600.png");
  40031. ui.setToolbarEditingForSnapshot (false);
  40032. // Ctrl+F11: only the menu and the hint bar
  40033. layout = lynx::toolbarlayout::Layout::makeDefault();
  40034. layout.visible = false;
  40035. ui.setToolbarLayoutForSnapshot (layout);
  40036. saveArea (ui, ui.getLocalBounds().withHeight (120), prefix + "-toolbar-hidden-1600.png");
  40037. }
  40038. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  40039. // quick tips: the toolbar and title bars with a few name bubbles, and every tip on one sheet
  40040. offline.dispatchPendingMessages();
  40041. saveQuickTips (ui, prefix);
  40042. ui.setBounds (size);
  40043. offline.dispatchPendingMessages();
  40044. }
  40045. // the hint bar: a value control while it is dragged (live value), a gesture line with mouse and key
  40046. // glyphs, and a text too long for one line (two lines)
  40047. {
  40048. const auto toolbar = ui.getToolbarBoundsForSnapshot().withWidth (juce::jmin (ui.getWidth(), 900));
  40049. const lynx::ui::Hint hints[] = {
  40050. { lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "-3.2 dB", true, true },
  40051. { lynx::tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"), {}, false, false },
  40052. { lynx::tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  40053. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"), {}, false, true },
  40054. };
  40055. for (int i = 0; i < 3; ++i)
  40056. {
  40057. ui.setHintForSnapshot (hints[i], i == 0);
  40058. saveArea (ui, toolbar, prefix + "-hint-" + juce::String (i + 1) + ".png");
  40059. }
  40060. }
  40061. ui.showDesktopForSnapshot (true);
  40062. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  40063. saveSnapshot (ui, prefix + "-desktop-all.png");
  40064. ui.selectTabForSnapshot (0);
  40065. saveSnapshot (ui, prefix + "-rack.png");
  40066. // round 190io (design190ia FM-10…14): steps on the first channels, audio clip channels included (they show
  40067. // their steps as in FL), a few selected rows, a muted channel; then the project as it was
  40068. {
  40069. const auto& kept = offline.getSong();
  40070. const auto keptSelection = offline.getSelectedChannels();
  40071. const auto keptPrimary = offline.getSelectedChannel();
  40072. const auto channels = (int) kept.channels.size();
  40073. offline.editSong ([channels] (lynx::Song& s) {
  40074. auto& p = s.activePattern();
  40075. for (int c = 0; c < juce::jmin (12, channels); ++c)
  40076. for (const auto step : { 0, 4 + (c % 3) * 2, 8, 12 + (c % 2) * 2 })
  40077. if (! p.hasStep (c, step))
  40078. p.toggleStep (c, step);
  40079. if (channels > 5)
  40080. s.channels[5].muted = true;
  40081. });
  40082. if (channels > 3)
  40083. offline.setChannelSelection ({ 1, 2, 3 }, 2);
  40084. offline.dispatchPendingMessages();
  40085. saveSnapshot (ui, prefix + "-rack190io-steps.png");
  40086. offline.undo(); // (one undo step: the project and its history as they were)
  40087. offline.setChannelSelection (keptSelection, keptPrimary);
  40088. offline.dispatchPendingMessages();
  40089. }
  40090. {
  40091. // a pattern with piano-roll notes: those rows show a miniature instead of steps (round 90)
  40092. int found = -1;
  40093. const auto before = offline.getSong().currentPattern;
  40094. {
  40095. const auto& song = offline.getSong();
  40096. for (int p = 0; p < (int) song.patterns.size() && found < 0; ++p)
  40097. for (int c = 0; c < (int) song.channels.size() && found < 0; ++c)
  40098. if (lynx::showsNotePreview (song.patterns[(std::size_t) p], c))
  40099. found = p;
  40100. }
  40101. if (found >= 0)
  40102. {
  40103. offline.editSong ([found] (lynx::Song& s) { s.currentPattern = found; }, false);
  40104. offline.dispatchPendingMessages();
  40105. saveSnapshot (ui, prefix + "-rack-preview.png");
  40106. offline.editSong ([before] (lynx::Song& s) { s.currentPattern = before; }, false);
  40107. offline.dispatchPendingMessages();
  40108. }
  40109. }
  40110. ui.selectTabForSnapshot (1);
  40111. saveSnapshot (ui, prefix + "-pianoroll.png");
  40112. {
  40113. // View › Keyboard style › Piano keys (round 190j, discussion #136), also with tall keys
  40114. auto& roll = ui.getPianoRollForSnapshot();
  40115. const auto keysBefore = lynx::PianoRollComponent::keyStyle; // (round 190oo: FL's keys are the default)
  40116. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::piano;
  40117. roll.repaint();
  40118. saveSnapshot (ui, prefix + "-pianoroll-pianokeys.png");
  40119. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::flat;
  40120. roll.repaint();
  40121. saveSnapshot (ui, prefix + "-pianoroll-flatkeys.png");
  40122. lynx::PianoRollComponent::keyStyle = keysBefore;
  40123. roll.repaint();
  40124. // round 190j (discussion #10): the toolbar in a narrow window: the chord stamp as an icon button, and
  40125. // the menu button still there
  40126. for (int narrower : { 150, 270, 330 })
  40127. {
  40128. roll.squeezeToolbarForSnapshot (narrower);
  40129. saveSnapshot (ui, prefix + "-pianoroll-narrow" + juce::String (narrower) + ".png");
  40130. roll.squeezeToolbarForSnapshot (-narrower);
  40131. }
  40132. }
  40133. if (const auto strip = ui.getToolStripAreaForSnapshot (false); ! strip.isEmpty())
  40134. saveArea (ui, strip, prefix + "-pianoroll-tools.png");
  40135. // the editors' mouse feel: the hovered note / clip edge (grip, outline) and its hint in the hint bar
  40136. ui.setHintForSnapshot (ui.getPianoRollForSnapshot().hoverForSnapshot());
  40137. saveSnapshot (ui, prefix + "-pianoroll-hover.png");
  40138. {
  40139. // a pattern with note Chance or a Velocity Range (round 187c): the Piano roll with those lanes
  40140. const auto& song = offline.getSong();
  40141. const auto& notes = song.patterns[(std::size_t) std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1)].notes;
  40142. if (std::any_of (notes.begin(), notes.end(), [] (const lynx::Note& n) { return n.hasChance(); }))
  40143. {
  40144. auto& roll = ui.getPianoRollForSnapshot();
  40145. ui.setHintForSnapshot ({});
  40146. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneChance, "chance" },
  40147. { lynx::PianoRollComponent::laneVelocityRange, "velrange" },
  40148. { lynx::PianoRollComponent::laneVelocity, "velocity" } })
  40149. {
  40150. roll.setLaneForSnapshot (lane);
  40151. offline.dispatchPendingMessages();
  40152. saveSnapshot (ui, prefix + "-pianoroll-" + name + ".png");
  40153. }
  40154. }
  40155. }
  40156. ui.selectTabForSnapshot (2);
  40157. saveSnapshot (ui, prefix + "-playlist.png");
  40158. {
  40159. // round 190nr: the same with the song zoomed to fit (the site's and the Store's Playlist picture: at FL's
  40160. // open zoom the demo song fills only the first fifth)
  40161. auto& pl = ui.getPlaylistForSnapshot();
  40162. const auto view = pl.viewForSnapshot();
  40163. pl.zoomAllForSnapshot();
  40164. saveSnapshot (ui, prefix + "-playlist-fit.png");
  40165. pl.restoreViewForSnapshot (view);
  40166. }
  40167. if (const auto strip = ui.getToolStripAreaForSnapshot (true); ! strip.isEmpty())
  40168. saveArea (ui, strip, prefix + "-playlist-tools.png");
  40169. ui.setHintForSnapshot (ui.getPlaylistForSnapshot().hoverForSnapshot());
  40170. saveSnapshot (ui, prefix + "-playlist-hover.png");
  40171. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  40172. // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
  40173. ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
  40174. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
  40175. offline.dispatchPendingMessages();
  40176. saveSnapshot (ui, prefix + "-playlist-timesel.png");
  40177. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
  40178. // round 177b: automation lanes on (two lanes under track 2: a volume ramp and a pan wobble)
  40179. {
  40180. const auto before = offline.getSong();
  40181. offline.editSong ([] (lynx::Song& s) {
  40182. s.loopStart = s.loopEnd = 0; // (no time selection in this one)
  40183. const auto bar = s.barTicks();
  40184. const auto vol = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Insert 1 - Volume", 0.3f);
  40185. s.automations[(std::size_t) vol].points = { { 0, 0.3f, 0.0f }, { bar * 2, 0.8f, 0.4f }, { bar * 4, 0.6f, 0.0f } };
  40186. const auto pan = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, "Insert 1 - Pan", 0.5f);
  40187. 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 } };
  40188. }, false);
  40189. lynx::autolanes::setShown (true);
  40190. ui.getPlaylistForSnapshot().resized();
  40191. offline.dispatchPendingMessages();
  40192. saveSnapshot (ui, prefix + "-playlist-lanes.png");
  40193. lynx::autolanes::setShown (false);
  40194. offline.editSong ([before] (lynx::Song& s) { s = before; }, false);
  40195. offline.dispatchPendingMessages();
  40196. }
  40197. // round 104: a folded track group (FL's thin member rows) and the Picker's audio tab
  40198. {
  40199. int header = -1;
  40200. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && header < 0; ++t)
  40201. if (lynx::noteedit::isGroupHeader (offline.getSong(), t))
  40202. header = t;
  40203. if (header >= 0)
  40204. {
  40205. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, true); }, false);
  40206. offline.dispatchPendingMessages();
  40207. saveSnapshot (ui, prefix + "-playlist-group-folded.png");
  40208. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, false); }, false);
  40209. }
  40210. ui.getPickerForSnapshot().setView (1);
  40211. offline.dispatchPendingMessages();
  40212. saveSnapshot (ui, prefix + "-playlist-picker-audio.png");
  40213. ui.getPickerForSnapshot().setView (0);
  40214. }
  40215. // round 104: the Channel Rack filtered to its first filter group
  40216. if (! offline.getSong().channelGroups.empty())
  40217. {
  40218. ui.selectTabForSnapshot (0);
  40219. ui.getRackForSnapshot().setFilterGroup (0);
  40220. offline.dispatchPendingMessages();
  40221. saveSnapshot (ui, prefix + "-rack-filter.png");
  40222. ui.getRackForSnapshot().setFilterGroup (-1);
  40223. }
  40224. ui.selectTabForSnapshot (3);
  40225. // LYNX_SNAPSHOT_ARRANGE=1 (round 186c): Mixer menu › "Arrange inserts like the Playlist" first
  40226. if (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_ARRANGE", {}) == "1")
  40227. {
  40228. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::arrangeLikePlaylist (s); });
  40229. offline.dispatchPendingMessages();
  40230. }
  40231. // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
  40232. if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
  40233. {
  40234. ui.selectMixerTrackForSnapshot (track.getIntValue(),
  40235. juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
  40236. offline.dispatchPendingMessages();
  40237. }
  40238. saveSnapshot (ui, prefix + "-mixer.png");
  40239. // round 190ir (Discord report, "it isnt picking up my audio input"): an armed insert without an input says so
  40240. // in its input box (record colour)
  40241. // (the first insert no channel plays into: armed without an input, it records silence)
  40242. {
  40243. const auto& song = offline.getSong();
  40244. auto target = -1;
  40245. for (int t = 1; t < (int) song.mixer.size() && target < 0; ++t)
  40246. if (song.mixer[(std::size_t) t].inputChannel < 0
  40247. && std::none_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  40248. target = t;
  40249. if (target > 0)
  40250. {
  40251. offline.setInsertArmed (target, true);
  40252. ui.selectMixerTrackForSnapshot (target, -1);
  40253. offline.dispatchPendingMessages();
  40254. saveSnapshot (ui, prefix + "-mixer190ir-armed-noinput.png");
  40255. offline.setInsertArmed (target, false);
  40256. offline.dispatchPendingMessages();
  40257. }
  40258. }
  40259. // round 190am: LYNX's two mixer extras, before and after (the demo project leaves most inserts unused). The
  40260. // loudness panel shows a real measurement of 12 s of a test tone (a 1 kHz sine at -14 dBFS after a quieter
  40261. // stretch, pushed through the Master's tap as the audio thread does)
  40262. {
  40263. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  40264. saveSnapshot (ui, prefix + "-mixer190am-before.png");
  40265. strips.setShowUsedOnly (true);
  40266. offline.dispatchPendingMessages();
  40267. saveSnapshot (ui, prefix + "-mixer190am-usedonly.png");
  40268. strips.setShowUsedOnly (false);
  40269. strips.setShowLoudness (true);
  40270. {
  40271. const double sr = 48000.0;
  40272. std::vector<float> tone (480);
  40273. auto& tap = offline.getMeters().loudness;
  40274. for (int block = 0; block < 1200; ++block)
  40275. {
  40276. const auto gain = std::pow (10.0, (block < 400 ? -20.0 : -14.0) / 20.0);
  40277. for (int i = 0; i < 480; ++i)
  40278. tone[(std::size_t) i] = (float) (gain * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * (block * 480 + i) / sr));
  40279. tap.push (tone.data(), tone.data(), 480, sr);
  40280. }
  40281. }
  40282. strips.refreshLoudnessForSnapshot();
  40283. offline.dispatchPendingMessages();
  40284. saveSnapshot (ui, prefix + "-mixer190am-loudness.png");
  40285. for (const auto l : { lynx::mixerlayout::Layout::compact, lynx::mixerlayout::Layout::extraLarge })
  40286. {
  40287. const auto was = lynx::MixerStrips::layout;
  40288. strips.setLayout (l);
  40289. offline.dispatchPendingMessages();
  40290. saveSnapshot (ui, prefix + "-mixer190am-loudness-" + juce::String ((int) l) + ".png");
  40291. strips.setLayout (was);
  40292. }
  40293. strips.setShowUsedOnly (true);
  40294. offline.dispatchPendingMessages();
  40295. saveSnapshot (ui, prefix + "-mixer190am-both.png");
  40296. strips.setShowUsedOnly (false);
  40297. strips.setShowLoudness (false);
  40298. offline.dispatchPendingMessages();
  40299. }
  40300. // round 168h (issue #52): FL's 8 Mixer layouts
  40301. {
  40302. const auto before = lynx::MixerStrips::layout;
  40303. for (int l = 0; l < lynx::mixerlayout::layoutCount; ++l)
  40304. {
  40305. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout ((lynx::mixerlayout::Layout) l);
  40306. offline.dispatchPendingMessages();
  40307. saveSnapshot (ui, prefix + "-mixer168h-" + juce::String (l) + ".png");
  40308. }
  40309. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout (before);
  40310. offline.dispatchPendingMessages();
  40311. }
  40312. // round 163: the Mixer at short heights (UI zoom 150%+): the EQ folds, then the effects panel scrolls
  40313. {
  40314. const auto size = ui.getBounds();
  40315. for (auto h : { 450, 560, 680, 820 })
  40316. {
  40317. ui.setSize (size.getWidth(), h);
  40318. offline.dispatchPendingMessages();
  40319. saveSnapshot (ui, prefix + "-mixer163-" + juce::String (h) + ".png");
  40320. }
  40321. ui.setBounds (size);
  40322. offline.dispatchPendingMessages();
  40323. }
  40324. // round 170b (Busy Works Beats' review): inserts 1-3 selected and routed together to insert 4, a single effect
  40325. // moved down into slot 2 (FL's slot places), and the plugin menus grouped by category, LYNX SHARE first
  40326. {
  40327. const auto before = offline.getSong();
  40328. offline.editSong ([] (lynx::Song& s) {
  40329. if (s.mixer.size() < 5)
  40330. return;
  40331. s.mixer[1].effects.clear();
  40332. lynx::EffectSlot fx;
  40333. fx.kind = lynx::EffectKind::compressor;
  40334. s.mixer[1].effects.push_back (fx);
  40335. lynx::mixerops::moveEffectBy (s, 1, 0, 1);
  40336. lynx::mixerops::switchSelectedRoute (s, { 1, 2, 3 }, 4, true);
  40337. });
  40338. ui.selectMixerTrackForSnapshot (1);
  40339. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 1);
  40340. offline.dispatchPendingMessages();
  40341. saveSnapshot (ui, prefix + "-mixer170b.png");
  40342. juce::PopupMenu effects, generators;
  40343. lynx::quickpick::addFolderGroups (effects, offline, std::function<void (lynx::EffectSlot)> ([] (lynx::EffectSlot) {}));
  40344. lynx::quickpick::addFolderViewItems (effects, offline);
  40345. lynx::quickpick::addGeneratorMenu (generators, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  40346. lynx::quickpick::addFolderViewItems (generators, offline);
  40347. saveMenus (juce::StringArray { "Mixer slot: add an effect", "Channel Rack: add" }, { effects, generators }, prefix + "-menus170b.png");
  40348. // round 190bf (fl190be Q3): the Channel Rack's "+" menu in FL's three views, with two root entries (plugins
  40349. // at the top of the database, in no folder) and the Categories / Simple / Tree switch at the end
  40350. {
  40351. auto& host = offline.getPluginHost();
  40352. const auto keep = host.databaseFolders();
  40353. auto folders = keep;
  40354. int added = 0;
  40355. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  40356. if (e.folder == 3 && e.available && added < 2) // (installed plugins: FL's root entries are such)
  40357. {
  40358. folders.top.insert (e.key);
  40359. ++added;
  40360. }
  40361. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  40362. if (e.folder != 3 && added < 2)
  40363. {
  40364. folders.top.insert (e.key);
  40365. ++added;
  40366. }
  40367. static const char* const views[] { "categories", "simple", "tree" };
  40368. for (int v = 0; v < 3; ++v)
  40369. {
  40370. folders.view = v;
  40371. host.setDatabaseFolders (folders);
  40372. juce::PopupMenu plus;
  40373. lynx::quickpick::addGeneratorMenu (plus, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  40374. lynx::quickpick::addFolderViewItems (plus, offline);
  40375. saveMenus (juce::StringArray { juce::String ("Channel Rack +: ") + views[v] }, { plus }, prefix + "-menus190bf-" + views[v] + ".png");
  40376. }
  40377. host.setDatabaseFolders (keep);
  40378. }
  40379. offline.setSong (before);
  40380. offline.dispatchPendingMessages();
  40381. }
  40382. // standalone windows, with the theme background
  40383. auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  40384. juce::Component frame;
  40385. frame.setSize (c->getWidth(), c->getHeight());
  40386. frame.setOpaque (true);
  40387. // an AlertWindow is built on the desktop: shown there first, it would take the foreground from whoever has it
  40388. // (TopLevelWindow::visibilityChanged calls toFront (true)). Off the desktop, its control that showing it would
  40389. // have focused (what grabKeyboardFocus picks) is marked, so the picture keeps that control's focus ring
  40390. if (c->isOnDesktop())
  40391. {
  40392. c->removeFromDesktop();
  40393. auto* focus = c.get();
  40394. for (int depth = 0; focus != nullptr && depth < 32; ++depth)
  40395. {
  40396. if (focus->getWantsKeyboardFocus() && (focus->isEnabled() || focus == c.get()))
  40397. {
  40398. focus->getProperties().set ("lynxSnapshotFocus", true);
  40399. break;
  40400. }
  40401. auto traverser = focus->createKeyboardFocusTraverser();
  40402. focus = traverser != nullptr ? traverser->getDefaultComponent (focus) : nullptr;
  40403. }
  40404. }
  40405. frame.addAndMakeVisible (*c);
  40406. c->setTopLeftPosition (0, 0);
  40407. checkTextFit (*c, name.fromFirstOccurrenceOf ("-", false, false).upToLastOccurrenceOf (".", false, false));
  40408. auto image = lynx::shot::paint (frame, lynx::theme::panel);
  40409. const auto file = lynx::shot::file (juce::File (prefix + name));
  40410. file.deleteFile();
  40411. juce::PNGImageFormat png;
  40412. if (auto out = file.createOutputStream())
  40413. png.writeImageToStream (image, *out);
  40414. };
  40415. saveWindow (lynx::makeExportPanel (offline), "-export.png");
  40416. saveWindow (lynx::makeExportPanel (offline, 1), "-export-mp3.png");
  40417. saveWindow (lynx::makeExportPanel (offline, 3), "-export-flac-stems.png");
  40418. saveWindow (lynx::makeExportPanel (offline, 4), "-export-aiff.png"); // owner decision D5
  40419. if (lynx::aac::available())
  40420. saveWindow (lynx::makeExportPanel (offline, 5), "-export-m4a.png");
  40421. {
  40422. // REA round 165f-mixer: the mixer track's Track latency / routing submenus, Disk recording, PDC, and the
  40423. // Export window for "Render selected tracks to wave file(s)"
  40424. const auto before = offline.getSong();
  40425. offline.editSong ([] (lynx::Song& s) {
  40426. if (s.mixer.size() > 3)
  40427. {
  40428. s.mixer[1].latencyMs = 5.0f;
  40429. s.mixer[1].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  40430. s.mixer[2].latencyMs = -1.5f;
  40431. }
  40432. });
  40433. offline.dispatchPendingMessages();
  40434. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  40435. strips.setSelection ({ 1, 2, 3 }, 1);
  40436. const auto menu = strips.buildMenu (1);
  40437. juce::StringArray names { "Mixer track" };
  40438. std::vector<juce::PopupMenu> menus { menu };
  40439. const auto latencyPrefix = lynx::tr ("Track latency: {0}", { juce::String() });
  40440. const juce::String wanted[] = { lynx::tr ("Selected tracks ⇄ this track"), lynx::tr ("Disk recording"),
  40441. lynx::tr ("Plugin delay compensation") };
  40442. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  40443. {
  40444. const auto& item = it.getItem();
  40445. if (item.subMenu != nullptr && (item.text.startsWith (latencyPrefix) || std::find (std::begin (wanted), std::end (wanted), item.text) != std::end (wanted)))
  40446. {
  40447. names.add (item.text.upToFirstOccurrenceOf (":", false, false));
  40448. menus.push_back (*item.subMenu);
  40449. }
  40450. }
  40451. saveMenus (names, menus, prefix + "-menus165-mixer.png");
  40452. saveWindow (lynx::makeExportPanelForTracks (offline, { 1, 2, 3 }), "-export165-tracks.png");
  40453. offline.setSong (before);
  40454. offline.dispatchPendingMessages();
  40455. }
  40456. saveSplashFrames (prefix);
  40457. saveIconSheet (prefix + "-icons.png", 1.0f);
  40458. saveIconSheet (prefix + "-icons-150.png", 1.5f);
  40459. saveStateSheet (prefix + "-states190je.png", 1.0f); // round 190je: the one state rule, per button kind
  40460. saveStateSheet (prefix + "-states190je-z3.png", 3.0f);
  40461. saveWindow (lynx::MainComponent::makeHelpContent (nullptr, [] {}), "-help.png"); // (round 190ns: with its Manage shortcuts link)
  40462. saveWindow (lynx::ui::makeTrackIconGrid (5, {}), "-trackicons168h.png"); // round 168h: the icon picker
  40463. saveWindow (std::make_unique<lynx::toolbar::CustomizePanel> (lynx::toolbarlayout::Layout::makeDefault()), "-customize-toolbar.png");
  40464. // two moved controls: Tools › Last tweaked and Add › Automation for last tweaked parameter show them (REA round 143)
  40465. offline.noteTweaked ({ lynx::AutomationTargetKind::channelVolume, 0 });
  40466. offline.noteTweaked ({ lynx::AutomationTargetKind::mixerVolume, 0 });
  40467. saveMenus (ui, prefix + "-menus.png");
  40468. {
  40469. // the windows' own menus (title bars) and the toolbar's recording menu
  40470. juce::StringArray names;
  40471. std::vector<juce::PopupMenu> menus;
  40472. for (auto [panel, name] : { std::pair { lynx::workspace::Panel::playlist, "Playlist" }, { lynx::workspace::Panel::channelRack, "Channel rack" },
  40473. { lynx::workspace::Panel::pianoRoll, "Piano roll" }, { lynx::workspace::Panel::mixer, "Mixer" },
  40474. { lynx::workspace::Panel::browser, "Browser" } })
  40475. {
  40476. names.add (name);
  40477. menus.push_back (ui.getPanelMenuForSnapshot (panel));
  40478. }
  40479. names.add ("Recording");
  40480. menus.push_back (ui.getRecordMenuForSnapshot());
  40481. names.add ("Toolbar");
  40482. menus.push_back (ui.getToolbarMenuForSnapshot());
  40483. saveMenus (names, menus, prefix + "-panel-menus.png");
  40484. }
  40485. // round 189e: the Playlist menu's Edit and Select submenus (FL's items and order) and the header drop question
  40486. saveMenus (juce::StringArray { "Playlist: Edit", "Playlist: Select" },
  40487. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().editMenu(), ui.getPlaylistForSnapshot().selectMenu() },
  40488. prefix + "-playlist-edit189e.png");
  40489. saveWindow (lynx::PlaylistComponent::makeHeaderDropDialog(), "-header-drop189e.png");
  40490. {
  40491. // round 189i: FL's fade handle menu (right-click on an audio clip's fade handle), on the song's first audio
  40492. // clip, or on one added for the shot
  40493. const auto before = offline.getSong();
  40494. auto clipIndex = -1;
  40495. for (std::size_t i = 0; i < before.playlist.size() && clipIndex < 0; ++i)
  40496. if (before.playlist[i].kind == lynx::ClipKind::audio)
  40497. clipIndex = (int) i;
  40498. if (clipIndex < 0)
  40499. {
  40500. auto song = before;
  40501. lynx::ChannelDef channel;
  40502. channel.instrument = lynx::InstrumentKind::audioClip;
  40503. channel.name = "Audio clip";
  40504. song.channels.push_back (channel);
  40505. lynx::Clip clip;
  40506. clip.kind = lynx::ClipKind::audio;
  40507. clip.channel = (int) song.channels.size() - 1;
  40508. clip.length = lynx::ppq * 4;
  40509. song.playlist.push_back (clip);
  40510. clipIndex = (int) song.playlist.size() - 1;
  40511. offline.setSong (song);
  40512. offline.dispatchPendingMessages();
  40513. }
  40514. saveMenus (juce::StringArray { "Fade handle" },
  40515. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().fadeHandleMenu (clipIndex, 1) },
  40516. prefix + "-fade-handle189i.png");
  40517. if (offline.getSong().playlist.size() != before.playlist.size())
  40518. {
  40519. offline.setSong (before);
  40520. offline.dispatchPendingMessages();
  40521. }
  40522. }
  40523. {
  40524. // round 189n: FL's gain handle menu with two overlapping clips selected (Normalize selection individually / as a
  40525. // group) and the later clip's fade in menu (Create crossfade enabled); FL shots in /mnt/e/lynx-work/flgap189n
  40526. const auto before = offline.getSong();
  40527. auto song = before;
  40528. lynx::ChannelDef channel;
  40529. channel.instrument = lynx::InstrumentKind::audioClip;
  40530. channel.name = "Audio clip";
  40531. song.channels.push_back (channel);
  40532. int lane = 0;
  40533. for (const auto& c : song.playlist)
  40534. lane = std::max (lane, c.track + 1);
  40535. for (int k = 0; k < 2; ++k)
  40536. {
  40537. lynx::Clip clip;
  40538. clip.kind = lynx::ClipKind::audio;
  40539. clip.channel = (int) song.channels.size() - 1;
  40540. clip.track = lane;
  40541. clip.start = k * lynx::ppq * 3;
  40542. clip.length = lynx::ppq * 4;
  40543. song.playlist.push_back (clip);
  40544. }
  40545. const auto second = (int) song.playlist.size() - 1;
  40546. song.autoCrossfades = true; // FL's capture: Thief has Automatic crossfades on
  40547. offline.setSong (song);
  40548. offline.dispatchPendingMessages();
  40549. auto& playlist = ui.getPlaylistForSnapshot();
  40550. playlist.selectForSnapshot ({ second - 1, second });
  40551. auto gain = playlist.gainMenu (second);
  40552. auto fadeIn = playlist.fadeHandleMenu (second, 0); // (both selected, as in FL's capture)
  40553. playlist.selectForSnapshot ({});
  40554. saveMenus (juce::StringArray { "Gain handle, 2 selected", "Fade in, overlapping" },
  40555. std::vector<juce::PopupMenu> { gain, fadeIn }, prefix + "-fade-gain189n.png");
  40556. // round 189o: the audio clip menu with both overlapping clips selected (FL's Fades › Crossfade selected
  40557. // shown) and with none selected (hidden)
  40558. playlist.selectForSnapshot ({ second - 1, second });
  40559. auto clipSelected = playlist.getClipMenuForSnapshot (second);
  40560. playlist.selectForSnapshot ({});
  40561. auto clipAlone = playlist.getClipMenuForSnapshot (second);
  40562. saveMenus (juce::StringArray { "Audio clip, 2 selected", "Audio clip, none selected" },
  40563. std::vector<juce::PopupMenu> { clipSelected, clipAlone }, prefix + "-xfadesel189o.png");
  40564. offline.setSong (before);
  40565. offline.dispatchPendingMessages();
  40566. }
  40567. {
  40568. // REA round 143: the piano roll Tools menu, a Playlist track menu and a mixer insert menu (FL's layouts)
  40569. std::vector<juce::PopupMenu> menus { ui.getPianoRollForSnapshot().getToolsMenuForSnapshot(),
  40570. ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (0),
  40571. ui.getMixerForSnapshot().getStripsForSnapshot().buildMenu (1) };
  40572. saveMenus (juce::StringArray { "Piano roll tools", "Playlist track", "Mixer track" }, menus, prefix + "-menus143.png");
  40573. // round 190as: the Piano roll's scripts (FL's Tools › Scripts column) and a script's form
  40574. saveMenus (juce::StringArray { "Piano roll scripts" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getScriptsMenuForSnapshot() },
  40575. prefix + "-prscripts-menu.png");
  40576. {
  40577. lynx::prscript::Score score;
  40578. const auto out = lynx::prscript::run (lynx::prscript::builtins().front().source, score, {});
  40579. if (out.status == lynx::prscript::Outcome::Status::needsForm)
  40580. {
  40581. lynx::ScriptPanel::Options options;
  40582. options.acceptText = lynx::tr ("Accept");
  40583. saveWindow (std::make_unique<lynx::ScriptPanel> (out.form, [] (const lynx::scriptform::Form&) {}, [] (const lynx::scriptform::Form&) {},
  40584. nullptr, options),
  40585. "-prscript-form.png");
  40586. }
  40587. }
  40588. // round 190j (discussion #10): the Piano roll menu's Chord stamp list
  40589. saveMenus (juce::StringArray { "Chord stamp" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getStampMenuForSnapshot() },
  40590. prefix + "-stamp-menu.png");
  40591. // round 167l: the channel menu ("Lock active/mute state")
  40592. if (! offline.getSong().channels.empty())
  40593. saveMenus (juce::StringArray { "Channel" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (0) }, prefix + "-channel-menu.png");
  40594. // round 163: menu density, compact (default) and comfortable, on a Browser folder menu
  40595. {
  40596. juce::PopupMenu folder;
  40597. folder.addSectionHeader ("Documents");
  40598. folder.addItem (1, "Expand all");
  40599. folder.addItem (2, "Collapse all");
  40600. folder.addSeparator();
  40601. folder.addItem (3, "Refresh");
  40602. folder.addSectionHeader ("System");
  40603. folder.addItem (4, "Open");
  40604. folder.addItem (5, "Copy the file path");
  40605. folder.addSectionHeader ("Tags");
  40606. folder.addItem (6, "Starred", true, true);
  40607. folder.addSeparator();
  40608. folder.addItem (7, "Add folder...");
  40609. const auto wasCompact = lynx::theme::menus::compact();
  40610. lynx::theme::menus::setCompact (true);
  40611. saveMenus (juce::StringArray { "Compact" }, { folder }, prefix + "-menu163-compact.png");
  40612. lynx::theme::menus::setCompact (false);
  40613. saveMenus (juce::StringArray { "Comfortable" }, { folder }, prefix + "-menu163-comfortable.png");
  40614. lynx::theme::menus::setCompact (wasCompact);
  40615. }
  40616. // and the clip menus of the first pattern, audio and automation clips of the project
  40617. juce::StringArray clipNames;
  40618. std::vector<juce::PopupMenu> clipMenus;
  40619. for (auto [kind, name] : { std::pair { lynx::ClipKind::pattern, "Pattern clip" }, { lynx::ClipKind::audio, "Audio clip" },
  40620. { lynx::ClipKind::automation, "Automation clip" } })
  40621. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  40622. if (offline.getSong().playlist[(std::size_t) c].kind == kind)
  40623. {
  40624. clipNames.add (name);
  40625. clipMenus.push_back (ui.getPlaylistForSnapshot().getClipMenuForSnapshot (c));
  40626. break;
  40627. }
  40628. if (! clipMenus.empty())
  40629. saveMenus (clipNames, clipMenus, prefix + "-menus143-clips.png");
  40630. }
  40631. auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
  40632. alert->setOpaque (true);
  40633. saveWindow (std::move (alert), name);
  40634. };
  40635. saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
  40636. saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
  40637. saveAlert (lynx::support::makeSupportWindow(), "-support.png"); // round 190fq: Help › Support LYNX SHARE...
  40638. saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
  40639. saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
  40640. // round 190ah: Online Sessions — a guest's "go back in?" at start-up, the host's question at a guest's file limit
  40641. saveAlert (lynx::liveui::makeRejoinDialog ("Ana", juce::Time (2026, 10, 10, 21, 40).toString (true, true, false, true)), "-live-rejoin.png");
  40642. saveAlert (lynx::liveui::makeMediaLimitDialog ("Pedro", (juce::int64) 1010 << 20, (juce::int64) 1 << 30), "-live-media-limit.png");
  40643. saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
  40644. saveAlert (lynx::makeGradientColourDialog (juce::Colour (0xffe5383b), juce::Colour (0xff3a7bd5), 8), "-gradient.png"); // round 177a
  40645. saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
  40646. // round 186c: FL's mixer "Delete" questions and its Settings › General › Manage messages menu
  40647. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Delete tracks"), lynx::tr ("This will |delete| {0} selected mixer track(s). Are you sure?", { "1" }),
  40648. { lynx::tr ("Yes"), lynx::tr ("No") }, true }),
  40649. "-delete-tracks.png");
  40650. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Playlist tracks"),
  40651. lynx::tr ("One or more mixer tracks that will be deleted are connected to instrument/audio tracks.") + "\n"
  40652. + lynx::tr ("Do you want to unlink the tracks and channels or delete them?"),
  40653. { lynx::tr ("Delete tracks and channels"), lynx::tr ("Unlink tracks and channels"), lynx::tr ("Cancel") }, false }),
  40654. "-delete-tracks-linked.png");
  40655. saveMenus (juce::StringArray { "Manage messages" }, std::vector<juce::PopupMenu> { lynx::messages::manageMenu() }, prefix + "-manage-messages.png");
  40656. saveWindow (lynx::makeSetupWizardContent (offline, {}, {}), "-setup.png");
  40657. saveWindow (lynx::crashreporter::makeDialogForSnapshot (false), "-crash-report.png"); // round 159
  40658. saveWindow (lynx::crashreporter::makeDialogForSnapshot (true), "-report-problem.png");
  40659. // round 166b: the update bar in its states (available, downloading, failed, ready) and the release notes window
  40660. {
  40661. struct Bars final : juce::Component
  40662. {
  40663. Bars()
  40664. {
  40665. constexpr int h = lynx::updater::UpdateBar::height;
  40666. setSize (1100, 7 * (h + 6));
  40667. for (int state = 0; state < 7; ++state) // (round 190gh: 4 going back, 5 went back; round 190sr: 6 AppImage updated)
  40668. {
  40669. bars[state].setBounds (0, state * (h + 6), getWidth(), h);
  40670. bars[state].showForSnapshot (state);
  40671. addAndMakeVisible (bars[state]);
  40672. }
  40673. }
  40674. lynx::updater::UpdateBar bars[7];
  40675. };
  40676. saveWindow (std::make_unique<Bars>(), "-update-bar.png");
  40677. saveWindow (lynx::updater::makeReleaseNotesForSnapshot(), "-update-notes.png");
  40678. // round 190gh (B23): Help › Test audio output... in its states
  40679. for (int state = 0; state < 5; ++state)
  40680. saveWindow (lynx::makeAudioCheckForSnapshot (offline, state), "-audio-check-" + juce::String (state) + ".png");
  40681. }
  40682. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 0, 1), "-missing-files.png");
  40683. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 1), "-missing-plugins.png");
  40684. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 2), "-missing-found.png");
  40685. {
  40686. // the Settings pages, with credits like a project imported from FL would carry
  40687. offline.editSong ([] (lynx::Song& s) {
  40688. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  40689. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  40690. }, false);
  40691. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::project), "-settings-project.png");
  40692. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::info), "-settings-info.png");
  40693. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::files), "-settings-files.png");
  40694. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::general), "-settings-general.png");
  40695. {
  40696. // round 189o: the whole General page (the Editing and Plugins sections hold FL's "Monophonic painting in
  40697. // piano roll" and "Limit the number of open plugin editors")
  40698. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  40699. tall->setSize (tall->getWidth(), 3200);
  40700. saveWindow (std::move (tall), "-settings-general-tall189o.png");
  40701. }
  40702. {
  40703. // the whole General page (round 186a: the Startup section is below the first screen)
  40704. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  40705. tall->setSize (tall->getWidth(), 1500);
  40706. saveWindow (std::move (tall), "-settings-general-tall.png");
  40707. }
  40708. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
  40709. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::extras), "-settings-extras.png"); // round 190am
  40710. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
  40711. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
  40712. {
  40713. // round 190bj (QA): the MIDI page in a small window keeps each row's switch and device name
  40714. auto small = lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi);
  40715. small->setSize (390, 390);
  40716. saveWindow (std::move (small), "-settings-midi-small.png");
  40717. }
  40718. {
  40719. // round 190bj (QA): the Apex Limiter's window content at its default size, as sized before (JUCE's ratio
  40720. // on the whole window: the status row cut off) and now
  40721. lynx::AudioEngine apexEngine (false);
  40722. lynx::Song song;
  40723. song.mixer.resize (2);
  40724. song.mixer[0].name = "Master";
  40725. song.mixer[1].name = "Insert 1";
  40726. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::apexLimiter));
  40727. apexEngine.setSong (std::move (song));
  40728. apexEngine.dispatchPendingMessages();
  40729. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, true), prefix + "-apex-window-before190bj.png");
  40730. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, false), prefix + "-apex-window.png");
  40731. }
  40732. saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
  40733. // round 190gg: the crash prompt and a plugin window's crash notice, with "Always run ... in a separate process"
  40734. saveWindow (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "-plugin-crash-prompt.png");
  40735. saveWindow (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "-plugin-crash-notice.png");
  40736. saveWindow (lynx::makeShortcutManagerPanel (false), "-shortcuts.png");
  40737. }
  40738. {
  40739. // round 84: New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
  40740. saveWindow (lynx::makeNewProjectPanel(), "-new-project.png");
  40741. const auto& clips = offline.getSong().playlist;
  40742. for (int i = 0; i < (int) clips.size(); ++i)
  40743. if (clips[(std::size_t) i].kind == lynx::ClipKind::pattern)
  40744. {
  40745. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i, (i + 1) % (int) clips.size() }), "-clip-properties.png");
  40746. break;
  40747. }
  40748. for (int i = 0; i < (int) clips.size(); ++i)
  40749. if (clips[(std::size_t) i].kind == lynx::ClipKind::audio)
  40750. {
  40751. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i }), "-clip-properties-audio.png");
  40752. break;
  40753. }
  40754. if (offline.getSong().arrangements.size() < 2)
  40755. offline.editSong ([] (lynx::Song& s) {
  40756. const auto current = s.currentArrangement;
  40757. s.addArrangement ("Radio edit", true);
  40758. s.addArrangement ("Intro loop");
  40759. s.selectArrangement (current);
  40760. }, false);
  40761. saveWindow (lynx::makeArrangementsPanel (offline), "-arrangements.png");
  40762. saveWindow (lynx::makePluginMonitorPanel (offline), "-plugin-monitor.png");
  40763. saveWindow (lynx::makeTouchKeyboardPanel (offline), "-touch-keyboard.png");
  40764. }
  40765. {
  40766. // round 142: the Newtone / Newtime editors on a synthetic sung line (A3 B3 C4 · E4), one note moved
  40767. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-newtone.wav");
  40768. {
  40769. juce::AudioBuffer<float> line (1, 44100 * 2);
  40770. const double hz[] = { 220.0, 246.94, 261.63, 0.0, 329.63 };
  40771. double ph = 0.0;
  40772. for (int i = 0; i < line.getNumSamples(); ++i)
  40773. {
  40774. const auto f0 = hz[std::min (4, i / 17640)];
  40775. 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;
  40776. float v = 0.0f;
  40777. for (int h = 1; f0 > 0.0 && h < 8; ++h)
  40778. v += (float) (0.3 / h * std::sin (h * ph));
  40779. line.setSample (0, i, v);
  40780. }
  40781. wav.deleteFile();
  40782. juce::WavAudioFormat format;
  40783. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  40784. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0) : nullptr)
  40785. {
  40786. out.release();
  40787. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  40788. writer->writeFromAudioSampleBuffer (line, 0, line.getNumSamples());
  40789. }
  40790. }
  40791. if (const auto sample = offline.getSampleLibrary().load (wav.getFullPathName()))
  40792. {
  40793. auto notes = lynx::newtonefx::analyseNotes (*sample);
  40794. if (notes.pitches.size() > 1)
  40795. notes.pitches[1].shift = 2.0;
  40796. lynx::newtonefx::WarpMap warp;
  40797. warp.frames = (std::int64_t) sample->frames();
  40798. warp.markers = { { 22050, 33075 } };
  40799. int at = 0;
  40800. offline.editSong ([&] (lynx::Song& song) {
  40801. if (song.mixer.size() < 2)
  40802. song.mixer.resize (2);
  40803. auto& fx = song.mixer[1].effects;
  40804. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  40805. tone.samplePath = wav.getFullPathName().toStdString();
  40806. tone.state = lynx::newtonefx::writeNative (notes);
  40807. auto time = lynx::makeEffectSlot (lynx::EffectKind::newtime);
  40808. time.samplePath = tone.samplePath;
  40809. time.state = lynx::newtonefx::writeWarp (warp);
  40810. at = (int) fx.size();
  40811. fx.push_back (tone);
  40812. fx.push_back (time);
  40813. }, false);
  40814. saveWindow (lynx::makeNewtoneEditor (offline, 1, at), "-newtone.png");
  40815. saveWindow (lynx::makeNewtoneEditor (offline, 1, at + 1), "-newtime.png");
  40816. offline.editSong ([at] (lynx::Song& song) {
  40817. auto& fx = song.mixer[1].effects;
  40818. fx.erase (fx.begin() + at, fx.begin() + at + 2);
  40819. }, false);
  40820. }
  40821. }
  40822. if (! offline.getSong().automations.empty())
  40823. {
  40824. auto editor = lynx::makeAutomationEditor (offline, 0);
  40825. editor->setSize (760, 300);
  40826. saveWindow (std::move (editor), "-automation.png");
  40827. // round 177b: the same clip in FL's LFO mode: FL's defaults, then one shaped state (the UI gate pairs)
  40828. const auto before = offline.getSong().automations[0].lfo;
  40829. const auto lfoShot = [&offline, &saveWindow] (std::function<void (lynx::AutomationLfo&)> set, const char* suffix) {
  40830. offline.editSong ([&set] (lynx::Song& song) {
  40831. auto& lfo = song.automations[0].lfo;
  40832. lfo = lynx::AutomationLfo {};
  40833. lfo.on = true;
  40834. set (lfo);
  40835. }, false);
  40836. auto lfoEditor = lynx::makeAutomationEditor (offline, 0);
  40837. lfoEditor->setSize (760, 346);
  40838. saveWindow (std::move (lfoEditor), suffix);
  40839. };
  40840. lfoShot ([] (lynx::AutomationLfo&) {}, "-automation-lfo.png");
  40841. lfoShot ([] (lynx::AutomationLfo& lfo) {
  40842. // the state set through FL's own UI for the UI gate (TNS 50 %, SKEW 25 %, PW 25 %, two points), as FL saved it
  40843. lfo.tension = 64;
  40844. lfo.skew = 32;
  40845. lfo.pulseWidth = 28;
  40846. lfo.amp = { { 0, 0.6716f, 0.0f }, { (std::int64_t) (lynx::ppq * 1.4128), 0.9204f, 0.0f } };
  40847. }, "-automation-lfo-shape.png");
  40848. offline.editSong ([before] (lynx::Song& song) { song.automations[0].lfo = before; }, false);
  40849. }
  40850. // round 177b: LYNX's modulators window, with one routed modulator
  40851. {
  40852. offline.editSong ([] (lynx::Song& song) {
  40853. lynx::Modulator m;
  40854. m.name = "LFO 1";
  40855. m.shape = lynx::ModShape::triangle;
  40856. m.routes = { { { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0.25f }, { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  40857. song.modulators.push_back (m);
  40858. lynx::Modulator r;
  40859. r.name = "LFO 2";
  40860. r.shape = lynx::ModShape::smoothRandom;
  40861. r.sync = false;
  40862. r.hz = 0.5;
  40863. song.modulators.push_back (r);
  40864. }, false);
  40865. auto mods = lynx::makeModulatorsPanel (offline);
  40866. mods->setSize (900, 420); // (round 190ox: the stage 2 rows are wider)
  40867. saveWindow (std::move (mods), "-modulators.png");
  40868. offline.editSong ([] (lynx::Song& song) { song.modulators.clear(); }, false);
  40869. }
  40870. saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
  40871. // the channel window frame (REA round 143b): header strip + tabs; the Misc tab of the first channel and of a synth
  40872. saveWindow (lynx::makeChannelFrame (offline, 0), "-channel-frame.png");
  40873. saveWindow (lynx::makeChannelFrame (offline, 0, -1), "-channel-misc.png");
  40874. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  40875. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
  40876. {
  40877. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
  40878. saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
  40879. break;
  40880. }
  40881. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  40882. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
  40883. {
  40884. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
  40885. break;
  40886. }
  40887. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  40888. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  40889. if (offline.getSong().channels[(std::size_t) c].instrument == kind)
  40890. {
  40891. saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
  40892. break;
  40893. }
  40894. // round 180c: Fruity Slicer's editor
  40895. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  40896. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fruityslicer)
  40897. {
  40898. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fruityslicer.png");
  40899. // rounds 190f / 190m: its Envelope / instrument page, one picture per target
  40900. saveWindow (lynx::makeChannelFrame (offline, c, 1), "-fruityslicer-envelope.png");
  40901. for (const auto& [target, name] : std::vector<std::pair<int, const char*>> { { 0, "panning" }, { 2, "modx" }, { 3, "mody" }, { 4, "pitch" } })
  40902. {
  40903. auto frame = lynx::makeChannelFrame (offline, c, 1);
  40904. lynx::showFlVoiceTarget (*frame, target);
  40905. saveWindow (std::move (frame), juce::String ("-fruityslicer-envelope-") + name + ".png");
  40906. }
  40907. break;
  40908. }
  40909. // round 190r: Slicex's editor
  40910. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  40911. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  40912. {
  40913. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-slicex.png");
  40914. break;
  40915. }
  40916. // round 190q: FPC's editor
  40917. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  40918. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fpc)
  40919. {
  40920. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fpc.png");
  40921. break;
  40922. }
  40923. // round 190hz: DirectWave's editor
  40924. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  40925. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::directwave)
  40926. {
  40927. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-directwave.png");
  40928. break;
  40929. }
  40930. // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
  40931. {
  40932. int bestTrack = -1, bestSlot = -1;
  40933. double bestShape = -1.0;
  40934. const auto& mixer = offline.getSong().mixer;
  40935. for (int t = 0; t < (int) mixer.size(); ++t)
  40936. for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
  40937. if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
  40938. {
  40939. double shape = 0.0;
  40940. for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
  40941. shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
  40942. if (shape > bestShape)
  40943. {
  40944. bestShape = shape;
  40945. bestTrack = t;
  40946. bestSlot = s;
  40947. }
  40948. }
  40949. if (bestTrack >= 0)
  40950. saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
  40951. }
  40952. // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
  40953. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
  40954. saveWindow (std::move (inspector), "-noteinspector.png");
  40955. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
  40956. saveWindow (std::move (inspector), "-noteinspector-one.png");
  40957. // workflow P2: note tool dialogs (they preview on the pattern; each one puts the notes back when destroyed)
  40958. {
  40959. auto& roll = ui.getPianoRollForSnapshot();
  40960. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::strum, "-tool-strum.png" },
  40961. { lynx::NoteTool::arpeggiate, "-tool-arpeggiate.png" },
  40962. { lynx::NoteTool::flip, "-tool-flip.png" },
  40963. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  40964. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  40965. { lynx::NoteTool::limit, "-tool-limit.png" },
  40966. { lynx::NoteTool::quantize, "-tool-quantize.png" },
  40967. { lynx::NoteTool::chop, "-tool-chop.png" },
  40968. { lynx::NoteTool::flam, "-tool-flam.png" },
  40969. { lynx::NoteTool::lfo, "-tool-lfo.png" },
  40970. { lynx::NoteTool::claw, "-tool-claw.png" },
  40971. { lynx::NoteTool::articulate, "-tool-articulate.png" },
  40972. { lynx::NoteTool::riffMachine, "-tool-riff.png" },
  40973. { lynx::NoteTool::chordProgression, "-tool-chords.png" } };
  40974. for (const auto& [tool, name] : tools)
  40975. saveWindow (lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot()), name);
  40976. }
  40977. // round 83: the event editor, with sample events on the selected channel's volume (removed afterwards)
  40978. {
  40979. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::channelVolume, offline.getSelectedChannel() };
  40980. const auto before = offline.getSong().patterns[(std::size_t) offline.getSong().currentPattern].events;
  40981. offline.editSong ([&] (lynx::Song& s) {
  40982. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], volume);
  40983. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.2f, 0.9f, lynx::ticksPerStep);
  40984. lynx::prtools::LfoOptions lfo;
  40985. lfo.startSpeed = 7 * 4096; // one beat
  40986. lynx::eventedit::applyLfo (lane, lynx::ppq * 2, lynx::ppq * 4, lfo, lynx::ticksPerStep);
  40987. }, false);
  40988. saveWindow (lynx::makeEventEditor (offline, volume), "-eventeditor.png");
  40989. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  40990. // issue #86: the same editor on the Tempo target, with the project's own Tempo events (a sample ramp if none)
  40991. const lynx::AutomationTarget tempo { lynx::AutomationTargetKind::tempo, 0 };
  40992. offline.editSong ([&] (lynx::Song& s) {
  40993. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], tempo);
  40994. if (lane.events.empty())
  40995. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.05f, 0.11f, lynx::ticksPerStep);
  40996. }, false);
  40997. saveWindow (lynx::makeEventEditor (offline, tempo), "-eventeditor-tempo.png");
  40998. {
  40999. auto compact = lynx::makeEventEditor (offline, tempo); // the toolbar in a small window
  41000. compact->setSize (640, 300);
  41001. saveWindow (std::move (compact), "-eventeditor-tempo-small.png");
  41002. auto narrowest = lynx::makeEventEditor (offline, tempo); // the tool window's lower limit
  41003. narrowest->setSize (400, 300);
  41004. saveWindow (std::move (narrowest), "-eventeditor-tempo-narrowest.png");
  41005. }
  41006. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  41007. }
  41008. // round 86: the audio editor with a synthetic drum loop (markers, a region, a loop), waveform and spectrogram,
  41009. // and its menu items (-audioeditor-menu.txt)
  41010. {
  41011. namespace ae = lynx::audioedit;
  41012. ae::Document d;
  41013. d.title = "Drum loop";
  41014. d.audio.sampleRate = 44100.0;
  41015. const auto frames = (std::size_t) (44100 * 2);
  41016. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  41017. std::uint32_t seed = 7;
  41018. for (int hit = 0; hit < 8; ++hit)
  41019. {
  41020. const auto at = (std::size_t) hit * frames / 8;
  41021. const auto kick = hit % 2 == 0;
  41022. double phase = 0.0;
  41023. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  41024. {
  41025. seed = seed * 1664525u + 1013904223u;
  41026. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  41027. const auto t = (double) i / 44100.0;
  41028. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  41029. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  41030. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  41031. d.audio.channels[0][at + i] += v;
  41032. d.audio.channels[1][at + i] += kick ? v : v * 0.8f + 0.1f * noise * (float) std::exp (-t * 30.0);
  41033. }
  41034. }
  41035. ae::addMarker (d, (std::int64_t) frames / 8, "Snare");
  41036. ae::addRegion (d, { (std::int64_t) frames / 2, (std::int64_t) frames * 3 / 4 }, "Fill");
  41037. ae::setLoop (d, { 0, (std::int64_t) frames });
  41038. auto wave = lynx::makeAudioEditorForSnapshot (offline, d, false);
  41039. juce::File (prefix + "-audioeditor-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*wave).joinIntoString ("\n") + "\n");
  41040. saveWindow (std::move (wave), "-audioeditor.png");
  41041. saveWindow (lynx::makeAudioEditorForSnapshot (offline, d, true), "-audioeditor-spectrum.png");
  41042. }
  41043. // warp markers (round 175a, M3): the audio editor of the first audio clip whose channel has warp markers,
  41044. // opened as the Playlist opens it, with its warp lane
  41045. {
  41046. const auto& song = offline.getSong();
  41047. for (int i = 0; i < (int) song.playlist.size(); ++i)
  41048. {
  41049. const auto& c = song.playlist[(std::size_t) i];
  41050. if (c.kind == lynx::ClipKind::audio && juce::isPositiveAndBelow (c.channel, (int) song.channels.size())
  41051. && song.channels[(std::size_t) c.channel].sampler.warp.size() >= 3)
  41052. {
  41053. if (auto panel = lynx::makeAudioEditorPanel (offline, c.channel, i, true))
  41054. saveWindow (std::move (panel), "-audioeditor-warp.png");
  41055. break;
  41056. }
  41057. }
  41058. }
  41059. // the tempo tapper after five steady taps (round 132)
  41060. saveWindow (lynx::makeTempoTapperForSnapshot (offline, 5, 128.0), "-tempotapper.png");
  41061. // the Channel Rack's piano-roll view (round 132)
  41062. ui.selectTabForSnapshot (0);
  41063. ui.getRackForSnapshot().setPianoRollView (true);
  41064. offline.dispatchPendingMessages();
  41065. saveSnapshot (ui, prefix + "-rack-pianoroll-view.png");
  41066. ui.getRackForSnapshot().setPianoRollView (false);
  41067. // the Channel Rack with the step graph lane (velocity), and the Euclidean fill window
  41068. ui.selectTabForSnapshot (0);
  41069. ui.getRackForSnapshot().setGraphLevelForSnapshot (0);
  41070. offline.dispatchPendingMessages();
  41071. saveSnapshot (ui, prefix + "-rack-graph.png");
  41072. ui.getRackForSnapshot().setGraphLevelForSnapshot (1);
  41073. saveSnapshot (ui, prefix + "-rack-graph-pan.png");
  41074. // FL's Note pitch, Shift and Repeat lanes (issue #208)
  41075. ui.getRackForSnapshot().setGraphLevelForSnapshot ((int) lynx::notetools::Level::notePitch);
  41076. saveSnapshot (ui, prefix + "-rack-graph-pitch.png");
  41077. ui.getRackForSnapshot().setGraphLevelForSnapshot ((int) lynx::notetools::Level::shift);
  41078. saveSnapshot (ui, prefix + "-rack-graph-shift.png");
  41079. ui.getRackForSnapshot().setGraphLevelForSnapshot ((int) lynx::notetools::Level::repeat);
  41080. saveSnapshot (ui, prefix + "-rack-graph-repeat.png");
  41081. ui.getRackForSnapshot().toggleGraphLanes();
  41082. saveWindow (ui.getRackForSnapshot().makeEuclideanPanel (0), "-euclidean.png");
  41083. // the Mixer with three inserts selected and one armed for recording
  41084. ui.selectTabForSnapshot (3);
  41085. if (offline.getSong().mixer.size() > 4)
  41086. {
  41087. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 2);
  41088. offline.setInsertArmed (3, true);
  41089. offline.dispatchPendingMessages();
  41090. saveSnapshot (ui, prefix + "-mixer-multi.png");
  41091. // the armed insert with an audio input (its input row in the side panel, the level bar on the strip)
  41092. offline.editSong ([] (lynx::Song& s) { s.mixer[3].inputChannel = 0; });
  41093. ui.getMixerForSnapshot().selectTrack (3);
  41094. offline.dispatchPendingMessages();
  41095. saveSnapshot (ui, prefix + "-mixer-input.png");
  41096. offline.undo();
  41097. offline.setInsertArmed (3, false);
  41098. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({}, 0);
  41099. }
  41100. // the Mixer's routing lane: an insert with sends selected (send knobs and wires)
  41101. if (offline.getSong().mixer.size() > 6)
  41102. {
  41103. int source = -1;
  41104. for (int t = 1; t < (int) offline.getSong().mixer.size() && source < 0; ++t)
  41105. if (! offline.getSong().mixer[(std::size_t) t].sends.empty())
  41106. source = t;
  41107. const auto temporary = source < 0;
  41108. if (temporary) // the demo has no sends: add two for the picture
  41109. {
  41110. source = 1;
  41111. 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); });
  41112. }
  41113. ui.getMixerForSnapshot().selectTrack (source);
  41114. offline.dispatchPendingMessages();
  41115. saveSnapshot (ui, prefix + "-mixer-sends.png");
  41116. if (temporary)
  41117. offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, false); s.setRoute (1, 6, false); s.setRoute (4, 1, false); });
  41118. ui.getMixerForSnapshot().selectTrack (0);
  41119. }
  41120. // round 190io (issue #154 part 2): the Mixer view that lists each strip's insert effects (a LYNX view, off by
  41121. // default), with an insert selected whose sends light the route arrows
  41122. {
  41123. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  41124. strips.setShowStripInserts (true);
  41125. offline.dispatchPendingMessages();
  41126. saveSnapshot (ui, prefix + "-mixer190io-inserts.png");
  41127. strips.setShowStripInserts (false);
  41128. offline.dispatchPendingMessages();
  41129. }
  41130. // the Playlist with ripple editing on
  41131. ui.selectTabForSnapshot (2);
  41132. ui.getPlaylistForSnapshot().setRipple (true);
  41133. saveSnapshot (ui, prefix + "-playlist-ripple.png");
  41134. ui.getPlaylistForSnapshot().setRipple (false);
  41135. // FL's legacy Pattern Blocks (round 170f, issue #60): the section under the clip tracks, a row per pattern
  41136. {
  41137. const auto saved = offline.getSong();
  41138. offline.editSong ([] (lynx::Song& s) {
  41139. s.patternBlocksOn = true;
  41140. while (s.patterns.size() < 5) // a few rows to show (Drums, Bass...: copies of the demo's pattern)
  41141. lynx::clonePattern (s, (int) s.patterns.size() - 1);
  41142. const auto rows = juce::jmin (6, (int) s.patterns.size());
  41143. for (int r = 0; r < rows; ++r)
  41144. lynx::patternblocks::paintRange (s, r, (std::int64_t) (r % 3) * 4 * lynx::ppq * 2,
  41145. (std::int64_t) (8 + r * 2) * 4 * lynx::ppq);
  41146. }, false);
  41147. offline.dispatchPendingMessages();
  41148. saveSnapshot (ui, prefix + "-playlist-blocks.png");
  41149. // issue #127 (PR #132 and our follow-up): the Playlist's pencil, brush and eraser on the blocks, driven
  41150. // with real mouse events on the view. One picture per tool, and the gestures' results in
  41151. // <prefix>-playlist-blocks-tools.txt ("OK", or the checks that failed).
  41152. if (auto* blocks = ui.getPlaylistForSnapshot().getBlocksViewForSnapshot())
  41153. {
  41154. juce::StringArray failed;
  41155. const auto expect = [&failed] (bool ok, const char* what) { if (! ok) failed.add (what); };
  41156. const auto bar = offline.getSong().barTicks();
  41157. offline.editSong ([bar] (lynx::Song& s) {
  41158. s.blocks.clear();
  41159. for (std::size_t r = 0; r < 4 && r < s.patterns.size(); ++r)
  41160. s.patterns[r].lengthTicks = r == 1 ? 2 * bar : bar; // row 2 holds a 2-bar pattern
  41161. }, false);
  41162. offline.dispatchPendingMessages();
  41163. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  41164. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
  41165. juce::Point<float> pressedAt;
  41166. const auto event = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  41167. const auto at = blocks->pointForSnapshot (row, tick).toFloat();
  41168. const auto now = juce::Time::getCurrentTime();
  41169. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, 1, false);
  41170. };
  41171. const auto press = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  41172. pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
  41173. blocks->mouseDown (event (row, tick, mods));
  41174. };
  41175. const auto dragTo = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (event (row, tick, mods)); };
  41176. const auto release = [&] (int row, std::int64_t tick) { blocks->mouseUp (event (row, tick, {})); };
  41177. // the starts of row `row`'s blocks, as "0,2,5" (bars from 0)
  41178. const auto rowBars = [&] (int row) {
  41179. juce::StringArray bars;
  41180. for (const auto& b : offline.getSong().blocks)
  41181. if (b.pattern == row)
  41182. bars.add (juce::String (b.start / bar) + (b.start % bar != 0 ? "+" : ""));
  41183. return bars.joinIntoString (",");
  41184. };
  41185. auto& tools = ui.getPlaylistForSnapshot();
  41186. // Pencil: a press on empty space places one block that follows the mouse along its row
  41187. tools.setToolForSnapshot (lynx::EditTool::pencil);
  41188. press (0, 2 * bar + 40, left);
  41189. expect (rowBars (0) == "2", "pencil: a press places one block");
  41190. dragTo (2, 5 * bar + 40, left); // (over another row: the block stays in its own)
  41191. release (2, 5 * bar + 40);
  41192. expect (rowBars (0) == "5" && rowBars (2).isEmpty(), "pencil: the placed block follows the drag in its row");
  41193. // a 2-bar block grabbed by its second bar keeps that bar under the mouse (it used to jump a bar)
  41194. press (1, 1 * bar + 40, left);
  41195. release (1, 1 * bar + 40);
  41196. expect (rowBars (1) == "1", "pencil: a click places the 2-bar block");
  41197. press (1, 2 * bar + 40, left);
  41198. dragTo (1, 2 * bar + bar / 2, left);
  41199. expect (rowBars (1) == "1", "move: a small move on the grabbed bar leaves the block in place");
  41200. dragTo (1, 4 * bar + 40, left);
  41201. release (1, 4 * bar + 40);
  41202. expect (rowBars (1) == "3", "move: the grabbed bar stays under the mouse");
  41203. offline.dispatchPendingMessages();
  41204. saveSnapshot (ui, prefix + "-playlist-blocks-pencil.png");
  41205. // Brush: a drag over empty space paints a run; a press on a block moves it
  41206. tools.setToolForSnapshot (lynx::EditTool::brush);
  41207. press (2, 0, left);
  41208. dragTo (2, 3 * bar + 40, left);
  41209. release (2, 3 * bar + 40);
  41210. expect (rowBars (2) == "0,1,2,3", "brush: a drag paints a run");
  41211. press (2, 3 * bar + 40, left);
  41212. dragTo (2, 6 * bar + 40, left);
  41213. release (2, 6 * bar + 40);
  41214. expect (rowBars (2) == "0,1,2,6", "brush: a press on a block moves it");
  41215. offline.dispatchPendingMessages();
  41216. saveSnapshot (ui, prefix + "-playlist-blocks-brush.png");
  41217. // Eraser, and the right button with any tool: only the blocks under the mouse, row by row
  41218. offline.editSong ([bar] (lynx::Song& s) {
  41219. for (int r = 0; r < 4 && r < (int) s.patterns.size(); ++r)
  41220. lynx::patternblocks::place (s, r, 8 * bar);
  41221. }, false);
  41222. offline.dispatchPendingMessages();
  41223. expect (rowBars (0) == "5,8" && rowBars (3) == "8", "eraser: the column is set up");
  41224. saveSnapshot (ui, prefix + "-playlist-blocks-eraser-before.png");
  41225. tools.setToolForSnapshot (lynx::EditTool::eraser);
  41226. press (0, 8 * bar + 40, left);
  41227. expect (rowBars (0) == "5" && rowBars (1) == "3,8" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8",
  41228. "eraser: a click takes only the block under the mouse");
  41229. dragTo (1, 8 * bar + 60, left); // down one row: that row's block goes too, the rows below stay
  41230. release (1, 8 * bar + 60);
  41231. expect (rowBars (1) == "3" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8", "eraser: the drag erases the rows it crosses, no others");
  41232. tools.setToolForSnapshot (lynx::EditTool::pencil);
  41233. press (3, 8 * bar + 40, right);
  41234. release (3, 8 * bar + 40);
  41235. expect (rowBars (3).isEmpty() && rowBars (2) == "0,1,2,6,8", "right click: erases only the block under the mouse");
  41236. offline.dispatchPendingMessages();
  41237. saveSnapshot (ui, prefix + "-playlist-blocks-eraser.png");
  41238. juce::File (prefix + "-playlist-blocks-tools.txt").replaceWithText (failed.isEmpty() ? juce::String ("OK\n") : "ERROR\n" + failed.joinIntoString ("\n") + "\n");
  41239. }
  41240. offline.editSong ([saved] (lynx::Song& s) { s = saved; }, false);
  41241. offline.dispatchPendingMessages();
  41242. }
  41243. // quick-add palette, and the Browser searching
  41244. saveWindow (ui.makeQuickAddForSnapshot(), "-quickadd.png");
  41245. ui.showDesktopForSnapshot (false);
  41246. ui.getBrowserForSnapshot().setSearchForSnapshot ("kick");
  41247. offline.dispatchPendingMessages();
  41248. saveSnapshot (ui, prefix + "-browser-search.png");
  41249. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  41250. ui.getBrowserForSnapshot().selectFirstSampleForSnapshot(); // the tree with a sample selected and its waveform
  41251. offline.dispatchPendingMessages();
  41252. saveSnapshot (ui, prefix + "-browser-tree.png");
  41253. // the Browser's PROJECT tab: the patterns, generators and audio files of the project in their colours
  41254. ui.getBrowserForSnapshot().showProjectForSnapshot();
  41255. offline.dispatchPendingMessages();
  41256. saveSnapshot (ui, prefix + "-browser-project.png");
  41257. ui.getBrowserForSnapshot().showPluginDatabaseForSnapshot(); // round 142: the Plugin database's FL engines
  41258. offline.dispatchPendingMessages();
  41259. saveSnapshot (ui, prefix + "-browser-plugins.png");
  41260. // round 190bf (fl190be Q1): the Plugin database's right-click menus, a folder's and an entry's (FL's System group)
  41261. saveMenus (juce::StringArray { "Plugin database: folder", "Plugin database: entry" }, ui.getBrowserForSnapshot().pluginDatabaseMenusForSnapshot(),
  41262. prefix + "-browser190bf-menus.png");
  41263. ui.getBrowserForSnapshot().setTab (lynx::BrowserComponent::allTab);
  41264. saveWindow (ui.getBrowserForSnapshot().makeFoldersPanelForSnapshot(), "-browser-folders.png"); // round 164
  41265. {
  41266. // round 164: the content filter leaves out the folders with nothing to list (a small library)
  41267. const auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-library");
  41268. lib.deleteRecursively();
  41269. for (const auto* path : { "Drums/Kicks/kick 1.wav", "Drums/Kicks/kick 2.wav", "Drums/snare.wav", "Keys/pad.sf2", "Presets/Synth/lead.fst",
  41270. "Projects/beat.flp", "Projects/MIDI/chords.mid", "Notes/readme.txt", "Empty/Nothing/.keep" })
  41271. lib.getChildFile (path).create();
  41272. ui.showDesktopForSnapshot (false);
  41273. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  41274. offline.dispatchPendingMessages();
  41275. saveSnapshot (ui, prefix + "-browser164-all.png");
  41276. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::samples);
  41277. offline.dispatchPendingMessages();
  41278. saveSnapshot (ui, prefix + "-browser164-samples.png");
  41279. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::projects);
  41280. offline.dispatchPendingMessages();
  41281. saveSnapshot (ui, prefix + "-browser164-projects.png");
  41282. lib.deleteRecursively();
  41283. ui.getBrowserForSnapshot().resetViewForSnapshot();
  41284. }
  41285. {
  41286. // round 190as: "Find similar samples" on a small library of kicks, hats and pads (LYNX_SNAPSHOT_SIMILAR =
  41287. // "<folder>|<file>" lists a real folder instead)
  41288. auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-similar");
  41289. auto query = lib.getChildFile ("Drums/Kicks/Kick 2.wav");
  41290. const auto real = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIMILAR", {});
  41291. const auto made = real.isEmpty();
  41292. if (made)
  41293. {
  41294. lib.deleteRecursively();
  41295. juce::Random random (190);
  41296. const auto write = [&] (const juce::String& path, char kind, int v) {
  41297. const auto rate = 44100.0;
  41298. const auto frames = (int) (rate * (kind == 'k' ? 0.35 : kind == 'h' ? 0.09 : 2.5));
  41299. juce::AudioBuffer<float> audio (1, frames);
  41300. double phase = 0.0;
  41301. float last = 0.0f;
  41302. for (int i = 0; i < frames; ++i)
  41303. {
  41304. const auto t = i / rate;
  41305. float x = 0.0f;
  41306. if (kind == 'k')
  41307. {
  41308. phase += juce::MathConstants<double>::twoPi * ((46.0 + 3.0 * v) + 150.0 * std::exp (-t * 35.0)) / rate;
  41309. x = (float) (std::sin (phase) * std::exp (-t * (8.0 + v)));
  41310. }
  41311. else if (kind == 'h')
  41312. {
  41313. const auto n = random.nextFloat() * 2.0f - 1.0f;
  41314. x = (n - last) * 0.5f * (float) std::exp (-t * (50.0 + 12.0 * v));
  41315. last = n;
  41316. }
  41317. else
  41318. {
  41319. const auto base = 220.0 * std::pow (2.0, v / 12.0);
  41320. x = (float) (0.25 * std::min (1.0, t / 0.4) * std::min (1.0, (2.5 - t) / 0.5)
  41321. * (std::sin (juce::MathConstants<double>::twoPi * base * t) + std::sin (juce::MathConstants<double>::twoPi * base * 1.5 * t)));
  41322. }
  41323. audio.setSample (0, i, 0.8f * x);
  41324. }
  41325. const auto file = lib.getChildFile (path);
  41326. file.getParentDirectory().createDirectory();
  41327. juce::WavAudioFormat wav;
  41328. if (auto out = file.createOutputStream())
  41329. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (out.release(), rate, 1, 16, {}, 0)))
  41330. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  41331. };
  41332. for (int v = 1; v <= 5; ++v)
  41333. {
  41334. write ("Drums/Kicks/Kick " + juce::String (v) + ".wav", 'k', v);
  41335. write ("Drums/Hats/Hat " + juce::String (v) + ".wav", 'h', v);
  41336. write ("Keys/Pad " + juce::String (v) + ".wav", 'p', v);
  41337. }
  41338. }
  41339. else
  41340. {
  41341. lib = juce::File (real.upToFirstOccurrenceOf ("|", false, false));
  41342. query = juce::File (real.fromFirstOccurrenceOf ("|", false, false));
  41343. }
  41344. ui.showDesktopForSnapshot (false);
  41345. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  41346. ui.getBrowserForSnapshot().findSimilarForSnapshot (query, lib);
  41347. offline.dispatchPendingMessages();
  41348. saveSnapshot (ui, prefix + "-browser-similar.png");
  41349. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  41350. if (made)
  41351. lib.deleteRecursively();
  41352. ui.getBrowserForSnapshot().resetViewForSnapshot();
  41353. }
  41354. // the undo history after a few edits
  41355. offline.editSong ([] (lynx::Song& s) { s.bpm += 1.0; });
  41356. offline.editSong ([] (lynx::Song& s) { if (! s.channels.empty()) s.channels[0].muted = ! s.channels[0].muted; });
  41357. offline.editSong ([] (lynx::Song& s) { if (! s.patterns.empty()) s.patterns[(std::size_t) s.currentPattern].notes.push_back ({}); });
  41358. offline.undo();
  41359. saveWindow (lynx::makeHistoryPanel (offline), "-history.png");
  41360. // spectral waveforms: a synthetic beat (kick, hats, a chord, a noise riser) as audio clips in spectral
  41361. // colours, zoomed in, classic and stereo; the same file in the Sampler editor and the Browser preview
  41362. {
  41363. const juce::File wav (prefix + "-wavedemo.wav");
  41364. writeWaveDemo (wav, offline.getSong().bpm);
  41365. const auto path = wav.getFullPathName();
  41366. const auto pathUtf8 = path.toStdString();
  41367. int samplerChannel = -1, firstTrack = 0;
  41368. offline.editSong ([&] (lynx::Song& s) {
  41369. for (const auto& clip : s.playlist)
  41370. firstTrack = std::max (firstTrack, clip.track + 1);
  41371. lynx::ChannelDef audio;
  41372. audio.name = "Beat (audio)";
  41373. audio.instrument = lynx::InstrumentKind::audioClip;
  41374. audio.samplePath = pathUtf8;
  41375. s.channels.push_back (audio);
  41376. const auto audioChannel = (int) s.channels.size() - 1;
  41377. lynx::ChannelDef sampler = audio;
  41378. sampler.name = "Beat (sampler)";
  41379. sampler.instrument = lynx::InstrumentKind::sampler;
  41380. sampler.sampler.regionStart = 0.06f;
  41381. sampler.sampler.regionEnd = 0.94f;
  41382. s.channels.push_back (sampler);
  41383. samplerChannel = (int) s.channels.size() - 1;
  41384. const auto bar = s.barTicks();
  41385. const auto whole = (std::int64_t) std::llround (8.0 * s.bpm / 60.0 * lynx::ppq);
  41386. lynx::Clip clip;
  41387. clip.kind = lynx::ClipKind::audio;
  41388. clip.channel = audioChannel;
  41389. clip.track = firstTrack;
  41390. clip.length = whole;
  41391. s.playlist.push_back (clip);
  41392. clip.track = firstTrack + 1; // a slice of it, later in the song
  41393. clip.start = bar;
  41394. clip.offset = bar;
  41395. clip.length = 2 * bar;
  41396. s.playlist.push_back (clip);
  41397. // taller rows for the audio (tracks can be resized: P18)
  41398. if ((int) s.playlistTracks.size() < firstTrack + 2)
  41399. s.playlistTracks.resize ((std::size_t) firstTrack + 2);
  41400. s.playlistTracks[(std::size_t) firstTrack].height = 80;
  41401. s.playlistTracks[(std::size_t) firstTrack + 1].height = 60;
  41402. });
  41403. offline.dispatchPendingMessages();
  41404. auto& cache = *lynx::ui::WaveformCache::getInstance();
  41405. cache.find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  41406. cache.waitUntilIdle (30000);
  41407. ui.selectTabForSnapshot (2);
  41408. auto& playlist = ui.getPlaylistForSnapshot();
  41409. playlist.setTimeSelectionForSnapshot (0, 0);
  41410. {
  41411. // the Playlist alone (the floating Channel Rack would cover the clips)
  41412. auto saveSnapshot = [&playlist] (juce::Component&, const juce::String& file) { saveArea (playlist, playlist.getLocalBounds(), file); };
  41413. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  41414. saveSnapshot (ui, prefix + "-playlist-audio.png");
  41415. playlist.setViewForSnapshot (1400.0, 0, std::max (0, firstTrack - 3));
  41416. saveSnapshot (ui, prefix + "-playlist-audio-zoom.png");
  41417. lynx::ui::WaveformCache::stereo = true;
  41418. saveSnapshot (ui, prefix + "-playlist-audio-stereo.png");
  41419. lynx::ui::WaveformCache::stereo = false;
  41420. lynx::ui::WaveformCache::spectral = true;
  41421. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  41422. saveSnapshot (ui, prefix + "-playlist-audio-spectral.png");
  41423. lynx::ui::WaveformCache::spectral = false;
  41424. playlist.setViewForSnapshot (40.0, 0, 0);
  41425. saveSnapshot (ui, prefix + "-playlist-audio-far.png");
  41426. // LYNX_SNAPSHOT_AUDIO=a.wav;b.wav...: real audio as clips (default-height tracks, one tall,
  41427. // a fade, a reversed copy), at three zoom levels
  41428. if (const auto files = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_AUDIO", {}), ";", "");
  41429. ! files.isEmpty())
  41430. {
  41431. const auto realTrack = firstTrack + 2;
  41432. std::vector<juce::String> paths;
  41433. for (const auto& f : files)
  41434. if (juce::File (f.trim()).existsAsFile())
  41435. paths.push_back (f.trim());
  41436. offline.editSong ([&] (lynx::Song& s) {
  41437. const auto bar = s.barTicks();
  41438. const std::uint32_t colours[] = { 0, 0xffd9a441, 0xff6fb36a, 0xffb06fd0, 0xff5fb7c9, 0xffd06f6f };
  41439. for (std::size_t i = 0; i < paths.size(); ++i)
  41440. {
  41441. lynx::ChannelDef audio;
  41442. audio.name = juce::File (paths[i]).getFileNameWithoutExtension().toStdString();
  41443. audio.instrument = lynx::InstrumentKind::audioClip;
  41444. audio.samplePath = paths[i].toStdString();
  41445. audio.colour = colours[i % 6];
  41446. audio.sampler.stretchBeats = i % 2 == 0 ? 16.0f : 0.0f; // fitted to 4 bars, or as recorded
  41447. audio.sampler.keepPitch = true;
  41448. s.channels.push_back (audio);
  41449. lynx::Clip clip;
  41450. clip.kind = lynx::ClipKind::audio;
  41451. clip.channel = (int) s.channels.size() - 1;
  41452. clip.track = realTrack + (int) i;
  41453. clip.length = 4 * bar;
  41454. clip.fadeIn = i == 1 ? bar / 2 : 0;
  41455. s.playlist.push_back (clip);
  41456. clip.start = 4 * bar;
  41457. clip.fadeIn = 0;
  41458. clip.fadeOut = i == 0 ? bar : 0;
  41459. s.playlist.push_back (clip);
  41460. }
  41461. if ((int) s.playlistTracks.size() < realTrack + (int) paths.size())
  41462. s.playlistTracks.resize ((std::size_t) realTrack + paths.size());
  41463. if (! paths.empty())
  41464. s.playlistTracks[(std::size_t) realTrack].height = 90;
  41465. });
  41466. offline.dispatchPendingMessages();
  41467. for (const auto& path2 : paths)
  41468. cache.find (path2, [&offline, path2] { return offline.getSampleLibrary().load (path2); });
  41469. cache.waitUntilIdle (60000);
  41470. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  41471. saveSnapshot (ui, prefix + "-playlist-real.png");
  41472. playlist.setViewForSnapshot (700.0, 0, std::max (0, realTrack - 1));
  41473. saveSnapshot (ui, prefix + "-playlist-real-zoom.png");
  41474. playlist.setViewForSnapshot (2400.0, 0, std::max (0, realTrack - 1));
  41475. saveSnapshot (ui, prefix + "-playlist-real-close.png");
  41476. playlist.setViewForSnapshot (50.0, 0, std::max (0, realTrack - 4));
  41477. saveSnapshot (ui, prefix + "-playlist-real-far.png");
  41478. // the clip menu of the first real clip
  41479. if (const auto menu = playlist.getClipMenuForSnapshot ((int) offline.getSong().playlist.size() - (int) paths.size() * 2); menu.getNumItems() > 0)
  41480. saveMenus (juce::StringArray { "Audio clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-audio.png");
  41481. if (const auto menu = playlist.getClipMenuForSnapshot (0); menu.getNumItems() > 0)
  41482. saveMenus (juce::StringArray { "Pattern clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-pattern.png");
  41483. // the clip menu's actions, run through the menu itself; results in -clip-actions.txt
  41484. {
  41485. juce::StringArray log;
  41486. auto clipOf = [&offline] (const std::string& channelName, int nth) {
  41487. const auto& sg = offline.getSong();
  41488. for (int i = 0; i < (int) sg.playlist.size(); ++i)
  41489. {
  41490. const auto& c = sg.playlist[(std::size_t) i];
  41491. if (c.kind == lynx::ClipKind::audio && c.channel >= 0 && sg.channels[(std::size_t) c.channel].name == channelName && nth-- == 0)
  41492. return i;
  41493. }
  41494. return -1;
  41495. };
  41496. std::function<bool (const juce::PopupMenu&, const juce::String&)> run = [&run] (const juce::PopupMenu& m, const juce::String& text) {
  41497. for (juce::PopupMenu::MenuItemIterator it (m); it.next();)
  41498. {
  41499. auto& item = it.getItem();
  41500. if (item.subMenu != nullptr && run (*item.subMenu, text))
  41501. return true;
  41502. // (without the menu mnemonic's mark: FL's underlined letters, round 190dz)
  41503. if (item.text.removeCharacters (juce::String::charToString (1)).startsWith (text) && item.isEnabled && item.action)
  41504. {
  41505. item.action();
  41506. return true;
  41507. }
  41508. }
  41509. return false;
  41510. };
  41511. auto act = [&] (const std::string& name, int nth, const juce::String& text) {
  41512. const auto clip = clipOf (name, nth);
  41513. const auto ok = clip >= 0 && run (playlist.getClipMenuForSnapshot (clip), text);
  41514. offline.dispatchPendingMessages();
  41515. return ok;
  41516. };
  41517. auto channelOf = [&] (const std::string& name) -> const lynx::ChannelDef* {
  41518. for (const auto& c : offline.getSong().channels)
  41519. if (c.name == name)
  41520. return &c;
  41521. return nullptr;
  41522. };
  41523. auto check = [&log] (const juce::String& what, bool ok) { log.add ((ok ? "OK " : "FAIL ") + what); };
  41524. const auto names = [&] { std::vector<std::string> n; for (auto& p2 : paths) n.push_back (juce::File (p2).getFileNameWithoutExtension().toStdString()); return n; }();
  41525. if (names.size() >= 4)
  41526. {
  41527. const auto channelsBefore = offline.getSong().channels.size();
  41528. check ("Reverse", act (names[2], 0, lynx::tr ("Reverse")) && channelOf (names[2])->sampler.reverse);
  41529. offline.undo();
  41530. offline.dispatchPendingMessages();
  41531. check ("Reverse undone", ! channelOf (names[2])->sampler.reverse);
  41532. act (names[2], 0, lynx::tr ("Reverse"));
  41533. check ("Make unique", act (names[3], 1, lynx::tr ("Make unique")) && offline.getSong().channels.size() == channelsBefore + 1
  41534. && channelOf (names[3] + " #2") != nullptr);
  41535. check ("Fit to tempo, resample", act (names[1], 0, lynx::tr ("Fit to tempo, resample ({0})", { juce::String() }).upToFirstOccurrenceOf ("(", false, false))
  41536. && channelOf (names[1])->sampler.stretchBeats > 0.0f && ! channelOf (names[1])->sampler.keepPitch);
  41537. const auto gainBefore = offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain;
  41538. check ("Normalize", act (names[0], 1, lynx::tr ("Normalize"))
  41539. && offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain != gainBefore);
  41540. const auto clipsBefore = offline.getSong().playlist.size();
  41541. check ("Split here", act (names[3], 0, lynx::tr ("Split here")) && offline.getSong().playlist.size() == clipsBefore + 1);
  41542. check ("Mute", act (names[0], 0, lynx::tr ("Mute")) && offline.getSong().playlist[(std::size_t) clipOf (names[0], 0)].muted);
  41543. check ("Copy + Paste here", act (names[0], 0, lynx::tr ("Copy")) && act (names[0], 1, lynx::tr ("Paste here"))
  41544. && offline.getSong().playlist.size() == clipsBefore + 2);
  41545. check ("Delete", act (names[0], 2, lynx::tr ("Delete")) && offline.getSong().playlist.size() == clipsBefore + 1);
  41546. check ("Chop to grid", act (names[3], 0, lynx::tr ("Chop to grid")) && offline.getSong().playlist.size() > clipsBefore + 1);
  41547. }
  41548. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  41549. saveSnapshot (ui, prefix + "-playlist-real-actions.png");
  41550. juce::File (prefix + "-clip-actions.txt").replaceWithText (log.joinIntoString ("\n") + "\n");
  41551. }
  41552. }
  41553. }
  41554. saveWindow (lynx::makeChannelSettingsPanel (offline, samplerChannel), "-sampler-wave.png");
  41555. ui.showDesktopForSnapshot (false);
  41556. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  41557. saveSnapshot (ui, prefix + "-browser-preview.png");
  41558. }
  41559. }
  41560. // round 165o: every Label / button / tick box whose text the drawing squeezes below its minimum scale or cuts
  41561. // (an ellipsis), per language: `LYNX --lang de --snapshot shots/de` -> shots/de-textfit.txt
  41562. juce::File (prefix + "-textfit.txt").replaceWithText (textFitLog().joinIntoString ("\n") + "\n");
  41563. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  41564. quit();
  41565. }
  41566. // --snapshot: 8 s of a synthetic stereo beat whose parts sit in different bands (kick = low, chord = mid,
  41567. // hats and the noise riser = high), to show the spectral waveform colours
  41568. #include "BrowserShot190iz.inc" // round 190iz
  41569. #include "LynxModelShot190ni.inc" // round 190ni
  41570. #include "UndoGesture190jv.inc" // round 190jv
  41571. #include "Q1a190rwCheck.inc" // round 190rw (0.1.32 Q1 part A)
  41572. #include "TrimShot190jv.inc" // round 190jv
  41573. #include "PrChordShot190kd.inc" // round 190kd
  41574. #include "ModalShot190mc.inc" // round 190mc
  41575. #include "KeysShot190nu.inc" // round chord2_190nu
  41576. #include "SectionsShot190ol.inc" // round 190ol (research190oe P1 / P6)
  41577. #include "ChordLaneShot190pf.inc" // round 190pf (research190oe P13 / P12)
  41578. #include "PrShot190jv.inc" // round 190jv
  41579. #include "HostPlay190ll.inc" // round 190ll (issue #199)
  41580. #include "IssuesShot190ll.inc" // round 190ll (issues #200, #201, #203)
  41581. #include "IssuesShot190qr.inc" // round 190qr (issues #274-#281: the FL | LYNX pictures)
  41582. #include "SimpleGbShot190ke.inc" // round 190ke
  41583. #include "LoopShot190kf.inc" // round gaps190kf
  41584. #include "QaRest190lcShot.inc" // rollup 0.1.30 step 7 (round 190lc)
  41585. #include "LoopInfoShot190kx.inc" // round 190kx
  41586. static void writeWaveDemo (const juce::File& file, double bpm)
  41587. {
  41588. constexpr double rate = 44100.0;
  41589. const auto frames = (int) (8.0 * rate);
  41590. juce::AudioBuffer<float> buffer (2, frames);
  41591. buffer.clear();
  41592. auto* l = buffer.getWritePointer (0);
  41593. auto* r = buffer.getWritePointer (1);
  41594. const auto beat = 60.0 / juce::jlimit (40.0, 300.0, bpm);
  41595. std::uint32_t noise = 0x9e3779b9u;
  41596. auto white = [&noise] {
  41597. noise ^= noise << 13;
  41598. noise ^= noise >> 17;
  41599. noise ^= noise << 5;
  41600. return (float) (noise & 0xffffff) / (float) 0x800000 - 1.0f;
  41601. };
  41602. float previous = 0.0f;
  41603. for (int i = 0; i < frames; ++i)
  41604. {
  41605. const auto t = i / rate;
  41606. const auto inBeat = std::fmod (t, beat);
  41607. const auto bar = (int) (t / (beat * 4.0));
  41608. float left = 0.0f, right = 0.0f;
  41609. // kick on every beat: a falling sine
  41610. {
  41611. const auto phase = 2.0 * juce::MathConstants<double>::pi * (48.0 * inBeat + 4.0 * (1.0 - std::exp (-inBeat * 30.0)));
  41612. const auto k = (float) (std::sin (phase) * std::exp (-inBeat * 7.0)) * 0.85f;
  41613. left += k;
  41614. right += k;
  41615. }
  41616. // hats on the off-beats: high-passed noise bursts, a little to the right
  41617. {
  41618. const auto h = std::fmod (t + beat * 0.5, beat);
  41619. const auto n = white();
  41620. const auto hp = (n - previous) * 0.5f;
  41621. previous = n;
  41622. const auto hat = hp * (float) std::exp (-h * 45.0) * 0.55f;
  41623. left += hat * 0.6f;
  41624. right += hat;
  41625. }
  41626. // a chord in the second and third bars (mid band)
  41627. if (bar == 1 || bar == 2)
  41628. {
  41629. const auto env = (float) std::min (1.0, std::min (t - beat * 4.0, beat * 12.0 - t) * 8.0);
  41630. float chord = 0.0f;
  41631. for (const auto hz : { 523.25, 659.25, 783.99 })
  41632. chord += (float) (std::sin (2.0 * juce::MathConstants<double>::pi * hz * t) + 0.3 * std::sin (4.0 * juce::MathConstants<double>::pi * hz * t));
  41633. left += chord * 0.09f * std::max (0.0f, env);
  41634. right += chord * 0.09f * std::max (0.0f, env);
  41635. }
  41636. // a white-noise riser over the last two seconds (high band)
  41637. if (t > 6.0)
  41638. {
  41639. const auto rise = (float) ((t - 6.0) / 2.0);
  41640. left += white() * 0.4f * rise * rise;
  41641. right += white() * 0.4f * rise * rise;
  41642. }
  41643. l[i] = left;
  41644. r[i] = right;
  41645. }
  41646. buffer.applyGain (0.9f / juce::jmax (1.0e-6f, buffer.getMagnitude (0, frames)));
  41647. file.deleteFile();
  41648. juce::WavAudioFormat wav;
  41649. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0) })
  41650. writer->writeFromAudioSampleBuffer (buffer, 0, frames);
  41651. }
  41652. // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
  41653. static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
  41654. {
  41655. const auto names = ui.getMenuNamesForSnapshot();
  41656. std::vector<juce::PopupMenu> source;
  41657. for (int m = 0; m < names.size(); ++m)
  41658. source.push_back (ui.getMenuForSnapshot (m));
  41659. saveMenus (names, source, path);
  41660. }
  41661. // menus side by side, each under its name, in the columns JUCE shows them in: its own column breaks, or (round 190je,
  41662. // cmake/LynxPatchJuce.cmake fix 40) the split of a menu taller than 70 % of a 1080 px screen
  41663. static void saveMenus (const juce::StringArray& names, const std::vector<juce::PopupMenu>& source, const juce::String& path)
  41664. {
  41665. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  41666. struct Row
  41667. {
  41668. const juce::PopupMenu::Item* item;
  41669. int height;
  41670. };
  41671. struct Laid
  41672. {
  41673. juce::PopupMenu menu;
  41674. std::vector<std::vector<Row>> columns;
  41675. std::vector<int> widths;
  41676. int width = 0, height = 0;
  41677. };
  41678. std::vector<Laid> menus;
  41679. menus.reserve ((std::size_t) names.size());
  41680. const auto border = lf.getPopupMenuBorderSize();
  41681. const auto separatorWidth = lf.getPopupMenuColumnSeparatorWidthWithOptions (juce::PopupMenu::Options());
  41682. for (int m = 0; m < names.size(); ++m)
  41683. {
  41684. menus.push_back (Laid { source[(std::size_t) m] });
  41685. auto& laid = menus.back();
  41686. std::vector<Row> rows;
  41687. std::vector<lynx::themes::MenuRow> shape;
  41688. std::vector<int> breaks;
  41689. for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
  41690. {
  41691. const auto& item = it.getItem();
  41692. int w = 0, h = 0;
  41693. if (item.customComponent != nullptr)
  41694. item.customComponent->getIdealSize (w, h); // (a title band: its own height, as JUCE asks it)
  41695. else
  41696. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  41697. if (item.isSectionHeader) h += h / 2; // as JUCE does
  41698. rows.push_back ({ &item, h });
  41699. shape.push_back ({ h, item.isSeparator, item.isSectionHeader });
  41700. if (item.shouldBreakAfter)
  41701. breaks.push_back ((int) rows.size() - 1);
  41702. }
  41703. if (breaks.empty())
  41704. if (const auto at = lynx::themes::tallMenuBreak (shape, 1080 * 7 / 10); at >= 0)
  41705. breaks.push_back (at);
  41706. laid.columns.emplace_back();
  41707. laid.widths.push_back (160);
  41708. for (int i = 0; i < (int) rows.size(); ++i)
  41709. {
  41710. const auto& item = *rows[(std::size_t) i].item;
  41711. int w = 0, h = 0;
  41712. if (item.customComponent != nullptr)
  41713. item.customComponent->getIdealSize (w, h);
  41714. else
  41715. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  41716. if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
  41717. w += 90;
  41718. laid.columns.back().push_back (rows[(std::size_t) i]);
  41719. laid.widths.back() = juce::jmax (laid.widths.back(), w + 10);
  41720. if (std::find (breaks.begin(), breaks.end(), i) != breaks.end() && i + 1 < (int) rows.size())
  41721. {
  41722. laid.columns.emplace_back();
  41723. laid.widths.push_back (160);
  41724. }
  41725. }
  41726. laid.width = (int) (laid.columns.size() - 1) * separatorWidth;
  41727. for (std::size_t c = 0; c < laid.columns.size(); ++c)
  41728. {
  41729. laid.width += laid.widths[c];
  41730. int h = 2 * border;
  41731. for (const auto& row : laid.columns[c])
  41732. h += row.height;
  41733. laid.height = juce::jmax (laid.height, h);
  41734. }
  41735. }
  41736. int totalWidth = 16, totalHeight = 0;
  41737. for (const auto& l : menus)
  41738. {
  41739. totalWidth += l.width + 16;
  41740. totalHeight = juce::jmax (totalHeight, l.height + 32);
  41741. }
  41742. auto image = lynx::shot::canvas (totalWidth, totalHeight);
  41743. {
  41744. juce::Graphics g (image);
  41745. lynx::shot::logical (g);
  41746. g.fillAll (lynx::theme::colour::bg1);
  41747. int x = 16;
  41748. bool first = true;
  41749. for (int m = 0; m < (int) menus.size(); ++m)
  41750. {
  41751. const auto& l = menus[(std::size_t) m];
  41752. g.setColour (lynx::theme::colour::textSecondary);
  41753. g.setFont (lynx::theme::font (lynx::theme::type::small, true));
  41754. g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
  41755. {
  41756. juce::Graphics::ScopedSaveState state (g);
  41757. g.reduceClipRegion (x, 24, l.width, l.height);
  41758. g.setOrigin (x, 24);
  41759. lf.drawPopupMenuBackground (g, l.width, l.height);
  41760. int columnX = 0;
  41761. for (std::size_t c = 0; c < l.columns.size(); ++c)
  41762. {
  41763. int y = border;
  41764. for (const auto& row : l.columns[c])
  41765. {
  41766. const auto& item = *row.item;
  41767. 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),
  41768. row.height);
  41769. auto text = item.text, shortcut = item.shortcutKeyDescription;
  41770. if (text.containsChar ('\t'))
  41771. {
  41772. shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
  41773. text = text.upToFirstOccurrenceOf ("\t", false, false);
  41774. }
  41775. if (item.isSectionHeader)
  41776. lf.drawPopupMenuSectionHeader (g, r, text);
  41777. else if (item.customComponent != nullptr)
  41778. {
  41779. juce::Graphics::ScopedSaveState itemState (g);
  41780. g.setOrigin (r.getPosition());
  41781. item.customComponent->setSize (r.getWidth(), r.getHeight());
  41782. item.customComponent->paintEntireComponent (g, false);
  41783. }
  41784. else
  41785. lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
  41786. item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
  41787. first = false;
  41788. y += row.height;
  41789. }
  41790. columnX += l.widths[c];
  41791. if (c + 1 < l.columns.size())
  41792. {
  41793. lf.drawPopupMenuColumnSeparatorWithOptions (g, juce::Rectangle<int> (columnX, border, separatorWidth, l.height - 2 * border),
  41794. juce::PopupMenu::Options());
  41795. columnX += separatorWidth;
  41796. }
  41797. }
  41798. }
  41799. x += l.width + 16;
  41800. }
  41801. }
  41802. const auto file = lynx::shot::file (juce::File (path));
  41803. file.deleteFile();
  41804. juce::PNGImageFormat png;
  41805. if (auto out = file.createOutputStream())
  41806. png.writeImageToStream (image, *out);
  41807. }
  41808. static void writePng (const juce::Image& image, const juce::String& path)
  41809. {
  41810. const auto file = lynx::shot::file (juce::File (path));
  41811. file.deleteFile();
  41812. juce::PNGImageFormat png;
  41813. if (auto out = file.createOutputStream())
  41814. png.writeImageToStream (image, *out);
  41815. }
  41816. // the splash screen: one settled frame, and a strip of frames through its animation
  41817. static void saveSplashFrames (const juce::String& prefix)
  41818. {
  41819. lynx::SplashScreen splash;
  41820. splash.setStatus (lynx::tr ("Loading the workspace..."));
  41821. splash.setTimeForSnapshot (1.6);
  41822. writePng (lynx::shot::snapshot (splash), prefix + "-splash.png");
  41823. const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
  41824. const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
  41825. auto strip = lynx::shot::canvas (4 * (w + 8) + 8, 2 * (h + 8) + 8);
  41826. {
  41827. juce::Graphics g (strip);
  41828. lynx::shot::logical (g);
  41829. g.fillAll (lynx::theme::colour::bg1);
  41830. for (int i = 0; i < 8; ++i)
  41831. {
  41832. splash.setTimeForSnapshot (times[i]);
  41833. const auto frame = lynx::shot::snapshot (splash);
  41834. g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
  41835. }
  41836. }
  41837. writePng (strip, prefix + "-splash-frames.png");
  41838. }
  41839. // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
  41840. // colours: at rest, hovered and switched on
  41841. // round 190je (design190ia G1): one state sheet per button kind: idle, hover, pressed, on, disabled, as the one state rule
  41842. // draws them (core/ThemePalette.h buttonLook); the menu rows in both menu styles
  41843. static void saveStateSheet (const juce::String& path, float scale)
  41844. {
  41845. using namespace lynx;
  41846. scale *= shot::scale();
  41847. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  41848. const int labelWidth = 220, cellW = 120, cellH = 40, columns = 5;
  41849. const juce::String heads[] = { "idle", "hover", "pressed", "on", "disabled" };
  41850. enum Kind { text, iconFilled, iconOnce, iconSwitch, iconSwitchOwn, tick, radio, combo, tab, menuDark, menuFl, kinds };
  41851. const char* names[] = { "Text button", "Icon button (filled)", "Toolbar icon (acts once)", "Toolbar switch", "Toolbar switch (own colours)",
  41852. "Tick box", "Radio choice", "Combo box", "Tab", "Menu item (LYNX dark)", "Menu item (FL classic)" };
  41853. const auto w = labelWidth + columns * cellW + 16, h = 30 + kinds * cellH + 16;
  41854. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  41855. {
  41856. juce::Graphics g (image);
  41857. g.addTransform (juce::AffineTransform::scale (scale));
  41858. g.fillAll (theme::colour::bg3);
  41859. g.setFont (theme::font (theme::type::small, true));
  41860. g.setColour (theme::colour::textSecondary);
  41861. for (int c = 0; c < columns; ++c)
  41862. g.drawText (heads[c], labelWidth + c * cellW, 6, cellW, 20, juce::Justification::centred);
  41863. const auto styleBefore = theme::menus::style();
  41864. for (int k = 0; k < kinds; ++k)
  41865. {
  41866. const auto y = 30 + k * cellH;
  41867. g.setFont (theme::font (theme::type::small));
  41868. g.setColour (theme::colour::textPrimary);
  41869. g.drawText (names[k], 8, y, labelWidth - 12, cellH, juce::Justification::centredLeft);
  41870. for (int c = 0; c < columns; ++c)
  41871. {
  41872. const auto hover = c == 1, down = c == 2, on = c == 3, disabled = c == 4;
  41873. const juce::Rectangle<int> cell (labelWidth + c * cellW, y, cellW, cellH);
  41874. juce::Graphics::ScopedSaveState state (g);
  41875. g.reduceClipRegion (cell);
  41876. switch (k)
  41877. {
  41878. case text:
  41879. {
  41880. juce::TextButton b ("Export");
  41881. b.setSize (96, 26);
  41882. b.setToggleState (on, juce::dontSendNotification);
  41883. b.setEnabled (! disabled);
  41884. g.setOrigin (cell.getX() + 12, cell.getY() + 7);
  41885. lf.drawButtonBackground (g, b, b.findColour (on ? juce::TextButton::buttonOnColourId : juce::TextButton::buttonColourId), hover, down);
  41886. lf.drawButtonText (g, b, hover, down);
  41887. break;
  41888. }
  41889. case iconFilled:
  41890. case iconOnce:
  41891. case iconSwitch:
  41892. case iconSwitchOwn:
  41893. {
  41894. IconButton b ("state", k == iconFilled ? Icon::plus : k == iconOnce ? Icon::save : Icon::metronome);
  41895. b.setFlat (k != iconFilled);
  41896. if (k == iconSwitch)
  41897. b.setToggleLook (true);
  41898. if (k == iconSwitchOwn)
  41899. {
  41900. b.setOnColour (theme::colour::bg6);
  41901. b.setIconColourWhenOn (theme::colour::accent);
  41902. }
  41903. b.setSize (k == iconFilled ? 34 : 30, 30);
  41904. b.setToggleState (on, juce::dontSendNotification);
  41905. b.setEnabled (! disabled);
  41906. g.setOrigin (cell.getX() + 12, cell.getY() + 5);
  41907. b.paintButton (g, hover, down);
  41908. break;
  41909. }
  41910. case tick:
  41911. case radio:
  41912. {
  41913. juce::ToggleButton b (k == tick ? "Snap to grid" : "Pattern");
  41914. if (k == radio)
  41915. b.getProperties().set ("lynxRadio", true);
  41916. b.setSize (110, 24);
  41917. b.setToggleState (on, juce::dontSendNotification);
  41918. b.setEnabled (! disabled);
  41919. g.setOrigin (cell.getX() + 6, cell.getY() + 8);
  41920. lf.drawToggleButton (g, b, hover, down);
  41921. break;
  41922. }
  41923. case combo:
  41924. {
  41925. if (hover || down || on) // (a combo box's hover comes from the mouse itself: --uitest covers it)
  41926. break;
  41927. juce::ComboBox b;
  41928. b.setSize (100, 24);
  41929. b.setEnabled (! disabled);
  41930. g.setOrigin (cell.getX() + 10, cell.getY() + 8);
  41931. lf.drawComboBox (g, 100, 24, false, 0, 0, 0, 0, b);
  41932. g.setColour (disabled ? theme::colour::textDisabled : theme::colour::textPrimary);
  41933. g.setFont (lf.getComboBoxFont (b));
  41934. g.drawText ("1/16 step", 6, 0, 70, 24, juce::Justification::centredLeft);
  41935. break;
  41936. }
  41937. case tab:
  41938. {
  41939. if (disabled)
  41940. break;
  41941. juce::TabbedButtonBar bar (juce::TabbedButtonBar::TabsAtTop);
  41942. bar.setSize (220, 32);
  41943. bar.addTab ("Audio", theme::colour::bg2, -1);
  41944. bar.addTab ("MIDI", theme::colour::bg2, -1);
  41945. bar.setCurrentTabIndex (on ? 1 : 0, false);
  41946. auto* tabButton = bar.getTabButton (1);
  41947. tabButton->setBounds (0, 0, 100, 32);
  41948. g.setOrigin (cell.getX() + 10, cell.getY() + 4);
  41949. g.setColour (theme::colour::bg1);
  41950. g.fillRect (0, 0, 100, 32);
  41951. lf.drawTabButton (*tabButton, g, hover, down);
  41952. break;
  41953. }
  41954. case menuDark:
  41955. case menuFl:
  41956. {
  41957. if (down)
  41958. break;
  41959. theme::menus::setStyle (k == menuFl ? themes::MenuStyle::flClassic : themes::MenuStyle::lynxDark);
  41960. g.setOrigin (cell.getX() + 4, cell.getY() + 8);
  41961. lf.drawPopupMenuBackground (g, 112, 25);
  41962. lf.drawPopupMenuItem (g, { 2, 2, 108, 21 }, false, ! disabled, hover, on, false, theme::mnemonic ("Open", 'O'), "Ctrl+O", nullptr, nullptr);
  41963. theme::menus::setStyle (styleBefore);
  41964. break;
  41965. }
  41966. default:
  41967. break;
  41968. }
  41969. }
  41970. }
  41971. }
  41972. writePng (image, path);
  41973. }
  41974. static void saveIconSheet (const juce::String& path, float scale)
  41975. {
  41976. scale *= lynx::shot::scale();
  41977. const int sizes[] = { 16, 20, 24 };
  41978. const int cell = 34, columns = 3 * 3, labelWidth = 110;
  41979. const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
  41980. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  41981. {
  41982. juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
  41983. g.addTransform (juce::AffineTransform::scale (scale));
  41984. g.fillAll (lynx::theme::colour::bg3);
  41985. g.setFont (lynx::theme::font (lynx::theme::type::small));
  41986. for (int i = 1; i < lynx::iconCount; ++i)
  41987. {
  41988. const auto y = 8 + (i - 1) * cell;
  41989. g.setColour (lynx::theme::colour::textDisabled);
  41990. g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
  41991. for (int v = 0; v < 3; ++v)
  41992. for (int s = 0; s < 3; ++s)
  41993. {
  41994. const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
  41995. const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
  41996. g.setColour (bg);
  41997. g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
  41998. const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
  41999. : lynx::theme::colour::textSecondary.brighter (0.25f);
  42000. lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
  42001. }
  42002. }
  42003. }
  42004. writePng (image, path);
  42005. }
  42006. // a part of a component (e.g. the main toolbar)
  42007. static void saveArea (juce::Component& c, juce::Rectangle<int> area, const juce::String& path)
  42008. {
  42009. const auto file = lynx::shot::file (juce::File (path));
  42010. file.deleteFile();
  42011. juce::PNGImageFormat png;
  42012. if (auto out = file.createOutputStream())
  42013. png.writeImageToStream (lynx::shot::snapshot (c, area), *out);
  42014. }
  42015. static void savePng (const juce::Image& image, const juce::String& path)
  42016. {
  42017. const auto file = lynx::shot::file (juce::File (path));
  42018. file.deleteFile();
  42019. juce::PNGImageFormat png;
  42020. if (auto out = file.createOutputStream())
  42021. png.writeImageToStream (image, *out);
  42022. }
  42023. // -toolbar-tips.png: the top of the window with the bubbles of a few controls as they appear under the
  42024. // mouse; -tips-sheet.png: every quick tip of the window, to check names, shortcuts and translations
  42025. static void saveQuickTips (lynx::MainComponent& ui, const juce::String& prefix)
  42026. {
  42027. const auto tips = ui.getQuickTipsForSnapshot();
  42028. const auto top = juce::Rectangle<int> (0, 0, ui.getWidth(), juce::jmin (ui.getHeight(), ui.getToolbarBoundsForSnapshot().getHeight() + 72));
  42029. auto image = lynx::shot::snapshot (ui, top);
  42030. {
  42031. juce::Graphics g (image);
  42032. lynx::shot::logical (g);
  42033. const juce::String shown[] = { lynx::tr ("Pattern mode"), lynx::tr ("Play"), lynx::tr ("Metronome"), lynx::tr ("Mixer"), lynx::tr ("Save project"),
  42034. lynx::tr ("Window options"), lynx::tr ("Close") };
  42035. std::vector<juce::Rectangle<int>> used;
  42036. for (const auto& [area, tip] : tips)
  42037. {
  42038. const auto name = tip.upToFirstOccurrenceOf ("\t", false, false);
  42039. if (std::find (std::begin (shown), std::end (shown), name) == std::end (shown))
  42040. continue;
  42041. const auto bubble = lynx::ui::quickTipBounds (tip, area, top);
  42042. if (std::any_of (used.begin(), used.end(), [&] (const auto& r) { return r.intersects (bubble); }))
  42043. continue;
  42044. used.push_back (bubble);
  42045. g.setColour (juce::Colours::white.withAlpha (0.075f)); // the hovered control
  42046. g.fillRoundedRectangle (area.toFloat().reduced (0.5f), lynx::theme::radius::md);
  42047. lynx::ui::paintQuickTip (g, bubble.toFloat(), tip);
  42048. }
  42049. }
  42050. savePng (image, prefix + "-toolbar-tips.png");
  42051. // the sheet: bubbles in rows
  42052. const int width = 900;
  42053. int x = 12, y = 12;
  42054. std::vector<std::pair<juce::Rectangle<int>, juce::String>> placed;
  42055. for (const auto& [area, tip] : tips)
  42056. {
  42057. auto r = lynx::ui::quickTipSize (tip);
  42058. if (x + r.getWidth() > width - 12)
  42059. {
  42060. x = 12;
  42061. y += r.getHeight() + 10;
  42062. }
  42063. placed.emplace_back (r.withPosition (x, y), tip);
  42064. x += r.getWidth() + 10;
  42065. }
  42066. auto sheet = lynx::shot::canvas (width, y + 20 + 12);
  42067. {
  42068. juce::Graphics g (sheet);
  42069. lynx::shot::logical (g);
  42070. g.fillAll (lynx::theme::colour::bg3);
  42071. for (const auto& [r, tip] : placed)
  42072. lynx::ui::paintQuickTip (g, r.toFloat(), tip);
  42073. }
  42074. savePng (sheet, prefix + "-tips-sheet.png");
  42075. }
  42076. static juce::StringArray& textFitLog()
  42077. {
  42078. static juce::StringArray log;
  42079. return log;
  42080. }
  42081. // drawFittedText would shrink `text` below `minScale` or cut it: fewer visible glyphs than the text has
  42082. static bool textIsCut (const juce::Font& font, const juce::String& text, juce::Rectangle<int> area, int maxLines, float minScale)
  42083. {
  42084. if (text.trim().isEmpty() || area.getWidth() <= 4 || area.getHeight() <= 4)
  42085. return false;
  42086. auto visible = [] (juce::GlyphArrangement& ga) {
  42087. int n = 0;
  42088. for (int i = 0; i < ga.getNumGlyphs(); ++i)
  42089. n += ga.getGlyph (i).isWhitespace() ? 0 : 1;
  42090. return n;
  42091. };
  42092. juce::GlyphArrangement fitted, full;
  42093. fitted.addFittedText (font, text, 0.0f, 0.0f, (float) area.getWidth(), (float) area.getHeight(), juce::Justification::centredLeft,
  42094. juce::jmax (1, maxLines), minScale);
  42095. full.addLineOfText (font, text, 0.0f, 0.0f);
  42096. return visible (fitted) < visible (full);
  42097. }
  42098. // walks the visible components under `root` and logs the texts that don't fit (labels, text buttons, tick boxes)
  42099. static void checkTextFit (juce::Component& root, const juce::String& where)
  42100. {
  42101. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  42102. if (! c.isVisible() || c.getWidth() <= 0 || c.getHeight() <= 0)
  42103. return;
  42104. juce::String text;
  42105. bool cut = false;
  42106. if (auto* label = dynamic_cast<juce::Label*> (&c); label != nullptr && ! label->isBeingEdited())
  42107. {
  42108. const auto font = label->getLookAndFeel().getLabelFont (*label);
  42109. const auto area = label->getBorderSize().subtractedFrom (label->getLocalBounds());
  42110. text = label->getText();
  42111. cut = textIsCut (font, text, area, juce::jmax (1, (int) ((float) area.getHeight() / font.getHeight())),
  42112. label->getMinimumHorizontalScale());
  42113. }
  42114. else if (auto* toggle = dynamic_cast<juce::ToggleButton*> (&c))
  42115. {
  42116. const auto tick = juce::jmin (16.0f, (float) c.getHeight() - 4.0f);
  42117. text = toggle->getButtonText();
  42118. cut = textIsCut (juce::Font (lynx::theme::font (juce::jmin ((float) lynx::theme::type::body, (float) c.getHeight() * 0.75f))), text,
  42119. c.getLocalBounds().withTrimmedLeft (juce::roundToInt (tick) + 8).withTrimmedRight (2), 2, 0.85f);
  42120. }
  42121. else if (auto* button = dynamic_cast<juce::TextButton*> (&c);
  42122. button != nullptr && (int) button->getProperties().getWithDefault (lynx::theme::LookAndFeel::iconProperty, 0) == 0)
  42123. {
  42124. text = button->getButtonText();
  42125. cut = textIsCut (button->getLookAndFeel().getTextButtonFont (*button, button->getHeight()), text,
  42126. button->getLocalBounds().reduced (juce::jmin (8, button->getWidth() / 6), 0), 2, 0.85f);
  42127. }
  42128. if (cut)
  42129. {
  42130. juce::String path;
  42131. for (auto* p = &c; p != nullptr && p != &root; p = p->getParentComponent())
  42132. if (p->getName().isNotEmpty())
  42133. path = p->getName() + (path.isEmpty() ? "" : "/") + path;
  42134. const auto line = where + " | " + juce::String (c.getWidth()) + "x" + juce::String (c.getHeight()) + " | " + text.replace ("\n", "\\n")
  42135. + (path.isEmpty() ? juce::String() : " | " + path);
  42136. textFitLog().addIfNotAlreadyThere (line);
  42137. }
  42138. for (auto* child : c.getChildren())
  42139. visit (*child);
  42140. };
  42141. visit (root);
  42142. }
  42143. static void saveSnapshot (juce::Component& c, const juce::String& path)
  42144. {
  42145. checkTextFit (c, juce::File (path).getFileNameWithoutExtension());
  42146. const auto file = lynx::shot::file (juce::File (path));
  42147. file.deleteFile();
  42148. juce::PNGImageFormat png;
  42149. if (auto out = file.createOutputStream())
  42150. png.writeImageToStream (lynx::shot::snapshot (c), *out);
  42151. }
  42152. class MainWindow final : public juce::DocumentWindow
  42153. {
  42154. public:
  42155. MainWindow (const juce::String& name, lynx::AudioEngine& engine)
  42156. : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons, false)
  42157. {
  42158. probeEngine = &engine;
  42159. // (round 190hd) one desktop window, made with the native title bar: before, JUCE made one with its own title
  42160. // bar and setUsingNativeTitleBar made it again (~20-35 ms each, the Direct2D context included)
  42161. setUsingNativeTitleBar (true);
  42162. addToDesktop();
  42163. setIcon (lynx::logoImage());
  42164. startupTrace.mark (" window: its desktop window (native title bar), icon");
  42165. content = new lynx::MainComponent (engine);
  42166. setContentOwned (content, true);
  42167. startupTrace.mark (" window: content set");
  42168. setResizable (true, true);
  42169. setResizeLimits (800, 400, 10000, 10000);
  42170. // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
  42171. // display: the AppImage catalog test runs on an 800x600 screen)
  42172. if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
  42173. {
  42174. const auto area = display->userArea;
  42175. const auto fit = [] (int design, int available) {
  42176. return juce::jmin (available, juce::jmax (design, (int) (available * 0.88)));
  42177. };
  42178. setSize (fit (getWidth(), area.getWidth()), fit (getHeight(), area.getHeight()));
  42179. }
  42180. centreWithSize (getWidth(), getHeight());
  42181. // where it was last time (round 167v); the first start opens maximized, the Playlist filling the screen
  42182. // with the Browser at the left and the Channel Rack above it, like FL Studio's first start
  42183. const auto saved = stateFile().loadFileAsString().trim();
  42184. // (LYNX_TEST_MODE keeps the fixed-size window scripted checks expect, unless LYNX_TEST_MAXIMIZE=1)
  42185. const auto firstStart = saved.isEmpty()
  42186. && (! lynx::platform::testMode() || juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MAXIMIZE", {}) == "1");
  42187. maximiseOnReveal = firstStart || saved.startsWithIgnoreCase ("fs");
  42188. if (saved.isNotEmpty())
  42189. restoreWindowStateFromString (saved.startsWithIgnoreCase ("fs") ? saved.substring (2).trim() : saved);
  42190. }
  42191. // Shows the window (built hidden while the splash screen is up).
  42192. void reveal()
  42193. {
  42194. if (lynx::uitrace::enabled()) // LYNX_TRACE_UI: the frames per second and the longest gap in ui.log (round 173f)
  42195. watchFrames ({});
  42196. setVisible (true);
  42197. // LYNX_LOCATOR_PROBE=1 (round 190ip, measurements): a floating window with a locator moving 30 times a second
  42198. if (juce::SystemStats::getEnvironmentVariable ("LYNX_LOCATOR_PROBE", {}) == "1")
  42199. juce::Timer::callAfterDelay (1500, [e = probeEngine] {
  42200. lynx::ui::openLocatorProbe ([e] {
  42201. const auto& transport = e->getTransport();
  42202. const auto bar = (double) juce::jmax<std::int64_t> (1, e->getSong().barTicks());
  42203. return transport.playing.load() ? std::fmod (transport.positionTicks.load(), bar) / bar : -1.0;
  42204. });
  42205. });
  42206. lynx::applyWindowChrome (*this);
  42207. lynx::fitWindowOnScreen (*this); // a size saved at another UI zoom still fits (round 163)
  42208. if (maximiseOnReveal)
  42209. setFullScreen (true); // (a title-bar window: maximized, the taskbar stays)
  42210. toFront (true);
  42211. content->grabKeyboardFocus();
  42212. // issue #62: the detached panels restored with the layout (built before this window was shown): their saved
  42213. // place and above it, once the window manager has placed this one
  42214. juce::Timer::callAfterDelay (250, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  42215. if (safe != nullptr)
  42216. safe->content->restoreDetachedWindows();
  42217. });
  42218. }
  42219. // Runs `then` once, right after the window's next frame (round 190go: the audio device opens behind the
  42220. // window's first frame, not before it); at the latest after 300 ms (a window that paints nothing: minimised).
  42221. void whenPainted (std::function<void()> then)
  42222. {
  42223. afterPaint = std::move (then);
  42224. afterPaintPosted = false;
  42225. repaint();
  42226. juce::Timer::callAfterDelay (300, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  42227. if (safe != nullptr)
  42228. safe->runAfterPaint();
  42229. });
  42230. }
  42231. void runAfterPaint()
  42232. {
  42233. if (auto then = std::exchange (afterPaint, nullptr))
  42234. then();
  42235. }
  42236. // The window's place and maximized state for the next start (main-window.txt in the settings folder).
  42237. void saveState() { stateFile().replaceWithText (getWindowStateAsString()); }
  42238. static juce::File stateFile() { return lynx::PluginHost::settingsFolder().getChildFile ("main-window.txt"); }
  42239. void openFile (const juce::File& file) { content->openFile (file); }
  42240. lynx::MainComponent& getContent() { return *content; }
  42241. void showSetupWizard() { content->showSetupWizard(); }
  42242. void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
  42243. void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
  42244. // Every frame the window paints, with its dirty area (ui/FrameProbe.h; --uiperf, LYNX_TRACE_UI). The trace keeps
  42245. // counting when --uiperf watches too.
  42246. void watchFrames (std::function<void (double, juce::Rectangle<int>)> callback)
  42247. {
  42248. if (probe == nullptr)
  42249. {
  42250. probe = std::make_unique<lynx::ui::FrameProbe>();
  42251. Component::addAndMakeVisible (*probe); // (ResizableWindow hides the plain overload)
  42252. probe->setBounds (getLocalBounds());
  42253. }
  42254. probe->onFrame = [callback = std::move (callback)] (double now, juce::Rectangle<int> area) {
  42255. if (lynx::uitrace::enabled())
  42256. lynx::uitrace::frame (now);
  42257. if (callback)
  42258. callback (now, area);
  42259. };
  42260. }
  42261. void resized() override
  42262. {
  42263. DocumentWindow::resized();
  42264. if (probe != nullptr)
  42265. probe->setBounds (getLocalBounds());
  42266. }
  42267. // --uiperf: the time of each frame the window paints (its own paint, then every child's, up to the last)
  42268. std::function<void (double)> onFrame;
  42269. void paint (juce::Graphics& g) override
  42270. {
  42271. if (onFrame)
  42272. frameStart = juce::Time::getMillisecondCounterHiRes();
  42273. DocumentWindow::paint (g);
  42274. }
  42275. void paintOverChildren (juce::Graphics& g) override
  42276. {
  42277. DocumentWindow::paintOverChildren (g);
  42278. if (afterPaint != nullptr && ! std::exchange (afterPaintPosted, true)) // (the frame is presented first)
  42279. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainWindow> (this)] {
  42280. if (safe != nullptr)
  42281. safe->runAfterPaint();
  42282. });
  42283. if (onFrame && frameStart > 0.0)
  42284. onFrame (juce::Time::getMillisecondCounterHiRes() - frameStart);
  42285. frameStart = 0.0;
  42286. }
  42287. private:
  42288. lynx::MainComponent* content = nullptr; // owned by the window
  42289. std::unique_ptr<lynx::ui::FrameProbe> probe; // (on top of the content; see watchFrames)
  42290. double frameStart = 0.0;
  42291. bool maximiseOnReveal = false;
  42292. std::function<void()> afterPaint; // (whenPainted)
  42293. lynx::AudioEngine* probeEngine = nullptr; // (LYNX_LOCATOR_PROBE)
  42294. bool afterPaintPosted = false;
  42295. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  42296. };
  42297. lynx::theme::LookAndFeel lookAndFeel;
  42298. std::unique_ptr<lynx::AudioEngine> engine;
  42299. std::unique_ptr<lynx::RemoteControl> remoteControl;
  42300. std::unique_ptr<juce::XmlElement> savedDeviceState; // --rtstress: the user's device before this run's --type/--buffer
  42301. // Hidden test mode --asiodll "<driver.dll>[|{CLSID}]" (REA round 97): an ASIO driver loaded straight from its file,
  42302. // without registering it, listed as the driver type "ASIO driver file". True when one was added.
  42303. bool addDriverFileDeviceType()
  42304. {
  42305. const auto args = juce::JUCEApplication::getCommandLineParameterArray();
  42306. const auto i = args.indexOf ("--asiodll");
  42307. if (i < 0 || i + 1 >= args.size() || engine == nullptr)
  42308. return false;
  42309. auto& devices = engine->getDeviceManager();
  42310. devices.getAvailableDeviceTypes(); // creates the standard types first
  42311. for (auto* t : devices.getAvailableDeviceTypes())
  42312. if (t->getTypeName() == lynx::dllAsioTypeName)
  42313. return true;
  42314. auto type = lynx::makeDllAsioDeviceType (args[i + 1].unquoted());
  42315. if (type == nullptr)
  42316. return false;
  42317. devices.addAudioDeviceType (std::move (type));
  42318. return true;
  42319. }
  42320. void restoreSavedDeviceState()
  42321. {
  42322. if (engine != nullptr)
  42323. engine->restoreAudioDeviceState (savedDeviceState.get());
  42324. }
  42325. std::unique_ptr<MainWindow> mainWindow;
  42326. std::unique_ptr<juce::Timer> perf; // --uiperf
  42327. std::unique_ptr<lynx::StartupSplash> splash;
  42328. static constexpr double landingSeconds = 1.05; // the logo's drop (SplashScreen::remainingDuration's `landing`)
  42329. std::shared_future<std::pair<juce::Image, double>> graphicsDeviceJob; // (round 190hd) holds the graphics device
  42330. bool graphicsDeviceMarked = false, windowRevealed = false;
  42331. std::future<std::shared_ptr<const lynx::SampleData>> startupSampleJob; // (round 190go: the built-in start-up sound)
  42332. bool startedAfterWindow = false, startupSoundPlayed = false;
  42333. double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
  42334. lynx::StartupOptions startupOptions;
  42335. juce::File fileToOpen;
  42336. bool startupFileHandled = false;
  42337. bool startWithoutPlugins = false; // --no-plugins project.lynx (round 190ap)
  42338. juce::String uncleanDevice; // round 190rp: "<type>: <name>" of the device the last session hung opening (uncleanDeviceOpen)
  42339. juce::File openTimeReport; // --opentime
  42340. int openTimeIdleSeconds = 10;
  42341. };
  42342. START_JUCE_APPLICATION (LynxApplication)