Main.cpp 2.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746
  1. #include <juce_gui_basics/juce_gui_basics.h>
  2. #include "engine/AraHost.h"
  3. #include "engine/FileSort.h"
  4. #include "platform/Paths.h"
  5. #include "core/SectionOps.h" // round 190ol (P1: the Sections lane)
  6. #include "core/SignatureEdit.h" // round 190ol (P6)
  7. #include "ui/SectionsLane190ol.h" // round 190ol (P1: the shot route drives the lane)
  8. #include "core/Offline.h"
  9. #include "core/GrooveAudio.h"
  10. #include "core/SmartDisableTip.h" // (round 190ok: --smarttipshot190ok)
  11. #include "core/EditorScale.h"
  12. #include "core/SimplePads.h"
  13. #include "core/ClipEnvelope.h"
  14. #include "core/ClipWarp.h"
  15. #include "core/KeyGuess.h"
  16. #include "core/EditorPolish.h"
  17. #include "core/FlpExport.h"
  18. #include "core/FruityBasicFx.h" // (round 190my: Fruity Balance in --details190myshot)
  19. #include "core/TrackClips.h"
  20. #include "core/Groove.h"
  21. #include "core/DrawMode.h"
  22. #include "core/SessionOps.h"
  23. #include "ui/ClipGridComponent.h"
  24. #include "ui/ArticulatorTools.h"
  25. #include "ui/ExternalDrag.h"
  26. #include "ui/LabelFont.h"
  27. #include "ui/SessionMixer.h"
  28. #include "core/FlSamplers.h"
  29. #include "core/ArrangeOps.h"
  30. #include "core/ClipSample.h"
  31. #include "core/WarpModes.h"
  32. #include "ui/ClipAudioPanel.h"
  33. #include "core/DetailChain.h"
  34. #include "core/SessionMixer.h"
  35. #include "core/PlaylistOps.h"
  36. #include "core/LastTweaked.h"
  37. #include "core/ClipOps.h"
  38. #include "core/TransportEdit.h" // (round 190jz: --issueshot190jz)
  39. #include "core/SamplerPage.h"
  40. #include "core/FlTrackMenus.h"
  41. #include "core/FlClipMenu.h"
  42. #include "core/OneClickRec.h"
  43. #include "core/WarpTools.h"
  44. #include "core/Comping.h"
  45. #include "core/ExportSilence.h"
  46. #include "core/Drumaxx.h"
  47. #include "core/PatternBlocks.h"
  48. #include "core/LoadTrace.h"
  49. #include "core/ProjectSafety.h"
  50. #include "core/Patcher.h"
  51. #include "core/Rack.h"
  52. #include "ui/RackEditor.h"
  53. #include "ui/HelixEditor.h"
  54. #include "ui/LynxModelEditor.h"
  55. #include "core/physmod/LynxModel.h"
  56. #include "core/PluginCatalog.h"
  57. #include "engine/GeneratorCatalog.h"
  58. #include "core/AlsDevices.h"
  59. #include "core/XmlLite.h"
  60. #include "ui/DrumRackShot.h"
  61. #include "ui/GroovePoolComponent.h"
  62. #include "core/Patcherize.h"
  63. #include "core/Performance.h"
  64. #include "core/VideoPlayer.h"
  65. #include "core/Effects.h"
  66. #include "core/MixSuite.h"
  67. #include "core/LowLifterFl.h" // (rollup step 12: the 0.1.28 copy item)
  68. #include "core/HardwareInsert.h"
  69. #include "core/EchoSuite.h"
  70. #include "core/LuxeVerb.h"
  71. #include "core/LynxVerbs.h"
  72. #include "core/LynxTune.h"
  73. #include "core/FlEffects.h"
  74. #include "core/FlpImport.h"
  75. #include "core/NoteEdit.h"
  76. #include "core/PlaylistTrackOps.h" // round 190jf (FoldersShot190jf.inc)
  77. #include "ui/DawProjectExport.h" // round 190jf (--dawprojcheck190jf)
  78. #include "ui/FlmExportDialog.h" // round 190og (--export-flm, --flmexportshot)
  79. #include "core/NoteNames.h"
  80. #include "core/MaximusFx.h"
  81. #include "core/ChainPresets.h"
  82. #include "core/GoalKnobs.h"
  83. #include "core/MasterLooks.h"
  84. #include "core/Harmor.h"
  85. #include "core/KiloheartsDsp.h" // (rollup step 14: the copy for 0.1.28 self-test)
  86. #include "core/WavetableSynth.h" // (round 190oc: the copy for 0.1.30 self-test)
  87. #include "core/AutoLook.h" // (rollup 0.1.31 step 4: the copy for 0.1.30 self-test)
  88. #include "flp/Flp.h"
  89. #include "core/DemoSongs.h"
  90. #include "core/FirstSongTour.h"
  91. #include "core/PerfProjects.h"
  92. #include "core/ShowcaseSong.h"
  93. #include "core/RenderAhead.h"
  94. #include "core/SynthPresets.h"
  95. #include "core/FlWrapper.h"
  96. #include "engine/AudioEngine.h"
  97. #include "engine/ProjectDowngrade.h"
  98. #include "ui/TrackerComponent.h"
  99. #include "core/ClipLauncher.h"
  100. #include "core/SimpleSteps.h"
  101. #include "core/DirectWaveState.h"
  102. #include "core/MixSnapshots.h"
  103. #include "core/VoiceShift.h"
  104. #include "core/PeakShapes.h" // rollup step 7: the copy for 0.1.28 self-test
  105. #include "core/DynamicsSuite.h"
  106. #include "core/TempoMarkers.h"
  107. #include "engine/RemoteControl.h"
  108. #include "engine/RemoteError.h"
  109. #include "ui/RemoteControlSettings.h"
  110. #include "engine/PreviewPlayer.h"
  111. #include "engine/Metronome.h"
  112. #include "engine/AudioLogger.h"
  113. #include "engine/DllAsioDevice.h"
  114. #include "engine/PipeWireDevice.h"
  115. #include "platform/LinuxRealtime.h"
  116. #include "engine/PowerHints.h"
  117. #include "engine/Exporter.h"
  118. #include "engine/AacEncoder.h"
  119. #include "engine/FlStudioExport.h"
  120. #include "engine/MidiFileIo.h"
  121. #include "engine/PluginHost.h"
  122. #include "engine/Vst3NoteTuning.h"
  123. #include "engine/PluginSandbox.h"
  124. #include "engine/Bridge32Test.h"
  125. #include "engine/ClapFormat.h"
  126. #include "engine/ClapTeardownTest.h"
  127. #include "engine/RenderAgainTest.h"
  128. #include "ui/TiltViewport.h"
  129. #if JUCE_LINUX
  130. #include <dlfcn.h> // (round 190ou: --hwheel254test presses X11 buttons through XTest)
  131. #endif
  132. #include "engine/HostingTests.h"
  133. #include "core/EdisonFx.h"
  134. #include "engine/ProjectFile.h"
  135. #include "ui/RemoteControl.h"
  136. #include "core/FlControlMenus.h"
  137. #include "core/PlaylistOps.h"
  138. #include "core/Sha256.h"
  139. #include "engine/SessionPack.h"
  140. #include "engine/LiveSessions.h"
  141. #include "engine/LiveTest.h"
  142. #include "engine/ShortExportTest.h"
  143. #include "core/SessionIds.h"
  144. #include "core/SessionParts.h"
  145. #include "engine/SampleLibrary.h"
  146. #include "engine/Text.h"
  147. #include "platform/FileTypes.h"
  148. #include "platform/Package.h"
  149. #include "core/AlsExport.h"
  150. #include "core/AlsImport.h"
  151. #include "core/PianoRollScript.h"
  152. #include "ui/ScriptPanel.h"
  153. #include "ui/AlsExportDialog.h"
  154. #include "ui/LiveRemoteUi.h"
  155. #include "ui/GamepadInput.h"
  156. #include "ui/SettingsPages.h"
  157. #include "ui/ExtendedHintPanel.h"
  158. #include "core/FlSettings.h"
  159. #include "ui/OtherAppsExport.h"
  160. #include "ui/TimerWhileShowing.h"
  161. #include "ui/MixerBasicsCheck.h"
  162. #include "ui/VideoPlayerView.h"
  163. #include "ui/VideoMedia.h"
  164. #include "ui/VideoTracks.h"
  165. #include "ui/AdrWindow.h"
  166. #include "ui/PluginPicker.h"
  167. #include "ui/PlaylistComponent.h"
  168. #include "ui/PictureCheck.h"
  169. #include "ui/PatternBlocksView.h"
  170. #include "ui/PaintAB.h"
  171. #include <typeinfo>
  172. #include "ui/PatcherEditor.h"
  173. #include "ui/VisualEditors.h"
  174. #include "ui/FlExtraEditors.h"
  175. #include "ui/VisualGl.h"
  176. #include "ui/DanceView.h"
  177. #include "ui/PluginPresetMenu.h"
  178. #include "ui/GeneratorPresetMenu.h"
  179. #include "core/GeneratorPresets.h"
  180. #include "ui/PluginWindow.h"
  181. #include "platform/NativeEmbed.h"
  182. #include "ui/Motion.h"
  183. #include "ui/ShotShowing.h"
  184. #include "ui/SimpleLook.h"
  185. #include "ui/NativeChild.h"
  186. #include "ui/FrameTicker.h"
  187. #include "ui/DockPaintCheck.h"
  188. #include "ui/Workspace.h"
  189. #include "ui/PluginThumbs.h"
  190. #include "ui/ClipProperties.h"
  191. #include "ui/NewProjectDialog.h"
  192. #include "ui/PluginMonitorWindow.h"
  193. #include "ui/TouchKeyboard.h"
  194. #include "ui/AutomationUi.h"
  195. #include "core/GrossBeatLocator.h"
  196. #include "ui/PluginSkin.h"
  197. #include "ui/ChannelSettings.h"
  198. #include "ui/TempoDetectionDialog.h"
  199. #include "ui/AudioClipboard.h"
  200. #include "ui/FlVoicePanel.h"
  201. #include "ui/SlicexEditor.h"
  202. #include "ui/DirectWaveEditor.h"
  203. #include "ui/FruitySlicerEditor.h"
  204. #include "core/GrossBeat.h"
  205. #include "core/LynxBanks.h"
  206. #include "core/NativeEngines.h"
  207. #include "ui/ControllerEditors.h"
  208. #include "ui/NewtoneEditor.h"
  209. #include "core/NewtoneFx.h"
  210. #include "core/FormulaController.h"
  211. #include "core/MidiControls.h"
  212. #include "core/FlSynths.h"
  213. #include "core/SoundFont.h"
  214. #include "core/Sfz.h"
  215. #include "core/Slicex.h"
  216. #include "ui/Dialogs.h"
  217. #include "ui/DialogFrame.h"
  218. #include "ui/FileChoosers.h"
  219. #include "ui/TrackIcons.h"
  220. #include "core/MeterScale.h"
  221. #include "core/RackOps.h"
  222. #include "core/Layer.h"
  223. #include "core/XyController.h"
  224. #include "core/FlCurve.h"
  225. #include "core/ControlSurface.h"
  226. #include "core/VoltageController.h"
  227. #include "ui/Controllers164.h"
  228. #include "core/StandIns.h"
  229. #include "ui/ExportDialog.h"
  230. #include "ui/QuickAddPalette.h"
  231. #include "ui/I18n.h"
  232. #include "ui/KeyFocus.h"
  233. #include "core/TrackIconScale.h"
  234. #include "core/EscClose.h"
  235. #include "ui/MainComponent.h"
  236. #include "ui/LynxWindows.h" // --tabs2test190nz (issue #232 stage 2)
  237. #include "ui/WindowClipboard.h"
  238. #include "ui/SimpleDock.h"
  239. #include "core/ScaleKeys.h"
  240. #include "core/KeyFollow.h"
  241. #include "core/SoundLibrary.h"
  242. #include "ui/MidiToolsPanel.h"
  243. #include "ui/FrameProbe.h"
  244. #include "ui/MotionOverlay.h"
  245. #include "ui/UiTrace.h"
  246. #include "core/MixerOps.h"
  247. #include "ui/QuickPick.h"
  248. #include "core/FolderWatcher.h"
  249. #include "core/FruityDynamics.h"
  250. #include "core/PluginDbFolder.h"
  251. #include "core/NoteTools.h"
  252. #include "engine/ProjectPackage.h"
  253. #include "ui/SetupWizard.h"
  254. #include "ui/DemoMode.h" // (round 190np)
  255. #if JUCE_LINUX || JUCE_WINDOWS // (rollup 0.1.31 step 2: Windows too, so --onboard190npshot runs its async callbacks there)
  256. namespace juce::detail { bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages); } // juce_Messaging_linux / _windows.cpp (--onboard190npshot)
  257. #endif
  258. #include "ui/Onboarding.h"
  259. #include "engine/FlStudio.h"
  260. #include "ui/HistoryPanel.h"
  261. #include "ui/VersionsPanel.h"
  262. #include "ui/CleanVoiceMenu.h"
  263. #include "ui/LyricsPanel.h"
  264. #include "ui/ReferenceMatchPanel.h"
  265. #include "ui/StartFromPanel.h"
  266. #include "ui/FirstSongTour.h"
  267. #include "ui/PluginsOffPanel.h"
  268. #include "ui/MissingFilesDialog.h"
  269. #include "ui/SettingsDialog.h"
  270. #include "ui/PluginManager.h"
  271. #include "ui/ShortcutManager.h"
  272. #include "ui/NoteToolDialogs.h"
  273. #include "ui/ChordStripView.h" // round 190kd (--prchord190kd)
  274. #include "ui/ChordHelper.h" // round 190mc (--modal190mc)
  275. #include "core/KeyRegions.h" // round chord2_190nu (--selftest, --keys190nu)
  276. #include "core/TransistorBass.h" // round 190mc (--modal190mc)
  277. #include "core/ModelParams.h" // round 190mc (--modal190mc)
  278. #include "ui/EventEditor.h"
  279. #include "ui/AudioEditor.h"
  280. #include "ui/SampleProperties.h"
  281. #include "ui/TempoTapper.h"
  282. #include "ui/ProjectPickerView.h" // (round 190my)
  283. #include "ui/WindowPlaces.h" // (round 190oa)
  284. #include "ui/HintBar.h" // (round 190oa)
  285. #include "core/EventEdit.h"
  286. #include "core/FacetEq.h"
  287. #include "core/LimiterLaw.h" // (rollup step 9: the copy for 0.1.28 self-test)
  288. #include "core/ApexLimiter.h" // (rollup step 10: likewise)
  289. #include "core/Reeverb2.h"
  290. #include "core/VoiceTools.h"
  291. #include "platform/ThreadInstructions.h" // (rollup step 9: --paintbench counts instructions)
  292. #include "ui/FacetEqEditor.h"
  293. #include "core/RackRenderer.h"
  294. #include "ui/ProEditors.h"
  295. #include "ui/ParametricEqEditor.h"
  296. #include "ui/PluginEditors.h"
  297. #include "core/PluginLayout.h"
  298. #include "core/EffectPresets.h"
  299. #include "ui/PluginHeader.h"
  300. #include "core/Vfx.h"
  301. #include "core/TransistorBass.h"
  302. #include "ui/Splash.h"
  303. #include "ui/Theme.h"
  304. #include "ui/ThemeSettings.h"
  305. #include "ui/AutoLookEditor.h" // (round 190od, issue #239)
  306. #include "ui/WaveformView.h"
  307. #include "ui/WindowOwner.h"
  308. #include "ui/PluginKeysTest.h"
  309. #include "ui/ZOrder191Test.h"
  310. #include "ui/Toolbar.h"
  311. #include "ui/ToolWindow.h"
  312. #include "core/Details190mv.h" // (round 190mv)
  313. #include "platform/CrashGuard.h"
  314. #include "ui/CrashReporter.h"
  315. #include "ui/Updater.h"
  316. #include "ui/AudioCheck.h"
  317. #include "ui/StemExtract.h"
  318. #include "core/RegionLoop.h" // round 190jr: --bandlab190jrshot
  319. #include "core/FactoryContent.h" // round 190ke: --simplegb190keshot
  320. #include "core/KeyFollow.h" // round 190kx: --loopinfo190kxshot
  321. #include "core/LoopAnalysis.h"
  322. #include "../tests/LoopCorpus190kx.h" // (LYNX's own synthetic loops, written for the shot)
  323. #include "core/SongFade.h"
  324. #include "core/SoundLibrary.h"
  325. #include "core/SynthParams.h"
  326. #include "core/GoalKnobs.h"
  327. #include "core/DetailChain.h"
  328. #include "ui/FinishDock.h"
  329. #include "ui/SimpleDock.h"
  330. #include "ui/SimpleTuner.h"
  331. #include "ui/AudioToMidi.h"
  332. #include "ui/PolyEditor.h"
  333. #include "core/PolyEdit.h"
  334. #include "ui/ShotScale.h"
  335. #include "core/LaneView.h" // round 190iu
  336. #include "core/PlaylistTrackOps.h"
  337. #include "core/MidiDrop.h"
  338. #include "core/TakeCleanup.h"
  339. #include "core/TrackOnly.h"
  340. #include "core/WheelZones.h"
  341. #include "ui/WorkflowExtras.h"
  342. #include "core/Links.h"
  343. #include <algorithm>
  344. #include <set> // (round 190jf: --dawprojcheck190jf)
  345. #include <atomic>
  346. #include <exception>
  347. #include <chrono>
  348. #include <cstdio>
  349. #include <ctime>
  350. #include <cstdlib>
  351. #include <future>
  352. #include <mutex>
  353. #include <thread>
  354. namespace
  355. {
  356. lynx::AudioEngine* crashEngine = nullptr;
  357. // Startup trace (REA round 116): with LYNX_TRACE_STARTUP set, the time of each startup step since the C++ runtime
  358. // started is written to %APPDATA%\LYNX\startup.log (the loader's own time before that is not included).
  359. struct StartupTrace
  360. {
  361. using clock = std::chrono::steady_clock;
  362. const clock::time_point t0 = clock::now(); // static initialisation: no JUCE yet, standard library only
  363. const std::chrono::system_clock::time_point t0System = std::chrono::system_clock::now(); // (round 190hd: vs the process's creation)
  364. // (round 190go: always kept, as a field-readable start-up timeline; written to startup.log 5 s and 15 s after the
  365. // window — with LYNX_TRACE_STARTUP set, at every step as before, so a start that hangs still leaves its last step)
  366. const bool on = true;
  367. const bool eachStep = std::getenv ("LYNX_TRACE_STARTUP") != nullptr;
  368. juce::String text;
  369. clock::time_point last = t0;
  370. std::int64_t lastPrivate = 0;
  371. double seconds() const { return std::chrono::duration<double> (clock::now() - t0).count(); } // since the process started
  372. void mark (const char* step)
  373. {
  374. if (! on)
  375. return;
  376. const auto now = clock::now();
  377. const auto ms = [] (clock::duration d) { return std::chrono::duration<double, std::milli> (d).count(); };
  378. // (round 190gd: the process's memory after each step too, so the log says where the megabytes of a start go)
  379. const auto mb = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1).paddedLeft (' ', 7); };
  380. const auto priv = lynx::toolbar::PerformanceMeter::processPrivateBytes();
  381. const auto ws = lynx::toolbar::PerformanceMeter::processMemoryBytes();
  382. text << juce::String (ms (now - t0), 1).paddedLeft (' ', 8) << " ms +" << juce::String (ms (now - last), 1).paddedLeft (' ', 7)
  383. << " private " << mb (priv) << " MB (+" << mb (priv - lastPrivate).trim() << ") ws " << mb (ws) << " MB " << step << "\n";
  384. lastPrivate = priv;
  385. last = now;
  386. if (eachStep)
  387. write();
  388. }
  389. void write() const { lynx::platform::settingsFile ("startup.log").replaceWithText (text); }
  390. };
  391. StartupTrace startupTrace;
  392. void startupMarkHook (const char* step) { startupTrace.mark (step); }
  393. juce::File crashFolderForTest; // --faulttest: where the crash file goes instead of the settings' autosave folder
  394. // Crashed: try to save the project and write the backtrace (like FL's "emergency save").
  395. void onCrash (void* exceptionPointers)
  396. {
  397. // round 190oh (Windows): a fault on a hosted plugin's own thread that nothing handled — that thread waits for good
  398. // inside this call and the main window's timer switches the plugin off (crashguard::parkFaultingPluginThread)
  399. if (lynx::crashguard::parkFaultingPluginThread (exceptionPointers))
  400. return;
  401. // (round 190ci: once. The hook for stacks Windows cannot walk, crashguard::setUnwalkableFaultHandler, may have run
  402. // this before the top-level filter does)
  403. static std::atomic<bool> reported { false };
  404. if (reported.exchange (true))
  405. return;
  406. // rollup 0.1.30 step 12 (owner decision after round 190mo): whatever follows, the process ends within the watchdog's
  407. // time (60 s): after a heap corruption everything below that allocates can wait for ever on the allocator's lock
  408. lynx::crashguard::armCrashWatchdog (exceptionPointers);
  409. // ... and after the C library's (or Windows') heap-corruption abort, nothing that allocates runs at all: a crash file
  410. // written without the heap, no session note, no emergency save (the project in memory may be what was broken)
  411. if (lynx::crashguard::heapCorruptionCrash (exceptionPointers))
  412. {
  413. lynx::crashguard::writeHeapCrashFile (exceptionPointers);
  414. return;
  415. }
  416. const auto folder = crashFolderForTest != juce::File() ? crashFolderForTest : lynx::platform::settingsFile ("autosave");
  417. folder.createDirectory();
  418. const auto stamp = juce::Time::getCurrentTime().formatted ("%Y-%m-%d %H-%M-%S");
  419. // JUCE's backtrace (named frames only), then every frame of the faulting thread as module+offset (round 157a: a
  420. // release LYNX.exe has no symbols, so its own frames were missing from the file)
  421. folder.getChildFile ("crash " + stamp + ".txt").replaceWithText (juce::SystemStats::getStackBacktrace() + "\n--- frames (module+offset)\n"
  422. + juce::String::fromUTF8 (lynx::crashguard::exceptionBacktrace (exceptionPointers).c_str()));
  423. lynx::crashguard::note (("crashed: backtrace in autosave\\crash " + stamp + ".txt").toStdString());
  424. if (lynx::crashguard::hangInCrashHandlerForTest()) // (--faulttest hang: a handler that never returns; the watchdog ends it)
  425. for (;;)
  426. std::this_thread::sleep_for (std::chrono::seconds (1));
  427. if (crashEngine != nullptr)
  428. {
  429. juce::String error;
  430. lynx::ProjectFile::save (crashEngine->getSong(), folder.getChildFile ("recovered " + stamp + lynx::ProjectFile::extension), error);
  431. }
  432. }
  433. juce::File sessionsFolder()
  434. {
  435. return lynx::PluginHost::settingsFolder().getChildFile ("sessions");
  436. }
  437. // Sessions of earlier runs whose process is gone without closing (a fail-fast, a crash, a forced end): each is appended
  438. // to %APPDATA%\LYNX\crash-history.log and its file removed. Returns the last step of the newest one ("" when none).
  439. juce::StringArray uncleanSteps; // the newest unclean session's steps (without their times)
  440. juce::String uncleanSessionText; // the newest unclean session's whole file (round 159: the crash report reads it)
  441. // What the newest unclean session tells (round 157a): the plugin whose editor was opening / shown when it ended, and
  442. // whether its crash file blames a graphics driver
  443. struct UncleanCause
  444. {
  445. juce::String editorPlugin; // the last steps were that plugin's editor
  446. bool gpuDriver = false; // the crash file's top frames are in a GPU driver / Direct3D / Direct2D module
  447. juce::String driverModule;
  448. };
  449. UncleanCause uncleanCause()
  450. {
  451. UncleanCause cause;
  452. juce::File crashFile;
  453. for (int i = uncleanSteps.size(); --i >= 0 && i >= uncleanSteps.size() - 4;)
  454. {
  455. const auto& step = uncleanSteps[i];
  456. if (step.startsWith ("crashed: backtrace in "))
  457. crashFile = lynx::platform::settingsFolder().getChildFile (step.fromFirstOccurrenceOf ("backtrace in ", false, false).replaceCharacter ('\\', '/'));
  458. for (const auto* prefix : { "opening the editor of ", "editor open: ", "editor shown: " })
  459. if (cause.editorPlugin.isEmpty() && step.startsWith (prefix))
  460. cause.editorPlugin = step.fromFirstOccurrenceOf (prefix, false, false).trim();
  461. if (step.startsWith ("closing the editor of ") || step.startsWith ("loaded plugin") || step.startsWith ("opening project"))
  462. break; // older steps than these did not end the session
  463. }
  464. // issue #32 (round 174a): a plugin whose editor already faulted in this session (caught, LYNX went on) is the
  465. // likely cause when the session then ended without a word: offer it a separate process too
  466. for (int i = uncleanSteps.size(); --i >= 0 && cause.editorPlugin.isEmpty();)
  467. if (const auto editor = lynx::crashreport::parseEditorCrashStep (uncleanSteps[i].toStdString()); ! editor.plugin.empty())
  468. cause.editorPlugin = juce::String::fromUTF8 (editor.plugin.c_str());
  469. if (crashFile.existsAsFile())
  470. {
  471. // the first frames after the crash handler's own (the "--- frames" part lists the faulting thread)
  472. auto text = crashFile.loadFileAsString();
  473. if (text.contains ("--- frames"))
  474. text = text.fromFirstOccurrenceOf ("--- frames", false, false);
  475. auto lines = juce::StringArray::fromLines (text);
  476. int looked = 0;
  477. for (const auto& line : lines)
  478. {
  479. const auto module = line.fromFirstOccurrenceOf (": ", false, false).upToFirstOccurrenceOf ("+", false, false).trim().toLowerCase();
  480. if (module.isEmpty() || ! module.endsWith (".dll"))
  481. continue;
  482. if (++looked > 12)
  483. break;
  484. for (const auto* driver : { "igd", "ig9icd", "ig7icd", "igxelp", "nvwgf2um", "nvoglv", "nvd3dum", "atidxx", "atio6axx", "amdxx", "aticfx",
  485. "d3d11.dll", "d3d10warp", "dxgi.dll", "d2d1.dll", "opengl32.dll", "dcomp.dll" })
  486. if (module.startsWith (driver))
  487. {
  488. cause.gpuDriver = true;
  489. cause.driverModule = module;
  490. break;
  491. }
  492. if (cause.gpuDriver)
  493. break;
  494. }
  495. }
  496. return cause;
  497. }
  498. juce::String collectUncleanSessions()
  499. {
  500. juce::String lastStep;
  501. juce::Time newest;
  502. for (const auto& file : sessionsFolder().findChildFiles (juce::File::findFiles, false, "session-*.txt"))
  503. {
  504. const auto text = file.loadFileAsString();
  505. juce::StringPairArray values;
  506. juce::StringArray steps;
  507. for (const auto& line : juce::StringArray::fromLines (text))
  508. {
  509. if (line.startsWith ("step="))
  510. steps.add (line.fromFirstOccurrenceOf ("=", false, false));
  511. else if (line.contains ("="))
  512. values.set (line.upToFirstOccurrenceOf ("=", false, false), line.fromFirstOccurrenceOf ("=", false, false));
  513. }
  514. const auto pid = (std::uint32_t) values["pid"].getLargeIntValue();
  515. const auto start = (std::uint64_t) values["start"].getLargeIntValue();
  516. if (pid == lynx::crashguard::processId() || lynx::crashguard::processRunning (pid, start))
  517. continue; // this run, or another LYNX window still open
  518. lynx::PluginHost::settingsFolder().getChildFile ("crash-history.log")
  519. .appendText (juce::Time::getCurrentTime().toISO8601 (true) + " previous session ended without closing\n" + text + "\n");
  520. file.deleteFile();
  521. if (const auto modified = file.getLastModificationTime(); lastStep.isEmpty() || modified > newest)
  522. {
  523. newest = modified;
  524. lastStep = steps.isEmpty() ? juce::String ("start-up") : steps[steps.size() - 1].fromFirstOccurrenceOf (" ", false, false);
  525. uncleanSessionText = text;
  526. uncleanSteps.clear();
  527. for (const auto& step : steps)
  528. uncleanSteps.add (step.fromFirstOccurrenceOf (" ", false, false));
  529. }
  530. }
  531. return lastStep;
  532. }
  533. } // namespace
  534. // --uiperf (round 173f, discussion #10): a mixer fader dragged up and down with the mouse while the pattern plays. A
  535. // high-resolution timer delivers 125 moves a second to the message thread through the window's own mouse path
  536. // (ComponentPeer::handleMouseEvent), at most one waiting at a time as Windows does with WM_MOUSEMOVE; every frame the
  537. // window paints tells whether it covered the fader. Measured: how long a move waited for the message thread, the time
  538. // from a move to the first frame that shows the fader after it (input → paint), and whether the value stays put when
  539. // the mouse is released.
  540. #if JUCE_WINDOWS
  541. namespace juce
  542. {
  543. extern int lynxD2DPresents; // (cmake/LynxPatchJuce.cmake, round 190gv: every Direct2D window present)
  544. }
  545. #endif
  546. // round 190jy: --uiperf's presents per second (190kb's cycles line reads it too)
  547. static int uiPerfPresents()
  548. {
  549. #if JUCE_WINDOWS
  550. return juce::lynxD2DPresents;
  551. #else
  552. return 0;
  553. #endif
  554. }
  555. struct UiPerfDrag final : public std::enable_shared_from_this<UiPerfDrag>,
  556. private juce::HighResolutionTimer
  557. {
  558. ~UiPerfDrag() override { stopTimer(); }
  559. void start (juce::Component& windowIn, juce::Component& strips, juce::Rectangle<int> rail, lynx::AudioEngine* engineIn, int trackIn)
  560. {
  561. window = &windowIn;
  562. engine = engineIn;
  563. track = trackIn;
  564. railInWindow = window->getLocalArea (&strips, rail);
  565. watch = railInWindow.expanded (6, 40); // the cap, its tip above and the dB read-out below
  566. visible = strips.isShowing() && window->getLocalArea (&strips, strips.getLocalBounds()).contains (railInWindow.getCentre());
  567. const auto volume = engine->getSong().mixer[(std::size_t) track].volume;
  568. x = (float) railInWindow.getCentreX();
  569. startY = (float) railInWindow.getBottom() - volume * (float) railInWindow.getHeight(); // on the cap: no jump
  570. amplitude = 0.4f * (float) railInWindow.getHeight();
  571. centreY = juce::jlimit ((float) railInWindow.getY() + amplitude, (float) railInWindow.getBottom() - amplitude, startY);
  572. t0 = juce::Time::getMillisecondCounterHiRes();
  573. inject (x, startY, false);
  574. juce::ModifierKeys::currentModifiers = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  575. inject (x, startY, true);
  576. active = true;
  577. startTimer (8);
  578. }
  579. // message thread
  580. void framePainted (double now, juce::Rectangle<int> area)
  581. {
  582. if (pending.empty() || ! area.intersects (watch))
  583. return;
  584. for (const auto t : pending)
  585. latencies.push_back (now - t);
  586. pending.clear();
  587. ++framesOverFader;
  588. }
  589. // the moves end; as in the reporter's clip, the song is stopped while the button is still down
  590. juce::String stop()
  591. {
  592. stopTimer();
  593. active = false;
  594. valueAtRelease = engine->getSong().mixer[(std::size_t) track].volume;
  595. engine->stop();
  596. juce::String text;
  597. text << " drag of insert " << track << "'s fader" << (visible ? "" : " (NOT VISIBLE)") << ": " << moves << " moves handled, " << dropped
  598. << " folded into the next (the message thread still busy with the previous one)\n"
  599. << " move waited for the message thread: " << describe (queueDelays) << "\n"
  600. << " input -> paint (move to the first frame over the fader): " << describe (latencies) << ", " << framesOverFader
  601. << " frames over the fader\n";
  602. return text;
  603. }
  604. juce::String release()
  605. {
  606. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  607. juce::ModifierKeys::currentModifiers = {};
  608. inject (x, lastY, false);
  609. return " song stopped, button still down: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " at the last move) "
  610. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  611. }
  612. juce::String released() const
  613. {
  614. const auto now = engine->getSong().mixer[(std::size_t) track].volume;
  615. return " after the release: fader " + juce::String (now, 4) + " (" + juce::String (valueAtRelease, 4) + " when released) "
  616. + (std::abs (now - valueAtRelease) < 1.0e-4f ? "kept" : "CHANGED") + "\n";
  617. }
  618. private:
  619. juce::Component* window = nullptr;
  620. lynx::AudioEngine* engine = nullptr;
  621. int track = 1;
  622. juce::Rectangle<int> railInWindow, watch;
  623. bool visible = false;
  624. float x = 0.0f, startY = 0.0f, centreY = 0.0f, amplitude = 0.0f, lastY = 0.0f;
  625. double t0 = 0.0;
  626. std::atomic<bool> active { false }, posted { false };
  627. std::atomic<int> dropped { 0 };
  628. int moves = 0, framesOverFader = 0;
  629. float valueAtRelease = 0.0f;
  630. std::vector<double> pending, latencies, queueDelays;
  631. static juce::String describe (std::vector<double> v)
  632. {
  633. if (v.empty())
  634. return "none";
  635. std::sort (v.begin(), v.end());
  636. const auto at = [&v] (double q) { return v[std::min (v.size() - 1, (std::size_t) (q * (double) v.size()))]; };
  637. return "p50 " + juce::String (at (0.5), 1) + " / p95 " + juce::String (at (0.95), 1) + " / p99 " + juce::String (at (0.99), 1) + " / max "
  638. + juce::String (v.back(), 1) + " ms";
  639. }
  640. void inject (float px, float py, bool down)
  641. {
  642. lastY = py;
  643. if (auto* peer = window != nullptr ? window->getPeer() : nullptr)
  644. {
  645. const auto local = peer->globalToLocal (window->localPointToGlobal (juce::Point<float> (px, py)));
  646. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local,
  647. down ? juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier) : juce::ModifierKeys(),
  648. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation,
  649. juce::Time::currentTimeMillis());
  650. }
  651. }
  652. void hiResTimerCallback() override
  653. {
  654. if (! active.load())
  655. return;
  656. if (posted.exchange (true))
  657. {
  658. ++dropped;
  659. return;
  660. }
  661. const auto postedAt = juce::Time::getMillisecondCounterHiRes();
  662. juce::MessageManager::callAsync ([self = shared_from_this(), postedAt] {
  663. self->posted = false;
  664. if (! self->active.load())
  665. return;
  666. const auto now = juce::Time::getMillisecondCounterHiRes();
  667. self->queueDelays.push_back (now - postedAt);
  668. // up and down ~1.3 times a second, like the reporter's hand
  669. const auto y = self->centreY + self->amplitude * (float) std::sin (2.0 * juce::MathConstants<double>::pi * 1.3 * (now - self->t0) / 1000.0);
  670. self->inject (self->x, y, true);
  671. self->pending.push_back (postedAt);
  672. ++self->moves;
  673. });
  674. }
  675. };
  676. class LynxApplication final : public juce::JUCEApplication
  677. {
  678. public:
  679. const juce::String getApplicationName() override { return JUCE_APPLICATION_NAME_STRING; }
  680. const juce::String getApplicationVersion() override { return JUCE_APPLICATION_VERSION_STRING; }
  681. // the plugin scan runs copies of LYNX as child processes
  682. bool moreThanOneInstanceAllowed() override { return true; }
  683. // A file handed to the running application. macOS does this for every Finder double-click, "Open With" and Dock drop,
  684. // also the one that starts LYNX (its argv has no file). On Windows and Linux a second start is a second process
  685. // (moreThanOneInstanceAllowed) with the file as an argument, so this is not called there. Only the first file of a
  686. // multiple selection opens: a project replaces the one before it. (D#92, round 180a)
  687. void anotherInstanceStarted (const juce::String& commandLine) override
  688. {
  689. const auto files = lynx::safety::filesInCommandLine (commandLine.toStdString());
  690. if (files.empty())
  691. return;
  692. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile (juce::String::fromUTF8 (files.front().c_str()));
  693. if (! startupFileHandled) // still starting: openStartupFile takes it, nothing to ask about yet
  694. {
  695. fileToOpen = file;
  696. return;
  697. }
  698. if (mainWindow != nullptr)
  699. {
  700. mainWindow->toFront (true);
  701. mainWindow->getContent().openFileRequest (file);
  702. }
  703. }
  704. void initialise (const juce::String& commandLine) override
  705. {
  706. // round 190nx: --offline (or LYNX_OFFLINE=1) = no network connection of LYNX's own, before anything can start one
  707. if (juce::StringArray::fromTokens (commandLine, true).contains ("--offline"))
  708. lynx::offline::set (true);
  709. // round 166b: the copy of LYNX.exe that installs an update (ui/Updater.h) waits, installs, starts LYNX again
  710. if (commandLine.contains ("--apply-update") && lynx::updater::runApplyHelper (juce::StringArray::fromTokens (commandLine, true)))
  711. {
  712. updateHelper = true;
  713. quit();
  714. return;
  715. }
  716. // Windows, LYNX.exe in a folder with accents: run again from its ASCII short path (Waves editors crash otherwise)
  717. if (int code = 0; lynx::platform::relaunchFromAsciiPath (code))
  718. {
  719. relaunched = true;
  720. setApplicationReturnValue (code);
  721. quit();
  722. return;
  723. }
  724. // a crash in any mode (UI, command line) writes its backtrace to %APPDATA%\LYNX\autosave
  725. juce::SystemStats::setApplicationCrashHandler (onCrash);
  726. // rollup step 12: the crash handler's watchdog and its allocation-free crash file (platform/CrashGuard.h)
  727. lynx::crashguard::prepareCrashWatchdog (lynx::platform::settingsFile ("autosave").getFullPathName().toStdString());
  728. // rollup 0.1.28 (REA 190hb action 4, FL's "Init DWM"): the compositor on MMCSS, steadier frames under CPU load
  729. // (Windows; LYNX_DWM_MMCSS=0 leaves it off)
  730. lynx::powerhints::enableCompositorMmcss();
  731. // round als190ka (issue #193): a video's sound track for the sample library (a Live set's video clips)
  732. lynx::SampleLibrary::setVideoSoundDecoder ([] (const juce::File& video) { return lynx::videotracks::soundTrackWav (video); });
  733. // round 190ci: also for a fault on a stack Windows cannot walk, which never reaches that handler (Windows)
  734. lynx::crashguard::setUnwalkableFaultHandler (onCrash);
  735. if (const auto args = juce::StringArray::fromTokens (commandLine, true); args.contains ("--faulttest"))
  736. {
  737. // LYNX.exe --faulttest plain|unwalkable <folder> (round 190ci): ends by an access violation on purpose,
  738. // before any window, so that --selftest can check that the crash file gets written (into <folder>)
  739. const auto i = args.indexOf ("--faulttest");
  740. crashFolderForTest = juce::File (args[i + 2].unquoted());
  741. lynx::crashguard::setCrashFolder (crashFolderForTest.getFullPathName().toStdString());
  742. lynx::crashguard::quietCrashReports();
  743. // rollup step 12: heap = the C library's heap-corruption abort (no recovered project may be written: an
  744. // engine is set for the emergency save on purpose); hang = a crash handler that never returns (the watchdog
  745. // must end the process: LYNX_CRASH_WATCHDOG_S makes the test short)
  746. if (args[i + 1] == "heap" || args[i + 1] == "hang")
  747. {
  748. static lynx::AudioEngine* engine = new lynx::AudioEngine (false);
  749. crashEngine = engine;
  750. if (args[i + 1] == "heap")
  751. lynx::crashguard::heapCorruptionForTest();
  752. lynx::crashguard::setHangInCrashHandlerForTest();
  753. lynx::crashguard::faultForTest (false);
  754. }
  755. // round 190dt: guarded / guarded-libc = LYNX's own fault inside a guarded plugin call (Linux / macOS): it must
  756. // reach the crash handler like any other; a return means the guard swallowed it
  757. // round 190gg: thread / thread-libc = a fault on a thread of LYNX's own, with LYNX's executable watched as
  758. // a plugin's module: it must not be parked as a plugin's thread
  759. if (args[i + 1].startsWith ("thread"))
  760. {
  761. lynx::crashguard::faultOnOwnThreadForTest (args[i + 1] == "thread-libc");
  762. crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText ("parked");
  763. lynx::crashguard::exitNow (4);
  764. }
  765. if (args[i + 1].startsWith ("guarded"))
  766. {
  767. const auto code = lynx::crashguard::faultInGuardedCallForTest (args[i + 1] == "guarded-libc");
  768. crashFolderForTest.getChildFile ("swallowed.txt").replaceWithText (lynx::crashguard::describe (code));
  769. lynx::crashguard::exitNow (4);
  770. }
  771. lynx::crashguard::faultForTest (args[i + 1] == "unwalkable");
  772. }
  773. lynx::crashguard::hardenSignals(); // issue #115: stack overflows and SIGTERM / SIGHUP leave a trace (Linux / macOS)
  774. // SFZ instruments (round 167o): their FLAC / OGG / AIFF / MP3 samples through JUCE's readers
  775. lynx::sfz::setDecoder ([] (const std::string& path, lynx::sfz::Audio& out) {
  776. juce::AudioFormatManager formats;
  777. formats.registerBasicFormats();
  778. std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (juce::File (juce::String::fromUTF8 (path.c_str()))));
  779. if (reader == nullptr || reader->lengthInSamples <= 0 || reader->lengthInSamples > (1 << 28) || reader->numChannels == 0)
  780. return false;
  781. const auto frames = (int) reader->lengthInSamples;
  782. juce::AudioBuffer<float> buffer ((int) std::min (2u, reader->numChannels), frames);
  783. if (! reader->read (&buffer, 0, frames, 0, true, buffer.getNumChannels() > 1))
  784. return false;
  785. out.channels.clear();
  786. for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
  787. out.channels.emplace_back (buffer.getReadPointer (ch), buffer.getReadPointer (ch) + frames);
  788. out.sampleRate = reader->sampleRate;
  789. out.loopStart = out.loopEnd = -1;
  790. return true;
  791. });
  792. // child process of a sandboxed plugin: no window or audio of its own
  793. if (lynx::runPluginSandboxWorker (commandLine))
  794. {
  795. lynx::crashguard::quietCrashReports();
  796. sandboxChild = true;
  797. return;
  798. }
  799. // --shot-scale <v> / --shot-suffix <text> (round 190bi, ui/ShotScale.h): the pixel scale and file-name suffix of every
  800. // picture route, taken out here so the routes' own arguments keep their places
  801. const auto args = lynx::shot::takeArguments (juce::StringArray::fromTokens (commandLine, true));
  802. // round 190np: whether this profile already had LYNX's UI settings before this start (an upgrade keeps what it had:
  803. // no welcome card), and --demo (ui/DemoMode.h: the tutorial-video pipeline's automation mode)
  804. lynx::onboardui::profileExistedAtStart() = lynx::PluginHost::settingsFolder().getChildFile ("ui-options.txt").existsAsFile();
  805. if (args.contains ("--demo"))
  806. lynx::demo::setActive (true);
  807. // interface language: saved in %APPDATA%\LYNX\language.txt; --lang pt-BR overrides it for this run
  808. lynx::i18n::initialise (args);
  809. // interface font: saved in Settings › General; --uifont "Name" overrides it for this run
  810. const auto uiFontArg = args.indexOf ("--uifont");
  811. lookAndFeel.applyInterfaceFont (lynx::i18n::current(), uiFontArg >= 0 ? args[uiFontArg + 1].unquoted() : juce::String());
  812. // text size (issue #189): saved in Settings › General; --textsize 125 overrides it for this run
  813. const auto textSizeArg = args.indexOf ("--textsize");
  814. lynx::theme::setTextSize (textSizeArg >= 0 ? args[textSizeArg + 1].getIntValue() : lynx::theme::savedTextSize());
  815. // bold text (round 190jp): saved in Settings › General; --boldtext 1 (labels) or 2 (all) overrides it for this run
  816. const auto boldTextArg = args.indexOf ("--boldtext");
  817. lynx::theme::setBoldText (boldTextArg >= 0 ? args[boldTextArg + 1].getIntValue() : lynx::theme::savedBoldText());
  818. // round 190je: FL-style condensed labels (Settings › General); --condensedlabels for one run. --menustyle flClassic: FL's
  819. // light menus for one run (Settings › Theme keeps the saved choice)
  820. lynx::theme::setCondensedLabels (args.contains ("--condensedlabels") || lynx::theme::savedCondensedLabels());
  821. if (const auto menuStyleArg = args.indexOf ("--menustyle"); menuStyleArg >= 0)
  822. {
  823. lynx::theme::menus::setStyle (lynx::themes::menuStyleFromId (args[menuStyleArg + 1].unquoted().toStdString()));
  824. lookAndFeel.refreshColours();
  825. }
  826. if (args.contains ("--showcase"))
  827. {
  828. // LYNX's own demo project (README screenshots): --showcase output.lynx [pattern]
  829. const auto i = args.indexOf ("--showcase");
  830. runShowcase (args[i + 1].unquoted(), args[i + 2].getIntValue());
  831. return;
  832. }
  833. if (args.contains ("--demosongs"))
  834. {
  835. // round 190dv: LYNX's two short genre demos (core/DemoSongs.h) as .lynx files: --demosongs <folder>
  836. // (resources/demos/ in the repository)
  837. const auto i = args.indexOf ("--demosongs");
  838. runDemoSongs (args[i + 1].unquoted());
  839. return;
  840. }
  841. if (args.contains ("--perfgen"))
  842. {
  843. // round perfgate190id: the big-project performance gate's synthetic projects (core/PerfProjects.h) as .lynx
  844. // files with their WAVs: --perfgen <folder> [report.txt] [name,name...]; the save and load times in the report
  845. const auto i = args.indexOf ("--perfgen");
  846. const auto report = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  847. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  848. runPerfGen (args[i + 1].unquoted(), report, only);
  849. return;
  850. }
  851. if (args.contains ("--sandboxtest"))
  852. {
  853. const auto i = args.indexOf ("--sandboxtest");
  854. runSandboxTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  855. return;
  856. }
  857. // round 190jg (BUILD-LIST 11 + 18, engine/HostingTests.h): grouped plugin processes, CLAP extensions, timing
  858. if (args.contains ("--sandboxgrouptest") || args.contains ("--sandboxbench") || args.contains ("--clapext")
  859. || args.contains ("--automationtimingtest") || args.contains ("--pluginbench"))
  860. {
  861. const auto value = [&args] (const char* name, int fallback) {
  862. return args.contains (name) ? args[args.indexOf (name) + 1].getIntValue() : fallback;
  863. };
  864. auto code = 1;
  865. if (const auto i = args.indexOf ("--sandboxgrouptest"); i >= 0)
  866. code = lynx::runSandboxGroupTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  867. args.contains ("--crash") ? args[args.indexOf ("--crash") + 1].unquoted() : juce::String());
  868. else if (const auto b = args.indexOf ("--sandboxbench"); b >= 0)
  869. code = lynx::runSandboxBench (args[b + 1].unquoted(), args[b + 2].unquoted(), value ("--plugins", 8), value ("--block", 256),
  870. args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 5.0);
  871. else if (const auto pb = args.indexOf ("--pluginbench"); pb >= 0) // round 190of: per-plugin cost (engine/HostingTests.h)
  872. code = lynx::runPluginBench (args[pb + 1].unquoted(), args[pb + 2].unquoted(), value ("--block", 256),
  873. args.contains ("--rate") ? args[args.indexOf ("--rate") + 1].getDoubleValue() : 48000.0,
  874. args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 4.0, value ("--types", 8),
  875. args.contains ("--names") ? args[args.indexOf ("--names") + 1].unquoted() : juce::String(),
  876. args.contains ("--editors"));
  877. else if (const auto c = args.indexOf ("--clapext"); c >= 0)
  878. code = lynx::runClapExtTest (args[c + 1].unquoted(), args[c + 2].unquoted());
  879. else if (const auto t = args.indexOf ("--automationtimingtest"); t >= 0)
  880. code = lynx::runAutomationTimingTest (args[t + 1].unquoted(), args[t + 2].unquoted());
  881. setApplicationReturnValue (code);
  882. quit();
  883. return;
  884. }
  885. if (args.contains ("--bridge32test"))
  886. {
  887. // LYNX.exe --bridge32test "LYNX Test Synth 32.dll" report.txt [--compare "LYNX Test Synth.dll"] (round 176a):
  888. // the 32-bit plugin bridge (engine/Bridge32Test.cpp)
  889. const auto i = args.indexOf ("--bridge32test");
  890. const auto compare = args.contains ("--compare") ? args[args.indexOf ("--compare") + 1].unquoted() : juce::String();
  891. setApplicationReturnValue (lynx::runBridge32Test (args[i + 1].unquoted(), args[i + 2].unquoted(), compare));
  892. quit();
  893. return;
  894. }
  895. if (args.contains ("--rtstress"))
  896. {
  897. // LYNX.exe --rtstress project.(flp|lynx) report.txt [seconds] [--buffer N] [--type "driver type"] [--device "output"]
  898. // [--no-window] [--record take.wav]: the real app (window, audio device) plays the project and reports the callbacks
  899. // that missed their deadline (REA round 87); --type/--device pick another driver for this run only (round 97);
  900. // --record also records the input during the run, like Rec + Play, and moves the take to take.wav (round 106)
  901. const auto i = args.indexOf ("--rtstress");
  902. const auto seconds = args[i + 3].getDoubleValue();
  903. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  904. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  905. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  906. runRealtimeStress (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), seconds > 0.0 ? seconds : 30.0, buffer,
  907. option ("--type"), option ("--device"), option ("--record"));
  908. return;
  909. }
  910. if (args.contains ("--renderaheadtest"))
  911. {
  912. // LYNX --renderaheadtest report.txt [project.flp|.lynx ...] [--buffer N] [--seconds S] (round 190gq): the engine's
  913. // own device callback (a stand-in device driven block by block, as --cliplooptest) plays the showcase song (from
  914. // the start, round a loop region that wraps mid-block, in Pattern mode) and each project with Options › Audio
  915. // settings › "Render ahead" off, then on. The two outputs must be the same to the bit, nothing rendered ahead
  916. // may be dropped, and most blocks must come from the ring. No window, no audio device.
  917. const auto i = args.indexOf ("--renderaheadtest");
  918. juce::StringArray projects;
  919. for (int k = i + 2; k < args.size() && ! args[k].startsWith ("--"); ++k)
  920. projects.add (args[k].unquoted());
  921. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 128;
  922. const auto seconds = args.contains ("--seconds") ? args[args.indexOf ("--seconds") + 1].getDoubleValue() : 12.0;
  923. runRenderAheadTest (juce::File (args[i + 1].unquoted()), projects, juce::jlimit (16, 2048, buffer), seconds > 0.0 ? seconds : 12.0);
  924. return;
  925. }
  926. if (args.contains ("--cliplooptest"))
  927. {
  928. // LYNX --cliplooptest report.txt [export.wav] (round 167q, issue #25: 0.1.21 drew the repeats of a stretched
  929. // pattern clip but played the pattern once). The real engine's device callback (a stand-in device, driven
  930. // block by block) plays a synth's 1-bar pattern in a 4-bar clip: every repeat must sound as bar 1, also
  931. // starting inside a repeat, after a jump mid-clip and in a loop region; the WAV export (written to
  932. // export.wav and read back) the same. With the LYNX extra off, bars 2-4 must be silent (FL's behaviour).
  933. const auto i = args.indexOf ("--cliplooptest");
  934. runClipLoopTest (juce::File (args[i + 1].unquoted()), args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File());
  935. return;
  936. }
  937. if (args.contains ("--devicechangetest"))
  938. {
  939. // LYNX --devicechangetest report.txt [switches] [--plugin file]... (round 190c, issue #134: changing the
  940. // output device with a project open crashed LYNX). The engine plays a project of every instrument and effect
  941. // it can make here on stand-in devices with real callback threads, while the output device, its sample
  942. // rate and its buffer size change the way Settings > Audio changes them (8 kHz mono to 192 kHz, buffers of
  943. // 32 to 16384 samples, a device plugged in, the open one unplugged, one that refuses to open). After every
  944. // change the song must sound, finite, at the new rate. No window, no real audio or MIDI device.
  945. const auto i = args.indexOf ("--devicechangetest");
  946. const juce::File report (args[i + 1].unquoted());
  947. const auto switches = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  948. juce::StringArray plugins;
  949. for (int k = 0; k + 1 < args.size(); ++k)
  950. if (args[k] == "--plugin")
  951. plugins.add (args[k + 1].unquoted());
  952. auto text = std::make_shared<juce::String>();
  953. // --quick: the selftest's handful of instruments and effects instead of every one
  954. const auto result = lynx::AudioEngine::deviceChangeSelfTest (switches > 0 ? switches : 40, ! args.contains ("--quick"), plugins, [report, text] (const juce::String& line) {
  955. *text << line << "\n";
  956. report.replaceWithText (*text + "(running)\n"); // what was reached, if it crashes
  957. });
  958. *text << "device_change=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  959. report.replaceWithText (*text);
  960. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  961. quit();
  962. return;
  963. }
  964. if (args.contains ("--exportlivetest"))
  965. {
  966. // LYNX --exportlivetest report.txt [--plugin file]... (round 190jb): exports with the live plugin instances (as
  967. // FL renders) against playback on a stand-in device, the plugins given back afterwards. No window.
  968. const auto i = args.indexOf ("--exportlivetest");
  969. const juce::File report (args[i + 1].unquoted());
  970. juce::StringArray files;
  971. for (int k = 0; k + 1 < args.size(); ++k)
  972. if (args[k] == "--plugin")
  973. files.add (args[k + 1].unquoted());
  974. juce::String text;
  975. const auto result = lynx::AudioEngine::exportLiveSelfTest ([&text] (const juce::String& line) { text << line << "\n"; }, files);
  976. text << "export_live=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  977. report.replaceWithText (text);
  978. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  979. quit();
  980. return;
  981. }
  982. if (args.contains ("--sharetest"))
  983. {
  984. // LYNX --sharetest <folder> <case> report.txt (round 190ks): the memory 8 identical SoundFont / Sampler channels
  985. // cost (LYNX_CONTENT_SHARE=0: byte copies held separately, as before). No window.
  986. const auto i = args.indexOf ("--sharetest");
  987. const auto result = lynx::AudioEngine::shareMemorySelfTest (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted());
  988. juce::File (args[i + 3].unquoted()).replaceWithText ("share=" + result + "\nresult=" + (result.startsWith ("OK") ? "OK" : "FAILED") + "\n");
  989. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  990. quit();
  991. return;
  992. }
  993. if (args.contains ("--padrectest"))
  994. {
  995. // LYNX --padrectest "<LYNX Test Pads.vst3>" report.txt (round 190ks, GitHub #198): a take records the notes a
  996. // hosted plugin plays from its own window (the live engine on a stand-in device). No window.
  997. const auto i = args.indexOf ("--padrectest");
  998. const auto result = lynx::AudioEngine::padRecordSelfTest (args[i + 1].unquoted());
  999. juce::File (args[i + 2].unquoted()).replaceWithText ("pad_record=" + result + "\nresult=" + (result.startsWith ("OK") ? "OK" : "FAILED") + "\n");
  1000. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1001. quit();
  1002. return;
  1003. }
  1004. if (args.contains ("--midiouttest"))
  1005. {
  1006. // LYNX --midiouttest report.txt (round 190jl): MIDI Out channels to the hardware MIDI outputs on their port
  1007. // (the sender's dry run and the live engine on a stand-in device). No window.
  1008. const auto i = args.indexOf ("--midiouttest");
  1009. const auto result = lynx::AudioEngine::midiOutPortSelfTest();
  1010. juce::File (args[i + 1].unquoted()).replaceWithText ("midi_out_ports=" + result + "\nresult=" + (result.startsWith ("OK") ? "OK" : "FAILED") + "\n");
  1011. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1012. quit();
  1013. return;
  1014. }
  1015. if (args.contains ("--aratest"))
  1016. {
  1017. // LYNX --aratest <plugin.vst3> <audio.wav> <out folder> [project.lynx] (round 190kx, engine/AraTest.cpp): ARA 2
  1018. // hosting end to end (a plain clip vs the clip in the ARA plugin, the document archived and restored). No window.
  1019. const auto i = args.indexOf ("--aratest");
  1020. const juce::File out (args[i + 3].unquoted());
  1021. juce::String text;
  1022. const auto result = lynx::araSelfTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), out,
  1023. args.size() > i + 4 ? juce::File (args[i + 4].unquoted()) : juce::File(),
  1024. [&text, out] (const juce::String& line) {
  1025. text << line << "\n";
  1026. out.getChildFile ("aratest.txt").replaceWithText (text + "(running)\n");
  1027. });
  1028. text << "ara=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1029. out.getChildFile ("aratest.txt").replaceWithText (text);
  1030. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1031. quit();
  1032. return;
  1033. }
  1034. if (args.contains ("--exportparitytest") || args.contains ("--midihotplugtest"))
  1035. {
  1036. // LYNX --exportparitytest report.txt (round 190gh, B7): the export against playback through a stand-in audio
  1037. // device, stems adding up to the mix with one length, the PDC trim. LYNX --midihotplugtest report.txt (B8):
  1038. // MIDI devices plugged in and out (stand-in device lists) while messages arrive. No window.
  1039. const auto parity = args.contains ("--exportparitytest");
  1040. const auto i = args.indexOf (parity ? "--exportparitytest" : "--midihotplugtest");
  1041. const juce::File report (args[i + 1].unquoted());
  1042. juce::String text;
  1043. const auto result = parity ? lynx::AudioEngine::exportParitySelfTest ([&text] (const juce::String& line) { text << line << "\n"; })
  1044. : lynx::AudioEngine::midiHotplugSelfTest();
  1045. text << (parity ? "export_parity=" : "midi_hotplug=") << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1046. report.replaceWithText (text);
  1047. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1048. quit();
  1049. return;
  1050. }
  1051. if (args.contains ("--shortexportstress"))
  1052. {
  1053. // LYNX --shortexportstress report.txt [count] [--seed N] [--no-realtime] [--plugin file] (round 190hn, issue #138): `count`
  1054. // random export settings over short sounds at the very start of the song, each exported again a bar later; a
  1055. // file that comes out silent or quieter fails (engine/ShortExportTest.h). No window.
  1056. const auto i = args.indexOf ("--shortexportstress");
  1057. const juce::File report (args[i + 1].unquoted());
  1058. const auto count = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 200;
  1059. const auto s = args.indexOf ("--seed");
  1060. const auto seed = s >= 0 && s + 1 < args.size() ? args[s + 1].getLargeIntValue() : juce::Time::currentTimeMillis();
  1061. auto text = std::make_shared<juce::String>();
  1062. const auto pl = args.indexOf ("--plugin");
  1063. lynx::shortexport::stress (count, seed, ! args.contains ("--no-realtime"), pl >= 0 && pl + 1 < args.size() ? args[pl + 1].unquoted() : juce::String(),
  1064. [report, text] (const juce::String& line) {
  1065. *text << line << "\n";
  1066. report.replaceWithText (*text + "(running)\n");
  1067. },
  1068. [this, report, text] (juce::String result) {
  1069. *text << "short_export_stress=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1070. report.replaceWithText (*text);
  1071. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1072. quit();
  1073. });
  1074. return;
  1075. }
  1076. if (args.contains ("--shortexporttest"))
  1077. {
  1078. // LYNX --shortexporttest report.txt [repeats] [--plugin file]... (round 190c, issue #138: a short note at
  1079. // the very start of the Playlist exported quiet). Every instrument LYNX can make here, and a synth with
  1080. // effects, tail modes, normalising and other rates, exported through the Export window's path (the job
  1081. // made on the message thread, run on its own thread, the message loop running) with a 2-second note at
  1082. // tick 0 and again with it at bar 2: the note must come out the same. No window.
  1083. const auto i = args.indexOf ("--shortexporttest");
  1084. const juce::File report (args[i + 1].unquoted());
  1085. const auto repeats = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getIntValue() : 0;
  1086. juce::StringArray plugins;
  1087. for (int k = 0; k + 1 < args.size(); ++k)
  1088. if (args[k] == "--plugin")
  1089. plugins.add (args[k + 1].unquoted());
  1090. auto text = std::make_shared<juce::String>();
  1091. lynx::shortexport::run (! args.contains ("--quick"), repeats > 0 ? repeats : 3, plugins, // (--quick: a handful of instruments, round 190hn)
  1092. [report, text] (const juce::String& line) {
  1093. *text << line << "\n";
  1094. report.replaceWithText (*text + "(running)\n");
  1095. },
  1096. [this, report, text] (juce::String result) {
  1097. *text << "short_export=" << result << "\nresult=" << (result.startsWith ("OK") ? "OK" : "FAILED") << "\n";
  1098. report.replaceWithText (*text);
  1099. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1100. quit();
  1101. });
  1102. return;
  1103. }
  1104. if (args.contains ("--slicexedittest"))
  1105. {
  1106. // LYNX --slicexedittest project script.txt report.txt [png-prefix] (round 190aj): the Slicex editor of the
  1107. // project's first Slicex channel, off screen, driven by the script's commands (ui/SlicexEditor.h; mouse
  1108. // gestures at fractions of the deck's width, the menu entries, shortcuts). The report holds each command
  1109. // and what the state held after it; "shot <name>" writes <png-prefix><name>.png.
  1110. const auto i = args.indexOf ("--slicexedittest");
  1111. runSlicexEditTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
  1112. args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
  1113. return;
  1114. }
  1115. if (args.contains ("--dwedittest"))
  1116. {
  1117. // LYNX --dwedittest project script.txt report.txt [png-prefix] (round 190hz): the DirectWave editor of the
  1118. // project's first DirectWave channel, off screen, driven by the script's commands (ui/DirectWaveEditor.h);
  1119. // "shot <name>" writes <png-prefix><name>.png. A project path "new" makes a new DirectWave channel.
  1120. const auto i = args.indexOf ("--dwedittest");
  1121. runDirectWaveEditTest (args[i + 1].unquoted(), juce::File (args[i + 2].unquoted()), juce::File (args[i + 3].unquoted()),
  1122. args.size() > i + 4 ? args[i + 4].unquoted() : juce::String());
  1123. return;
  1124. }
  1125. if (args.contains ("--slicexkeytest"))
  1126. {
  1127. // LYNX --slicexkeytest report.txt (round 190ac): what a click on the Slicex editor's keyboard sends
  1128. // (AudioEngine::sendLiveNote on the channel, velocity 100/128) through the real engine's device callback
  1129. // (a stand-in device, driven block by block): the key's region must sound, on the channel's mixer meter
  1130. // too, another key must play another region, and the note-off must end it.
  1131. runSlicexKeyTest (juce::File (args[args.indexOf ("--slicexkeytest") + 1].unquoted()));
  1132. return;
  1133. }
  1134. if (args.contains ("--countinrectest"))
  1135. {
  1136. // LYNX --countinrectest report.txt (round 170d, the Busy Works video: the chord on the downbeat after the
  1137. // pre-count was lost). The real engine's device callback (a stand-in device: 48 kHz, blocks of 512, 256
  1138. // samples of output latency) records a Song-mode take from bar 3 with a 1-bar count-in. Pass 1 finds where
  1139. // the metronome's bar-3 click is heard; pass 2 plays MIDI notes stamped at the times they are heard around
  1140. // 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
  1141. // LYNX's MIDI input. Every note must land on the tick it was heard at (the chord on bar 3).
  1142. const auto i = args.indexOf ("--countinrectest");
  1143. runCountInRecordTest (juce::File (args[i + 1].unquoted()));
  1144. return;
  1145. }
  1146. if (args.contains ("--bendrectest"))
  1147. {
  1148. // LYNX --bendrectest report.txt [song|pattern] (round 167a, issue #12): pitch bend recording end to end. A
  1149. // controller's pitch wheel is injected into LYNX's MIDI input (as a device would send it) while recording
  1150. // plays: a held note and a wheel sweep 0 → full up → full down → centre. The recorded lane (pattern mode) or
  1151. // automation clip (song mode) of the channel's pitch bend must follow the sweep.
  1152. const auto i = args.indexOf ("--bendrectest");
  1153. const auto songMode = args.size() > i + 2 && args[i + 2] == "song";
  1154. runBendRecordTest (juce::File (args[i + 1].unquoted()), songMode);
  1155. return;
  1156. }
  1157. if (args.contains ("--rectest"))
  1158. {
  1159. // LYNX --rectest report.txt [seconds] [--type T] [--device D] [--input I] [--loop] [--buffer N]
  1160. // (round 163): records a click track through a loopback (cable, interface loopback or PipeWire's
  1161. // pw-loopback): pings the round trip, plays a click on every beat from an audio clip, records it on Insert 1,
  1162. // stops, and checks every recorded click's song position on the Playlist against its beat (samples).
  1163. // --loop: loop recording over bars 2-4 (take lanes). --punch: punch in/out on bars 3-4 with 1 bar of pre-roll
  1164. // and 1 of post-roll (playback stops by itself after the post-roll).
  1165. const auto i = args.indexOf ("--rectest");
  1166. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  1167. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  1168. runRecordTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 20.0, option ("--type"), option ("--device"), option ("--input"),
  1169. args.contains ("--loop") ? 1 : args.contains ("--punch") ? 2 : 0, option ("--pdc").getIntValue(), option ("--buffer").getIntValue());
  1170. return;
  1171. }
  1172. if (args.contains ("--hwinserttest"))
  1173. {
  1174. // LYNX --hwinserttest report.txt [seconds] [--type T] [--device D] [--input I] [--buffer N] (round 164d): a
  1175. // hardware insert through a loopback cable (output pair 1-2 -> input pair 1-2; the Master plays nowhere, so
  1176. // the cable carries the send only). The same click track plays on two inserts: Insert 1 through the
  1177. // hardware insert (panned left), Insert 2 dry (panned right). The insert's own ping measures the round
  1178. // trip, PDC delays the dry path by it, and every click of the Master's left side must sit on the same
  1179. // sample as the right side's.
  1180. const auto i = args.indexOf ("--hwinserttest");
  1181. const auto option = [&args] (const char* name) { return args.contains (name) ? args[args.indexOf (name) + 1].unquoted() : juce::String(); };
  1182. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 10.0;
  1183. // round 165c: --patcher puts the insert inside a Patcher on Insert 1; --bounce file.wav then exports the song in real
  1184. // time through the device (Export › "Render through the hardware in real time") and offline, and compares them
  1185. runHwInsertTest (juce::File (args[i + 1].unquoted()), seconds > 0.0 ? seconds : 10.0, option ("--type"), option ("--device"), option ("--input"),
  1186. option ("--buffer").getIntValue(), args.contains ("--patcher"),
  1187. args.contains ("--bounce") ? juce::File (option ("--bounce")) : juce::File());
  1188. return;
  1189. }
  1190. if (args.contains ("--uiperf"))
  1191. {
  1192. // LYNX --uiperf project.(flp|lynx) report.txt: the heavy UI cases in the real window, every frame timed (round 161)
  1193. const auto i = args.indexOf ("--uiperf");
  1194. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1195. runUiPerf (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1196. return;
  1197. }
  1198. if (args.contains ("--cachetest"))
  1199. {
  1200. // LYNX --cachetest project.(flp|lynx) report.txt (round 174f): the Playlist's cached picture against exact
  1201. // paints after zooms, scrolls and repaints, off screen (no window)
  1202. const auto i = args.indexOf ("--cachetest");
  1203. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1204. runCacheTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  1205. return;
  1206. }
  1207. if (args.contains ("--picturetest"))
  1208. {
  1209. // LYNX --picturetest report.txt [project.(flp|lynx)] (round 190bm): the Playlist and the Mixer drawn through
  1210. // their cached pictures at 100-300 %, into native and software targets, against straight paints; off
  1211. // screen (no window)
  1212. const auto i = args.indexOf ("--picturetest");
  1213. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1214. runPictureTest (juce::File (args[i + 1].unquoted()), i + 2 < args.size() ? juce::File (args[i + 2].unquoted()) : juce::File());
  1215. return;
  1216. }
  1217. if (args.contains ("--paintcachetest"))
  1218. {
  1219. // LYNX --paintcachetest report.txt (round 190ki): --selftest's paint_caches item alone (the shape tiles, the
  1220. // cached FL toolbar tiles; LYNX_TILE_DEBUG=<folder> keeps the tiles' pictures as PNGs), off screen
  1221. const auto i = args.indexOf ("--paintcachetest");
  1222. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1223. auto result = lynx::theme::paintCacheSelfTest();
  1224. const auto tiles = lynx::flTileCacheSelfTest();
  1225. juce::File (args[i + 1].unquoted()).replaceWithText ("paint_caches=" + result + "\nfl_tiles=" + tiles + "\n");
  1226. setApplicationReturnValue (result.startsWith ("OK") && tiles == "OK" ? 0 : 1);
  1227. quit();
  1228. return;
  1229. }
  1230. if (args.contains ("--timertest"))
  1231. {
  1232. // LYNX --timertest report.txt (round 174f): ui::TimerWhileShowing through hide / show / minimise (opens a small window)
  1233. runTimerTest (juce::File (args[args.indexOf ("--timertest") + 1].unquoted()));
  1234. return;
  1235. }
  1236. if (args.contains ("--livepeer"))
  1237. {
  1238. // LYNX --livepeer host|guest|rejoin <folder> [--relay URL] [--code CODE|@file]: one computer's side of a live
  1239. // session between two real computers, no window (round 190ah)
  1240. setApplicationReturnValue (lynx::livetest::runPeer (args));
  1241. quit();
  1242. return;
  1243. }
  1244. if (args.contains ("--offlinetest"))
  1245. {
  1246. // LYNX --offlinetest report.txt [--offline] (round 190nx): with LYNX_OFFLINE=1 or --offline every place that
  1247. // would use the network refuses and says so. The test script runs it under `unshare -rn` with strace and counts
  1248. // the connect() calls of internet sockets: zero (tests/offline-network-test.sh)
  1249. const auto report = juce::File::getCurrentWorkingDirectory().getChildFile (args[args.indexOf ("--offlinetest") + 1].unquoted());
  1250. juce::String log;
  1251. bool ok = true;
  1252. auto check = [&] (bool good, const juce::String& what) {
  1253. ok = ok && good;
  1254. log << (good ? "ok " : "FAIL ") << what << "\n";
  1255. };
  1256. check (lynx::offline::enabled(), "offline mode is on");
  1257. {
  1258. std::string why;
  1259. check (! lynx::livelink::Connection::available (&why) && why.find ("offline") != std::string::npos, "live link unavailable: " + juce::String (why));
  1260. 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");
  1261. }
  1262. {
  1263. lynx::AudioEngine offlineEngine (false);
  1264. lynx::LiveSessionManager live (offlineEngine);
  1265. lynx::LiveSessionManager::Options o;
  1266. o.relay = "https://relay.lynx-share.com";
  1267. o.name = "Offline test";
  1268. o.inlineWork = true;
  1269. live.start (o);
  1270. check (live.getState() == lynx::LiveSessionManager::State::ended && ! live.isActive(), "Start live session refused: " + live.getStatus());
  1271. lynx::LiveSessionManager joiner (offlineEngine);
  1272. joiner.join ("LYNX-AAAA-AAAA-AAAA-AAAA-AAAA", o);
  1273. check (joiner.getState() == lynx::LiveSessionManager::State::ended && ! joiner.isActive(), "Join live session refused: " + joiner.getStatus());
  1274. }
  1275. {
  1276. const auto err = lynx::crashreporter::sendNow ("{\"offline\":\"test\"}");
  1277. check (err.containsIgnoreCase ("offline"), "crash report upload refused: " + err);
  1278. }
  1279. lynx::updater::startAutomaticCheck();
  1280. lynx::updater::checkNow();
  1281. lynx::updater::goBack();
  1282. check (true, "update check, update dialog and go-back opened no connection (see strace)");
  1283. log << (ok ? "RESULT OK\n" : "RESULT FAIL\n");
  1284. report.replaceWithText (log);
  1285. setApplicationReturnValue (ok ? 0 : 1);
  1286. quit();
  1287. return;
  1288. }
  1289. if (args.contains ("--livetest"))
  1290. {
  1291. // LYNX --livetest report.txt [--relay URL]: a live session of four peers over the relay (round 169b)
  1292. setApplicationReturnValue (lynx::livetest::run (args));
  1293. quit();
  1294. return;
  1295. }
  1296. if (args.contains ("--selftest"))
  1297. {
  1298. const auto i = args.indexOf ("--selftest");
  1299. // round 190mo: a temp folder of this run alone (two runs at once shared the fixed temp names of its items),
  1300. // and on Linux room for its main-thread stack (it reached 7.4 of the usual 8 MB: AudioEngines on the stack)
  1301. selfTestTemp = lynx::platform::useOwnTempFolder ("lynx-selftest");
  1302. lynx::platform::allowMainThreadStack ((std::size_t) 64 << 20);
  1303. runSelfTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1304. return;
  1305. }
  1306. if (args.contains ("--scan-one"))
  1307. {
  1308. // child process of the plugin scan (see PluginHost::scan)
  1309. const auto i = args.indexOf ("--scan-one");
  1310. // no crash dialogs from the plugin being examined; and once the result is written, the process ends without
  1311. // unloading it: a Waves shell crashed in its own teardown at exit (Intel GPU driver fail-fast, 0xC0000409),
  1312. // which showed Windows' crash dialog and made the scan reject the whole shell (round 111)
  1313. lynx::crashguard::quietCrashReports();
  1314. lynx::PluginHost::scanOneFile (args[i + 1].unquoted(), args[i + 2].unquoted(), juce::File (args[i + 3].unquoted()));
  1315. lynx::crashguard::exitNow (0);
  1316. }
  1317. if (args.contains ("--splashshot"))
  1318. {
  1319. // LYNX --splashshot <folder> (round 190hd): the splash card drawn as the JUCE card is and as the card on its own
  1320. // thread is (ui/Splash.h), side by side; no window
  1321. const auto shots = lynx::writeSplashShots (juce::File (args[args.indexOf ("--splashshot") + 1].unquoted()));
  1322. setApplicationReturnValue (shots.size() == 20 ? 0 : 1);
  1323. quit();
  1324. return;
  1325. }
  1326. if (args.contains ("--browser-indexer"))
  1327. {
  1328. // round 190hd: the Browser's indexer, a low-priority child of the LYNX window (BrowserComponent.h): no window,
  1329. // no session, no audio; it ends with its parent
  1330. lynx::crashguard::quietCrashReports();
  1331. lynx::crashguard::exitNow (lynx::BrowserComponent::runIndexerProcess (args));
  1332. }
  1333. if (args.contains ("--packageinfo"))
  1334. {
  1335. // round 165n: the Microsoft Store (MSIX) build's identity and folders (platform/Package.h); the release
  1336. // workflow runs it inside the installed test package
  1337. juce::File (args[args.indexOf ("--packageinfo") + 1].unquoted()).replaceWithText (lynx::platform::packageReport());
  1338. quit();
  1339. return;
  1340. }
  1341. if (args.contains ("--paths"))
  1342. {
  1343. // diagnostics: folders LYNX searches
  1344. const auto programs = juce::File::getSpecialLocation (juce::File::globalApplicationsDirectory);
  1345. juce::String report;
  1346. report << "programs=" << programs.getFullPathName() << "\n";
  1347. for (const auto& dir : programs.getChildFile ("Image-Line").findChildFiles (juce::File::findDirectories, false, "FL Studio*"))
  1348. report << "fl=" << dir.getFullPathName() << " packs=" << (int) dir.getChildFile ("Data").getChildFile ("Patches").getChildFile ("Packs").isDirectory() << "\n";
  1349. juce::File (args[args.indexOf ("--paths") + 1].unquoted()).replaceWithText (report);
  1350. quit();
  1351. return;
  1352. }
  1353. if (args.contains ("--fldb"))
  1354. {
  1355. // diagnostics: LYNX.exe --fldb report.txt [project.flp]: the FL Studio installation, its plugin database,
  1356. // the suggested plugin folders and, for a project, how each of its plugins resolves (read-only)
  1357. const auto i = args.indexOf ("--fldb");
  1358. const auto fl = lynx::findFlStudio();
  1359. lynx::PluginHost host (false);
  1360. juce::String report;
  1361. report << "install=" << fl.installDir.getFullPathName() << "\nuserdata=" << fl.userData.getFullPathName() << "\n";
  1362. for (const auto& f : fl.vstFolders)
  1363. report << "flvstfolder=" << f << "\n";
  1364. report << "dbfiles=" << host.flPluginDatabaseFiles() << " entries=" << (int) host.flPluginDatabase().entries().size() << "\n";
  1365. for (const auto& e : host.flPluginDatabase().entries())
  1366. report << " entry: " << juce::String::fromUTF8 (e.name.c_str()) << " | " << juce::String::fromUTF8 (e.path.c_str()) << " | role=" << e.role << "\n";
  1367. const auto suggested = host.suggestedFolders();
  1368. for (int k = 0; k < suggested.getNumPaths(); ++k)
  1369. report << "folder=" << suggested[k].getFullPathName() << "\n";
  1370. if (const juce::File project (args[i + 2].unquoted()); project.existsAsFile())
  1371. {
  1372. juce::MemoryBlock data;
  1373. project.loadFileAsData (data);
  1374. try
  1375. {
  1376. for (const auto& use : lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })))
  1377. {
  1378. juce::String how;
  1379. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  1380. const auto* entry = host.flPluginDatabase().match (use.plugin, use.instrument);
  1381. report << "plugin: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  1382. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known"))
  1383. << (entry != nullptr ? " | fl db: " + juce::String::fromUTF8 (entry->path.c_str()) : juce::String()) << "\n";
  1384. }
  1385. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  1386. const auto candidates = host.filesToScanFor (uses);
  1387. report << "scan_candidates=" << candidates.joinIntoString (";") << "\n";
  1388. if (args.contains ("--scan"))
  1389. {
  1390. // the targeted scan an open would run (child processes; the user's plugin list is not touched)
  1391. report << "scanned_new=" << host.scanFiles (candidates, {}) << "\n";
  1392. for (const auto& use : uses)
  1393. {
  1394. juce::String how;
  1395. const auto d = host.findForeign (use.plugin, use.instrument, &how);
  1396. report << "after_scan: " << juce::String::fromUTF8 (use.plugin.name.c_str()) << " -> "
  1397. << (d ? d->fileOrIdentifier + " (" + how + ")" : juce::String ("not known")) << "\n";
  1398. }
  1399. }
  1400. }
  1401. catch (const flp::Error& e)
  1402. {
  1403. report << "error=" << e.what() << "\n";
  1404. }
  1405. }
  1406. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1407. quit();
  1408. return;
  1409. }
  1410. if (args.contains ("--midisync-test"))
  1411. {
  1412. // LYNX --midisync-test report.txt ["output device"] ["input device"] (round 165f): MIDI clock timing
  1413. const auto i = args.indexOf ("--midisync-test");
  1414. const auto out = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1415. const auto in = args.size() > i + 3 && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1416. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::MidiSyncIo::selfTest (out, in));
  1417. quit();
  1418. return;
  1419. }
  1420. if (args.contains ("--linktest"))
  1421. {
  1422. // LYNX --linktest report.txt [seconds] [peer] (round 190gl): Ableton Link with simulated audio callbacks; with
  1423. // "peer" a second Link peer in this process, else a peer on the network (Ableton's LinkHut) is expected
  1424. const auto i = args.indexOf ("--linktest");
  1425. const auto seconds = args.size() > i + 2 && ! args[i + 2].startsWith ("--") ? args[i + 2].getDoubleValue() : 20.0;
  1426. const auto ownPeer = args.contains ("peer");
  1427. juce::File (args[i + 1].unquoted()).replaceWithText (juce::String (lynx::AbletonLink::selfTest (seconds > 0.0 ? seconds : 20.0, ownPeer)));
  1428. quit();
  1429. return;
  1430. }
  1431. if (args.contains ("--devices") || args.contains ("--dispositivos")) // --dispositivos: legacy alias
  1432. {
  1433. // diagnostics: driver types and output devices JUCE offers (without opening any)
  1434. juce::AudioDeviceManager manager;
  1435. juce::String report;
  1436. manager.getAvailableDeviceTypes();
  1437. if (auto pipeWire = lynx::makePipeWireDeviceType()) // Linux: LYNX's own PipeWire client (round 161)
  1438. manager.addAudioDeviceType (std::move (pipeWire));
  1439. #if JUCE_LINUX
  1440. report << lynx::describePipeWire() << "\n";
  1441. #endif
  1442. for (auto* type : manager.getAvailableDeviceTypes())
  1443. {
  1444. type->scanForDevices();
  1445. report << "type=" << type->getTypeName() << "\n";
  1446. for (const auto& name : type->getDeviceNames (false))
  1447. report << " output=" << name << "\n";
  1448. for (const auto& name : type->getDeviceNames (true))
  1449. report << " input=" << name << "\n";
  1450. }
  1451. for (const auto& d : juce::MidiInput::getAvailableDevices())
  1452. report << "midi-in=" << d.name << "\n";
  1453. for (const auto& d : juce::MidiOutput::getAvailableDevices())
  1454. report << "midi-out=" << d.name << "\n";
  1455. const auto flag = args.contains ("--devices") ? args.indexOf ("--devices") : args.indexOf ("--dispositivos");
  1456. juce::File (args[flag + 1].unquoted()).replaceWithText (report);
  1457. quit();
  1458. return;
  1459. }
  1460. if (args.contains ("--devicetest"))
  1461. {
  1462. // LYNX.exe --devicetest "type" "device" report.txt ["input device"] [--buffer N] [--roundtrip]: opens that output device (and, with the
  1463. // 4th argument, an input: "*" = the same device / the driver's default input), receives 1 s of callbacks
  1464. // writing silence, closes it and reports rate, block size, latency, callbacks and the input channels with
  1465. // their peak level (driver check, no sound). --roundtrip: clicks out, found again on input 1 through a loopback
  1466. // cable / PipeWire link: the round-trip latency (3 s)
  1467. const auto i = args.indexOf ("--devicetest");
  1468. const auto typeName = args[i + 1].unquoted(), deviceName = args[i + 2].unquoted();
  1469. auto inputName = args.size() > i + 4 && ! args[i + 4].startsWith ("--") ? args[i + 4].unquoted() : juce::String();
  1470. const auto wantInput = inputName.isNotEmpty();
  1471. juce::String report;
  1472. const juce::File reportFile (args[i + 3].unquoted());
  1473. auto step = [&] (const juce::String& line) { report << line << "\n"; reportFile.replaceWithText (report); }; // progress survives a driver that ends the process
  1474. step ("step=start");
  1475. juce::AudioDeviceManager manager;
  1476. manager.getAvailableDeviceTypes();
  1477. if (auto pipeWire = lynx::makePipeWireDeviceType())
  1478. manager.addAudioDeviceType (std::move (pipeWire));
  1479. std::unique_ptr<juce::AudioIODevice> device;
  1480. for (auto* type : manager.getAvailableDeviceTypes())
  1481. if (type->getTypeName() == typeName)
  1482. {
  1483. type->scanForDevices();
  1484. if (wantInput && type->hasSeparateInputsAndOutputs())
  1485. {
  1486. const auto inputs = type->getDeviceNames (true);
  1487. if (inputName == "*" || ! inputs.contains (inputName))
  1488. {
  1489. const auto index = type->getDefaultDeviceIndex (true);
  1490. inputName = juce::isPositiveAndBelow (index, inputs.size()) ? inputs[index] : juce::String();
  1491. }
  1492. for (const auto& n : inputs)
  1493. step ("input_device=" + n);
  1494. step ("input_chosen=" + inputName);
  1495. }
  1496. else if (wantInput)
  1497. inputName = deviceName;
  1498. step ("step=create");
  1499. device.reset (type->createDevice (deviceName, type->hasSeparateInputsAndOutputs() ? inputName : juce::String()));
  1500. step ("step=created");
  1501. }
  1502. struct Silence final : juce::AudioIODeviceCallback
  1503. {
  1504. std::atomic<int> calls { 0 }, inputs { 0 };
  1505. std::array<std::atomic<float>, 64> peaks {};
  1506. // --roundtrip (round 161): a click every quarter second on the outputs, found again on input 1 through a
  1507. // loopback; the delays in samples
  1508. bool roundtrip = false;
  1509. int period = 12000;
  1510. std::int64_t position = 0, lastClick = -1;
  1511. std::vector<int> delays;
  1512. void audioDeviceIOCallbackWithContext (const float* const* in, int numIn, float* const* out, int channels, int n,
  1513. const juce::AudioIODeviceCallbackContext&) override
  1514. {
  1515. for (int c = 0; c < channels; ++c)
  1516. if (out[c] != nullptr)
  1517. juce::FloatVectorOperations::clear (out[c], n);
  1518. if (roundtrip)
  1519. {
  1520. for (int i = 0; i < n; ++i)
  1521. {
  1522. if (numIn > 0 && in[0] != nullptr && lastClick >= 0 && std::abs (in[0][i]) > 0.5f)
  1523. {
  1524. if (delays.size() < delays.capacity())
  1525. delays.push_back ((int) (position + i - lastClick));
  1526. lastClick = -1;
  1527. }
  1528. if ((position + i) % period == 0 && position + i > 0)
  1529. {
  1530. for (int c = 0; c < channels; ++c)
  1531. if (out[c] != nullptr)
  1532. out[c][i] = 0.9f;
  1533. lastClick = position + i;
  1534. }
  1535. }
  1536. position += n;
  1537. }
  1538. inputs.store (numIn);
  1539. for (int c = 0; c < juce::jmin (numIn, 64); ++c)
  1540. if (in[c] != nullptr)
  1541. {
  1542. const auto range = juce::FloatVectorOperations::findMinAndMax (in[c], n);
  1543. const auto peak = juce::jmax (std::abs (range.getStart()), std::abs (range.getEnd()));
  1544. if (peak > peaks[(std::size_t) c].load())
  1545. peaks[(std::size_t) c].store (peak);
  1546. }
  1547. ++calls;
  1548. }
  1549. void audioDeviceAboutToStart (juce::AudioIODevice*) override {}
  1550. void audioDeviceStopped() override {}
  1551. } silence;
  1552. bool ok = false;
  1553. if (device == nullptr)
  1554. step ("error=device not found");
  1555. else
  1556. {
  1557. step ("step=open");
  1558. juce::BigInteger outputs;
  1559. outputs.setRange (0, 2, true);
  1560. const auto rates = device->getAvailableSampleRates();
  1561. const auto rate = device->getCurrentSampleRate() > 0 ? device->getCurrentSampleRate()
  1562. : rates.contains (48000.0) ? 48000.0 : rates.isEmpty() ? 44100.0 : rates[0];
  1563. step ("rates=" + juce::String (rates.size()) + " chosen=" + juce::String (rate) + " default_block=" + juce::String (device->getDefaultBufferSize()));
  1564. juce::BigInteger inputs;
  1565. if (wantInput)
  1566. {
  1567. const auto names = device->getInputChannelNames();
  1568. step ("input_channels=" + juce::String (names.size()));
  1569. for (int c = 0; c < names.size(); ++c)
  1570. step (" in" + juce::String (c + 1) + "=" + names[c]);
  1571. inputs.setRange (0, juce::jmin (64, names.size()), true);
  1572. }
  1573. // --buffer N: ask for that block size (REA round 97 latency survey); default: the driver's default
  1574. const auto wantedBlock = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 0;
  1575. const auto error = device->open (inputs, outputs, rate, wantedBlock > 0 ? wantedBlock : device->getDefaultBufferSize());
  1576. if (error.isNotEmpty())
  1577. step ("error=" + error);
  1578. else
  1579. {
  1580. step ("step=start_callbacks");
  1581. silence.roundtrip = args.contains ("--roundtrip");
  1582. silence.period = juce::jmax (1, (int) (rate / 4));
  1583. silence.delays.reserve (64);
  1584. device->start (&silence);
  1585. juce::Thread::sleep (silence.roundtrip ? 3000 : 1000);
  1586. device->stop();
  1587. if (silence.roundtrip)
  1588. {
  1589. auto d = silence.delays;
  1590. std::sort (d.begin(), d.end());
  1591. report << "roundtrip_clicks=" << (int) d.size() << "\n";
  1592. if (! d.empty())
  1593. report << "roundtrip_samples=min " << d.front() << " median " << d[d.size() / 2] << " max " << d.back() << "\n"
  1594. << "roundtrip_ms=" << juce::String (1000.0 * d[d.size() / 2] / device->getCurrentSampleRate(), 2) << "\n";
  1595. }
  1596. report << "rate=" << device->getCurrentSampleRate() << "\n"
  1597. << "block=" << device->getCurrentBufferSizeSamples() << "\n"
  1598. << "output_latency=" << device->getOutputLatencyInSamples() << "\n"
  1599. << "callbacks=" << silence.calls.load() << "\n";
  1600. if (wantInput)
  1601. {
  1602. report << "input_latency=" << device->getInputLatencyInSamples() << "\n"
  1603. << "active_inputs=" << device->getActiveInputChannels().countNumberOfSetBits() << "\n"
  1604. << "callback_inputs=" << silence.inputs.load() << "\n";
  1605. for (int c = 0; c < juce::jmin (64, silence.inputs.load()); ++c)
  1606. report << " peak_in" << (c + 1) << "=" << juce::Decibels::gainToDecibels (silence.peaks[(std::size_t) c].load(), -150.0f) << " dB\n";
  1607. }
  1608. ok = silence.calls.load() > 0 && (! wantInput || silence.inputs.load() > 0);
  1609. device->close();
  1610. }
  1611. }
  1612. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  1613. setApplicationReturnValue (ok ? 0 : 1);
  1614. quit();
  1615. return;
  1616. }
  1617. if (args.contains ("--pickertime"))
  1618. {
  1619. // LYNX.exe --pickertime report.txt (issue #209): the plugin lists' opening times with the profile's plugin
  1620. // list (LYNX_PROFILE_MAIN samples the message thread meanwhile)
  1621. const auto i = args.indexOf ("--pickertime");
  1622. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1623. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  1624. lynx::crashguard::startMainProfiler (profile.toStdString());
  1625. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1626. lynx::AudioEngine offline (false);
  1627. const auto engineMs = juce::Time::getMillisecondCounterHiRes() - t0;
  1628. const auto report = "engine_ms=" + juce::String (engineMs) + "\n" + lynx::pluginPickerTimings (offline);
  1629. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1630. lynx::crashguard::stopMainProfiler();
  1631. setApplicationReturnValue (0);
  1632. quit();
  1633. return;
  1634. }
  1635. if (args.contains ("--plusmenutime"))
  1636. {
  1637. // LYNX --plusmenutime report.txt [watched] (round 190mf): the Channel rack "+" menu's build time (as
  1638. // showAddChannelMenu builds it, without showing it) with the profile's plugin list and Plugin database
  1639. // folder: the first one, then each one after the old two-second throttle ran out; then one after the
  1640. // folder was marked changed. "watched": as the app (a folder watcher), else as before round 190mf.
  1641. const auto i = args.indexOf ("--plusmenutime");
  1642. const auto watched = i + 2 < args.size() && args[i + 2] == "watched";
  1643. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  1644. lynx::AudioEngine offline (false);
  1645. lynx::quickpick::installPluginDatabase (offline);
  1646. std::unique_ptr<lynx::folderwatch::Watcher> watcher;
  1647. if (watched)
  1648. {
  1649. const auto root = lynx::quickpick::pluginDatabaseFolder();
  1650. watcher = std::make_unique<lynx::folderwatch::Watcher> (
  1651. std::vector<std::string> { root.getChildFile ("Effects").getFullPathName().toStdString(), root.getChildFile ("Generators").getFullPathName().toStdString() },
  1652. [] { juce::MessageManager::callAsync ([] { lynx::quickpick::markPluginDatabaseChanged(); }); });
  1653. lynx::quickpick::setPluginDatabaseWatched (true);
  1654. }
  1655. juce::String report;
  1656. report << "types=" << offline.getPluginHost().getKnownPlugins().getNumTypes() << " watched=" << (watched ? 1 : 0) << "\n";
  1657. auto build = [&offline] (int& items) {
  1658. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  1659. juce::PopupMenu menu;
  1660. auto picks = lynx::quickpick::renamedGenerators (offline, [] (lynx::ChannelDef) {});
  1661. lynx::quickpick::addPicks (menu, picks);
  1662. lynx::quickpick::addGeneratorMenu (menu, offline, [] (lynx::ChannelDef) {}, [] {}, nullptr, nullptr);
  1663. lynx::quickpick::addFolderViewItems (menu, offline);
  1664. items = menu.getNumItems();
  1665. return juce::Time::getMillisecondCounterHiRes() - t0;
  1666. };
  1667. auto line = [&report, &build] (const juce::String& what) {
  1668. const auto readsBefore = lynx::quickpick::lastRefreshTimes().reads;
  1669. int items = 0;
  1670. const auto ms = build (items);
  1671. const auto t = lynx::quickpick::lastRefreshTimes();
  1672. const auto read = t.reads != readsBefore;
  1673. report << what << " menu_ms=" << juce::String (ms, 2) << " items=" << items << " folder_read=" << (read ? 1 : 0);
  1674. if (read)
  1675. report << " list_ms=" << juce::String (t.listMs, 2) << " read_ms=" << juce::String (t.readMs, 2);
  1676. report << "\n";
  1677. };
  1678. line ("first");
  1679. for (int k = 1; k <= 5; ++k)
  1680. {
  1681. juce::Thread::sleep (2100);
  1682. line ("again" + juce::String (k));
  1683. }
  1684. for (int k = 1; k <= 3; ++k)
  1685. line ("quick" + juce::String (k));
  1686. lynx::quickpick::markPluginDatabaseChanged();
  1687. line ("marked");
  1688. line ("after");
  1689. lynx::quickpick::setPluginDatabaseWatched (false);
  1690. watcher.reset();
  1691. lynx::plugindb::finishInstalledWrites();
  1692. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  1693. setApplicationReturnValue (0);
  1694. quit();
  1695. return;
  1696. }
  1697. if (args.contains ("--scantest"))
  1698. {
  1699. // LYNX.exe --scantest folder report.txt: scan (in child processes) without touching the user's list
  1700. const auto i = args.indexOf ("--scantest");
  1701. lynx::PluginHost host (false);
  1702. const auto found = host.scan (juce::FileSearchPath (args[i + 1].unquoted()), {});
  1703. juce::String report;
  1704. report << "found=" << found << "\n";
  1705. for (const auto& t : host.getKnownPlugins().getTypes())
  1706. report << " " << (t.isInstrument ? "instrument: " : "effect: ") << t.name << "\n";
  1707. for (const auto& f : host.getKnownPlugins().getBlacklistedFiles())
  1708. report << " blacklisted: " << f << "\n";
  1709. juce::File (args[i + 2].unquoted()).replaceWithText (report);
  1710. setApplicationReturnValue (found > 0 ? 0 : 1);
  1711. quit();
  1712. return;
  1713. }
  1714. if (args.contains ("--wrappermiditest"))
  1715. {
  1716. // LYNX.exe --wrappermiditest plugin.dll report.txt (round 181c), with LYNX_TEST_VST2_MIDILOG set: what a
  1717. // hosted plugin receives after a wrapper MIDI option changes while it runs
  1718. const auto i = args.indexOf ("--wrappermiditest");
  1719. runWrapperMidiTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1720. return;
  1721. }
  1722. if (args.contains ("--wrappershot190oh"))
  1723. {
  1724. // LYNX --wrappershot190oh plugin <folder> [--open] (round 190oh, P3: FL's wrapper Settings › GUI): the
  1725. // plugin (any format; an effect on insert 1) and its wrapper Settings tab drawn offscreen at 100 % and 150 %,
  1726. // with FL's defaults and with "DPI aware" off + "Scale editor dimensions" on; --open also opens its editor
  1727. // with each setting (a real window: Windows reports the editor windows' DPI awareness) -> report.txt
  1728. const auto i = args.indexOf ("--wrappershot190oh");
  1729. runWrapperShot190oh (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--open"));
  1730. return;
  1731. }
  1732. if (args.contains ("--wrappershot"))
  1733. {
  1734. const auto i = args.indexOf ("--wrappershot");
  1735. runWrapperShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  1736. return;
  1737. }
  1738. if (args.contains ("--multiouttest"))
  1739. {
  1740. const auto i = args.indexOf ("--multiouttest");
  1741. runMultiOutTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1742. return;
  1743. }
  1744. if (args.contains ("--vstitest"))
  1745. {
  1746. // LYNX --vstitest plugin folder [project.lynx] (round 190fw, issue #162): an instrument plugin (Image-Line's
  1747. // "FL Studio VSTi") on a channel: notes in, audio out, its state through a saved project, its outputs and
  1748. // the host tempo it follows. See runVstiTest.
  1749. const auto i = args.indexOf ("--vstitest");
  1750. const auto project = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1751. runVstiTest (args[i + 1].unquoted(), args[i + 2].unquoted(), project);
  1752. return;
  1753. }
  1754. if (args.contains ("--vst2test"))
  1755. {
  1756. const auto i = args.indexOf ("--vst2test");
  1757. runVst2Test (args[i + 1].unquoted(), args[i + 2].unquoted());
  1758. return;
  1759. }
  1760. if (args.contains ("--issuesshot190ll"))
  1761. {
  1762. // --issuesshot190ll <prefix> (round 190ll, issues #200 / #203): src/IssuesShot190ll.inc
  1763. setApplicationReturnValue (runIssuesShot190ll (args[args.indexOf ("--issuesshot190ll") + 1].unquoted()) ? 0 : 1);
  1764. quit();
  1765. return;
  1766. }
  1767. if (args.contains ("--hostplaytest190ll"))
  1768. {
  1769. // LYNX --hostplaytest190ll report.txt "<LYNX Test Synth.vst3>" [--buffer N] (round 190ll, issue #199): src/HostPlay190ll.inc
  1770. const auto i = args.indexOf ("--hostplaytest190ll");
  1771. const auto buffer = args.contains ("--buffer") ? args[args.indexOf ("--buffer") + 1].getIntValue() : 1024;
  1772. runHostPlayTest190ll (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), juce::jlimit (16, 4096, buffer));
  1773. return;
  1774. }
  1775. if (args.contains ("--vst3noteidtest"))
  1776. {
  1777. const auto i = args.indexOf ("--vst3noteidtest");
  1778. runVst3NoteIdTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1779. return;
  1780. }
  1781. if (args.contains ("--lv2scantest"))
  1782. {
  1783. runLv2ScanTest (args[args.indexOf ("--lv2scantest") + 1].unquoted());
  1784. return;
  1785. }
  1786. if (args.contains ("--wrappertest"))
  1787. {
  1788. const auto i = args.indexOf ("--wrappertest");
  1789. runWrapperTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1790. return;
  1791. }
  1792. if (args.contains ("--plugintest"))
  1793. {
  1794. const auto i = args.indexOf ("--plugintest");
  1795. // optional 3rd argument: the plugin's name inside a shell (e.g. "CLA-2A Stereo" in a WaveShell)
  1796. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1797. runPluginTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  1798. return;
  1799. }
  1800. if (args.contains ("--crashguardtest"))
  1801. {
  1802. // LYNX --crashguardtest "LYNX Test Crash.vst3|.clap" report.txt [process|memcpy] (round 190dt,
  1803. // tools/testplugin/lynx_test_crash*.{c,cpp}): the plugin crashes in its 40th block on insert 1; LYNX must
  1804. // catch it, mark the slot, keep playing the other inserts, save the project, reload the plugin; then the
  1805. // saved project opens with the plugin crashing on its state; and LYNX's own faults are still crashes
  1806. const auto i = args.indexOf ("--crashguardtest");
  1807. runCrashGuardTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1808. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("process"));
  1809. return;
  1810. }
  1811. if (args.contains ("--claprestarttest"))
  1812. {
  1813. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c)
  1814. const auto i = args.indexOf ("--claprestarttest");
  1815. runClapRestartTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1816. return;
  1817. }
  1818. if (args.contains ("--hwheel254test"))
  1819. {
  1820. // LYNX --hwheel254test report.txt (round 190ou, issue #254): the horizontal wheel in the Playlist (three layouts),
  1821. // Piano roll, Mixer and Browser, off screen (src/HWheel254Test.inc)
  1822. const auto i = args.indexOf ("--hwheel254test");
  1823. setApplicationReturnValue (runHWheel254Test (args[i + 1].unquoted()) ? 0 : 1);
  1824. quit();
  1825. return;
  1826. }
  1827. if (args.contains ("--renderagaintest"))
  1828. {
  1829. // LYNX --renderagaintest report.txt (round 190ou, engine/RenderAgainTest.cpp): offline renders made again
  1830. const auto i = args.indexOf ("--renderagaintest");
  1831. juce::String lines;
  1832. const auto result = lynx::renderagain::check ([&lines] (const juce::String& line) { lines << line << "\n"; });
  1833. juce::File (args[i + 1].unquoted()).replaceWithText (lines + "renderagain190ou=" + result + "\n");
  1834. setApplicationReturnValue (result.startsWith ("OK") ? 0 : 1);
  1835. quit();
  1836. return;
  1837. }
  1838. if (args.contains ("--clapteardowntest"))
  1839. {
  1840. // LYNX.exe --clapteardowntest "LYNX Test Restart.clap" report.txt (round 190az, engine/ClapTeardownTest.cpp)
  1841. const auto i = args.indexOf ("--clapteardowntest");
  1842. lynx::runClapTeardownTest (args[i + 1].unquoted(), args[i + 2].unquoted(), [this] (int code) {
  1843. setApplicationReturnValue (code);
  1844. quit();
  1845. });
  1846. return;
  1847. }
  1848. if (args.contains ("--mpetest"))
  1849. {
  1850. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108)
  1851. const auto i = args.indexOf ("--mpetest");
  1852. runMpeTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1853. return;
  1854. }
  1855. if (args.contains ("--mpeplaytest190hy"))
  1856. {
  1857. // LYNX --mpeplaytest190hy plugin.(clap|vst3) report.txt (round 190hy, issue #108): a song note with a pitch
  1858. // curve played by a hosted plugin with MPE on, through the whole song path (scheduler, renderer, the wrapper's
  1859. // MPE / CLAP note expressions), rendered offline; the pitch heard is measured (report.txt, report.wav)
  1860. const auto i = args.indexOf ("--mpeplaytest190hy");
  1861. runMpePlayTest190hy (args[i + 1].unquoted(), args[i + 2].unquoted());
  1862. return;
  1863. }
  1864. if (args.contains ("--editortest"))
  1865. {
  1866. // LYNX.exe --editortest plugin.vst3 report.txt ["name"]: opens the plugin's own editor in a window for a few
  1867. // seconds, then closes it (a plugin whose UI crashes the host ends the process before the report says OK)
  1868. const auto i = args.indexOf ("--editortest");
  1869. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  1870. runEditorTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only);
  1871. return;
  1872. }
  1873. if (args.contains ("--editorcrashtest"))
  1874. {
  1875. // LYNX.exe --editorcrashtest "LYNX Test Crash.clap" report.txt (issue #32, round 174a; Windows): the test
  1876. // plugin's editor faults in its own window procedure (LYNX_TEST_CRASH=editor). LYNX must catch it, close
  1877. // that editor, record the trace and keep running its message loop.
  1878. const auto i = args.indexOf ("--editorcrashtest");
  1879. runEditorCrashTest (args[i + 1].unquoted(), args[i + 2].unquoted());
  1880. return;
  1881. }
  1882. if (args.contains ("--reloadtest"))
  1883. {
  1884. // LYNX --reloadtest plugin report.txt [shots folder] [--wait-kill]: round 190ao (reload a crashed plugin).
  1885. // Hosts the plugin in a separate process (a channel for an instrument, insert 1 for an effect) in an offline
  1886. // engine, crashes its process (--wait-kill: writes <report>.pid and waits for the process to be killed
  1887. // from outside), checks that nothing reloads by itself, reloads it on request and checks the new process,
  1888. // the state captured last, the untouched song and undo history; twice. With a shots folder: PNGs of the
  1889. // plugin window's crash notice and of the prompt.
  1890. const auto i = args.indexOf ("--reloadtest");
  1891. runReloadTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1892. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String(), args.contains ("--wait-kill"));
  1893. return;
  1894. }
  1895. if (args.contains ("--pluginoptionstest"))
  1896. {
  1897. // LYNX --pluginoptionstest plugin report.txt [shots folder]: round 190ao. Hosts the plugin inside LYNX (a
  1898. // channel for an instrument, insert 1 for an effect) in an offline engine, opens its window and checks
  1899. // LYNX's own plugin-window options: Pin on top (set, kept above another window, saved with the plugin,
  1900. // back when the window opens again). With a shots folder: PNGs of each state. The window is on screen.
  1901. const auto i = args.indexOf ("--pluginoptionstest");
  1902. runPluginOptionsTest (args[i + 1].unquoted(), args[i + 2].unquoted(),
  1903. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String());
  1904. return;
  1905. }
  1906. if (args.contains ("--plugwintest"))
  1907. {
  1908. // LYNX --plugwintest plugin report.txt ["name"] [seconds]: round 162d. Puts the plugin in a channel (an
  1909. // instrument) or on insert 1 (an effect) of an offline engine, opens its plugin window (wrapper header,
  1910. // presets), checks a preset round trip, keeps the window `seconds` on screen (default 15: time for xdotool /
  1911. // screenshots), then removes the plugin from the song and reports whether its window closed by itself.
  1912. const auto i = args.indexOf ("--plugwintest");
  1913. const auto only = i + 3 < args.size() && ! args[i + 3].startsWith ("--") && ! args[i + 3].containsOnly ("0123456789") ? args[i + 3].unquoted() : juce::String();
  1914. auto seconds = 15;
  1915. for (int k = i + 3; k < juce::jmin (args.size(), i + 5); ++k)
  1916. if (args[k].containsOnly ("0123456789"))
  1917. seconds = args[k].getIntValue();
  1918. runPlugWinTest (args[i + 1].unquoted(), args[i + 2].unquoted(), only, seconds);
  1919. return;
  1920. }
  1921. if (args.contains ("--zorder191test"))
  1922. {
  1923. // LYNX --zorder191test report.txt [plugin.vst3]: issue #191 (round 190mx), ui/ZOrder191Test.h
  1924. const auto i = args.indexOf ("--zorder191test");
  1925. const auto plugin = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  1926. lynx::runZOrder191Test (args[i + 1].unquoted(), plugin, &lookAndFeel, [this] (bool ok) {
  1927. setApplicationReturnValue (ok ? 0 : 1);
  1928. quit();
  1929. });
  1930. return;
  1931. }
  1932. if (args.contains ("--fittest"))
  1933. {
  1934. // LYNX.exe --fittest report.txt [percent]: round 163 — at that UI zoom (default 150) a window taller than
  1935. // the screen and a big resizable window that grows with a zoom change keep their title bar and close
  1936. // button on the screen. The windows show for about two seconds.
  1937. const auto i = args.indexOf ("--fittest");
  1938. runFitTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].getIntValue() : 150);
  1939. return;
  1940. }
  1941. if (args.contains ("--windowtest"))
  1942. {
  1943. // LYNX.exe --windowtest report.txt: opens the Quick-add palette, the Audio editor, a plugin-like window and a name dialog
  1944. // over the main window and checks that each one stays in front, owned by the main window, with the
  1945. // keyboard focus (issue #4). The windows appear on screen for a few seconds.
  1946. runWindowTest (args[args.indexOf ("--windowtest") + 1].unquoted());
  1947. return;
  1948. }
  1949. if (args.contains ("--minimizeclicktest"))
  1950. {
  1951. // LYNX --minimizeclicktest report.txt (issue #188, round 190ir): a tool window over the main window is
  1952. // minimised (through the window manager), the main window comes to the front, and a click where the tool
  1953. // window was must reach the main window's component. Run it under a window manager (openbox on a private
  1954. // Xvfb); exit code 0 = OK.
  1955. runMinimizeClickTest (args[args.indexOf ("--minimizeclicktest") + 1].unquoted());
  1956. return;
  1957. }
  1958. if (args.contains ("--focustest"))
  1959. {
  1960. // LYNX --focustest report.txt (issue #161): the main window with the Playlist and the Piano roll (native
  1961. // child windows with docking on). For each: LYNX goes to the background (the main window loses the focus),
  1962. // the user comes back with a click in the panel, then presses Space: playback must start. Also: a text
  1963. // field's focus comes back with the window, and inside the active window the click's answer is unchanged.
  1964. // Shows a window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  1965. runFocusTest (args[args.indexOf ("--focustest") + 1].unquoted());
  1966. return;
  1967. }
  1968. if (args.contains ("--simplekeytest"))
  1969. {
  1970. // LYNX --simplekeytest report.txt (round 190fc, 0.1.27 RC H2): the main window in the Simple layout; after a
  1971. // demo opened from Welcome › Start from and after clicks in the dock, its tabs, the Lyrics button, a track
  1972. // header and the grid, Space must start playback (a text field clicked into keeps its typing keys). Shows a
  1973. // window (takes the foreground on Windows: GUI lock); exit code 0 = OK.
  1974. runSimpleKeyTest (args[args.indexOf ("--simplekeytest") + 1].unquoted());
  1975. return;
  1976. }
  1977. if (args.contains ("--pluginstyle")) // round 126: force one style for this run (glow, neon, hardware, vivid; auto = per plugin)
  1978. {
  1979. const auto i = args.indexOf ("--pluginstyle");
  1980. if (i + 1 < args.size())
  1981. {
  1982. const auto name = args[i + 1].unquoted();
  1983. lynx::skin::setForcedStyle (name.equalsIgnoreCase ("auto") ? -1 : (int) lynx::skin::styleFromName (name));
  1984. }
  1985. }
  1986. if (args.contains ("--gfxprobe"))
  1987. {
  1988. // LYNX.exe --gfxprobe report.txt (round 170c, issue #11): renderer checks on this platform's native images —
  1989. // text drawn with a gradient fill (a word with a space in it) and an empty path filled with a gradient must
  1990. // stay inside their shapes. JUCE 8.0.4's CoreGraphics renderer (macOS) clipped to an empty glyph or path as
  1991. // "no clip" and flooded the whole component (Facet EQ's blank pink window).
  1992. const auto i = args.indexOf ("--gfxprobe");
  1993. juce::File (args[i + 1].unquoted()).replaceWithText (lynx::skin::rendererProbeReport());
  1994. quit();
  1995. return;
  1996. }
  1997. if (args.contains ("--steppertest"))
  1998. {
  1999. // LYNX.exe --steppertest <report.txt>: round 170c (#14) — every value stepper of every generated effect editor
  2000. // driven by synthetic input (arrows, click on the value, drag, wheel, trackpad); ends with result=OK / FAIL
  2001. const auto i = args.indexOf ("--steppertest");
  2002. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2003. juce::String report;
  2004. int fails = 0, count = 0, skips = 0;
  2005. {
  2006. lynx::AudioEngine offline (false);
  2007. auto kinds = lynx::plugui::flLayoutKinds();
  2008. for (const auto own : lynx::plugui::ownLayoutKinds())
  2009. kinds.push_back (own);
  2010. // FL's Default preset when the installation has one (the state-backed controls need FL's state)
  2011. const auto roots = lynx::findFlStudioRoots();
  2012. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  2013. for (const auto kind : kinds)
  2014. {
  2015. auto fx = lynx::makeEffectSlot (kind);
  2016. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  2017. {
  2018. juce::MemoryBlock data;
  2019. const auto file = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str())).getChildFile ("Default.fst");
  2020. if (file.existsAsFile() && file.loadFileAsData (data))
  2021. {
  2022. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  2023. 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)
  2024. fx = *loaded;
  2025. }
  2026. break;
  2027. }
  2028. lynx::Song song;
  2029. song.mixer.resize (2);
  2030. song.mixer[0].name = "Master";
  2031. song.mixer[1].name = "Insert 1";
  2032. song.mixer[1].effects.push_back (fx);
  2033. offline.setSong (std::move (song));
  2034. offline.dispatchPendingMessages();
  2035. const auto lines = lynx::stepperSelfTest (offline, 1, 0, (int) lynx::plugui::layoutFor (kind).pages.size());
  2036. for (const auto& line : juce::StringArray::fromLines (lines))
  2037. if (line.isNotEmpty())
  2038. {
  2039. ++count;
  2040. fails += line.contains (": FAIL") ? 1 : 0;
  2041. skips += line.contains (": SKIP") ? 1 : 0;
  2042. }
  2043. report << lines;
  2044. juce::PopupMenu::dismissAllActiveMenus();
  2045. offline.dispatchPendingMessages();
  2046. }
  2047. }
  2048. report << "steppers=" << count << " failures=" << fails << " skipped=" << skips << "\nresult=" << (fails == 0 && count > 0 ? "OK" : "FAIL") << "\n";
  2049. juce::File (args[i + 1].unquoted()).replaceWithText (report);
  2050. quit();
  2051. return;
  2052. }
  2053. if (args.contains ("--design190inshot"))
  2054. {
  2055. // LYNX --design190inshot prefix [project.flp]: round 190in off screen (no desktop window, no audio device) —
  2056. // the channel window as it shows docked (FL's ▸, two-tone title, presets in the title bar, the 46 px strip
  2057. // with icon tabs, LED, knobs, RANGE / TRACK badges) on each tab, the floating strip, and FL's ▸ menu
  2058. const auto i = args.indexOf ("--design190inshot");
  2059. runDesign190inShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String());
  2060. quit();
  2061. return;
  2062. }
  2063. if (args.contains ("--plugui"))
  2064. {
  2065. // LYNX.exe --plugui <folder>: the native effect editors at FL's size (one PNG per editor and page), each
  2066. // loaded with the FL plugin's Default preset when the FL installation has one
  2067. const auto i = args.indexOf ("--plugui");
  2068. runPluginEditorSnapshots (args[i + 1].unquoted());
  2069. return;
  2070. }
  2071. if (args.contains ("--parityshot"))
  2072. {
  2073. // LYNX.exe --parityshot <out.png> <effect name> [<params file>]: one built-in effect's editor with the given
  2074. // parameters ("index value" lines, tools/fxrender --dump), its displays fed by the demo song — the LYNX side
  2075. // of the third-party parity pictures (round tp172b)
  2076. const auto i = args.indexOf ("--parityshot");
  2077. runParityShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  2078. if (parityShotFailed)
  2079. setApplicationReturnValue (2);
  2080. if (parityShow == nullptr)
  2081. quit();
  2082. return;
  2083. }
  2084. if (args.contains ("--design168rshot"))
  2085. {
  2086. // LYNX.exe --design168rshot <folder>: round 168r's editors (FL effects that had a generated page and LYNX's own
  2087. // simple built-ins) at 100 % and 200 %, with their default settings and, when they have one, the first
  2088. // preset of LYNX's own bank. "--design168rshot <folder> generated": the generated pages they had before
  2089. const auto i = args.indexOf ("--design168rshot");
  2090. if (i + 2 < args.size() && args[i + 2] == "generated")
  2091. lynx::plugui::showGeneratedLayoutsOnly (true);
  2092. runDesign168rShots (args[i + 1].unquoted());
  2093. quit();
  2094. return;
  2095. }
  2096. if (args.contains ("--eq166fshot"))
  2097. {
  2098. // LYNX.exe --eq166fshot <folder>: round 166f's pictures (issue #16) — Parametric EQ 2's spectrum and heatmap
  2099. // (flat, a +12 dB band, a -12 dB band, Top position) and Facet EQ's comparative EQ (listening to the target,
  2100. // its spectrum over the source's), each fed by the demo song rendered offline
  2101. const auto i = args.indexOf ("--eq166fshot");
  2102. runEq166fShots (args[i + 1].unquoted());
  2103. quit();
  2104. return;
  2105. }
  2106. if (args.contains ("--editorcpu"))
  2107. {
  2108. // LYNX.exe --editorcpu report.txt: opens built-in plugin editors one at a time in a small window (no audio
  2109. // device: a silent, idle editor) and writes the process CPU each costs while idle and while its display
  2110. // animates (demo signal) — round 122's check that an idle editor burns no CPU
  2111. const auto i = args.indexOf ("--editorcpu");
  2112. runEditorCpu (args[i + 1].unquoted());
  2113. return;
  2114. }
  2115. if (args.contains ("--precomputeshot"))
  2116. {
  2117. // LYNX.exe --precomputeshot project.(flp|lynx) <prefix>: round 167h — <prefix>-precompute.png (channel 1's
  2118. // Precomputed effects panel) and <prefix>-project.png (Options › Project with "Fast declick for cut groups")
  2119. const auto i = args.indexOf ("--precomputeshot");
  2120. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2121. lynx::AudioEngine shotEngine (false);
  2122. const juce::File input (args[i + 1].unquoted());
  2123. const auto prefix = args[i + 2].unquoted();
  2124. juce::String error;
  2125. bool ok = false;
  2126. if (input.hasFileExtension ("flp"))
  2127. ok = shotEngine.importFlpFile (input, error);
  2128. else if (auto song = lynx::ProjectFile::load (input, error))
  2129. shotEngine.setSong (std::move (*song)), ok = true;
  2130. shotEngine.dispatchPendingMessages();
  2131. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  2132. if (c == nullptr)
  2133. return false;
  2134. if (c->getWidth() <= 0)
  2135. c->setSize (520, 600);
  2136. savePng (lynx::shot::snapshot (*c), prefix + name);
  2137. return true;
  2138. };
  2139. ok = ok && shoot (lynx::makeChannelPrecomputePanel (shotEngine, 0), "-precompute.png");
  2140. ok = ok && shoot (lynx::makeSettingsPanel (shotEngine, lynx::SettingsPage::project), "-project.png");
  2141. setApplicationReturnValue (ok ? 0 : 1);
  2142. quit();
  2143. return;
  2144. }
  2145. if (args.contains ("--pluginthumbs"))
  2146. {
  2147. // LYNX.exe --pluginthumbs <folder> [key,key...]: the Plugin picker's pictures of LYNX's own plugins (round 171c,
  2148. // ui/PluginThumbs.h), each editor drawn off-screen and kept as <folder>/<name>.png; the picker starts this in
  2149. // the background when pictures are missing. One line per plugin on stdout.
  2150. const auto i = args.indexOf ("--pluginthumbs");
  2151. lynx::crashguard::quietCrashReports();
  2152. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2153. juce::StringArray only;
  2154. if (i + 2 < args.size() && ! args[i + 2].startsWith ("--"))
  2155. only.addTokens (args[i + 2].unquoted(), ",", "");
  2156. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  2157. // round 190bi: with --shot-scale / LYNX_SHOT_SCALE each plugin's whole editor at that scale, not the picker's
  2158. // small thumbnail (never for the picker's own cache folder, whatever the environment says)
  2159. const juce::File folder (args[i + 1].unquoted());
  2160. const auto full = lynx::shot::given() && folder != lynx::pluginthumbs::nativeFolder() ? lynx::shot::scale() : 0.0f;
  2161. const auto drawn = lynx::pluginthumbs::renderNative (folder, only, [] (const juce::String& line) {
  2162. std::printf ("%s\n", line.toRawUTF8());
  2163. std::fflush (stdout);
  2164. }, full);
  2165. std::printf ("drawn %d in %.0f ms\n", drawn, juce::Time::getMillisecondCounterHiRes() - t0);
  2166. setApplicationReturnValue (0);
  2167. quit();
  2168. return;
  2169. }
  2170. if (args.contains ("--jsonroundtrip"))
  2171. {
  2172. // LYNX.exe --jsonroundtrip <folder>: round 183c's finding — a project saved, loaded and saved again: both texts
  2173. // (a.json, b.json) and the first lines that differ (diff.txt) for the default song, with and without a Patcher
  2174. const auto i = args.indexOf ("--jsonroundtrip");
  2175. const juce::File out (args[i + 1].unquoted());
  2176. out.createDirectory();
  2177. juce::String report;
  2178. auto check = [&] (const lynx::Song& song, const juce::String& name) {
  2179. const auto a = lynx::ProjectFile::toJson (song);
  2180. juce::String error;
  2181. const auto back = lynx::ProjectFile::fromJson (a, error);
  2182. const auto b = back ? lynx::ProjectFile::toJson (*back) : juce::String ("(not loaded: " + error + ")");
  2183. out.getChildFile (name + "-a.json").replaceWithText (a);
  2184. out.getChildFile (name + "-b.json").replaceWithText (b);
  2185. juce::StringArray la, lb;
  2186. la.addLines (a);
  2187. lb.addLines (b);
  2188. report << name << ": " << (a == b ? "stable" : "DIFFERS") << " (" << la.size() << " / " << lb.size() << " lines)\n";
  2189. int shown = 0;
  2190. for (int k = 0; k < juce::jmax (la.size(), lb.size()) && shown < 12; ++k)
  2191. if (la[k] != lb[k])
  2192. {
  2193. report << " line " << (k + 1) << "\n a: " << la[k].trim().substring (0, 200) << "\n b: " << lb[k].trim().substring (0, 200) << "\n";
  2194. ++shown;
  2195. }
  2196. };
  2197. auto song = lynx::Song::makeDefault();
  2198. check (song, "default");
  2199. song.mixer.resize (3);
  2200. song.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::patcher) };
  2201. check (song, "patcher");
  2202. song.mixer[1].effects = { lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect) };
  2203. check (song, "rack");
  2204. out.getChildFile ("diff.txt").replaceWithText (report);
  2205. setApplicationReturnValue (0);
  2206. quit();
  2207. return;
  2208. }
  2209. // --prshot190jv <folder> (round 190jv: Piano roll › Scale highlighting › Automatic): src/PrShot190jv.inc
  2210. if (args.contains ("--prshot190jv"))
  2211. {
  2212. setApplicationReturnValue (runPrShot190jv (juce::File (args[args.indexOf ("--prshot190jv") + 1].unquoted())) ? 0 : 1);
  2213. quit();
  2214. return;
  2215. }
  2216. // --prchord190kd <folder> (round 190kd: FL's chord tool strip, scale shading, rack name alignment): src/PrChordShot190kd.inc
  2217. if (args.contains ("--prchord190kd"))
  2218. {
  2219. setApplicationReturnValue (runPrChordShot190kd (juce::File (args[args.indexOf ("--prchord190kd") + 1].unquoted())) ? 0 : 1);
  2220. quit();
  2221. return;
  2222. }
  2223. // --keys190nu <folder> (round chord2_190nu: key regions, the Scale degree chord, pinned Chord helper relationships)
  2224. if (args.contains ("--keys190nu"))
  2225. {
  2226. setApplicationReturnValue (runKeysShot190nu (juce::File (args[args.indexOf ("--keys190nu") + 1].unquoted())) ? 0 : 1);
  2227. quit();
  2228. return;
  2229. }
  2230. // --modal190mc <folder> (round 190mc: the Chord helper, Transistor Bass's program row): src/ModalShot190mc.inc
  2231. if (args.contains ("--modal190mc"))
  2232. {
  2233. setApplicationReturnValue (runModalShot190mc (juce::File (args[args.indexOf ("--modal190mc") + 1].unquoted())) ? 0 : 1);
  2234. quit();
  2235. return;
  2236. }
  2237. // --trimshot190jv <folder> (round 190jv: Mixer menu › Trim unused tracks): src/TrimShot190jv.inc
  2238. if (args.contains ("--trimshot190jv"))
  2239. {
  2240. setApplicationReturnValue (runTrimShot190jv (juce::File (args[args.indexOf ("--trimshot190jv") + 1].unquoted())) ? 0 : 1);
  2241. quit();
  2242. return;
  2243. }
  2244. // --undogesture190jv <report.txt> (round 190jv, queue item 73: one undo step per drag): src/UndoGesture190jv.inc
  2245. if (args.contains ("--undogesture190jv"))
  2246. {
  2247. setApplicationReturnValue (runUndoGesture190jv (juce::File (args[args.indexOf ("--undogesture190jv") + 1].unquoted())) ? 0 : 1);
  2248. quit();
  2249. return;
  2250. }
  2251. // --simplegb190keshot <folder> (round 190ke: tuner, fade-out, Controls tab, LYNX content): src/SimpleGbShot190ke.inc
  2252. if (args.contains ("--simplegb190keshot"))
  2253. {
  2254. setApplicationReturnValue (runSimpleGbShot190ke (juce::File (args[args.indexOf ("--simplegb190keshot") + 1].unquoted())) ? 0 : 1);
  2255. quit();
  2256. return;
  2257. }
  2258. // --browsershot190iz <folder> (round 190iz: FL's tabs, tags, Live's browser): src/BrowserShot190iz.inc
  2259. // --qarest190lcshot <folder> [Live set] (rollup step 7: QA-8's View menu submenu, QA-2's take lanes in Simple):
  2260. // src/QaRest190lcShot.inc
  2261. if (args.contains ("--qarest190lcshot"))
  2262. {
  2263. const auto i = args.indexOf ("--qarest190lcshot");
  2264. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2265. setApplicationReturnValue (runQaRest190lcShot (juce::File (args[i + 1].unquoted()), set) ? 0 : 1);
  2266. quit();
  2267. return;
  2268. }
  2269. // --loopinfo190kxshot <folder> (round 190kx: loop key / tempo in the Simple rows, the Loop Browser, the clip menu)
  2270. if (args.contains ("--loopinfo190kxshot"))
  2271. {
  2272. setApplicationReturnValue (runLoopInfoShot190kx (juce::File (args[args.indexOf ("--loopinfo190kxshot") + 1].unquoted())) ? 0 : 1);
  2273. quit();
  2274. return;
  2275. }
  2276. // --loopshot190kf <folder> (round gaps190kf: the Loop Browser): src/LoopShot190kf.inc
  2277. if (args.contains ("--loopshot190kf"))
  2278. {
  2279. setApplicationReturnValue (runLoopShot190kf (juce::File (args[args.indexOf ("--loopshot190kf") + 1].unquoted())) ? 0 : 1);
  2280. quit();
  2281. return;
  2282. }
  2283. if (args.contains ("--lynxmodelshot190ni"))
  2284. {
  2285. // LYNX --lynxmodelshot190ni prefix: round 190ni, LYNX Model's window per preset, its Browser entry, checks
  2286. setApplicationReturnValue (runLynxModelShot190ni (args[args.indexOf ("--lynxmodelshot190ni") + 1].unquoted()) ? 0 : 1);
  2287. quit();
  2288. return;
  2289. }
  2290. if (args.contains ("--browsershot190iz"))
  2291. {
  2292. setApplicationReturnValue (runBrowserShot190iz (juce::File (args[args.indexOf ("--browsershot190iz") + 1].unquoted())) ? 0 : 1);
  2293. quit();
  2294. return;
  2295. }
  2296. if (args.contains ("--rackshot"))
  2297. {
  2298. // LYNX.exe --rackshot <folder>: round 183c's Rack view drawn off-screen (no window), for the LYNX | Live pairs:
  2299. // rack-deviceview.png (an Audio Effect Rack laid out as in Live's reference shot), rack-mapmode.png (Map mode
  2300. // with the mapping list), rack-instrument.png (an Instrument Rack with its key zones)
  2301. const auto i = args.indexOf ("--rackshot");
  2302. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2303. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2304. setApplicationReturnValue (runRackShots (juce::File (args[i + 1].unquoted()), set) ? 0 : 1);
  2305. quit();
  2306. return;
  2307. }
  2308. if (args.contains ("--artshot"))
  2309. {
  2310. // LYNX.exe --artshot <folder> [before|after] [name,name...]: every editor with art of its own (round 170j/170k: the
  2311. // Themed style; or only the named ones, e.g. "sakura,facet-eq") drawn off-screen at 100 % and 200 % as
  2312. // <folder>/<plugin>-<before|after>-<scale>.png. "before" draws each in the style it had before the Themed style
  2313. const auto i = args.indexOf ("--artshot");
  2314. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2315. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  2316. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  2317. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  2318. setApplicationReturnValue (runArtShots (juce::File (args[i + 1].unquoted()), mode == "before") ? 0 : 1);
  2319. quit();
  2320. return;
  2321. }
  2322. if (args.contains ("--artgui"))
  2323. {
  2324. // LYNX.exe --artgui <folder> [before|after|still] [name,name...]: the same editors in REAL windows on the desktop, one at a
  2325. // time (always on top, no focus taken), each held while an outside script screenshots it (it writes
  2326. // <folder>/<plugin>.ready with the window's bounds and waits up to 10 s for <folder>/<plugin>.done), then the
  2327. // process CPU it costs over 6 s is written to <folder>/cpu-<mode>.txt. "still": Themed with the motion off
  2328. const auto i = args.indexOf ("--artgui");
  2329. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2330. const auto mode = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("after");
  2331. if (i + 3 < args.size() && ! args[i + 3].startsWith ("--")) // [name,name...]: only these arts
  2332. artOnly().addTokens (args[i + 3].unquoted(), ",", "");
  2333. runArtGui (juce::File (args[i + 1].unquoted()), mode);
  2334. return;
  2335. }
  2336. if (args.contains ("--instrumentshot"))
  2337. {
  2338. // LYNX.exe --instrumentshot <folder> <engine,engine...|banks> [lynx|fl]: round 168n — the channel window of
  2339. // each engine (its Plugin tab) at 100 %, 150 % and 200 %, as <folder>/<engine>-<source>-<scale>.png. Source
  2340. // "lynx" starts from the engine's LYNX bank (what a PC without FL gets), "fl" from FL's Default preset.
  2341. const auto i = args.indexOf ("--instrumentshot");
  2342. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2343. const auto source = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String ("lynx");
  2344. setApplicationReturnValue (runInstrumentShots (juce::File (args[i + 1].unquoted()), args[i + 2].unquoted(), source) ? 0 : 1);
  2345. quit();
  2346. return;
  2347. }
  2348. if (args.contains ("--flextrashot"))
  2349. {
  2350. // LYNX.exe --flextrashot <folder>: pictures of the editors of round 165g (Big Clock, Tuner, HTML NoteBook, Mute 2, Scratcher, Transmitter) + round 167n Transporter
  2351. const auto i = args.indexOf ("--flextrashot");
  2352. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2353. lynx::AudioEngine shotEngine (false);
  2354. const auto ok = lynx::runFlExtraShots (shotEngine, juce::File (args[i + 1].unquoted()));
  2355. setApplicationReturnValue (ok ? 0 : 1);
  2356. quit();
  2357. return;
  2358. }
  2359. if (args.contains ("--visualtest"))
  2360. {
  2361. // LYNX.exe --visualtest <folder> [project.flp]: the visual plugins (round 164c) — the audio path's CPU, every
  2362. // Wave Candy mode and Visualizer scene drawn from a test signal (PNG + the editor's CPU each), and the video
  2363. // export of a project (default: FL's first ZGameEditor demo) with ffmpeg and as images. Writes report.txt.
  2364. const auto i = args.indexOf ("--visualtest");
  2365. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2366. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? juce::File (args[i + 2].unquoted()) : juce::File();
  2367. lynx::runVisualTest (juce::File (args[i + 1].unquoted()), project, [this] (bool ok) {
  2368. setApplicationReturnValue (ok ? 0 : 1);
  2369. quit();
  2370. });
  2371. return;
  2372. }
  2373. if (args.contains ("--menu-entry"))
  2374. {
  2375. // LYNX.AppImage --menu-entry on|off: puts the AppImage in the applications menu (and .lynx files on it) or
  2376. // takes it out again, without opening a window; the same as the switch in Options › General (round 161)
  2377. const auto i = args.indexOf ("--menu-entry");
  2378. const auto on = args[i + 1].unquoted() != "off";
  2379. const auto ok = lynx::runningAsAppImage() && lynx::setAppImageMenuEntry (on);
  2380. std::fprintf (ok ? stdout : stderr, "%s\n", ok ? (on ? "LYNX SHARE added to the applications menu" : "LYNX SHARE removed from the applications menu")
  2381. : "only the LYNX SHARE AppImage on Linux can do this");
  2382. setApplicationReturnValue (ok ? 0 : 1);
  2383. quit();
  2384. return;
  2385. }
  2386. if (args.contains ("--leftovers190nrtest"))
  2387. {
  2388. // round 190nr: going back to an older version removes what newer versions added to the install folder
  2389. // (the --apply-update helper's step after the installer). Prints "result=OK" or the failing check.
  2390. const auto root = juce::File::createTempFile ("lynx-leftovers190nr");
  2391. juce::StringArray fails;
  2392. auto run = [&] (const juce::String& version, bool licensesGone, bool listGone) {
  2393. root.deleteRecursively();
  2394. root.getChildFile ("install/licenses").createDirectory();
  2395. root.getChildFile ("install/licenses/onnxruntime-LICENSE.txt").replaceWithText ("x");
  2396. root.getChildFile ("install/LYNX.exe").replaceWithText ("x");
  2397. root.getChildFile ("install/installed-files.txt").replaceWithText ("LYNX.exe\r\nlicenses\r\n");
  2398. root.getChildFile ("install/My notes.txt").replaceWithText ("x");
  2399. root.getChildFile ("update/installing.txt").create();
  2400. if (version.isNotEmpty())
  2401. root.getChildFile ("update/installing.txt").replaceWithText ("from=0.1.31\nrollback=1\nversion=" + version + "\n");
  2402. const auto removed = lynx::updater::removeNewerLeftovers (root.getChildFile ("install"), root.getChildFile ("update/installing.txt"));
  2403. const auto in = root.getChildFile ("install");
  2404. if (in.getChildFile ("licenses").exists() == licensesGone) fails.add (version + ": licenses");
  2405. if (in.getChildFile ("installed-files.txt").exists() == listGone) fails.add (version + ": installed-files.txt");
  2406. if (! in.getChildFile ("LYNX.exe").existsAsFile() || ! in.getChildFile ("My notes.txt").existsAsFile()) fails.add (version + ": removed too much");
  2407. std::printf ("%s -> removed [%s]\n", version.toRawUTF8(), removed.joinIntoString (", ").toRawUTF8());
  2408. };
  2409. run ("0.1.29-alpha", true, true); // going back to 0.1.29: both newer entries go
  2410. run ("0.1.28.1-alpha", true, true);
  2411. run ("0.1.30-alpha", false, true); // 0.1.30 installs licenses itself
  2412. run ("0.1.31-alpha", false, false); // same or newer: nothing goes
  2413. run ("0.1.32", false, false);
  2414. run ("", false, false); // unreadable note: nothing goes
  2415. root.deleteRecursively();
  2416. std::printf ("result=%s%s\n", fails.isEmpty() ? "OK" : "FAILED ", fails.joinIntoString ("; ").toRawUTF8());
  2417. setApplicationReturnValue (fails.isEmpty() ? 0 : 1);
  2418. quit();
  2419. return;
  2420. }
  2421. if (args.contains ("--send-test-report"))
  2422. {
  2423. // LYNX.exe --send-test-report out.txt [--dry]: builds a crash report marked "test" from the newest crash /
  2424. // hang file and this computer's facts, writes its JSON to out.txt.json and (without --dry) sends it to
  2425. // lynx-share.com (LYNX_CRASH_ENDPOINT overrides); out.txt gets "id=…" and "result=OK" or the error (round 159)
  2426. const auto i = args.indexOf ("--send-test-report");
  2427. const juce::File out (args[i + 1].unquoted());
  2428. lynx::crashreporter::Session session;
  2429. session.version = getApplicationVersion();
  2430. for (const auto* pattern : { "crash *.txt", "hang *.txt" })
  2431. {
  2432. auto files = lynx::platform::settingsFile ("autosave").findChildFiles (juce::File::findFiles, false, pattern);
  2433. lynx::filesort::byTime (files, lynx::filesort::By::modificationTime, true);
  2434. if (! files.isEmpty())
  2435. (juce::String (pattern).startsWith ("crash") ? session.crashFile : session.hangFile) = files[0];
  2436. }
  2437. session.steps = { "00:00:01 test report (LYNX.exe --send-test-report)", "00:00:02 opening project " + out.getFileName() };
  2438. auto input = lynx::crashreporter::makeInput (session, session.crashFile.existsAsFile() ? "crash" : "manual", nullptr);
  2439. input.test = true;
  2440. const auto json = lynx::crashreporter::buildJson (input, false);
  2441. out.withFileExtension (out.getFileExtension() + ".json").replaceWithText (json);
  2442. const auto error = args.contains ("--dry") ? juce::String() : lynx::crashreporter::sendNow (json);
  2443. out.replaceWithText ("id=" + juce::String::fromUTF8 (input.id.c_str()) + "\nendpoint=" + lynx::crashreporter::endpoint() + "\nbytes="
  2444. + juce::String (json.getNumBytesAsUTF8()) + "\nresult=" + (error.isEmpty() ? juce::String ("OK") : error) + "\n");
  2445. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  2446. quit();
  2447. return;
  2448. }
  2449. if (args.contains ("--symbolize"))
  2450. {
  2451. // LYNX.exe --symbolize "crash … .txt" out.txt: names the LYNX.exe+offset frames of a user's crash / hang file
  2452. // (needs this build's LYNX.pdb next to LYNX.exe — the release's "LYNX-symbols" CI artifact; round 157a)
  2453. const auto i = args.indexOf ("--symbolize");
  2454. const auto text = juce::File (args[i + 1].unquoted()).loadFileAsString();
  2455. juce::File (args[i + 2].unquoted()).replaceWithText (juce::String::fromUTF8 (lynx::crashguard::symbolizeOwnFrames (text.toStdString()).c_str()));
  2456. quit();
  2457. return;
  2458. }
  2459. if (args.contains ("--opentest"))
  2460. {
  2461. // LYNX.exe --opentest report.txt [--visible]: every built-in effect and instrument window opened as the mixer /
  2462. // Channel rack open them, with default, extreme, random and old-project states; a watchdog fails the test on
  2463. // a hang (round 157a: opening the Parametric EQ froze LYNX). Windows stay off-screen without --visible.
  2464. const auto i = args.indexOf ("--opentest");
  2465. runOpenTest (args[i + 1].unquoted(), args.contains ("--visible"), [this] (bool ok) {
  2466. setApplicationReturnValue (ok ? 0 : 1);
  2467. quit();
  2468. });
  2469. return;
  2470. }
  2471. if (args.contains ("--fxfuzz"))
  2472. {
  2473. // LYNX.exe --fxfuzz report.txt [rounds] [--drags]: every built-in effect in its editor, parameters swept (and
  2474. // dragged with the mouse), audio rendered at several rates; a crash ends the process (round 111)
  2475. const auto i = args.indexOf ("--fxfuzz");
  2476. const auto rounds = args.size() > i + 2 ? juce::jmax (1, args[i + 2].getIntValue()) : 6;
  2477. // --drags: also mouse drags over the editors (their menus may flash on screen: not for the selftest)
  2478. const auto ok = runEffectFuzz (rounds, args[i + 1].unquoted(), args.contains ("--drags"));
  2479. setApplicationReturnValue (ok ? 0 : 1);
  2480. quit();
  2481. return;
  2482. }
  2483. if (args.contains ("--controllershot"))
  2484. {
  2485. // LYNX.exe --controllershot prefix: the built-in controllers' editors (round 133) as PNGs
  2486. const auto i = args.indexOf ("--controllershot");
  2487. runControllerShot (args[i + 1].unquoted());
  2488. quit();
  2489. return;
  2490. }
  2491. if (args.contains ("--edisonshot"))
  2492. {
  2493. // LYNX.exe --edisonshot prefix [audio.wav]: the audio editor's Edison tool windows (round 165l) and the
  2494. // editor before / after some of them, as PNGs (a synthetic drum loop without a file)
  2495. const auto i = args.indexOf ("--edisonshot");
  2496. runEdisonShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2497. quit();
  2498. return;
  2499. }
  2500. if (args.contains ("--arashot190kx"))
  2501. {
  2502. // LYNX --arashot190kx prefix (round 190kx): the Playlist's audio clip menu with its "Edit in ARA plugin" submenu
  2503. // (a stand-in Melodyne entry in this engine's plugin list, as a scan lists the installed one), before and after the
  2504. // clip's channel is edited in it
  2505. const auto i = args.indexOf ("--arashot190kx");
  2506. runAraShot190kx (args[i + 1].unquoted());
  2507. quit();
  2508. return;
  2509. }
  2510. if (args.contains ("--polyshot190lj") && args.indexOf ("--polyshot190lj") + 2 < args.size())
  2511. {
  2512. // LYNX --polyshot190lj prefix audio.wav [bends.wav] (round 190lj): "Convert to MIDI (polyphonic)" — the audio
  2513. // clip menu (Pattern and Simple layouts), the options dialog, Edison's Tools menu, and the result of a
  2514. // conversion (Playlist, Piano roll; with bends on the second file), plus <prefix>-checks.txt (OK / FAIL)
  2515. const auto i = args.indexOf ("--polyshot190lj");
  2516. 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());
  2517. setApplicationReturnValue (ok ? 0 : 1);
  2518. quit();
  2519. return;
  2520. }
  2521. if (args.contains ("--newtoneshot190li"))
  2522. {
  2523. // LYNX --newtoneshot190li prefix audio.wav (round 190li): Newtone with the natural engine (a new slot), as
  2524. // analysed and after Correct pitch 100 / 100 (centre and drift; the vibrato kept), and its Edit menu with the
  2525. // round's items, for the Melodyne | LYNX pairs (with --shot-scale 1.5 for @150)
  2526. const auto i = args.indexOf ("--newtoneshot190li");
  2527. runNewtoneShot190li (args[i + 1].unquoted(), args[i + 2].unquoted());
  2528. quit();
  2529. return;
  2530. }
  2531. if (args.contains ("--polyeditshot190lk") && args.indexOf ("--polyeditshot190lk") + 2 < args.size())
  2532. {
  2533. // LYNX --polyeditshot190lk prefix audio.wav [key] (round 190lk): "Edit notes (polyphonic)" — the audio clip menu,
  2534. // the editor as analysed and after one note (the one nearest `key`, default 64 = E4) moved down a semitone,
  2535. // at 100 % and 150 %, plus <prefix>-checks.txt (OK / FAIL, timings) and <prefix>-notes.txt
  2536. const auto i = args.indexOf ("--polyeditshot190lk");
  2537. const auto ok = runPolyEditShot190lk (args[i + 1].unquoted(), args[i + 2].unquoted(),
  2538. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].getDoubleValue() : 64.0);
  2539. setApplicationReturnValue (ok ? 0 : 1);
  2540. quit();
  2541. return;
  2542. }
  2543. if (args.contains ("--polyeditshot190lo") && args.indexOf ("--polyeditshot190lo") + 2 < args.size())
  2544. {
  2545. // LYNX --polyeditshot190lo prefix audio.wav [key] (round 190lo): the polyphonic note editor's round-2 tools —
  2546. // note assignment, rubber band and moving several notes, stretch handles, modulation / drift / drawn pitch,
  2547. // a dragged note's preview, Edison's buffer mode and its undo, "Prepare edited clips when a project opens" —
  2548. // at 100 % and 150 %, plus <prefix>-checks.txt and <prefix>-notes.txt
  2549. const auto i = args.indexOf ("--polyeditshot190lo");
  2550. const auto ok = runPolyEditShot190lo (args[i + 1].unquoted(), args[i + 2].unquoted(),
  2551. i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].getDoubleValue() : 64.0);
  2552. setApplicationReturnValue (ok ? 0 : 1);
  2553. quit();
  2554. return;
  2555. }
  2556. if (args.contains ("--newtoneshot190kx"))
  2557. {
  2558. // LYNX --newtoneshot190kx prefix audio.wav (round 190kx): Newtone with FL's analysis and with "Separate close
  2559. // notes", each as analysed and after Center 100 % (Melodyne's Correct Pitch), for the Melodyne | LYNX pairs
  2560. const auto i = args.indexOf ("--newtoneshot190kx");
  2561. runNewtoneShot190kx (args[i + 1].unquoted(), args[i + 2].unquoted());
  2562. quit();
  2563. return;
  2564. }
  2565. if (args.contains ("--newtoneshot"))
  2566. {
  2567. // LYNX --newtoneshot prefix audio.wav (round natives190kj): FL's Newtone window with the sample analysed, in a
  2568. // few states (-plain, -selected, -advanced, -cut, -timesel, -moved) and the paint time of the FL look against
  2569. // the round-165g layout (-paint.txt)
  2570. const auto i = args.indexOf ("--newtoneshot");
  2571. runNewtoneShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2572. quit();
  2573. return;
  2574. }
  2575. if (args.contains ("--edisonslottest"))
  2576. {
  2577. // LYNX.exe --edisonslottest folder [project.flp]: round 190cd — the audio editor as a mixer-slot plugin through
  2578. // the engine and the project file (report.txt: one "name=ok|FAIL" per check), its window as slot-*.png, and
  2579. // the Edison slots of an FL project (what was read of each)
  2580. const auto i = args.indexOf ("--edisonslottest");
  2581. const auto ok = runEdisonSlotTest (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2582. setApplicationReturnValue (ok ? 0 : 1);
  2583. quit();
  2584. return;
  2585. }
  2586. if (args.contains ("--danceshot"))
  2587. {
  2588. // LYNX.exe --danceshot prefix: LYNX Dance (round 165e) — every move as a contact sheet, the channel's editor,
  2589. // and a demo project with two dance channels (for --snapshot)
  2590. const auto i = args.indexOf ("--danceshot");
  2591. runDanceShot (args[i + 1].unquoted());
  2592. quit();
  2593. return;
  2594. }
  2595. if (args.contains ("--videoshot") && args.indexOf ("--videoshot") + 2 < args.size())
  2596. {
  2597. // LYNX.exe --videoshot prefix video: the Video Player's editor (round 165g) at a few song positions, with
  2598. // the user's ffmpeg, as PNGs + report.txt (frames decoded, the sound track)
  2599. const auto i = args.indexOf ("--videoshot");
  2600. runVideoShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2601. return;
  2602. }
  2603. if (args.contains ("--videotrackshot") && args.indexOf ("--videotrackshot") + 2 < args.size())
  2604. {
  2605. // LYNX.exe --videotrackshot prefix video [video2]: round 174d — the Playlist with video tracks (filmstrips,
  2606. // timecode row) and the video window at a few song positions, as PNGs + report.txt (the decoder, the
  2607. // frame shown for each wanted time: frame accuracy, frames dropped)
  2608. const auto i = args.indexOf ("--videotrackshot");
  2609. runVideoTrackShot (args[i + 1].unquoted(), args[i + 2].unquoted(), i + 3 < args.size() ? args[i + 3].unquoted() : juce::String());
  2610. return;
  2611. }
  2612. if (args.contains ("--vfxshot"))
  2613. {
  2614. // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
  2615. const auto i = args.indexOf ("--vfxshot");
  2616. runVfxShot (args[i + 1].unquoted());
  2617. quit();
  2618. return;
  2619. }
  2620. if (args.contains ("--patchershot"))
  2621. {
  2622. // LYNX.exe --patchershot prefix [project]: every Patcher's editor (round 141) as PNGs (a demo one without a project)
  2623. const auto i = args.indexOf ("--patchershot");
  2624. runPatcherShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2625. quit();
  2626. return;
  2627. }
  2628. if (args.contains ("--audioxshot"))
  2629. {
  2630. // LYNX.exe --audioxshot prefix (round 190aq): the pre-fader send, the "Low latency while recording" mark on a
  2631. // bypassed slot and the Browser's "Preview in time", drawn off-screen
  2632. runAudioXShot (args[args.indexOf ("--audioxshot") + 1].unquoted());
  2633. quit();
  2634. return;
  2635. }
  2636. if (args.contains ("--comp177shot"))
  2637. {
  2638. // LYNX.exe --comp177shot prefix project (round 177c): a project of loop takes in the maximised
  2639. // Playlist as it opened; every group after "Comp these takes", with a swipe on the first; the track and record menus
  2640. const auto i = args.indexOf ("--comp177shot");
  2641. runComp177Shot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2642. quit();
  2643. return;
  2644. }
  2645. if (args.contains ("--evpaneshot"))
  2646. {
  2647. // LYNX --evpaneshot prefix [project] (round 190fz): the Piano roll's event editor divider driven with the mouse
  2648. // handlers (drag, right-click = alternate size and back, middle-click = default, a drag into the snap zone),
  2649. // a picture of each state and prefix-report.txt with the heights and the remembered settings file
  2650. const auto i = args.indexOf ("--evpaneshot");
  2651. setApplicationReturnValue (runEvPaneShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2652. quit();
  2653. return;
  2654. }
  2655. if (args.contains ("--feat166shot"))
  2656. {
  2657. // LYNX.exe --feat166shot prefix [project]: round 166d (issue #14) — the Piano Roll with a scale, folded to
  2658. // it, with one ghost channel, the ghost channels menu, and the Mixer filled to 500 inserts (its start and
  2659. // its end, and the time a full repaint takes)
  2660. const auto i = args.indexOf ("--feat166shot");
  2661. runFeat166Shot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2662. quit();
  2663. return;
  2664. }
  2665. if (args.contains ("--pickerdropshot"))
  2666. {
  2667. // LYNX --pickerdropshot prefix: round 190hm (issue #177) — Picker panel entries dropped on the Playlist as FL
  2668. // places them (plain drop: one track per entry at the snapped time; Shift: one after another), off-screen,
  2669. // with <prefix>-checks.txt (OK / FAIL per placement)
  2670. setApplicationReturnValue (runPickerDropShot (args[args.indexOf ("--pickerdropshot") + 1].unquoted()) ? 0 : 1);
  2671. quit();
  2672. return;
  2673. }
  2674. if (args.contains ("--trackmodeshot"))
  2675. {
  2676. // LYNX --trackmodeshot prefix: rollup 190cv (UI gate of PR #151) — Playlist track header › Track mode › Audio
  2677. // track, off-screen, in three states of FL's live check 190cu (q1-01 fresh, q1-02 one insert linked
  2678. // elsewhere and one renamed, q1-07 the full state), plus a report that compares each list with FL's
  2679. setApplicationReturnValue (runTrackModeShot (args[args.indexOf ("--trackmodeshot") + 1].unquoted()) ? 0 : 1);
  2680. quit();
  2681. return;
  2682. }
  2683. if (args.contains ("--curveshot"))
  2684. {
  2685. // LYNX.exe --curveshot prefix: round 190bw — an automation clip with one segment per FL curve mode in the
  2686. // point editor and in the Playlist, and FL's point menu, off-screen
  2687. runCurveShot (args[args.indexOf ("--curveshot") + 1].unquoted());
  2688. quit();
  2689. return;
  2690. }
  2691. if (args.contains ("--remoteshot"))
  2692. {
  2693. // LYNX.exe --remoteshot prefix: Online Sessions P5-A1 (round 190ai) — the host's "Share plugins with guests"
  2694. // list and a guest's parameter editor of a plugin the host plays, off-screen with sample data
  2695. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  2696. lynx::liveui::saveRemoteShots (args[args.indexOf ("--remoteshot") + 1].unquoted());
  2697. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  2698. quit();
  2699. return;
  2700. }
  2701. if (args.contains ("--settingsshot") && ! args.contains ("--rtstress")) // (--rtstress has its own --settingsshot file.png option, round 161)
  2702. {
  2703. // LYNX.exe --settingsshot prefix: round 190bx — every Settings page off-screen at the window's size, in a
  2704. // small window (390 x 390) and, for the long pages, whole (see runSettingsShot)
  2705. runSettingsShot (args[args.indexOf ("--settingsshot") + 1].unquoted());
  2706. quit();
  2707. return;
  2708. }
  2709. if (args.contains ("--perfshot"))
  2710. {
  2711. // LYNX.exe --perfshot prefix project: the Playlist in Performance mode with a few clips launched and waiting,
  2712. // then the project patcherized (every insert's effects, the first channels) saved as prefix-patcherized.lynx
  2713. // for --patchershot (round 165m)
  2714. const auto i = args.indexOf ("--perfshot");
  2715. runPerfShot (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  2716. quit();
  2717. return;
  2718. }
  2719. if (args.contains ("--freezetest"))
  2720. {
  2721. // LYNX.exe --freezetest prefix [project]: round 190ay's Freeze end to end, off-screen (see runFreezeTest)
  2722. const auto i = args.indexOf ("--freezetest");
  2723. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2724. // a word after the project: "keep" = freeze, save prefix-frozen.lynx and stop (the audio stays);
  2725. // "measure" = only load and render the project, for the memory and time of a process of its own
  2726. const auto mode = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2727. setApplicationReturnValue (runFreezeTest (args[i + 1].unquoted(), project, mode) ? 0 : 1);
  2728. quit();
  2729. return;
  2730. }
  2731. if (args.contains ("--trackfreezetest"))
  2732. {
  2733. // LYNX --trackfreezetest prefix: round 190ff's Freeze Track, Flatten / Bounce Track in Place, Bounce to New
  2734. // Track and Consolidate end to end in the Clip-launch workflow, off-screen (see runTrackFreezeTest)
  2735. const auto i = args.indexOf ("--trackfreezetest");
  2736. setApplicationReturnValue (runTrackFreezeTest (args[i + 1].unquoted()) ? 0 : 1);
  2737. quit();
  2738. return;
  2739. }
  2740. if (args.contains ("--details190ihshot"))
  2741. {
  2742. // LYNX --details190ihshot prefix: round 190ih's live states off screen (no window, no audio device) — Gross
  2743. // Beat's locator and slots from its real engine, the rack's activity light, Play / Pause, the Record blink,
  2744. // the "Note on" hint, the save reminder, the Simple dock's input level, the Envelope Controller's key line
  2745. const auto i = args.indexOf ("--details190ihshot");
  2746. runDetails190ihShot (args[i + 1].unquoted());
  2747. quit();
  2748. return;
  2749. }
  2750. if (args.contains ("--paintbench"))
  2751. {
  2752. // LYNX --paintbench project.(flp|lynx|als) report.txt (round 190ge): each main view drawn off screen, whole, many
  2753. // times (the message thread's CPU per frame), with the playhead mid-song; no window, no audio device
  2754. const auto i = args.indexOf ("--paintbench");
  2755. runPaintBench (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  2756. quit();
  2757. return;
  2758. }
  2759. if (args.contains ("--design190igshot"))
  2760. {
  2761. // LYNX --design190igshot prefix project.flp: round 190ig off-screen (design190ia slice 3) — the Pattern layout's
  2762. // 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),
  2763. // at FL's "zoom 17" (50 px tracks, 39.75 px a bar), and playing (the activity column), as FL's reference shots
  2764. const auto i = args.indexOf ("--design190igshot");
  2765. runDesign190igShot (args[i + 1].unquoted(), args[i + 2].unquoted());
  2766. quit();
  2767. return;
  2768. }
  2769. if (args.contains ("--cliplaunch190kcshot"))
  2770. {
  2771. // LYNX --cliplaunch190kcshot prefix set.als: round 190kc off screen (Live's return tracks, Sends rows, Pre / Post,
  2772. // the crossfader, the map modes' crossfader positions and relative strip, Commit / Extract on audio); prefix-checks.txt
  2773. const auto i = args.indexOf ("--cliplaunch190kcshot");
  2774. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2775. runClipLaunch190kcShot (args[i + 1].unquoted(), set);
  2776. quit();
  2777. return;
  2778. }
  2779. if (args.contains ("--livelook190jnshot"))
  2780. {
  2781. // LYNX --livelook190jnshot prefix [set.als]: round 190jn off screen (design190ia slices 13, 17, 18, 19, 25: the
  2782. // Clip-launch layout in Live's look, and the classic look); prefix-checks.txt
  2783. const auto i = args.indexOf ("--livelook190jnshot");
  2784. const auto set = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2785. runLiveLook190jnShot (args[i + 1].unquoted(), set);
  2786. quit();
  2787. return;
  2788. }
  2789. if (args.contains ("--fllook190joshot"))
  2790. {
  2791. // LYNX --fllook190joshot prefix project.flp: round 190jo off screen (design190ia slices 12, 21, 23): the Pattern
  2792. // toolbar's tiles in every state, time / tempo / hint / menu bar, at 1920 / 1600 / 1366 / 1280; the Piano roll
  2793. // (FL's rows, notes, keys, grid, ghosts); the audio editor in Edison's layout with FL's "DL Breaker.wav";
  2794. // prefix-checks.txt (note label contrast)
  2795. const auto i = args.indexOf ("--fllook190joshot");
  2796. runFllook190joShot (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String());
  2797. quit();
  2798. return;
  2799. }
  2800. if (args.contains ("--capfix190jjshot"))
  2801. {
  2802. // LYNX --capfix190jjshot prefix project.flp [set.als]: round 190jj off screen (capture190ji's changes: Simple
  2803. // capsule states, master meter, pads press, held keys, drop lane ghosts; Live's control bar; FL's C-11 drop ghost
  2804. // and the picker's playing mark); prefix-checks.txt
  2805. const auto i = args.indexOf ("--capfix190jjshot");
  2806. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2807. runCapfix190jjShot (args[i + 1].unquoted(), args[i + 2].unquoted(), set);
  2808. quit();
  2809. return;
  2810. }
  2811. if (args.contains ("--onboard190npshot"))
  2812. {
  2813. // LYNX --onboard190npshot prefix: round 190np off screen (src/OnboardShot190np.inc): the welcome card, the choices,
  2814. // the Next-3 card, the empty-state hints, the tips and the Help menu, 100 % and @150, with <prefix>-checks.txt
  2815. const auto i = args.indexOf ("--onboard190npshot");
  2816. setApplicationReturnValue (runOnboardShot190np (args[i + 1].unquoted()) ? 0 : 1);
  2817. quit();
  2818. return;
  2819. }
  2820. if (args.contains ("--details190oashot"))
  2821. {
  2822. // LYNX --details190oashot prefix project.flp: round 190oa off screen (src/DetailsShot190oa.inc)
  2823. const auto i = args.indexOf ("--details190oashot");
  2824. setApplicationReturnValue (runDetailsShot190oa (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2825. quit();
  2826. return;
  2827. }
  2828. if (args.contains ("--details190myshot"))
  2829. {
  2830. // LYNX --details190myshot prefix project.flp: round 190my off screen (src/DetailsShot190my.inc)
  2831. const auto i = args.indexOf ("--details190myshot");
  2832. setApplicationReturnValue (runDetailsShot190my (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2833. quit();
  2834. return;
  2835. }
  2836. if (args.contains ("--details190mvshot"))
  2837. {
  2838. // LYNX --details190mvshot prefix project.flp: round 190mv off screen (src/DetailsShot190mv.inc)
  2839. const auto i = args.indexOf ("--details190mvshot");
  2840. setApplicationReturnValue (runDetailsShot190mv (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2841. quit();
  2842. return;
  2843. }
  2844. if (args.contains ("--details190mrshot"))
  2845. {
  2846. // LYNX --details190mrshot prefix project.flp: round 190mr off screen (src/DetailsShot190mr.inc)
  2847. const auto i = args.indexOf ("--details190mrshot");
  2848. setApplicationReturnValue (runDetailsShot190mr (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2849. quit();
  2850. return;
  2851. }
  2852. if (args.contains ("--rack190ncshot") && args.indexOf ("--rack190ncshot") + 1 < args.size())
  2853. {
  2854. // LYNX --rack190ncshot prefix: round 190nc off screen (src/RackShot190nc.inc): Live's rack with its devices
  2855. // inline and the Macro Map overlay (DL-95), the Session mixer's Solo / Cue (DL-110)
  2856. setApplicationReturnValue (runRackShot190nc (args[args.indexOf ("--rack190ncshot") + 1].unquoted()) ? 0 : 1);
  2857. quit();
  2858. return;
  2859. }
  2860. if (args.contains ("--details190mpshot"))
  2861. {
  2862. // LYNX --details190mpshot prefix project.flp: round 190mp off screen (src/DetailsShot190mp.inc)
  2863. const auto i = args.indexOf ("--details190mpshot");
  2864. setApplicationReturnValue (runDetailsShot190mp (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2865. quit();
  2866. return;
  2867. }
  2868. if (args.contains ("--details190mkshot"))
  2869. {
  2870. // LYNX --details190mkshot prefix project.flp: round 190mk off screen (src/DetailsShot190mk.inc)
  2871. const auto i = args.indexOf ("--details190mkshot");
  2872. setApplicationReturnValue (runDetailsShot190mk (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2873. quit();
  2874. return;
  2875. }
  2876. if (args.contains ("--details190mfshot"))
  2877. {
  2878. // LYNX --details190mfshot prefix project.flp: round 190mf off screen (src/DetailsShot190mf.inc)
  2879. const auto i = args.indexOf ("--details190mfshot");
  2880. setApplicationReturnValue (runDetailsShot190mf (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  2881. quit();
  2882. return;
  2883. }
  2884. if (args.contains ("--details190lxshot"))
  2885. {
  2886. // LYNX --details190lxshot prefix project.flp [set.als]: round 190lx off screen (src/DetailsShot190lx.inc)
  2887. const auto i = args.indexOf ("--details190lxshot");
  2888. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2889. setApplicationReturnValue (runDetailsShot190lx (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  2890. quit();
  2891. return;
  2892. }
  2893. if (args.contains ("--details190lrshot"))
  2894. {
  2895. // LYNX --details190lrshot prefix project.flp [set.als]: round 190lr off screen (src/DetailsShot190lr.inc)
  2896. const auto i = args.indexOf ("--details190lrshot");
  2897. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2898. setApplicationReturnValue (runDetailsShot190lr (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  2899. quit();
  2900. return;
  2901. }
  2902. if (args.contains ("--details190ldshot"))
  2903. {
  2904. // LYNX --details190ldshot prefix project.flp [set.als]: round 190ld off screen (src/DetailsShot190ld.inc)
  2905. const auto i = args.indexOf ("--details190ldshot");
  2906. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2907. setApplicationReturnValue (runDetailsShot190ld (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  2908. quit();
  2909. return;
  2910. }
  2911. if (args.contains ("--details190knshot"))
  2912. {
  2913. // LYNX --details190knshot prefix project.flp [set.als]: round 190kn off screen (src/DetailsShot190kn.inc)
  2914. const auto i = args.indexOf ("--details190knshot");
  2915. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2916. setApplicationReturnValue (runDetailsShot190kn (args[i + 1].unquoted(), args[i + 2].unquoted(), set) ? 0 : 1);
  2917. quit();
  2918. return;
  2919. }
  2920. if (args.contains ("--details190imshot"))
  2921. {
  2922. // LYNX --details190imshot prefix project.flp [set.als]: round 190im off-screen (details190if R1, R5, R6, R11, R12,
  2923. // R13, R15) — the automation hints, the Playlist playing (picker marks, glow, overview, activity levels), a drop
  2924. // preview, Follow's pause, the Sampler's handles, and with the Live set the grid's one-shot / follow / queued
  2925. // scene / deactivated clip / hints and the Clip View's launched position; prefix-checks.txt
  2926. const auto i = args.indexOf ("--details190imshot");
  2927. const auto set = i + 3 < args.size() && ! args[i + 3].startsWith ("--") ? args[i + 3].unquoted() : juce::String();
  2928. runDetails190imShot (args[i + 1].unquoted(), args[i + 2].unquoted(), set);
  2929. quit();
  2930. return;
  2931. }
  2932. if (args.contains ("--toolbarshot190iv"))
  2933. {
  2934. // LYNX --toolbarshot190iv prefix [project.als]: round 190iv off screen — the toolbar of each layout style (Pattern,
  2935. // Simple, Clip-launch) at 1920 / 1366 / 1280, the Simple transport capsule idle / hover / pressed / playing /
  2936. // recording, the "Last saved" status in its four states, Live's control bar with every button idle / hover /
  2937. // pressed / lit, the "⋯" menus, and a report of the parts' bounds
  2938. const auto i = args.indexOf ("--toolbarshot190iv");
  2939. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2940. runToolbarShot190iv (args[i + 1].unquoted(), project);
  2941. quit();
  2942. return;
  2943. }
  2944. if (args.contains ("--gridshot"))
  2945. {
  2946. // LYNX.exe --gridshot prefix [project]: the Clip-launch workflow's layout off-screen, with a grid of sample
  2947. // clips, some playing and waiting, at the size of LYNX_SNAPSHOT_SIZE (round 181a); with a project (.lynx,
  2948. // .flp, .als), that project's grid instead (round 181c: a Live set's Session view as LYNX imports it)
  2949. const auto i = args.indexOf ("--gridshot");
  2950. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  2951. runGridShot (args[i + 1].unquoted(), project);
  2952. quit();
  2953. return;
  2954. }
  2955. if (args.contains ("--tour190dvshot"))
  2956. {
  2957. // LYNX.exe --tour190dvshot prefix: round 190dv off-screen — the Simple workflow's Welcome screen, every step of
  2958. // the first-song tour done with its "Do it for me" (a loop dropped for the loop step), the end card, Back /
  2959. // Next / close, the Help menu, the chooser's tour button, Start from with the three demo songs, a demo
  2960. // opened in Simple — and a text report of the checks (incl. resources/demos/*.lynx = the generated songs)
  2961. const auto i = args.indexOf ("--tour190dvshot");
  2962. runTour190dvShot (args[i + 1].unquoted());
  2963. quit();
  2964. return;
  2965. }
  2966. if (args.contains ("--donateshot"))
  2967. {
  2968. // LYNX --donateshot prefix: round 190fq off-screen (no window) — Help › Support LYNX SHARE... in the three
  2969. // layouts, the Support window, the About window's Support button, the start-up support note in the main
  2970. // window, and the note's rules end to end on its saved state (run it with LYNX_PROFILE_DIR: it writes
  2971. // support-note.txt there, and puts the old one back at the end); report prefix-report.txt, exit 0 = OK
  2972. const auto i = args.indexOf ("--donateshot");
  2973. setApplicationReturnValue (runDonateShot (args[i + 1].unquoted()) ? 0 : 1);
  2974. quit();
  2975. return;
  2976. }
  2977. if (args.contains ("--simpleclosetest"))
  2978. {
  2979. // LYNX --simpleclosetest <report.txt>: round 190fc off-screen (no window) — the main window in the Simple
  2980. // layout with Welcome, the tour, Start from, a demo, the dock's tabs, Finish and Lyrics open, then closed as at
  2981. // shutdown (the 0.1.27 RC crashed on every such close); exit code 0 = OK
  2982. const auto i = args.indexOf ("--simpleclosetest");
  2983. setApplicationReturnValue (runSimpleCloseTest (args[i + 1].unquoted()) ? 0 : 1);
  2984. quit();
  2985. return;
  2986. }
  2987. if (args.contains ("--patterns190ea"))
  2988. {
  2989. // LYNX --patterns190ea <report.txt>: round 190ea off-screen (no window) — a song with no pattern at all
  2990. // reaching the engine in every layout (the Simple dock's Editor tab, the Piano roll panel of the Pattern
  2991. // layout, the Clip-launch layout), the last pattern deleted, all patterns cleared by an edit, undo / redo,
  2992. // a live session's remote song and an out-of-range current pattern; each must leave one pattern and not crash
  2993. const auto i = args.indexOf ("--patterns190ea");
  2994. setApplicationReturnValue (runPatterns190ea (args[i + 1].unquoted()) ? 0 : 1);
  2995. quit();
  2996. return;
  2997. }
  2998. if (args.contains ("--reabl190foshot"))
  2999. {
  3000. // LYNX --reabl190foshot prefix: round 190fo off-screen — the Simple Sampler track's 16 pads in the dock, its
  3001. // menus and kits, the typing keys, the .lynx round trip, a folder of stems and MIDI files — and a report
  3002. const auto i = args.indexOf ("--reabl190foshot");
  3003. runReabl190foShot (args[i + 1].unquoted());
  3004. quit();
  3005. return;
  3006. }
  3007. if (args.contains ("--simple190dsshot"))
  3008. {
  3009. // LYNX.exe --simple190dsshot prefix: round 190ds off-screen, at 1x and 2x — loops dropped in the Simple
  3010. // workflow following the project key (the dock's switch, the clip menu), the docked Piano roll in the Editor
  3011. // tab, the keyboard's modes Keys / Scale keys / Chord pad with the scale selector — and a text report
  3012. const auto i = args.indexOf ("--simple190dsshot");
  3013. runSimple190dsShot (args[i + 1].unquoted());
  3014. quit();
  3015. return;
  3016. }
  3017. if (args.contains ("--simple190dgshot"))
  3018. {
  3019. // LYNX.exe --simple190dgshot prefix: round 190dg's additions to the Simple dock off-screen, at 1x and 2x —
  3020. // the Effects tab with all eight one-knob cards and each card alone, a chain preset with Blend, the
  3021. // favourites in the Preset menu, the sound picker (a search, My plugins with a made-up plugin list) — and a
  3022. // text report of the checks
  3023. const auto i = args.indexOf ("--simple190dgshot");
  3024. runSimple190dgShot (args[i + 1].unquoted());
  3025. quit();
  3026. return;
  3027. }
  3028. if (args.contains ("--simplefxshot"))
  3029. {
  3030. // LYNX.exe --simplefxshot prefix: round 190bu's track dock of the Simple workflow off-screen, at 1x and 2x —
  3031. // the Instrument tab (LYNX sounds, My SoundFonts), the Effects tab (empty, a preset, its menus), and a text
  3032. // report: the dock's edits, a user preset saved and loaded, the same slots in the Pattern workflow's Mixer
  3033. const auto i = args.indexOf ("--simplefxshot");
  3034. runSimpleFxShot (args[i + 1].unquoted());
  3035. quit();
  3036. return;
  3037. }
  3038. if (args.contains ("--simple190jcshot"))
  3039. {
  3040. // LYNX.exe --simple190jcshot prefix: round 190jc's Simple layout look (design190ia slices 5, 14, 15, 22, 24 and
  3041. // Large controls) off-screen, at 1x and 2x, with a text report
  3042. const auto i = args.indexOf ("--simple190jcshot");
  3043. runSimple190jcShot (args[i + 1].unquoted());
  3044. quit();
  3045. return;
  3046. }
  3047. if (args.contains ("--simpleshot"))
  3048. {
  3049. // LYNX.exe --simpleshot prefix: round 184a's Simple workflow off-screen — View › Layout style with each style
  3050. // chosen, Settings › General (Pattern, then Simple selected) with its style list, the window in Pattern, then
  3051. // Simple, then Pattern again, and how many Simple workflow objects existed before and after (0 before)
  3052. const auto i = args.indexOf ("--simpleshot");
  3053. runSimpleShot (args[i + 1].unquoted());
  3054. quit();
  3055. return;
  3056. }
  3057. // --versionsshot <prefix> (round 190ap): the Versions panel, File's new items, a project opened without its
  3058. // third-party plugins (window, list, File menu) and the Export window's additions, offscreen
  3059. if (args.contains ("--versionsshot"))
  3060. {
  3061. runVersionsShot (args[args.indexOf ("--versionsshot") + 1].unquoted());
  3062. quit();
  3063. return;
  3064. }
  3065. // --linkshot <prefix> (round 190bt): FL's Remote control settings / Global link settings windows, the control
  3066. // menu with "Link to controller...", the formula presets and controller menus and the Multilink items,
  3067. // offscreen; prefix-checks.txt holds the round's checks of the engine, the project file and the settings
  3068. if (args.contains ("--linkshot"))
  3069. {
  3070. setApplicationReturnValue (runLinkShot (args[args.indexOf ("--linkshot") + 1].unquoted()) ? 0 : 1);
  3071. quit();
  3072. return;
  3073. }
  3074. // --flctlshot <prefix> (round 190df): FL's multilink menu (on / off), the plugin menu's A/B and "Link all
  3075. // parameters...", the sampler's File row with its Sample history, and the Envelope / instrument page of a sampler
  3076. // running FL's voice with its envelope presets, offscreen; prefix-checks.txt holds the checks
  3077. if (args.contains ("--flctlshot"))
  3078. {
  3079. setApplicationReturnValue (runFlCtlShot (args[args.indexOf ("--flctlshot") + 1].unquoted()) ? 0 : 1);
  3080. quit();
  3081. return;
  3082. }
  3083. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen (shots and checks in prefix-checks.txt)
  3084. if (args.contains ("--samplerpageshot"))
  3085. {
  3086. setApplicationReturnValue (runSamplerPageShot (args[args.indexOf ("--samplerpageshot") + 1].unquoted()) ? 0 : 1);
  3087. quit();
  3088. return;
  3089. }
  3090. // --flplshot <prefix> (round 190dx): the audio clip menu (Preview, Automate › Panning / Volume), the Playlist's "+"
  3091. // and its menu, Track mode › Instrument track, the Channel rack's "Assign to new instrument track", Tools › One-click
  3092. // audio recording and Mixer › Disk recording › Latency compensation, offscreen; prefix-checks.txt holds the checks
  3093. // --hdrshot190ft <prefix> (round 190ft, issues #163 / #164): FL's track-header selection and resize rules driven
  3094. // with synthetic mouse events on the Playlist headers and the mixer strips, offscreen; prefix-checks.txt
  3095. if (args.contains ("--hdrshot190ft"))
  3096. {
  3097. setApplicationReturnValue (runHdrShot190ft (args[args.indexOf ("--hdrshot190ft") + 1].unquoted()) ? 0 : 1);
  3098. quit();
  3099. return;
  3100. }
  3101. // --dawprojcheck190jf <prefix> <project> (round 190jf, slice B22): export to DAWproject and open it again
  3102. if (args.contains ("--dawprojcheck190jf") && args.indexOf ("--dawprojcheck190jf") + 2 < args.size())
  3103. {
  3104. const auto at = args.indexOf ("--dawprojcheck190jf");
  3105. setApplicationReturnValue (runDawProjectCheck190jf (args[at + 1].unquoted(), juce::File (args[at + 2].unquoted())) ? 0 : 1);
  3106. quit();
  3107. return;
  3108. }
  3109. // --foldersshot190jf <prefix> <thief.flp> (round 190jf, slice B17): the Playlist's folders; prefix-checks.txt
  3110. if (args.contains ("--foldersshot190jf") && args.indexOf ("--foldersshot190jf") + 2 < args.size())
  3111. {
  3112. const auto at = args.indexOf ("--foldersshot190jf");
  3113. setApplicationReturnValue (runFoldersShot190jf (args[at + 1].unquoted(), juce::File (args[at + 2].unquoted())) ? 0 : 1);
  3114. quit();
  3115. return;
  3116. }
  3117. // --userfixshot190ib <prefix> (round 190ib): issue #182's type-to-jump in a real popup menu (the Playlist's Edit menu
  3118. // of the issue's screenshot, typed into), #183's Piano roll item, #181's Ctrl+, through the main window's keys;
  3119. // prefix-checks.txt
  3120. if (args.contains ("--userfixshot190ib"))
  3121. {
  3122. setApplicationReturnValue (runUserFixShot190ib (args[args.indexOf ("--userfixshot190ib") + 1].unquoted()) ? 0 : 1);
  3123. quit();
  3124. return;
  3125. }
  3126. // --issuesshot190ht <prefix> (round 190ht): issue #127's other tools on Pattern Blocks (Mute, Select + group move,
  3127. // Slice, Zoom) and issue #154's insert effects list on linked headers, driven with synthetic mouse events,
  3128. // offscreen; prefix-checks.txt and pictures
  3129. if (args.contains ("--issuesshot190ht"))
  3130. {
  3131. setApplicationReturnValue (runIssuesShot190ht (args[args.indexOf ("--issuesshot190ht") + 1].unquoted()) ? 0 : 1);
  3132. quit();
  3133. return;
  3134. }
  3135. // --sections190olshot <prefix> (round 190ol, research190oe P1 / P6): src/SectionsShot190ol.inc
  3136. if (args.contains ("--sections190olshot"))
  3137. {
  3138. setApplicationReturnValue (runSectionsShot190ol (args[args.indexOf ("--sections190olshot") + 1].unquoted()) ? 0 : 1);
  3139. quit();
  3140. return;
  3141. }
  3142. // --playlistshot190jq <prefix> (round 190jq, issues #164 and #191): src/PlaylistShot190jq.inc
  3143. if (args.contains ("--playlistshot190jq"))
  3144. {
  3145. setApplicationReturnValue (runPlaylistShot190jq (args[args.indexOf ("--playlistshot190jq") + 1].unquoted()) ? 0 : 1);
  3146. quit();
  3147. return;
  3148. }
  3149. // --focus218shot190ng <prefix> (round 190ng, issue #218): src/Focus218Shot190ng.inc
  3150. if (args.contains ("--focus218shot190ng"))
  3151. {
  3152. setApplicationReturnValue (runFocus218Shot190ng (args[args.indexOf ("--focus218shot190ng") + 1].unquoted()) ? 0 : 1);
  3153. quit();
  3154. return;
  3155. }
  3156. // --mixer221shot190ng <prefix> (round 190ng, issue #221): src/Mixer221Shot190ng.inc
  3157. if (args.contains ("--mixer221shot190ng"))
  3158. {
  3159. setApplicationReturnValue (runMixer221Shot190ng (args[args.indexOf ("--mixer221shot190ng") + 1].unquoted()) ? 0 : 1);
  3160. quit();
  3161. return;
  3162. }
  3163. // --research190onshot <prefix> (round 190on: research190oe P2, P8, P10): src/Research190onShot.inc
  3164. if (args.contains ("--research190onshot"))
  3165. {
  3166. setApplicationReturnValue (runResearchShot190on (args[args.indexOf ("--research190onshot") + 1].unquoted()) ? 0 : 1);
  3167. quit();
  3168. return;
  3169. }
  3170. // --issuesshot190nq <prefix> (round 190nq, issues #193, #225-#230): src/IssuesShot190nq.inc
  3171. if (args.contains ("--issuesshot190nq"))
  3172. {
  3173. setApplicationReturnValue (runIssuesShot190nq (args[args.indexOf ("--issuesshot190nq") + 1].unquoted()) ? 0 : 1);
  3174. quit();
  3175. return;
  3176. }
  3177. // --rollup031s3shot <prefix> (rollup 0.1.31 step 3, round 190ny): src/Rollup031S3Shot.inc
  3178. if (args.contains ("--rollup031s3shot"))
  3179. {
  3180. setApplicationReturnValue (runRollup031S3Shot (args[args.indexOf ("--rollup031s3shot") + 1].unquoted()) ? 0 : 1);
  3181. quit();
  3182. return;
  3183. }
  3184. // --tabs2test190nz <a|b> <folder> (round 190nz, issue #232 stage 2: copy and paste between two LYNX windows):
  3185. // src/Tabs2Test190nz.inc
  3186. if (args.contains ("--tabs2test190nz"))
  3187. {
  3188. const auto i = args.indexOf ("--tabs2test190nz");
  3189. setApplicationReturnValue (runTabs2Test190nz (args[i + 1].unquoted(), juce::File (args[i + 2].unquoted())) ? 0 : 1);
  3190. quit();
  3191. return;
  3192. }
  3193. // --issuesshot190od <prefix> (round 190od, issues #236-#242): src/IssuesShot190od.inc
  3194. if (args.contains ("--issuesshot190od"))
  3195. {
  3196. setApplicationReturnValue (runIssuesShot190od (args[args.indexOf ("--issuesshot190od") + 1].unquoted()) ? 0 : 1);
  3197. quit();
  3198. return;
  3199. }
  3200. // --issuesshot190ns <prefix> (round 190ns, issues #231-#235): src/IssuesShot190ns.inc
  3201. if (args.contains ("--issuesshot190ns"))
  3202. {
  3203. setApplicationReturnValue (runIssuesShot190ns (args[args.indexOf ("--issuesshot190ns") + 1].unquoted()) ? 0 : 1);
  3204. quit();
  3205. return;
  3206. }
  3207. // --issuesshot190ng <prefix> (round 190ng, issues #215, #217, #219, #220, #222): src/IssuesShot190ng.inc
  3208. if (args.contains ("--issuesshot190ng"))
  3209. {
  3210. setApplicationReturnValue (runIssuesShot190ng (args[args.indexOf ("--issuesshot190ng") + 1].unquoted()) ? 0 : 1);
  3211. quit();
  3212. return;
  3213. }
  3214. // --tracker190nwshot <prefix> [module] (round 190nw, 0.1.31: the built-in tracker): src/TrackerShot190nw.inc
  3215. if (args.contains ("--tracker190nwshot"))
  3216. {
  3217. const auto i = args.indexOf ("--tracker190nwshot");
  3218. setApplicationReturnValue (runTrackerShot190nw (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String()) ? 0 : 1);
  3219. quit();
  3220. return;
  3221. }
  3222. // --trackclips190neshot <prefix> (round 190ne, 0.1.31: track clips): src/TrackClipsShot190ne.inc
  3223. if (args.contains ("--trackclips190neshot"))
  3224. {
  3225. setApplicationReturnValue (runTrackClipsShot190ne (args[args.indexOf ("--trackclips190neshot") + 1].unquoted()) ? 0 : 1);
  3226. quit();
  3227. return;
  3228. }
  3229. // --issueshot190mq <prefix> (round 190mq, issues #211, #212, #213): src/IssuesShot190mq.inc
  3230. if (args.contains ("--issueshot190mq"))
  3231. {
  3232. setApplicationReturnValue (runIssuesShot190mq (args[args.indexOf ("--issueshot190mq") + 1].unquoted()) ? 0 : 1);
  3233. quit();
  3234. return;
  3235. }
  3236. // --issueshot190lw <prefix> (round 190lw, issues #205, #206, #207): src/IssuesShot190lw.inc
  3237. if (args.contains ("--issueshot190lw"))
  3238. {
  3239. setApplicationReturnValue (runIssuesShot190lw (args[args.indexOf ("--issueshot190lw") + 1].unquoted()) ? 0 : 1);
  3240. quit();
  3241. return;
  3242. }
  3243. // --issueshot190jz <prefix> (round 190jz, issues #192, #194, #195): src/IssuesShot190jz.inc
  3244. if (args.contains ("--issueshot190jz"))
  3245. {
  3246. setApplicationReturnValue (runIssuesShot190jz (args[args.indexOf ("--issueshot190jz") + 1].unquoted()) ? 0 : 1);
  3247. quit();
  3248. return;
  3249. }
  3250. // --workflowshot190iu <prefix> (round 190iu, issues #186 and #191): src/WorkflowShot190iu.inc
  3251. if (args.contains ("--workflowshot190iu"))
  3252. {
  3253. setApplicationReturnValue (runWorkflowShot190iu (args[args.indexOf ("--workflowshot190iu") + 1].unquoted()) ? 0 : 1);
  3254. quit();
  3255. return;
  3256. }
  3257. // --trackautoshot190gz <prefix> (round 190gz, issue #170): LYNX's "Link Playlist tracks to mixer tracks" — the
  3258. // switch, the linked headers' M / S / volume / pan driven with synthetic mouse events, row sizes, undo and the
  3259. // .lynx round trip, offscreen; prefix-checks.txt
  3260. if (args.contains ("--trackautoshot190gz"))
  3261. {
  3262. setApplicationReturnValue (runTrackAutoShot190gz (args[args.indexOf ("--trackautoshot190gz") + 1].unquoted()) ? 0 : 1);
  3263. quit();
  3264. return;
  3265. }
  3266. if (args.contains ("--flplshot"))
  3267. {
  3268. setApplicationReturnValue (runFlPlShot (args[args.indexOf ("--flplshot") + 1].unquoted()) ? 0 : 1);
  3269. quit();
  3270. return;
  3271. }
  3272. // --genpresetshot <prefix> (round 190fs): the channel window's preset box with the user's own presets (Save
  3273. // preset..., Your presets, Delete preset, Show the presets folder) for Fruity DX10, 3x Osc and LYNX's synth, the
  3274. // name box, a load (one undo step) and the Browser's new channel, offscreen; prefix-checks.txt holds the checks
  3275. if (args.contains ("--genpresetshot"))
  3276. {
  3277. setApplicationReturnValue (runGenPresetShot (args[args.indexOf ("--genpresetshot") + 1].unquoted()) ? 0 : 1);
  3278. quit();
  3279. return;
  3280. }
  3281. // --flfixshot <prefix> (round 190ey): what the live FL session 190ew found different (the Sampler page, the
  3282. // Multilink menu, the Playlist, issue #152's question), offscreen; prefix-checks.txt holds the checks
  3283. if (args.contains ("--flfixshot"))
  3284. {
  3285. setApplicationReturnValue (runFlFixShot (args[args.indexOf ("--flfixshot") + 1].unquoted()) ? 0 : 1);
  3286. quit();
  3287. return;
  3288. }
  3289. // --flclipshot <prefix> (round 190dz): FL's audio clip menu layout (two columns, FL's sections, LYNX's own items at
  3290. // the end) and the channel's Misc › Levels adjustment, offscreen; prefix-checks.txt holds the checks
  3291. if (args.contains ("--flclipshot"))
  3292. {
  3293. setApplicationReturnValue (runFlClipShot (args[args.indexOf ("--flclipshot") + 1].unquoted()) ? 0 : 1);
  3294. quit();
  3295. return;
  3296. }
  3297. if (args.contains ("--warpshot"))
  3298. {
  3299. // LYNX.exe --warpshot prefix: round 190cg's pictures (warp commands in the audio editor, the Clip page's
  3300. // Audio panel, the arrangement with the loop switched off, a folded track, signature changes), off-screen
  3301. const auto i = args.indexOf ("--warpshot");
  3302. runWarpShot (args[i + 1].unquoted());
  3303. quit();
  3304. return;
  3305. }
  3306. // --bandlab190jrshot <prefix> (round 190jr): a .blx imported as Simple tracks, the region loop handle, the Simple
  3307. // automation view and its menu, the Extract stems form; <prefix>-report.txt with ok / FAIL lines
  3308. if (args.contains ("--bandlab190jrshot"))
  3309. {
  3310. runBandlab190jrShot (args[args.indexOf ("--bandlab190jrshot") + 1].unquoted());
  3311. quit();
  3312. return;
  3313. }
  3314. // --bandlabshot <prefix> (round 190ch): Lyrics / Notes, Reference match, Start from and Clean voice, offscreen
  3315. if (args.contains ("--bandlabshot"))
  3316. {
  3317. runBandlabShot (args[args.indexOf ("--bandlabshot") + 1].unquoted());
  3318. quit();
  3319. return;
  3320. }
  3321. if (args.contains ("--mpeshot190hy"))
  3322. {
  3323. // LYNX --mpeshot190hy prefix: round 190hy (issue #108, MPE stage 2) off-screen: the Piano roll's MPE lanes (pitch
  3324. // bend, slide, pressure) over notes with curves in Pattern workflow, then the Clip-launch layout's Clip page with
  3325. // its Notes and MPE tabs. Writes prefix-checks.txt.
  3326. runMpeShot190hy (args[args.indexOf ("--mpeshot190hy") + 1].unquoted());
  3327. quit();
  3328. return;
  3329. }
  3330. if (args.contains ("--detailshot"))
  3331. {
  3332. // LYNX.exe --detailshot prefix: the Clip-launch workflow's detail view off-screen (round 183a): a track's chain
  3333. // (instrument, effects, one off, one folded), its clip page, and Pattern workflow before / after, at
  3334. // LYNX_SNAPSHOT_SIZE. Writes prefix-counts.txt with what the chain shows.
  3335. const auto i = args.indexOf ("--detailshot");
  3336. runDetailShot (args[i + 1].unquoted());
  3337. quit();
  3338. return;
  3339. }
  3340. if (args.contains ("--meldshot190ko"))
  3341. {
  3342. // LYNX.exe --meldshot190ko prefix meld.adv spectraltime.adv spectralresonator.adv: round 190ko off-screen, in the
  3343. // Clip-launch layout: a track whose instrument is what a Live Meld preset imports onto (Braid) and whose insert
  3344. // holds what Spectral Time and Spectral Resonator presets import onto (Timeprism, Harmonia), on the Device View.
  3345. // Writes prefix-devices.png and prefix-checks.txt.
  3346. const auto i = args.indexOf ("--meldshot190ko");
  3347. runMeldShot190ko (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].unquoted(), args[i + 4].unquoted());
  3348. quit();
  3349. return;
  3350. }
  3351. if (args.contains ("--livedevshot190kk"))
  3352. {
  3353. // LYNX.exe --livedevshot190kk prefix: round 190kk off-screen, in the Clip-launch layout: a track whose insert holds
  3354. // what Live's Erosion, Vinyl Distortion and Corpus (Core Library presets) import onto — Corrode, Platter,
  3355. // Soundboard — on the Device View as ordinary effect cards. Writes prefix-devices.png and prefix-checks.txt.
  3356. runLiveDevShot190kk (args[args.indexOf ("--livedevshot190kk") + 1].unquoted());
  3357. quit();
  3358. return;
  3359. }
  3360. if (args.contains ("--liverackshot190hr"))
  3361. {
  3362. // LYNX.exe --liverackshot190hr prefix: round 190hr off-screen, in the Ableton-style layout: the Device View's
  3363. // instrument menu with Group / Ungroup, an instrument grouped into an Instrument Rack and back, a rack's Save
  3364. // Preset button and drop area (a device dropped in, an instrument refused), Live's own .adg presets opened
  3365. // with their chains, and a saved .adg read back. Writes prefix-checks.txt.
  3366. runLiveRackShot190hr (args[args.indexOf ("--liverackshot190hr") + 1].unquoted());
  3367. quit();
  3368. return;
  3369. }
  3370. if (args.contains ("--helixshot190mi"))
  3371. {
  3372. // LYNX --helixshot190mi prefix [bank preset name]: round 190mi off-screen, the Pattern layout's Helix channel
  3373. // window with Helix+'s strip, from a factory preset (default "Growl FM"): the device + strip, LFO 1 (drawn),
  3374. // the Matrix page (macros, Helix+'s rows); --shot-scale 1.5 --shot-suffix @150 for the 150 % pictures.
  3375. const auto i = args.indexOf ("--helixshot190mi");
  3376. runHelixShot190mi (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String ("Growl FM"));
  3377. quit();
  3378. return;
  3379. }
  3380. if (args.contains ("--helixshot190oc"))
  3381. {
  3382. // LYNX --helixshot190oc prefix: round 190oc off-screen: the Pattern layout's Helix channel window with round 4's
  3383. // row (Grain Swarm, Spectral Ensemble; Frozen Choir and Triple Stack for the side by side with 190mt), the strip's
  3384. // row alone; paint costs in prefix-checks.txt
  3385. runHelixShot190oc (args[args.indexOf ("--helixshot190oc") + 1].unquoted());
  3386. quit();
  3387. return;
  3388. }
  3389. if (args.contains ("--helixshot190mt"))
  3390. {
  3391. // LYNX --helixshot190mt prefix: round 190mt off-screen: the Pattern layout's Helix channel window with round 3's
  3392. // row (Grain Cloud, Frozen Choir, Spectral Glass; Triple Stack for the side by side with 190ml), the Matrix page with
  3393. // the new rows, and the Clip-launch Device View card's Helix+ panel; paint costs in prefix-checks.txt.
  3394. runHelixShot190mt (args[args.indexOf ("--helixshot190mt") + 1].unquoted());
  3395. quit();
  3396. return;
  3397. }
  3398. if (args.contains ("--helixshot190ml"))
  3399. {
  3400. // LYNX --helixshot190ml prefix: round 190ml off-screen: the Pattern layout's Helix channel window with Helix+ 2's
  3401. // rows (Triple Stack, Vowel Sync), the Matrix page's Macros tab, the table editor (Draw, Harmonics) and the
  3402. // Clip-launch Device View card without / with its Helix+ panel; paint costs in prefix-checks.txt.
  3403. runHelixShot190ml (args[args.indexOf ("--helixshot190ml") + 1].unquoted());
  3404. quit();
  3405. return;
  3406. }
  3407. if (args.contains ("--helixshot190ja"))
  3408. {
  3409. // LYNX --helixshot190ja prefix [Wavetable preset .adv]: round 190ja off-screen, the Clip-launch layout's Device
  3410. // View with a Helix track (the preset's values imported as a Live set would bring them, else Helix's defaults):
  3411. // the device and its pages (Matrix, MIDI, MPE, Env 2, LFO 1, Osc 2), then the Pattern layout's channel window.
  3412. const auto i = args.indexOf ("--helixshot190ja");
  3413. runHelixShot190ja (args[i + 1].unquoted(), i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String());
  3414. quit();
  3415. return;
  3416. }
  3417. if (args.contains ("--liveshot190ce"))
  3418. {
  3419. // LYNX.exe --liveshot190ce prefix: round 190ce off-screen, in the Ableton-style layout: the Device View's cards
  3420. // with their hot-swap and save buttons, a device's menu, hot-swap on (the Browser's bar, the lit button), a
  3421. // swap and its undo, a duplicate, and the Browser's collections (STARRED tab, the Collections menu, a search
  3422. // by a collection's name). Writes prefix-checks.txt.
  3423. runLiveShot190ce (args[args.indexOf ("--liveshot190ce") + 1].unquoted());
  3424. quit();
  3425. return;
  3426. }
  3427. if (args.contains ("--missingsearchshot190eo"))
  3428. {
  3429. // LYNX --missingsearchshot190eo prefix folder...: round 190eo (integration of issue #159's fix) off-screen: the
  3430. // Missing files window's Samples page while a real search of the folders runs (matches streamed in, Stop
  3431. // shown, Apply usable). Writes prefix-searching.png and prefix-checks.txt; the search is let go at the end.
  3432. const auto i = args.indexOf ("--missingsearchshot190eo");
  3433. const auto prefix = args[i + 1].unquoted();
  3434. juce::StringArray folders;
  3435. for (int k = i + 2; k < args.size(); ++k)
  3436. folders.add (args[k].unquoted());
  3437. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3438. std::shared_ptr<juce::Component> panel = lynx::makeMissingFilesPanelSearching (lynx::missingFilesSnapshotInfo(), folders);
  3439. juce::Timer::callAfterDelay (700, [this, panel, prefix] {
  3440. juce::String status;
  3441. bool stopShown = false, applyEnabled = false;
  3442. const auto searching = lynx::missingFilesSearchState (*panel, status, stopShown, applyEnabled);
  3443. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  3444. const auto file = juce::File (prefix + "-searching.png");
  3445. file.deleteFile();
  3446. if (auto out = file.createOutputStream())
  3447. juce::PNGImageFormat().writeImageToStream (image, *out);
  3448. juce::String checks;
  3449. auto check = [&checks] (const char* name, bool ok, const juce::String& detail) {
  3450. checks << name << "=" << (ok ? "OK" : "FAIL") << " " << detail << "\n";
  3451. };
  3452. check ("still_searching_at_the_shot", searching, {});
  3453. check ("status_shows_the_walk", status.contains (lynx::tr ("Searching {0}... {1} files looked at").upToFirstOccurrenceOf ("{0}", false, false)), status);
  3454. check ("stop_shown", stopShown, {});
  3455. check ("apply_usable_during_the_search", applyEnabled, {});
  3456. lynx::stopMissingFilesSearch (*panel);
  3457. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  3458. quit();
  3459. });
  3460. return;
  3461. }
  3462. // --grooveshot190fm <prefix> (round 190fm): a Playlist pattern clip's menu with its Groove items (the chooser, Commit,
  3463. // Extract) and the "Classic swing" folder, and a Groove Pool holding classic swing grooves, offscreen;
  3464. // prefix-checks.txt holds the checks (also the .lynx round trip of a Playlist clip's groove)
  3465. if (args.contains ("--grooveshot190fm"))
  3466. {
  3467. setApplicationReturnValue (runGrooveShot190fm (args[args.indexOf ("--grooveshot190fm") + 1].unquoted()) ? 0 : 1);
  3468. quit();
  3469. return;
  3470. }
  3471. if (args.contains ("--mtshot190fm"))
  3472. {
  3473. // LYNX --mtshot190fm prefix: round 190fm off-screen: the MIDI Tools panel's Generate tab with each generator
  3474. // (prefix-generate-rhythm.png … -euclidean.png), the five side by side as Live's picture shows them
  3475. // (prefix-generate-panels.png; Live's: ableton190o/shots/live-04-generate-panels.png), then each generator
  3476. // written into a one-bar pattern and undone again: prefix-checks.txt.
  3477. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3478. runMtShot190fm (args[args.indexOf ("--mtshot190fm") + 1].unquoted());
  3479. quit();
  3480. return;
  3481. }
  3482. if (args.contains ("--drumshot190ec"))
  3483. {
  3484. // LYNX.exe --drumshot190ec prefix: round 190ec off-screen: a demo Drum Rack's pad view (default and scrolled), its
  3485. // chain list with I-O, sends and return chains, a new empty Drum Rack and the Piano roll's pad names. Writes
  3486. // prefix-checks.txt (hit tests: C1 bottom-left, overview scroll, a pad dragged onto another swaps them).
  3487. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3488. lynx::drumshot::run (args[args.indexOf ("--drumshot190ec") + 1].unquoted());
  3489. quit();
  3490. return;
  3491. }
  3492. if (args.contains ("--linkshot190gl"))
  3493. {
  3494. // LYNX --linkshot190gl prefix (round 190gl): Ableton Link off-screen with a second Link peer in this process —
  3495. // the toolbar in FL's Pattern layout (hidden by default, then shown, off and on) and in the Clip-launch layout
  3496. // ("1 Link", the position display's progress bar, Play waiting), Settings › Ableton Link, the toggle's
  3497. // drop-down and the Options menu. Writes prefix-checks.txt.
  3498. runLinkShot190gl (args[args.indexOf ("--linkshot190gl") + 1].unquoted());
  3499. quit();
  3500. return;
  3501. }
  3502. if (args.contains ("--communityshot190hp"))
  3503. {
  3504. // LYNX --communityshot190hp prefix (round 190hp): global MIDI mappings, Mix snapshots and Split at silence
  3505. // off-screen; writes prefix-checks.txt
  3506. runCommunityShot190hp (args[args.indexOf ("--communityshot190hp") + 1].unquoted());
  3507. quit();
  3508. return;
  3509. }
  3510. if (args.contains ("--mapshot190ef"))
  3511. {
  3512. // LYNX.exe --mapshot190ef prefix: round 190ef's map modes off-screen, in the Clip-launch workflow: MIDI Map Mode
  3513. // (the overlay over the grid, the Session mixer, the Device View and the transport; the Mapping Browser with
  3514. // Min / Max), Key Map Mode, the row menu, the title bar's Draw / Key / MIDI switches, Ctrl+M / Ctrl+K and the
  3515. // Pattern layout keeping Ctrl+M. Writes prefix-checks.txt.
  3516. runMapShot190ef (args[args.indexOf ("--mapshot190ef") + 1].unquoted());
  3517. quit();
  3518. return;
  3519. }
  3520. if (args.contains ("--sceneshot190ef"))
  3521. {
  3522. // LYNX.exe --sceneshot190ef prefix: round 190ef's scene work off-screen, in the Clip-launch workflow: the scene
  3523. // column with its tempo / time signature fields, the scene menu, a scene field's menu, the column title's menu
  3524. // (Rename, colours), a duplicated scene and a captured scene. Writes prefix-checks.txt.
  3525. runSceneShot190ef (args[args.indexOf ("--sceneshot190ef") + 1].unquoted());
  3526. quit();
  3527. return;
  3528. }
  3529. if (args.contains ("--drawshot190ef"))
  3530. {
  3531. // LYNX.exe --drawshot190ef prefix: round 190ef off-screen, in the Clip-launch workflow: Draw Mode in an
  3532. // automation lane, steps at the grid width and an Alt (no grid) freehand stroke drawn through the Playlist's
  3533. // own mouse handlers, and the Options menu with "Draw Mode". Writes prefix-checks.txt.
  3534. runDrawShot190ef (args[args.indexOf ("--drawshot190ef") + 1].unquoted());
  3535. quit();
  3536. return;
  3537. }
  3538. if (args.contains ("--clipenvshot190gi"))
  3539. {
  3540. // LYNX.exe --clipenvshot190gi prefix: round 190gi off-screen: audio clip envelopes on the Playlist (volume and
  3541. // pan lanes, edited through the Playlist's own mouse handlers), the clip menu's LYNX extras (Clip envelope ›,
  3542. // Auto-warp, Quantize audio, run from the menu), warp flags added on the flag strip and moved with Alt + drag,
  3543. // and the Clip-launch Clip View's Envelopes tab (Clip › Gain, Mixer › Track Panning). Writes prefix-checks.txt.
  3544. runClipEnvShot190gi (args[args.indexOf ("--clipenvshot190gi") + 1].unquoted());
  3545. quit();
  3546. return;
  3547. }
  3548. if (args.contains ("--gapsshot190kf"))
  3549. {
  3550. // LYNX.exe --gapsshot190kf prefix [file.wav]: round gaps190kf off-screen: the Clip View's warp time line (Live's
  3551. // loop brace and Start / End markers under the beat-time ruler, the seconds ruler of an unwarped clip) on the
  3552. // probe of gaps190kf/live/cv-clipview.als (voice.wav, warp markers at 30 % / 55 %, Loop 1.3 … 3.3, Start 1.4).
  3553. const auto i = args.indexOf ("--gapsshot190kf");
  3554. runGapsShot190kf (args[i + 1].unquoted(), i + 2 < args.size() ? args[i + 2].unquoted() : juce::String());
  3555. quit();
  3556. return;
  3557. }
  3558. if (args.contains ("--livefactsshot190gx"))
  3559. {
  3560. // LYNX.exe --livefactsshot190gx prefix: round 190gx off-screen: the Clip page's Audio panel in Live's 190gu
  3561. // layout (Beats: Preserve label + chooser, the loop-mode icon chooser beside the Transient Envelope box;
  3562. // Tones / Texture: Grain Size [+ Flux]; Complex [Pro]), the Envelopes tab with a Clip Gain staircase on Live's
  3563. // axis, choosers at the bottom left, and an unwarped clip without the Envelopes tab. Writes prefix-checks.txt.
  3564. runLiveFactsShot190gx (args[args.indexOf ("--livefactsshot190gx") + 1].unquoted());
  3565. quit();
  3566. return;
  3567. }
  3568. if (args.contains ("--dvshot190hr"))
  3569. {
  3570. // LYNX.exe --dvshot190hr prefix: round 190hr off-screen, the Clip-launch Clip View: a MIDI clip whose Start
  3571. // marker sits inside its loop, with its own scale and a follow action (Launch panel controls), the docked
  3572. // editor's grid value and menu, Ctrl+1 / Ctrl+3 / Ctrl+U on it, the Quantize Settings panel, and an audio clip
  3573. // transposed past ±12. Writes prefix-checks.txt.
  3574. runDvShot190hr (args[args.indexOf ("--dvshot190hr") + 1].unquoted());
  3575. quit();
  3576. return;
  3577. }
  3578. if (args.contains ("--warpshot190fm"))
  3579. {
  3580. // LYNX.exe --warpshot190fm prefix: round 190fm off-screen: the Clip page's Audio panel of a grid audio clip in
  3581. // Beats (Preserve, Transient Loop Mode, Envelope), Tones and Texture (Grain Size), Complex (none), and the clip
  3582. // made unique by a mode change while another clip shares its channel (O16). Writes prefix-checks.txt.
  3583. runWarpShot190fm (args[args.indexOf ("--warpshot190fm") + 1].unquoted());
  3584. quit();
  3585. return;
  3586. }
  3587. if (args.contains ("--liveshot190dr"))
  3588. {
  3589. // LYNX.exe --liveshot190dr prefix: round 190dr off-screen, in the Clip-launch workflow: the Session mixer
  3590. // under the clip grid (default sections, Track Options, Volume only, hidden, its View menu), the Clip page's
  3591. // Sample panel of an audio clip (Warp on / off, the Set buttons while it plays, the sample's title) and a
  3592. // device dragged from one track's Device View to another track. Writes prefix-checks.txt.
  3593. runLiveShot190dr (args[args.indexOf ("--liveshot190dr") + 1].unquoted());
  3594. quit();
  3595. return;
  3596. }
  3597. if (args.contains ("--gapshot190og"))
  3598. {
  3599. // LYNX.exe --gapshot190og prefix [--shot-scale 1.5 --shot-suffix @150] (round gap190og, coverage rows still open on
  3600. // 0.1.31): in the Clip-launch layout, the Edit menu's Live block on the Device View (deviceview-0012), the Clip
  3601. // panel's Duplicate (Loop) button (detail-019), the clip menu's Crop Clip and Ctrl+Shift+J (detail-020), the
  3602. // Velocity lane's Randomize footer (detail-047), Key Map Mode on the transport switches (mapping-0028);
  3603. // checks in prefix-checks.txt
  3604. runGapShot190og (args[args.indexOf ("--gapshot190og") + 1].unquoted());
  3605. quit();
  3606. return;
  3607. }
  3608. if (args.contains ("--undoshot190mz"))
  3609. {
  3610. // LYNX.exe --undoshot190mz prefix [--shot-scale 1.5 --shot-suffix @150] (round 190mz, issue #214): the main
  3611. // window's undo keys with three edits, in both "Alternate undo mode" settings, and the Edit menu after each
  3612. // step in the Pattern, Clip-launch and Simple layouts (prefix-menu-*.png); checks in prefix-checks.txt
  3613. runUndoShot190mz (args[args.indexOf ("--undoshot190mz") + 1].unquoted());
  3614. quit();
  3615. return;
  3616. }
  3617. if (args.contains ("--design190igs4shot"))
  3618. {
  3619. // LYNX.exe --design190igs4shot prefix [set.als]: round 190ig slice 4 off-screen, in the Clip-launch layout with the
  3620. // set imported there (Live's colours, CL-6): the Session grid in Live's look idle, then the launch states —
  3621. // playing, a launch waiting (both blink phases), a stop waiting, recording, the status pie at 25 / 50 / 75 % —
  3622. // and the same with Animations off, then round 181a's look (the option); prefix-checks.txt
  3623. const auto i = args.indexOf ("--design190igs4shot");
  3624. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3625. runDesign190igS4Shot (args[i + 1].unquoted(), project);
  3626. quit();
  3627. return;
  3628. }
  3629. if (args.contains ("--typeaheadtest"))
  3630. {
  3631. // LYNX.exe --typeaheadtest out.txt: issue #64 — a real popup menu (headings, a submenu) driven by key presses
  3632. // through its window's peer, as the OS delivers them; writes what got the highlight and what was picked
  3633. const auto i = args.indexOf ("--typeaheadtest");
  3634. runTypeAheadTest (juce::File (args[i + 1].unquoted()));
  3635. return;
  3636. }
  3637. if (args.contains ("--choosertest"))
  3638. {
  3639. // LYNX --choosertest out.txt file: issue #72 — opens LYNX's file chooser as the UI does (makeFileChooser +
  3640. // launchChooser) and reports which dialog came up and what reached the callback. A built-in dialog is shot
  3641. // (out.txt.png), `file` typed into it and confirmed; a native one (zenity / kdialog) is left to answer.
  3642. const auto i = args.indexOf ("--choosertest");
  3643. runChooserTest (juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()));
  3644. return;
  3645. }
  3646. if (args.contains ("--stabilityshot"))
  3647. {
  3648. // LYNX --stabilityshot <folder> (round 190gg): offscreen PNGs of the crash prompt, the plugin window's crash
  3649. // notice, the Plugin manager's "Separate process" column and the monitor's dropout line (no window opens)
  3650. const auto i = args.indexOf ("--stabilityshot");
  3651. runStabilityShot (args[i + 1].unquoted());
  3652. return;
  3653. }
  3654. if (args.contains ("--smarttipshot190ok"))
  3655. {
  3656. // LYNX --smarttipshot190ok <folder> [project.flp] (round 190ok, D1): the smart-disable tip at 100 / 150 %
  3657. const auto i = args.indexOf ("--smarttipshot190ok");
  3658. const auto project = i + 2 < args.size() && ! args[i + 2].startsWith ("--") ? args[i + 2].unquoted() : juce::String();
  3659. setApplicationReturnValue (runSmartTipShot190ok (args[i + 1].unquoted(), project) ? 0 : 1);
  3660. quit();
  3661. return;
  3662. }
  3663. if (args.contains ("--monitorshot190of"))
  3664. {
  3665. // LYNX --monitorshot190of <folder> (round 190of): the Plugin performance monitor with its sample numbers
  3666. // (Longest, Spikes) at 100 % and 150 %, off screen
  3667. const juce::File dir (args[args.indexOf ("--monitorshot190of") + 1].unquoted());
  3668. dir.createDirectory();
  3669. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3670. {
  3671. lynx::AudioEngine offline (false);
  3672. lynx::MainComponent ui (offline, false);
  3673. offline.dispatchPendingMessages();
  3674. for (const auto scale : { 1.0f, 1.5f })
  3675. {
  3676. auto panel = lynx::makePluginMonitorPanel (offline);
  3677. juce::Component frame;
  3678. frame.setSize (panel->getWidth(), panel->getHeight());
  3679. frame.setOpaque (true);
  3680. frame.addAndMakeVisible (*panel);
  3681. savePng (frame.createComponentSnapshot (frame.getLocalBounds(), true, scale),
  3682. dir.getChildFile (scale > 1.0f ? "plugin-monitor@150.png" : "plugin-monitor.png").getFullPathName());
  3683. }
  3684. }
  3685. setApplicationReturnValue (0);
  3686. quit();
  3687. return;
  3688. }
  3689. if (args.contains ("--snapshot"))
  3690. {
  3691. const auto i = args.indexOf ("--snapshot");
  3692. runSnapshot (args[i + 1].unquoted(), args[i + 2].unquoted());
  3693. return;
  3694. }
  3695. if (args.contains ("--stemsplit"))
  3696. {
  3697. // LYNX.exe --stemsplit input.wav folder ["stems=111100 model=2 ..."]: the stem separation of the clip menu,
  3698. // without the window (round 190jr: the options as the settings file writes them; none = every stem, Standard)
  3699. const auto i = args.indexOf ("--stemsplit");
  3700. lynx::AudioEngine loader (false);
  3701. const auto options = i + 3 < args.size() && args[i + 3].unquoted().containsChar ('=') ? lynx::stemsplit::optionsFromText (args[i + 3].unquoted().toStdString())
  3702. : lynx::stemsplit::Options {};
  3703. const auto started = juce::Time::getMillisecondCounterHiRes();
  3704. const auto error = lynx::extractStemsToFolder (loader, juce::File (args[i + 1].unquoted()), juce::File (args[i + 2].unquoted()), options);
  3705. std::fprintf (stderr, "stemsplit: %.0f ms\n", juce::Time::getMillisecondCounterHiRes() - started);
  3706. juce::File (args[i + 2].unquoted()).getSiblingFile ("stemsplit.txt").replaceWithText (error.isEmpty() ? "result=OK\n" : "result=FAIL " + error + "\n");
  3707. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  3708. quit();
  3709. return;
  3710. }
  3711. if (args.contains ("--audio2midi"))
  3712. {
  3713. // LYNX.exe --audio2midi input.wav melody|harmony|drums notes.csv: the clip menu's Convert to MIDI, without the
  3714. // window (round a2m189b's measurements)
  3715. // Round 190lj: mode "poly" = the "Convert to MIDI (polyphonic)" dialog's path, settings after the CSV as
  3716. // 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
  3717. // seconds spent resampling, in the model and making the notes.
  3718. const auto i = args.indexOf ("--audio2midi");
  3719. const auto mode = args[i + 2] == "drums" ? lynx::a2m::Mode::drums : args[i + 2] == "harmony" ? lynx::a2m::Mode::harmony : lynx::a2m::Mode::melody;
  3720. lynx::AudioEngine loader (false);
  3721. const juce::File csv (args[i + 3].unquoted());
  3722. juce::String error, timing;
  3723. if (args[i + 2] == "poly")
  3724. {
  3725. lynx::a2m::ConvertOptions options;
  3726. for (int k = i + 4; k < args.size() && args[k].containsChar ('='); ++k)
  3727. {
  3728. const auto key = args[k].upToFirstOccurrenceOf ("=", false, false);
  3729. const auto value = args[k].fromFirstOccurrenceOf ("=", false, false);
  3730. if (key == "poly") options.polyphonic = value.getIntValue() != 0;
  3731. else if (key == "note") options.noteSensitivity = value.getFloatValue();
  3732. else if (key == "split") options.splitSensitivity = value.getFloatValue();
  3733. else if (key == "minms") options.minNoteMs = value.getDoubleValue();
  3734. else if (key == "low") options.minKey = value.getIntValue();
  3735. else if (key == "high") options.maxKey = value.getIntValue();
  3736. else if (key == "bends") options.pitchBends = value.getIntValue() != 0;
  3737. }
  3738. error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), options, csv, &timing);
  3739. }
  3740. else
  3741. error = lynx::convertFileToMidiCsv (loader, juce::File (args[i + 1].unquoted()), mode, csv);
  3742. csv.getSiblingFile ("audio2midi.txt").replaceWithText (error.isEmpty() ? "result=OK\n" + (timing.isEmpty() ? juce::String() : "seconds=" + timing + "\n")
  3743. : "result=FAIL " + error + "\n");
  3744. setApplicationReturnValue (error.isEmpty() ? 0 : 1);
  3745. quit();
  3746. return;
  3747. }
  3748. if (args.contains ("--stems") || args.contains ("--stemexport"))
  3749. {
  3750. // LYNX.exe --stems project.(flp|als|lynx) base.wav [--separate]: one WAV per insert that has sound (like
  3751. // "Export stems"), in one render of the song (round 190gj; --separate: one render per insert, as before).
  3752. // LYNX.exe --stemexport project base.ext options.txt [--separate]: what the Export window writes with these
  3753. // options (exportopts::toText lines: stems, sections, the full mix, formats...), the same code.
  3754. // Both write <base>.txt: the files with their peaks, the renders, the wall and CPU time.
  3755. const auto full = args.contains ("--stemexport");
  3756. const auto i = args.indexOf (full ? "--stemexport" : "--stems");
  3757. const auto separate = args.contains ("--separate");
  3758. juce::String error, report;
  3759. int written = 0;
  3760. {
  3761. lynx::AudioEngine loader (false);
  3762. const juce::File input (args[i + 1].unquoted()), base (args[i + 2].unquoted());
  3763. // an .flp or a Live set (.als) opens through the import, as File › Open does (round 182b)
  3764. auto ok = input.hasFileExtension ("flp;als") ? loader.importFlpFile (input, error) : false;
  3765. if (! input.hasFileExtension ("flp;als"))
  3766. if (auto song = lynx::ProjectFile::load (input, error))
  3767. {
  3768. loader.setSong (std::move (*song));
  3769. ok = true;
  3770. }
  3771. const auto& song = loader.getSong();
  3772. lynx::StemPlan plan;
  3773. if (full && ok)
  3774. plan = lynx::planStemExport (song, lynx::exportopts::fromText (juce::File (args[i + 3].unquoted()).loadFileAsString().toStdString()), base);
  3775. else if (ok)
  3776. {
  3777. // every insert a channel goes to, as "<base> - <insert>.wav", 24-bit, 6 s of tail at most
  3778. lynx::ExportSettings settings;
  3779. plan.sets.push_back ({ song, settings.toOptions() });
  3780. for (int t = 1; t < (int) song.mixer.size(); ++t)
  3781. if (std::any_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  3782. plan.items.push_back ({ juce::String (t), base.getSiblingFile (base.getFileNameWithoutExtension() + " - " + juce::String (t) + ".wav"), 0, t,
  3783. lynx::makeBounceSong (song, t), settings.toOptions() });
  3784. }
  3785. const auto wallStart = juce::Time::getMillisecondCounterHiRes();
  3786. const auto cpuStart = std::clock();
  3787. lynx::StemRunStats stats;
  3788. std::vector<juce::String> lines (plan.items.size());
  3789. auto previous = wallStart; // (one render per file: the time since the file before is its render's)
  3790. written = lynx::runStemExport (
  3791. plan, [] (std::function<void()> f) { f(); }, {}, {}, {},
  3792. [&] (std::size_t k, bool done, float peak) {
  3793. const auto now = juce::Time::getMillisecondCounterHiRes();
  3794. if (done)
  3795. lines[k] = plan.items[k].file.getFileName() + " peak=" + juce::String (peak) + " ms=" + juce::String (now - previous, 0) + "\n";
  3796. previous = now;
  3797. },
  3798. separate, full, &stats);
  3799. const auto wallMs = juce::Time::getMillisecondCounterHiRes() - wallStart;
  3800. const auto cpuMs = 1000.0 * (double) (std::clock() - cpuStart) / (double) CLOCKS_PER_SEC;
  3801. for (const auto& line : lines)
  3802. report << line;
  3803. report << "renders=" << (stats.passes + stats.alone) << " shared=" << stats.passes << " inshared=" << stats.inPass
  3804. << " alone=" << stats.alone << "\n";
  3805. for (const auto& why : stats.why)
  3806. report << "alone: " << why << "\n";
  3807. report << "wall_ms=" << juce::String (wallMs, 0) << " cpu_ms=" << juce::String (cpuMs, 0) << " make_ms=" << juce::String (stats.makeMs, 0)
  3808. << " render_ms=" << juce::String (stats.renderMs, 0) << "\n";
  3809. }
  3810. report << "stems=" << written << "\n";
  3811. juce::File (args[i + 2].unquoted() + ".txt").replaceWithText (report);
  3812. setApplicationReturnValue (written > 0 ? 0 : 1);
  3813. quit();
  3814. return;
  3815. }
  3816. // --export-als <in.lynx|.flp|.als> <folder> [--live11] [--reference] [--scan]: "<folder>/<name> Project/<name>.als" (round 175a)
  3817. if (args.contains ("--export-als"))
  3818. {
  3819. const auto i = args.indexOf ("--export-als");
  3820. runAlsExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--live11"), args.contains ("--reference"));
  3821. return;
  3822. }
  3823. // --export-flm <in.lynx|.flp|.als|.flm|...> <out.flm> (round 190og, FLM coverage app-0003): File › "Save a copy as FL
  3824. // Studio Mobile project" without the window; the samples go beside it, the losses and the result to "<out>.txt".
  3825. // --flmexportshot <prefix> <project> [--shot-scale 1.5 --shot-suffix @150]: the window with that project's losses
  3826. if (args.contains ("--export-flm") || args.contains ("--flmexportshot"))
  3827. {
  3828. const auto shot = args.contains ("--flmexportshot");
  3829. const auto i = args.indexOf (shot ? "--flmexportshot" : "--export-flm");
  3830. const juce::File input (args[i + (shot ? 2 : 1)].unquoted());
  3831. juce::String error, report;
  3832. auto ok = false;
  3833. {
  3834. lynx::AudioEngine loader (false);
  3835. if (input.hasFileExtension ("flp;als;flm;songtmpl;band;blx;mod;xm;s3m;it;dawproject"))
  3836. ok = loader.importFlpFile (input, error);
  3837. else if (auto song = lynx::ProjectFile::load (input, error))
  3838. {
  3839. loader.setSong (std::move (*song));
  3840. ok = true;
  3841. }
  3842. if (ok && shot)
  3843. {
  3844. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3845. lynx::FlmExportOptions o;
  3846. o.title = input.getFileNameWithoutExtension().toStdString();
  3847. const auto dry = lynx::exportFlm (loader.getSong(), o);
  3848. auto list = std::make_shared<juce::TextEditor>();
  3849. std::unique_ptr<juce::AlertWindow> w (lynx::buildFlmExportWindow (dry, list));
  3850. saveSnapshot (*w, args[i + 1].unquoted() + "-flmexport.png");
  3851. report << lynx::flmExportLossText (dry) << "\n";
  3852. }
  3853. else if (ok)
  3854. {
  3855. loader.capturePluginStates();
  3856. lynx::FlmExportResult result;
  3857. const juce::File out (args[i + 2].unquoted());
  3858. ok = lynx::writeFlmCopy (loader.getSong(), out, result, error);
  3859. report << "bytes=" << (int) result.bytes.size() << "\nsamples=" << (int) result.samples.size() << "\n";
  3860. for (const auto& l : result.lost)
  3861. report << (l.sound ? "sound: " : "other: ") << juce::String::fromUTF8 (l.text.c_str()).replace ("{0}", juce::String::fromUTF8 (l.detail.c_str())) << "\n";
  3862. }
  3863. }
  3864. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  3865. juce::File (args[i + (shot ? 1 : 2)].unquoted() + (shot ? "-flmexport.txt" : ".txt")).replaceWithText (report);
  3866. setApplicationReturnValue (ok ? 0 : 1);
  3867. quit();
  3868. return;
  3869. }
  3870. // --gamepadshot <prefix> (round 184a, S16): the game controller's hints overlay and the MIDI settings page with
  3871. // the option on, offscreen, plus the poller fed fake pad states ("<prefix>-gamepad.txt")
  3872. if (args.contains ("--gamepadshot"))
  3873. {
  3874. runGamepadShot (args[args.indexOf ("--gamepadshot") + 1].unquoted());
  3875. return;
  3876. }
  3877. // --midioutshot <prefix> [--shot-scale 1.5] (round 190jl): Settings › MIDI with the output devices' Port boxes
  3878. // (the snapshot's sample devices: the volca on port 1 of its own, the drum machine with master sync), offscreen
  3879. if (args.contains ("--midioutshot"))
  3880. {
  3881. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3882. {
  3883. lynx::AudioEngine engine (false);
  3884. auto page = lynx::makeMidiPage (engine, {}, false);
  3885. page->setSize (1000, 1300);
  3886. savePng (lynx::shot::snapshot (*page), args[args.indexOf ("--midioutshot") + 1].unquoted() + "-settings-midi.png");
  3887. }
  3888. setApplicationReturnValue (0);
  3889. quit();
  3890. return;
  3891. }
  3892. // --export-bundle <in.lynx|.flp|.als> <folder> [--zip] [--no-mixdown] [--shot <prefix>] (round 184a, S9): File ›
  3893. // Export › "For other apps..." without the window; the report goes to "<folder>/export-bundle.txt"
  3894. if (args.contains ("--export-bundle"))
  3895. {
  3896. const auto i = args.indexOf ("--export-bundle");
  3897. runBundleExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--zip"), ! args.contains ("--no-mixdown"),
  3898. args.contains ("--shot") ? args[args.indexOf ("--shot") + 1].unquoted() : juce::String());
  3899. return;
  3900. }
  3901. if (args.contains ("--export-flp"))
  3902. {
  3903. const auto i = args.indexOf ("--export-flp");
  3904. runFlExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--substitute"));
  3905. return;
  3906. }
  3907. if (args.contains ("--export"))
  3908. {
  3909. const auto i = args.indexOf ("--export");
  3910. const auto insert = args.contains ("--insert") ? args[args.indexOf ("--insert") + 1].getIntValue() : 0;
  3911. runExport (args[i + 1].unquoted(), args[i + 2].unquoted(), args.contains ("--pattern"), insert);
  3912. return;
  3913. }
  3914. if (args.contains ("--tempomarkershot"))
  3915. {
  3916. // LYNX --tempomarkershot <prefix> <project.lynx> (round 190hq): the Playlist of the project with its tempo
  3917. // markers on the ruler (-playlist.png) and the "Save a copy for an older LYNX" window for each release
  3918. // (-savecopy-<release>.png); no window, nothing saved
  3919. const auto i = args.indexOf ("--tempomarkershot");
  3920. const auto prefix = args[i + 1].unquoted();
  3921. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  3922. lynx::AudioEngine shotEngine (false);
  3923. juce::String error;
  3924. auto ok = false;
  3925. if (auto song = lynx::ProjectFile::load (juce::File (args[i + 2].unquoted()), error))
  3926. shotEngine.setSong (std::move (*song)), ok = true;
  3927. if (ok)
  3928. {
  3929. {
  3930. lynx::PlaylistComponent playlist (shotEngine);
  3931. playlist.setBounds (0, 0, 1400, 420);
  3932. playlist.setVisible (true);
  3933. playlist.setViewForSnapshot (70.0, 0, 0);
  3934. shotEngine.dispatchPendingMessages();
  3935. saveSnapshot (playlist, prefix + "-playlist.png");
  3936. }
  3937. auto list = std::make_shared<juce::TextEditor>();
  3938. std::unique_ptr<juce::AlertWindow> w (lynx::MainComponent::buildSaveCopyWindow (lynx::ProjectFile::toJson (shotEngine.getSong()), list));
  3939. const auto releases = lynx::olderlynx::releases();
  3940. for (int k = 0; k < releases.size(); ++k)
  3941. {
  3942. w->getComboBoxComponent ("release")->setSelectedItemIndex (k, juce::sendNotificationSync);
  3943. saveSnapshot (*w, prefix + "-savecopy-" + releases[k] + ".png");
  3944. }
  3945. }
  3946. setApplicationReturnValue (ok ? 0 : 1);
  3947. quit();
  3948. return;
  3949. }
  3950. if (args.contains ("--savecopyfor"))
  3951. {
  3952. // LYNX --savecopyfor <in.lynx> <release> <out.lynx> (round 190hq, B20): File › "Save a copy for an older
  3953. // LYNX..." without the window; what the copy loses goes to <out.lynx>.txt (English), then result=OK
  3954. const auto i = args.indexOf ("--savecopyfor");
  3955. const juce::File input (args[i + 1].unquoted()), output (args[i + 3].unquoted());
  3956. const auto release = args[i + 2].unquoted();
  3957. juce::String report, error;
  3958. auto ok = false;
  3959. if (const auto song = lynx::ProjectFile::load (input, error))
  3960. {
  3961. const auto copy = lynx::olderlynx::forRelease (*song, release);
  3962. for (const auto& l : copy.lost)
  3963. report << (l.sound ? "sound: " : "view: ") << juce::String::fromUTF8 (l.text).replace ("{0}", l.detail) << "\n";
  3964. ok = copy.ok && output.replaceWithText (copy.json, false, false, nullptr);
  3965. if (! copy.ok)
  3966. error = copy.error;
  3967. }
  3968. report << "result=" << (ok ? juce::String ("OK") : "ERROR " + error) << "\n";
  3969. juce::File (output.getFullPathName() + ".txt").replaceWithText (report);
  3970. setApplicationReturnValue (ok ? 0 : 1);
  3971. quit();
  3972. return;
  3973. }
  3974. if (args.contains ("--render"))
  3975. {
  3976. const auto i = args.indexOf ("--render");
  3977. runRender (args[i + 1].unquoted(), args[i + 2].unquoted(), args[i + 3].getDoubleValue());
  3978. return;
  3979. }
  3980. // session breadcrumb: a fail-fast (no crash handler runs) still leaves the last steps behind (round 111)
  3981. uncleanLastStep = collectUncleanSessions();
  3982. sessionsFolder().createDirectory();
  3983. lynx::crashguard::beginSession (
  3984. sessionsFolder().getChildFile ("session-" + juce::String (lynx::crashguard::processId()) + ".txt").getFullPathName().toStdString(),
  3985. ("LYNX session\nversion=" + getApplicationVersion() + "\npid=" + juce::String (lynx::crashguard::processId())
  3986. + "\nstart=" + juce::String ((juce::int64) lynx::crashguard::processStartTime())
  3987. + "\nstarted=" + juce::Time::getCurrentTime().toISO8601 (true) + "\n").toStdString());
  3988. startHangWatch();
  3989. // LYNX_PROFILE_MAIN=<file> (round 174f): the message thread sampled every millisecond, 5-second windows
  3990. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  3991. lynx::crashguard::startMainProfiler (profile.toStdString());
  3992. startupTrace.mark ("initialise (normal start)");
  3993. // (round 190hd, Windows) how long before the trace's 0 the process was made: the loader (the exe, its DLLs,
  3994. // relocations) and the static initialisers that ran before this file's
  3995. if (const auto created = lynx::crashguard::processStartTime(); created != 0)
  3996. {
  3997. const auto t0 = (std::uint64_t) std::chrono::duration_cast<std::chrono::microseconds> (startupTrace.t0System.time_since_epoch()).count() * 10u
  3998. + 116444736000000000ull; // (FILETIME: 100 ns since 1601)
  3999. if (t0 > created)
  4000. startupTrace.mark ((" (the process was made " + juce::String ((double) (t0 - created) / 10000.0, 1)
  4001. + " ms before this trace's 0: the loader, the DLLs, the first static initialisers)").toRawUTF8());
  4002. }
  4003. prepareGraphicsDevice();
  4004. if (startupTrace.on)
  4005. lynx::startupMark = startupMarkHook;
  4006. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  4007. lynx::themeui::loadSaved(); // the user's theme (Options › Theme, round 162d)
  4008. startupOptions = lynx::StartupOptions::load();
  4009. if (lynx::demo::active()) // (round 190np: --demo records from the first frame: no splash card, no start-up sound)
  4010. startupOptions.splash = startupOptions.sound = false;
  4011. lynx::registerFileTypes();
  4012. startupTrace.mark ("options + file types");
  4013. // Double-clicking a .lynx/.flp opens LYNX with the file as an argument; a path typed in a terminal may be relative
  4014. // (D#92, round 180a: it was ignored, leaving the blank project with no message). A missing file gets "Could not open".
  4015. if (args.size() > 0 && lynx::safety::isFileArgument (args[0].unquoted().toStdString()))
  4016. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[0].unquoted());
  4017. // LYNX --no-plugins project.lynx (round 190ap): File › "Open without third-party plugins..." from the command
  4018. // line, for a project a plugin keeps from opening — no hosted plugin is created, each keeps its settings
  4019. if (const auto i = args.indexOf ("--no-plugins"); i >= 0)
  4020. {
  4021. if (i + 1 < args.size() && lynx::safety::isFileArgument (args[i + 1].unquoted().toStdString()))
  4022. fileToOpen = juce::File::getCurrentWorkingDirectory().getChildFile (args[i + 1].unquoted());
  4023. startWithoutPlugins = fileToOpen.hasFileExtension ("lynx");
  4024. }
  4025. // LYNX_TEST_MODE=1 LYNX --open-event-test <ms> <file>: the file arrives the way macOS's Finder delivers it (a Linux
  4026. // or Windows run can exercise that path): 0 ms = at once, before the window exists
  4027. if (lynx::platform::testMode() && args[0] == "--open-event-test" && args.size() > 2)
  4028. {
  4029. const auto file = args[2].unquoted().quoted();
  4030. if (args[1].getIntValue() == 0)
  4031. anotherInstanceStarted (file);
  4032. else
  4033. juce::Timer::callAfterDelay (args[1].getIntValue(), [this, file] { anotherInstanceStarted (file); });
  4034. }
  4035. // LYNX --opentime project.(flp|lynx)|- report.txt [idle seconds] (round 165i): the normal start-up (splash, audio
  4036. // device, window) opens the project, waits until it is loaded and LYNX has gone quiet, measures the idle CPU and
  4037. // memory, writes the times and quits normally (a benchmark that killed LYNX left "closed unexpectedly" behind)
  4038. if (args.contains ("--opentime"))
  4039. {
  4040. const auto i = args.indexOf ("--opentime");
  4041. const auto project = args[i + 1].unquoted();
  4042. fileToOpen = project != "-" && juce::File::isAbsolutePath (project) ? juce::File (project) : juce::File();
  4043. openTimeReport = juce::File (args[i + 2].unquoted());
  4044. if (args.size() > i + 3 && ! args[i + 3].startsWith ("--"))
  4045. openTimeIdleSeconds = juce::jlimit (1, 120, args[i + 3].getIntValue());
  4046. }
  4047. // round 190go: the ASIO device of the last session is made and opened from now on, while the splash and the
  4048. // window come up (see below)
  4049. lynx::AudioEngine::prewarmAudioDevice();
  4050. // round 190go: the built-in start-up sound is made while the splash and the window come up (pure maths)
  4051. if (startupOptions.sound && lynx::themeui::current().startupSound.empty())
  4052. startupSampleJob = std::async (std::launch::async, [] { return lynx::makeStartupSample(); });
  4053. // Round 190go (start-up faster than FL Studio): the main window is built first, with the engine ready but no
  4054. // audio device open; the device opens after it. An ASIO device of the last session was made and opened ahead,
  4055. // on a worker, while the window was built (AudioEngine::prewarmAudioDevice; the driver itself only ever runs on
  4056. // JUCE's ASIO thread, as COM wants). Play pressed before the device is open starts with it.
  4057. if (! startupOptions.splash)
  4058. {
  4059. startEngine();
  4060. createMainWindow();
  4061. mainWindow->reveal();
  4062. startupTrace.mark ("window revealed");
  4063. // the device (and the start-up sound) once the window's first frame is on screen
  4064. mainWindow->whenPainted ([this] {
  4065. openAudioDevice();
  4066. openMidiDevices();
  4067. startAfterWindow (lynx::demo::active()); // (round 190np: --demo has no splash; its first run still gets the welcome card)
  4068. });
  4069. return;
  4070. }
  4071. // the splash first; the main window is built behind its card (still: the logo has not started to drop; building
  4072. // it during the drop would stop the animation, both run on the message thread), then the audio device opens
  4073. // (the start-up sound needs it), and the drop starts with its sound. The window shows the moment the logo has
  4074. // landed (round 190go, A4: before, the window was built only after the drop: the drop, then ~0.6 s of build).
  4075. // Round 190hd (Windows): the card draws on a thread of its own, so the main window is built DURING the drop
  4076. // (startOnItsOwnThread below).
  4077. splash = lynx::makeStartupSplash();
  4078. startupTrace.mark ("splash made");
  4079. splash->showOnDesktop();
  4080. startupTrace.mark ("splash on the desktop");
  4081. if (splash->drawsOnItsOwnThread())
  4082. {
  4083. startWithThreadedSplash();
  4084. return;
  4085. }
  4086. // the rest once the card's first frame is on the screen (round 190go: before, a fixed 40 ms), at the latest
  4087. // after 40 ms
  4088. const auto goOn = [this, started = std::make_shared<bool> (false)] {
  4089. if (std::exchange (*started, true) || splash == nullptr) // (once; or quit meanwhile)
  4090. return;
  4091. startEngine();
  4092. if (splash == nullptr) // quit meanwhile
  4093. return;
  4094. createMainWindow();
  4095. if (splash == nullptr || mainWindow == nullptr)
  4096. return;
  4097. if (startupOptions.sound)
  4098. openAudioDevice (false); // (else after the splash: nothing waits for it)
  4099. // one turn of the message loop before the drop: what fell due while the window was built (JUCE's timers,
  4100. // the window's own async work) runs now, on the still card, not in the drop's first frames
  4101. juce::MessageManager::callAsync ([this] { startDrop(); });
  4102. };
  4103. splash->onFirstFrame = goOn;
  4104. juce::Timer::callAfterDelay (40, goOn);
  4105. }
  4106. // Round 190hd (start-up faster than FL Studio, Windows): the card draws on a thread of its own (ui/Splash.cpp), so
  4107. // nothing the message thread does stops the drop. The card shows at once (no Direct2D device is made for it); the
  4108. // engine starts and the audio device opens behind the still card (an ASIO device of the last session was made and
  4109. // opened ahead on its own thread meanwhile), the drop starts with its sound, and the main window is built while
  4110. // 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
  4111. // fades the moment the logo has landed. The card stays for the drop only (the JUCE card's
  4112. // 2.1 s from the process start was there to keep a fast start from flashing; the drop alone is 1.05 s).
  4113. void startWithThreadedSplash()
  4114. {
  4115. splash->onFirstFrame = [this] {
  4116. if (splash != nullptr && startupTrace.on)
  4117. startupTrace.mark ((" splash: first frame on the screen at "
  4118. + juce::String (std::chrono::duration<double, std::milli> (splash->getFirstFrameTime() - startupTrace.t0).count(), 1) + " ms (its own thread)")
  4119. .toRawUTF8());
  4120. };
  4121. juce::MessageManager::callAsync ([this] {
  4122. if (splash == nullptr) // (quit meanwhile)
  4123. return;
  4124. startEngine();
  4125. if (splash == nullptr)
  4126. return;
  4127. if (startupOptions.sound)
  4128. openAudioDevice (false); // (else after the splash: nothing waits for it)
  4129. startDrop();
  4130. // the main window while the logo drops (one more message, so the drop's start is not held by it)
  4131. juce::MessageManager::callAsync ([this] {
  4132. if (splash == nullptr || mainWindow != nullptr || engine == nullptr)
  4133. return;
  4134. createMainWindow();
  4135. // shown as soon as it is built, behind the card: the logo goes on dropping above it and the card fades at
  4136. // the landing as before (LYNX_REVEAL_AT_LANDING=1: the window shows at the landing, as in round 190go)
  4137. if (mainWindow != nullptr && splash != nullptr
  4138. && juce::SystemStats::getEnvironmentVariable ("LYNX_REVEAL_AT_LANDING", {}) != "1")
  4139. {
  4140. mainWindow->reveal();
  4141. windowRevealed = true;
  4142. startupTrace.mark ("window revealed (behind the card, while the logo drops)");
  4143. splash->raise();
  4144. }
  4145. });
  4146. });
  4147. }
  4148. // the logo's drop and the start-up sound together; the window shows the moment the logo has landed
  4149. void startDrop()
  4150. {
  4151. const auto ownThread = splash != nullptr && splash->drawsOnItsOwnThread(); // (the window is built during the drop)
  4152. if (splash == nullptr || (mainWindow == nullptr && ! ownThread) || engine == nullptr)
  4153. return;
  4154. if (startupOptions.sound)
  4155. playStartupSound();
  4156. splash->setStatus (lynx::tr ("Loading the workspace..."));
  4157. splash->startClock();
  4158. // the minimum counts from the process start (the window and the audio device took part of it already); a card
  4159. // on its own thread stays for the drop (round 190hd)
  4160. splashDuration = ownThread ? landingSeconds : lynx::SplashScreen::remainingDuration (startupTrace.seconds());
  4161. splash->setBarDuration (splashDuration);
  4162. splash->whenLanded (splashDuration, [this] {
  4163. if (splash == nullptr || mainWindow == nullptr)
  4164. return;
  4165. if (startupTrace.on)
  4166. startupTrace.mark (("splash: the drop in " + juce::String (splash->getDropFrames()) + " frames, longest gap "
  4167. + juce::String (splash->getLongestDropGapMs(), 1) + " ms"
  4168. + (splash->getLongestDropGapAt() >= 0.0 ? " (at " + juce::String (splash->getLongestDropGapAt(), 3) + " s of its clock; the frame before: "
  4169. + splash->getLongestDropGapDetail() + ")"
  4170. : juce::String()))
  4171. .toRawUTF8());
  4172. if (! std::exchange (windowRevealed, true))
  4173. {
  4174. mainWindow->reveal();
  4175. startupTrace.mark ("window revealed (after the splash)");
  4176. }
  4177. splash->raise();
  4178. const auto deviceOpen = ! engine->isAudioDeviceOpenPending();
  4179. splash->finish ([this, deviceOpen] {
  4180. splash = nullptr;
  4181. // without the start-up sound the device opens now, once the card has faded (the window is up)
  4182. if (! deviceOpen)
  4183. openAudioDevice();
  4184. openMidiDevices();
  4185. if (! deviceOpen)
  4186. startAfterWindow (true);
  4187. });
  4188. if (deviceOpen)
  4189. mainWindow->whenPainted ([this] { startAfterWindow (true); });
  4190. });
  4191. }
  4192. // what follows the window's first frame (the audio device is open): the notice of an unclean end, the start-up
  4193. // project, the probes and the update check; on a first run (with the splash) the setup wizard
  4194. void startAfterWindow (bool offerSetupWizard)
  4195. {
  4196. if (std::exchange (startedAfterWindow, true) || mainWindow == nullptr)
  4197. return;
  4198. // (round 190go) each step after the window is a timed line of the start-up trace
  4199. showUncleanNotice();
  4200. startupTrace.mark ("after the window: unclean-session notice");
  4201. openStartupFile();
  4202. startupTrace.mark ("startup file opened");
  4203. startOpenTimeProbe();
  4204. if (! lynx::demo::active()) // (round 190np: --demo records videos: no update prompt, no support note)
  4205. {
  4206. startUpdateCheck();
  4207. startSupportNote(); // (round 190fq)
  4208. }
  4209. startupTrace.mark ("after the window: probes, update check scheduled");
  4210. juce::MessageManager::callAsync ([] { startupTrace.mark ("first message loop turn"); });
  4211. markSettled(); // (round 190gd)
  4212. // first run: language, audio, plugin folders (FL Studio's included) and a background scan
  4213. if (! offerSetupWizard)
  4214. return;
  4215. // round 190np: a fresh profile gets the welcome card ("Where are you coming from?"); a profile that had LYNX's
  4216. // settings and never finished the old wizard keeps the old wizard; an answered one gets nothing (core/Onboarding.h)
  4217. const auto action = lynx::onboarding::startAction (lynx::setupWizardDone(), lynx::onboardui::profileExistedAtStart(),
  4218. mainWindow->getContent().onboardingStateForCheck().pending);
  4219. using StartAction = lynx::onboarding::StartAction;
  4220. if (action != StartAction::none && lynx::platform::testMode())
  4221. lynx::platform::testModeLog (action == StartAction::welcomeCard ? "setup wizard: welcome card" : "setup wizard");
  4222. else if (action == StartAction::welcomeCard)
  4223. {
  4224. mainWindow->getContent().showWelcomeCard (true);
  4225. startupTrace.mark ("after the window: welcome card shown");
  4226. }
  4227. else if (action == StartAction::setupWizard)
  4228. {
  4229. mainWindow->showSetupWizard();
  4230. startupTrace.mark ("after the window: setup wizard shown");
  4231. }
  4232. }
  4233. // round 190fq: the start-up support note (ui/SupportLynx.h) counts this start and, from the 10th on, may show its
  4234. // card once at a quiet moment. Only here, on the normal start path (the command-line modes returned earlier); test
  4235. // mode and CI machines neither count nor show it.
  4236. void startSupportNote()
  4237. {
  4238. if (mainWindow == nullptr)
  4239. return;
  4240. const auto env = [] (const char* name) { return juce::SystemStats::getEnvironmentVariable (name, {}).toStdString(); };
  4241. const auto quiet = lynx::supportnote::quietEnvironment (lynx::platform::testMode(), env ("CI"), env ("GITHUB_ACTIONS"), env ("LYNX_NO_SUPPORT_NOTE"));
  4242. if (quiet && lynx::platform::testMode())
  4243. lynx::platform::testModeLog ("support note: not counted (test mode)");
  4244. mainWindow->getContent().startSupportNote (quiet);
  4245. }
  4246. // the start-up trace's last lines: what the first seconds after the window add (lazy work, caches, the first paints)
  4247. static void markSettled()
  4248. {
  4249. if (! startupTrace.on)
  4250. return;
  4251. juce::Timer::callAfterDelay (5000, [] { startupTrace.mark ("5 s after the window"); startupTrace.write(); });
  4252. juce::Timer::callAfterDelay (15000, [] { startupTrace.mark ("15 s after the window"); startupTrace.write(); });
  4253. }
  4254. // Round 190hd (Windows): the Direct3D 11 + Direct2D device (~0.35 s: the graphics driver loads) is made once, on a
  4255. // worker, while the splash card, the engine and the audio device come up, and kept until LYNX closes: a 1 x 1
  4256. // Direct2D image holds JUCE's shared DirectX object (its devices), so the main window finds them made and nothing
  4257. // makes them again (before, every holder going away -- the splash's logo, a temporary one -- could mean a new device
  4258. // at its next use). Other systems: nothing to do.
  4259. void prepareGraphicsDevice()
  4260. {
  4261. #if JUCE_WINDOWS
  4262. if (juce::SystemStats::getEnvironmentVariable ("LYNX_GPU_PREWARM", {}) == "0")
  4263. return;
  4264. graphicsDeviceJob = std::async (std::launch::async, [] {
  4265. const auto from = std::chrono::steady_clock::now();
  4266. juce::Image holder (juce::Image::ARGB, 1, 1, false); // (NativeImageType: Direct2D, the shared device)
  4267. return std::make_pair (holder, std::chrono::duration<double, std::milli> (std::chrono::steady_clock::now() - from).count());
  4268. });
  4269. #endif
  4270. }
  4271. void markGraphicsDevice()
  4272. {
  4273. if (! graphicsDeviceJob.valid() || ! startupTrace.on || std::exchange (graphicsDeviceMarked, true))
  4274. return;
  4275. const auto ready = graphicsDeviceJob.wait_for (std::chrono::seconds (0)) == std::future_status::ready;
  4276. startupTrace.mark (ready ? (" graphics device made on a worker in " + juce::String (graphicsDeviceJob.get().second, 1) + " ms").toRawUTF8()
  4277. : " graphics device: still being made on its worker");
  4278. }
  4279. void startEngine()
  4280. {
  4281. startupTrace.mark ("before the audio engine");
  4282. lynx::BrowserComponent::allowIndexerProcess = true; // (round 190hd: the normal window only)
  4283. // (round 190go) ready to play, no device open yet: see openAudioDevice
  4284. engine = std::make_unique<lynx::AudioEngine> (true, -1, true, true);
  4285. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  4286. startupTrace.mark ("audio engine (no device yet)");
  4287. crashEngine = engine.get();
  4288. lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
  4289. // a project given on the command line: its slow plugin modules (a Waves shell) start now, on their own
  4290. // thread, while the splash and the main window come up (round 121)
  4291. if (fileToOpen.hasFileExtension ("flp"))
  4292. if (juce::MemoryBlock data; fileToOpen.loadFileAsData (data))
  4293. try
  4294. {
  4295. engine->getPluginHost().startModulesFor (lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() })));
  4296. startupTrace.mark ("plugin modules started ahead");
  4297. }
  4298. catch (const flp::Error&)
  4299. {
  4300. }
  4301. }
  4302. // The audio device of the last session, then (withSound) the start-up sound on it (once; message thread)
  4303. void openAudioDevice (bool withSound = true)
  4304. {
  4305. if (engine == nullptr || ! engine->isAudioDeviceOpenPending())
  4306. return;
  4307. engine->openAudioDevice();
  4308. if (const auto prewarmed = lynx::asioPrewarmReport(); prewarmed.isNotEmpty() && startupTrace.on)
  4309. startupTrace.mark ((" " + prewarmed).toRawUTF8());
  4310. startupTrace.mark ("audio device opened");
  4311. addDriverFileDeviceType();
  4312. if (withSound)
  4313. playStartupSound();
  4314. }
  4315. void playStartupSound()
  4316. {
  4317. if (startupOptions.sound && ! std::exchange (startupSoundPlayed, true) && engine != nullptr)
  4318. {
  4319. // Options › Theme › Startup sound (issue #12): the user's file, else (or when it can't be read) LYNX's own
  4320. std::shared_ptr<const lynx::SampleData> sound;
  4321. if (const auto& own = lynx::themeui::current().startupSound; ! own.empty() && juce::File (juce::String::fromUTF8 (own.c_str())).existsAsFile())
  4322. sound = engine->getSampleLibrary().load (juce::String::fromUTF8 (own.c_str()));
  4323. if (sound == nullptr && startupSampleJob.valid())
  4324. sound = startupSampleJob.get();
  4325. engine->previewSample (sound != nullptr ? sound : lynx::makeStartupSample());
  4326. }
  4327. startupTrace.mark ("startup sound");
  4328. }
  4329. void openMidiDevices()
  4330. {
  4331. if (engine != nullptr)
  4332. engine->openMidiDevices(); // (its own line in the start-up trace: "engine: MIDI inputs")
  4333. }
  4334. void createMainWindow()
  4335. {
  4336. mainWindow = std::make_unique<MainWindow> ("LYNX SHARE", *engine); // the brand; getApplicationName() stays "LYNX" (an id: instance lock, X11 WM_CLASS, ALSA client)
  4337. lynx::setMainWindowForOwnership (mainWindow.get());
  4338. lynx::applyRenderingChoice (*mainWindow); // (GPU rendering off: GDI; round 157a)
  4339. lynx::startRenderingWatch();
  4340. startupTrace.mark ("main window built");
  4341. lynx::remoteui::install ([this] (bool enabled) {
  4342. remoteControl = nullptr;
  4343. if (enabled)
  4344. remoteControl = lynx::RemoteControl::create (*engine, true, [this] {
  4345. const auto title = mainWindow != nullptr ? mainWindow->getName() : juce::String ("Untitled");
  4346. const auto separator = title.indexOf (" - ");
  4347. return separator >= 0 ? title.substring (separator + 3) : title;
  4348. }, [this] {
  4349. const auto file = mainWindow != nullptr ? mainWindow->getContent().getCurrentProjectFile() : juce::File();
  4350. return file == juce::File() ? juce::String() : file.getFullPathName();
  4351. });
  4352. lynx::remoteui::setRuntimeStatus (remoteControl != nullptr && remoteControl->active());
  4353. });
  4354. if (lynx::demo::active()) // round 190np: --demo's view operations (ui.find, ui.click, ui.layout...) on the API
  4355. lynx::RemoteControl::setExtension (lynx::demo::operations(), [this] (const juce::String& op, const juce::var& args) -> juce::var {
  4356. if (mainWindow == nullptr)
  4357. throw std::runtime_error ("No main window");
  4358. return mainWindow->getContent().handleDemoOp (op, args);
  4359. });
  4360. markGraphicsDevice();
  4361. }
  4362. // the previous run ended without closing (see collectUncleanSessions): say so once, with its last step — and, as
  4363. // Settings › General › "Crash reports" says (round 159), ask whether to send a report, send it unasked, or not
  4364. void showUncleanNotice()
  4365. {
  4366. if (lynx::platform::testMode()) // LYNX_TEST_MODE: no prompt, no report sent (written to test-mode.log)
  4367. {
  4368. if (uncleanLastStep.isNotEmpty())
  4369. lynx::platform::testModeLog ("\"closed unexpectedly\" notice (last step: " + uncleanLastStep + ")");
  4370. return;
  4371. }
  4372. if (uncleanLastStep.isEmpty())
  4373. {
  4374. lynx::crashreporter::retryPending(); // (reports an earlier run could not send: once more)
  4375. return;
  4376. }
  4377. auto message = lynx::tr ("The last session ended without closing normally. Last step: {0}. Backup copies of your project are in "
  4378. "LYNX SHARE's autosave folder; details in crash-history.log.",
  4379. { uncleanLastStep });
  4380. uncleanLastStep.clear();
  4381. const auto cause = uncleanCause();
  4382. // round 157a: a plugin's editor was opening — it crashed (often in the graphics driver, inside the plugin's own
  4383. // OpenGL window): offer to keep that plugin in its own process, where a crash takes only the plugin down
  4384. juce::String separatePlugin;
  4385. if (cause.editorPlugin.isNotEmpty() && ! lynx::pluginSandboxEnabled() && ! lynx::pluginAlwaysSeparate (cause.editorPlugin))
  4386. separatePlugin = cause.editorPlugin;
  4387. // LYNX's own drawing crashed in the graphics driver (Direct2D / Direct3D): draw with the CPU from now on
  4388. else if (cause.gpuDriver && lynx::gpuRenderingEnabled())
  4389. {
  4390. lynx::setGpuRenderingEnabled (false);
  4391. message << "\n\n"
  4392. << lynx::tr ("The crash was in the graphics driver ({0}). LYNX SHARE now draws its windows without the GPU; you can turn GPU "
  4393. "rendering back on in Options > General settings (after a driver update, for example).",
  4394. { cause.driverModule });
  4395. }
  4396. // round 165e: the Visualizer's GPU view was drawing when the session ended (a driver crash, a hang, the machine
  4397. // going down): the Visualizer draws with the 2D renderer from now on (its GPU button turns it back on)
  4398. for (int i = uncleanSteps.size(); --i >= 0;)
  4399. {
  4400. if (uncleanSteps[i].contains (lynx::visualgl::stopNote))
  4401. break;
  4402. if (uncleanSteps[i].contains (lynx::visualgl::startNote))
  4403. {
  4404. if (lynx::visualgl::enabled())
  4405. {
  4406. lynx::visualgl::setEnabled (false);
  4407. message << "\n\n"
  4408. << lynx::tr ("The Visualizer was drawing with the GPU (OpenGL) when it happened. It now draws without the GPU; its GPU "
  4409. "button turns it back on.");
  4410. }
  4411. break;
  4412. }
  4413. }
  4414. const auto session = lynx::crashreporter::parseSession (uncleanSessionText);
  4415. auto* devices = engine != nullptr ? &engine->getDeviceManager() : nullptr;
  4416. const auto action = lynx::crashreport::actionFor (lynx::crashreporter::consent());
  4417. lynx::crashreporter::retryPending();
  4418. if (action == lynx::crashreport::Action::askUser)
  4419. {
  4420. if (separatePlugin.isNotEmpty())
  4421. message << "\n\n"
  4422. << lynx::tr ("It happened while the window of {0} was opening{1}.",
  4423. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() });
  4424. lynx::crashreporter::showStartupDialog (session, message, separatePlugin, [separatePlugin] { lynx::setPluginAlwaysSeparate (separatePlugin, true); },
  4425. devices);
  4426. return;
  4427. }
  4428. if (action == lynx::crashreport::Action::sendSilently)
  4429. {
  4430. const auto input = lynx::crashreporter::makeInput (session, session.kind(), devices);
  4431. lynx::crashreporter::send (lynx::crashreporter::buildJson (input, false), juce::String::fromUTF8 (input.id.c_str()));
  4432. message << "\n\n" << lynx::tr ("A crash report is being sent to help fix it (Options > General settings > Crash reports).");
  4433. }
  4434. if (separatePlugin.isNotEmpty())
  4435. {
  4436. juce::AlertWindow::showOkCancelBox (
  4437. juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"),
  4438. message + "\n\n"
  4439. + lynx::tr ("It happened while the window of {0} was opening{1}. Run {0} in a separate process from now on? If it "
  4440. "crashes again, only the plugin stops and LYNX SHARE keeps running (Plugin wrapper menu: \"Always run in a "
  4441. "separate process\").",
  4442. { separatePlugin, cause.gpuDriver ? lynx::tr (" (in the graphics driver, {0})", { cause.driverModule }) : juce::String() }),
  4443. lynx::tr ("Run separately"), lynx::tr ("No"), nullptr,
  4444. juce::ModalCallbackFunction::create ([separatePlugin] (int result) {
  4445. if (result != 0)
  4446. lynx::setPluginAlwaysSeparate (separatePlugin, true);
  4447. }));
  4448. return;
  4449. }
  4450. juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, lynx::tr ("LYNX SHARE closed unexpectedly"), message);
  4451. }
  4452. // --opentime: after the start-up file was handed to the window
  4453. void startOpenTimeProbe()
  4454. {
  4455. if (openTimeReport == juce::File())
  4456. return;
  4457. struct Probe final : juce::Timer
  4458. {
  4459. LynxApplication& app;
  4460. juce::File report, project;
  4461. int idleSeconds;
  4462. int phase = 0; // 0 loading, 1 settling, 2 idle measurement
  4463. double revealedS = 0.0, loadedS = -1.0, settledS = -1.0, cpuAtLoaded = 0.0;
  4464. double lastCpu = 0.0, lastT = 0.0, quietSince = -1.0, idleCpu0 = 0.0, idleT0 = 0.0;
  4465. Probe (LynxApplication& a, juce::File r, juce::File p, int idle)
  4466. : app (a), report (std::move (r)), project (std::move (p)), idleSeconds (idle)
  4467. {
  4468. revealedS = startupTrace.seconds();
  4469. startTimer (250);
  4470. }
  4471. bool loaded() const
  4472. {
  4473. if (project == juce::File())
  4474. return true;
  4475. return app.mainWindow != nullptr
  4476. && app.mainWindow->getName().containsIgnoreCase (project.getFileNameWithoutExtension());
  4477. }
  4478. void finish (const juce::String& result)
  4479. {
  4480. stopTimer();
  4481. const auto now = startupTrace.seconds();
  4482. const auto cpu = lynx::processCpuSeconds();
  4483. juce::String text;
  4484. text << "project=" << (project == juce::File() ? juce::String ("-") : project.getFullPathName()) << "\n"
  4485. << "window_s=" << juce::String (revealedS, 3) << "\n"
  4486. << "loaded_s=" << juce::String (loadedS, 3) << "\n"
  4487. << "settled_s=" << juce::String (settledS, 3) << "\n"
  4488. << "cpu_at_loaded_s=" << juce::String (cpuAtLoaded, 3) << "\n"
  4489. << "idle_s=" << juce::String (now - idleT0, 2) << "\n"
  4490. << "idle_cpu_pct=" << juce::String (phase == 2 && now > idleT0 ? 100.0 * (cpu - idleCpu0) / (now - idleT0) : -1.0, 1) << "\n"
  4491. << "working_set_mb=" << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << "\n"
  4492. << "cpu_total_s=" << juce::String (cpu, 3) << "\n"
  4493. << "result=" << result << "\n";
  4494. report.replaceWithText (text);
  4495. app.setApplicationReturnValue (result == "OK" ? 0 : 1);
  4496. app.quit();
  4497. }
  4498. void timerCallback() override
  4499. {
  4500. const auto now = startupTrace.seconds();
  4501. const auto cpu = lynx::processCpuSeconds();
  4502. if (phase == 0)
  4503. {
  4504. if (loaded())
  4505. {
  4506. loadedS = now;
  4507. cpuAtLoaded = cpu;
  4508. phase = 1;
  4509. lastCpu = cpu;
  4510. lastT = now;
  4511. }
  4512. else if (now - revealedS > 240.0)
  4513. finish ("TIMEOUT loading");
  4514. return;
  4515. }
  4516. if (phase == 1)
  4517. {
  4518. // quiet = under 10 % of one core for 1.5 s (the harness's rule), at most 30 s after loading
  4519. const auto use = now > lastT ? 100.0 * (cpu - lastCpu) / (now - lastT) : 0.0;
  4520. lastCpu = cpu;
  4521. lastT = now;
  4522. if (use < 10.0)
  4523. {
  4524. if (quietSince < 0.0)
  4525. quietSince = now - 0.25;
  4526. if (now - quietSince >= 1.5)
  4527. settledS = quietSince;
  4528. }
  4529. else
  4530. quietSince = -1.0;
  4531. if (settledS >= 0.0 || now - loadedS > 30.0)
  4532. {
  4533. phase = 2;
  4534. idleCpu0 = cpu;
  4535. idleT0 = now;
  4536. }
  4537. return;
  4538. }
  4539. if (now - idleT0 >= (double) idleSeconds)
  4540. finish ("OK");
  4541. }
  4542. };
  4543. perf = std::make_unique<Probe> (*this, openTimeReport, fileToOpen, openTimeIdleSeconds);
  4544. }
  4545. // round 166b: the update check of a normal start (never in --opentime and the other command-line modes), a few
  4546. // seconds after the window is up so it never competes with the start-up; and the result of an update just installed
  4547. void startUpdateCheck()
  4548. {
  4549. if (openTimeReport != juce::File())
  4550. return;
  4551. lynx::updater::afterStart();
  4552. juce::Timer::callAfterDelay (3000, [] { lynx::updater::startAutomaticCheck(); });
  4553. }
  4554. void openStartupFile()
  4555. {
  4556. startupFileHandled = true;
  4557. if (fileToOpen != juce::File() && mainWindow != nullptr)
  4558. {
  4559. if (std::exchange (startWithoutPlugins, false)) // --no-plugins (round 190ap)
  4560. mainWindow->getContent().openNextWithoutPlugins (true);
  4561. mainWindow->openFile (fileToOpen);
  4562. mainWindow->getContent().openNextWithoutPlugins (false); // (a file that did not open leaves nothing behind)
  4563. }
  4564. else if (mainWindow != nullptr && openTimeReport == juce::File())
  4565. mainWindow->getContent().openStartupProject(); // issue #123 (FL's Startup project)
  4566. }
  4567. void shutdown() override
  4568. {
  4569. parityShow.reset(); // (LYNX_PARITYSHOT_SHOW's window, before the engine it shows)
  4570. if (relaunched || updateHelper)
  4571. return; // the copy that ran owns the session (its crash notes stay for the next start)
  4572. lynx::crashguard::note ("closing");
  4573. lynx::shutdownPluginSandboxWorker();
  4574. splash = nullptr;
  4575. lynx::shutdownStemExtraction(); // (a separation in flight stops before its window and the engine go)
  4576. lynx::shutdownAudioToMidi(); // (the same for a conversion to MIDI)
  4577. if (mainWindow != nullptr && mainWindow->isVisible())
  4578. mainWindow->saveState();
  4579. lynx::remoteui::shutdown();
  4580. remoteControl = nullptr; // cancels queued control work before its engine and UI go
  4581. mainWindow = nullptr; // the UI goes before the engine
  4582. graphicsDeviceJob = {}; // (round 190hd: the graphics device's holder, after every window)
  4583. lynx::updater::shutdown(); // (a check or download in flight stops)
  4584. crashEngine = nullptr;
  4585. engine = nullptr;
  4586. // separate-process plugins end on threads of their own (issue #159): a moment for them, never the 10 s a dead
  4587. // child's pipe can take
  4588. lynx::finishSandboxTeardowns (2000);
  4589. // CLAP plugins whose instance another thread deleted while this one was busy: deactivated and destroyed now
  4590. lynx::ClapPluginFormat::finishPendingTeardowns();
  4591. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  4592. heartbeat.stopTimer();
  4593. lynx::crashreporter::shutdown(); // (an upload in flight gets a moment, never long)
  4594. lynx::crashguard::stopHangWatch();
  4595. lynx::crashguard::stopMainProfiler();
  4596. lynx::crashguard::endSession(); // a clean exit: no breadcrumb left behind
  4597. // everything is saved and closed: a process that loaded third-party plugins ends here, before the DLLs' own
  4598. // teardown runs (some crash in it at exit, round 111)
  4599. if (sandboxChild || lynx::PluginHost::pluginsWereLoaded())
  4600. lynx::crashguard::exitNow (getApplicationReturnValue());
  4601. }
  4602. void systemRequestedQuit() override
  4603. {
  4604. if (mainWindow != nullptr)
  4605. mainWindow->confirmDiscard ([] { juce::JUCEApplication::quit(); });
  4606. else
  4607. quit();
  4608. }
  4609. private:
  4610. // round 157a: a frozen UI (Windows' "not responding") writes the message thread's stack to autosave\hang <time>.txt
  4611. // and a session step, so a freeze can be told apart from a crash and located. The timer is the heartbeat.
  4612. struct Heartbeat final : juce::Timer
  4613. {
  4614. void timerCallback() override { lynx::crashguard::heartbeat(); }
  4615. } heartbeat;
  4616. void startHangWatch()
  4617. {
  4618. const auto folder = lynx::platform::settingsFile ("autosave");
  4619. folder.createDirectory();
  4620. // keep the newest hang files only
  4621. auto old = folder.findChildFiles (juce::File::findFiles, false, "hang *.txt");
  4622. lynx::filesort::byTime (old, lynx::filesort::By::modificationTime, true);
  4623. for (int i = 20; i < old.size(); ++i)
  4624. old.getReference (i).deleteFile();
  4625. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString());
  4626. heartbeat.startTimerHz (5);
  4627. }
  4628. bool sandboxChild = false;
  4629. bool relaunched = false; // relaunchFromAsciiPath ran LYNX from its short path: this process only waited
  4630. bool updateHelper = false; // --apply-update (round 166b)
  4631. juce::String uncleanLastStep; // last step of a previous run that ended without closing
  4632. // LYNX_PROFILE_DIR=<folder> LYNX --lv2scantest report.txt (Linux, issue #85): the LV2 scan's promise, with real child
  4633. // processes. A new PluginHost per step, as every start of LYNX has. The LV2 folders of the machine are read too.
  4634. void runLv2ScanTest (const juce::String& reportPath)
  4635. {
  4636. juce::String report;
  4637. auto ok = lynx::platform::profileOverride() != juce::File();
  4638. #if JUCE_LINUX
  4639. const auto folder = lynx::platform::profileOverride().getChildFile ("lv2-test");
  4640. const juce::FileSearchPath paths (folder.getFullPathName());
  4641. const auto check = [&] (const juce::String& name, bool passed) {
  4642. report << name << "=" << (passed ? "ok" : "FAILED") << "\n";
  4643. ok = ok && passed;
  4644. };
  4645. const auto install = [&] (const juce::String& name) {
  4646. const auto bundle = folder.getChildFile (name + ".lv2");
  4647. bundle.createDirectory();
  4648. bundle.getChildFile ("manifest.ttl").replaceWithText ("@prefix lv2: <http://lv2plug.in/ns/lv2core#> .\n@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n"
  4649. "<urn:lynx-test:" + name + "> a lv2:Plugin ; lv2:binary <" + name + ".so> ; rdfs:seeAlso <plugin.ttl> .\n");
  4650. bundle.getChildFile ("plugin.ttl").replaceWithText ("@prefix doap: <http://usefulinc.com/ns/doap#> .\n<urn:lynx-test:" + name + "> doap:name \"" + name + "\" .\n");
  4651. };
  4652. auto date = juce::Time::getCurrentTime();
  4653. const auto touch = [&] { // the next date, whatever the file system's date resolution
  4654. date += juce::RelativeTime::seconds (2.0);
  4655. folder.getChildFile ("a.lv2/plugin.ttl").setLastModificationTime (date);
  4656. };
  4657. const auto listed = [] (lynx::PluginHost& host, const juce::String& name) {
  4658. for (const auto& d : host.getKnownPlugins().getTypes())
  4659. if (d.fileOrIdentifier == "urn:lynx-test:" + name)
  4660. return true;
  4661. return false;
  4662. };
  4663. const auto step = [&] (const juce::String& name, int children, const std::function<void (lynx::PluginHost&)>& prepare = {}) {
  4664. lynx::PluginHost host (true);
  4665. if (prepare)
  4666. prepare (host);
  4667. host.scan (paths, {});
  4668. check (name, host.scanChildrenStarted() == children && listed (host, "a"));
  4669. };
  4670. install ("a");
  4671. step ("first_scan_one_child", 1);
  4672. step ("nothing_changed_no_child", 0);
  4673. touch();
  4674. step ("ttl_updated", 1);
  4675. install ("b");
  4676. step ("bundle_installed", 1);
  4677. step ("forget_file", 1, [] (lynx::PluginHost& host) { host.forgetFile ("urn:lynx-test:a"); });
  4678. step ("forget_all", 1, [] (lynx::PluginHost& host) { host.forgetAll(); });
  4679. lynx::platform::settingsFile ("plugins.xml").deleteFile();
  4680. step ("list_lost", 1);
  4681. step ("nothing_changed_again", 0);
  4682. // cancelled while the child works: stopped at once, and nothing is taken for done
  4683. touch();
  4684. setenv ("LYNX_TEST_CRASH", "lv2-batch-hang", 1);
  4685. {
  4686. lynx::PluginHost host (true);
  4687. const auto started = juce::Time::getMillisecondCounter();
  4688. host.scan (paths, [] (float, const juce::String&) { return false; });
  4689. check ("cancel_stops_the_child", host.scanChildrenStarted() == 1 && juce::Time::getMillisecondCounter() - started < 20000);
  4690. }
  4691. unsetenv ("LYNX_TEST_CRASH");
  4692. step ("described_after_cancel", 1);
  4693. // the child dies: plugin by plugin takes over (stopped after two of them: a machine may have hundreds)
  4694. touch();
  4695. setenv ("LYNX_TEST_CRASH", "lv2-batch", 1);
  4696. {
  4697. lynx::PluginHost host (true);
  4698. host.scan (paths, [&host] (float, const juce::String&) { return host.scanChildrenStarted() < 3; });
  4699. check ("crash_falls_back_plugin_by_plugin", host.scanChildrenStarted() == 3);
  4700. auto blamed = false;
  4701. for (const auto& file : host.getKnownPlugins().getBlacklistedFiles())
  4702. blamed = blamed || file.startsWith ("lv2-folders:");
  4703. check ("crash_blacklists_nothing", ! blamed);
  4704. }
  4705. unsetenv ("LYNX_TEST_CRASH");
  4706. step ("described_after_crash", 1);
  4707. // round 190fw: past the first limit, a child that still works is waited for (FL Studio's own VST plugin boots
  4708. // the FL engine), one that sits still is killed as before, and a busy one only up to the cap. Limits are
  4709. // shortened for the test: 2 s first limit, 2 s without work, 8 s cap (real: 30 s, 30 s, 5 min).
  4710. setenv ("LYNX_TEST_SCAN_MS", "2000,2000,8000", 1);
  4711. const auto timed = [&] (const char* fault, const std::function<bool (lynx::PluginHost&)>& progress) {
  4712. touch();
  4713. setenv ("LYNX_TEST_CRASH", fault, 1);
  4714. lynx::PluginHost host (true);
  4715. const auto started = juce::Time::getMillisecondCounter();
  4716. host.scan (paths, [&] (float, const juce::String&) { return ! progress || progress (host); });
  4717. unsetenv ("LYNX_TEST_CRASH");
  4718. const auto took = (int) (juce::Time::getMillisecondCounter() - started);
  4719. report << " " << fault << ": " << took << " ms, children " << host.scanChildrenStarted() << "\n";
  4720. return std::make_pair (took, host.scanChildrenStarted());
  4721. };
  4722. // (after a failed batch, one plugin-by-plugin child and no more: it describes quickly)
  4723. const auto stopAfterBatch = [] (lynx::PluginHost& host) { return host.scanChildrenStarted() < 2; };
  4724. {
  4725. const auto [took, children] = timed ("lv2-batch-busy:5000", {});
  4726. check ("busy_child_is_waited_for", children == 1 && took >= 4500);
  4727. }
  4728. {
  4729. const auto [took, children] = timed ("lv2-batch-hang", stopAfterBatch);
  4730. check ("idle_child_ends_near_the_first_limit", children == 2 && took >= 1900 && took < 9000);
  4731. }
  4732. {
  4733. const auto [took, children] = timed ("lv2-batch-busy:60000", stopAfterBatch);
  4734. check ("busy_child_ends_at_the_cap", children == 2 && took >= 7500 && took < 20000);
  4735. }
  4736. unsetenv ("LYNX_TEST_SCAN_MS");
  4737. step ("described_after_slow_children", 1);
  4738. #endif
  4739. juce::File (reportPath).replaceWithText (report + "result=" + (ok ? "OK" : "FAILED") + "\n");
  4740. setApplicationReturnValue (ok ? 0 : 1);
  4741. quit();
  4742. }
  4743. // LYNX.exe --selftest report.txt: renders 2 s without a sound card and writes the result.
  4744. // Exit code 0 = audio came out, 1 = silence.
  4745. // --selftest (round 190ci): two more copies of LYNX end by a fault on purpose (--faulttest), one on a normal stack
  4746. // (the top-level filter) and one on a stack Windows cannot walk (the first-chance hook); each must leave
  4747. // "crash <time>.txt" with the access violation in the folder it is given.
  4748. // Round 190dt (Linux / macOS): a plain fault, and LYNX's own fault inside a guarded plugin call (in its code, and in
  4749. // the C library called from its code), must each leave the crash file with the signal: the plugin guard passes
  4750. // LYNX's own faults on to the crash handler instead of swallowing them ("swallowed.txt" = it did).
  4751. // Round 190gj (P9): the inserts' stems from one render are the files each stem's own render writes, byte for byte
  4752. // (a short song with a bus, a send return, delay compensation, a channel on the Master, an automated insert and a
  4753. // side-chained insert), streamed (24-bit WAV with the full mix) and buffered (normalised float).
  4754. static juce::String stemsSinglePassSelfTest()
  4755. {
  4756. auto s = lynx::Song::makeDefault();
  4757. s.mixer = lynx::Song::defaultMixer (7);
  4758. for (std::size_t c = 0; c < s.channels.size(); ++c)
  4759. s.channels[c].mixerTrack = (int) c + 1;
  4760. auto onMaster = s.channels[2];
  4761. onMaster.mixerTrack = 0;
  4762. onMaster.pan = -0.4f;
  4763. s.channels.push_back (onMaster);
  4764. for (int step : { 1, 5, 9, 13 })
  4765. s.patterns[0].toggleStep ((int) s.channels.size() - 1, step);
  4766. for (int step : { 4, 12 })
  4767. s.patterns[0].toggleStep (3, step); // the snare
  4768. for (int k = 0; k < 4; ++k) // the synth under the kick (its compressor listens to it)
  4769. s.patterns[0].notes.push_back ({ (std::int64_t) k * lynx::ppq, lynx::ppq - 60, 4, 57 + 3 * k, 0.9f });
  4770. s.patterns[0].sortNotes();
  4771. s.mixer[0].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  4772. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::compressor));
  4773. s.mixer[2].toMaster = false;
  4774. s.mixer[2].sends = { lynx::MixerSend { 6, 1.0f } };
  4775. s.mixer[3].sends = { lynx::MixerSend { 7, 0.5f } };
  4776. s.mixer[3].latencyMs = 3.0f;
  4777. s.mixer[4].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  4778. s.mixer[4].latencyMs = 5.0f;
  4779. s.mixer[4].sends = { lynx::MixerSend { 6, 0.7f } };
  4780. s.mixer[4].masterLevel = 0.8f;
  4781. auto keyed = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  4782. keyed.params[0] = 0.5f; // (−30 dB: the kick's hits pull the synth down)
  4783. keyed.sidechain = 1;
  4784. s.mixer[5].effects.push_back (keyed);
  4785. s.mixer[6].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::distortion));
  4786. s.mixer[7].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::reverb));
  4787. lynx::Automation a;
  4788. a.target = { lynx::AutomationTargetKind::mixerPan, 3 };
  4789. a.points = { { 0, 0.2f, 0.0f }, { 8 * lynx::ppq, 0.9f, 0.0f } };
  4790. s.automations.push_back (a);
  4791. s.playlist.clear();
  4792. for (int bar = 0; bar < 2; ++bar)
  4793. s.playlist.push_back ({ 0, 0, bar * 4 * lynx::ppq, 4 * lynx::ppq, 0 });
  4794. lynx::Clip automationClip;
  4795. automationClip.kind = lynx::ClipKind::automation;
  4796. automationClip.automation = 0;
  4797. automationClip.length = 8 * lynx::ppq;
  4798. automationClip.track = 1;
  4799. s.playlist.push_back (automationClip);
  4800. s.mode = lynx::PlayMode::song;
  4801. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-stems190gj-" + juce::String (juce::Time::currentTimeMillis()));
  4802. juce::String problems;
  4803. auto run = [&] (lynx::exportopts::Options o, const juce::String& name) {
  4804. o.stems = lynx::exportopts::Stems::mixerTracks;
  4805. o.maxTailSeconds = 3.0;
  4806. const auto alone = dir.getChildFile ("alone"), shared = dir.getChildFile ("shared");
  4807. alone.createDirectory();
  4808. shared.createDirectory();
  4809. const auto ext = juce::String (lynx::exportopts::extension (o.format));
  4810. const auto planAlone = lynx::planStemExport (s, o, alone.getChildFile (name + ext));
  4811. const auto planShared = lynx::planStemExport (s, o, shared.getChildFile (name + ext));
  4812. auto now = [] (std::function<void()> f) { f(); };
  4813. lynx::StemRunStats stats;
  4814. const auto a = lynx::runStemExport (planAlone, now, {}, {}, {}, {}, true);
  4815. const auto b = lynx::runStemExport (planShared, now, {}, {}, {}, {}, false, true, &stats);
  4816. if (a != (int) planAlone.items.size() || b != a)
  4817. problems << name << ": " << a << " / " << b << " files; ";
  4818. // (every insert from the one render, insert 5 with its side-chain too: it stays ducked as in the mix)
  4819. if (stats.passes != 1 || stats.inPass < 6)
  4820. problems << name << ": renders " << stats.passes << " shared, " << stats.inPass << " in it, " << stats.alone << " alone; ";
  4821. for (std::size_t k = 0; k < planShared.items.size() && k < planAlone.items.size(); ++k)
  4822. {
  4823. juce::MemoryBlock x, y;
  4824. planAlone.items[k].file.loadFileAsData (x);
  4825. planShared.items[k].file.loadFileAsData (y);
  4826. if (x.getSize() == 0 || x != y)
  4827. problems << name << ": " << planShared.items[k].file.getFileName() << " differs; ";
  4828. }
  4829. };
  4830. lynx::exportopts::Options streamed;
  4831. streamed.wavBits = 24;
  4832. streamed.stemsIncludeMaster = true;
  4833. run (streamed, "streamed");
  4834. lynx::exportopts::Options buffered;
  4835. buffered.wavBits = 32;
  4836. buffered.normalize = true;
  4837. run (buffered, "buffered");
  4838. dir.deleteRecursively();
  4839. return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems;
  4840. }
  4841. static juce::String faultReportSelfTest()
  4842. {
  4843. #if (JUCE_WINDOWS && (defined (_M_X64) || defined (__x86_64__))) \
  4844. || ((JUCE_LINUX || JUCE_MAC) && (defined (__x86_64__) || defined (__aarch64__)))
  4845. const auto exe = juce::File::getSpecialLocation (juce::File::currentExecutableFile);
  4846. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  4847. .getChildFile ("lynx-faulttest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  4848. juce::StringArray problems;
  4849. // (rollup step 12: + hang = the crash handler's watchdog ends a handler that never returns, within its time limit
  4850. // (3 s here); heap = the C library's heap-corruption abort leaves the allocation-free crash file and no recovered
  4851. // project, at once (before the watchdog: the old handler waited for ever on the allocator's lock); Linux / macOS)
  4852. #if JUCE_WINDOWS
  4853. const char* const kinds[] = { "plain", "unwalkable", "hang" };
  4854. #else
  4855. const char* const kinds[] = { "plain", "guarded", "guarded-libc", "thread", "thread-libc", "hang", "heap" };
  4856. #endif
  4857. for (const auto* kind : kinds)
  4858. {
  4859. const auto folder = root.getChildFile (kind);
  4860. folder.createDirectory();
  4861. const auto watchdogTest = juce::String (kind) == "hang" || juce::String (kind) == "heap";
  4862. #if JUCE_WINDOWS
  4863. _putenv_s ("LYNX_CRASH_WATCHDOG_S", watchdogTest ? "3" : "");
  4864. #else
  4865. if (watchdogTest)
  4866. setenv ("LYNX_CRASH_WATCHDOG_S", "3", 1);
  4867. else
  4868. unsetenv ("LYNX_CRASH_WATCHDOG_S");
  4869. #endif
  4870. juce::ChildProcess child;
  4871. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  4872. const auto started = child.start (juce::StringArray { exe.getFullPathName(), "--faulttest", kind, folder.getFullPathName() }, 0);
  4873. const auto ended = started && child.waitForProcessToFinish (60000);
  4874. const auto seconds = (juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0;
  4875. if (! ended)
  4876. {
  4877. child.kill();
  4878. problems.add (juce::String (kind) + ": " + (started ? "did not end" : "did not start"));
  4879. continue;
  4880. }
  4881. juce::String text;
  4882. for (const auto& file : folder.findChildFiles (juce::File::findFiles, false, "crash *.txt"))
  4883. text = file.loadFileAsString();
  4884. if (watchdogTest)
  4885. {
  4886. const auto recovered = folder.findChildFiles (juce::File::findFiles, false, "recovered *").size();
  4887. if (juce::String (kind) == "hang" && (seconds < 2.5 || seconds > 30.0 || text.isEmpty()))
  4888. problems.add ("hang: ended after " + juce::String (seconds, 1) + " s (the watchdog: 3 s)" + (text.isEmpty() ? ", no crash file" : ""));
  4889. if (juce::String (kind) == "heap" && (seconds > 20.0 || ! text.contains ("heap-corruption abort") || recovered != 0))
  4890. problems.add ("heap: " + juce::String (seconds, 1) + " s, " + (text.isEmpty() ? juce::String ("no crash file") : text.upToFirstOccurrenceOf ("\n", false, false))
  4891. + ", " + juce::String (recovered) + " recovered project(s)");
  4892. continue;
  4893. }
  4894. #if JUCE_WINDOWS
  4895. const auto found = text.contains ("0xc0000005");
  4896. #else
  4897. const auto found = text.contains ("segmentation fault") || text.contains ("bus error");
  4898. #endif
  4899. if (folder.getChildFile ("swallowed.txt").existsAsFile())
  4900. problems.add (juce::String (kind) + ": LYNX's own fault was caught as a plugin's ("
  4901. + folder.getChildFile ("swallowed.txt").loadFileAsString() + ")");
  4902. else if (! found)
  4903. problems.add (juce::String (kind) + ": " + (text.isEmpty() ? "no crash file" : "a crash file without the fault")
  4904. + " (exit code 0x" + juce::String::toHexString ((juce::int64) child.getExitCode()) + ")");
  4905. }
  4906. root.deleteRecursively();
  4907. #if JUCE_WINDOWS
  4908. _putenv_s ("LYNX_CRASH_WATCHDOG_S", "");
  4909. #else
  4910. unsetenv ("LYNX_CRASH_WATCHDOG_S");
  4911. #endif
  4912. return problems.isEmpty() ? juce::String ("OK") : "ERROR " + problems.joinIntoString ("; ");
  4913. #else
  4914. return "SKIPPED (Windows x64, Linux / macOS x86-64 / ARM64 only)";
  4915. #endif
  4916. }
  4917. void runSelfTest (const juce::String& reportPath, const juce::String& demoProjectPath)
  4918. {
  4919. lynx::AudioEngine offline (false);
  4920. const auto peak = offline.renderOffline (2.0, 48000.0);
  4921. const auto audioOk = peak > 0.01f && peak < 10.0f;
  4922. // project format round trip, with accents in the name
  4923. auto original = lynx::Song::makeDefault();
  4924. original.channels[0].name = "Bumbo ação";
  4925. original.playlist.push_back ({ 0, 2, 3840, 1920, 960 });
  4926. original.mode = lynx::PlayMode::song;
  4927. original.mixer[3].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  4928. original.mixer[3].effects[0].params[1] = 0.25f;
  4929. lynx::Automation automation;
  4930. automation.name = "Pan";
  4931. automation.target = { lynx::AutomationTargetKind::effectParam, 3, 0, 1 };
  4932. automation.points = { { 0, 0.25f, 0.5f }, { 3840, 1.0f, 0.0f } };
  4933. original.automations.push_back (automation);
  4934. lynx::Clip automationClip;
  4935. automationClip.kind = lynx::ClipKind::automation;
  4936. automationClip.automation = 0;
  4937. automationClip.track = 4;
  4938. automationClip.length = 3840;
  4939. original.playlist.push_back (automationClip);
  4940. original.loopStart = 960;
  4941. original.loopEnd = 7680;
  4942. original.playlistTracks.resize (3);
  4943. original.playlistTracks[2].colour = 0xFF2A6FDB; // a track colour (round 90)
  4944. { // the clip grid (round 181a)
  4945. lynx::launcher::setClip (original, 1, 2, { 0, 0, 0, 1920, 0 });
  4946. auto& slot = *lynx::launcher::settingsAt (*original.clipGrid, 1, 2);
  4947. slot.name = "Clip ação";
  4948. slot.mode = lynx::LaunchMode::toggle;
  4949. slot.quant = lynx::LaunchQuant::eighthTriplet;
  4950. slot.legato = true;
  4951. slot.loop = false;
  4952. original.clipGrid->scenes[0].name = "Intro";
  4953. original.clipGrid->globalQuant = lynx::LaunchQuant::bars2;
  4954. }
  4955. std::uint32_t savedGroove = 0;
  4956. { // round 190bv: the groove pool, a groove on the slot's clip, and that clip copied and the copy moved
  4957. lynx::Groove g;
  4958. g.name = "Balanço";
  4959. g.base = lynx::GrooveBase::eighth;
  4960. g.quantize = 0.25f;
  4961. g.timing = 0.8f;
  4962. g.random = 0.1f;
  4963. g.velocity = -0.5f;
  4964. g.length = 1920;
  4965. g.points = { { 0, 1.0f }, { 560, 0.5f } };
  4966. savedGroove = lynx::groove::add (original.grooves, g);
  4967. original.grooves.amount = 1.2f;
  4968. lynx::groove::setClipGroove (original, 1, 2, savedGroove);
  4969. lynx::session::moveClip (original, 1, 2, 0, 1, true);
  4970. lynx::session::moveClip (original, 0, 1, 2, 0, false);
  4971. original.playlist[0].groove = savedGroove; // round 190fm: a Playlist pattern clip's groove
  4972. }
  4973. original.playlistTracks[2].grouped = true; // track groups and rack filter groups (round 104)
  4974. original.playlistTracks[1].collapsed = true;
  4975. original.channelGroups = { "Drums", "Keys" };
  4976. original.channels[1].group = 1;
  4977. original.channels[1].cutOthersOnly = original.channels[1].cutAtNoteEnd = true; // FL Studio Mobile's cut rule (round 190fe)
  4978. juce::String error;
  4979. if (demoProjectPath.isNotEmpty()) // sample project for checking the UI with --snapshot
  4980. lynx::ProjectFile::save (original, juce::File (demoProjectPath), error);
  4981. const auto reloaded = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (original), error);
  4982. // round 190bw: FL's curve modes of automation points come back from a project, tension whole; a bent point
  4983. // without a mode (a project saved before the modes: [tick, value, tension]) keeps LYNX's older law
  4984. const auto curveModesOk = [&original] {
  4985. auto song = original;
  4986. auto& a = song.automations[0];
  4987. a.points = { { 0, 0.25f, 0.5f, (std::uint8_t) lynx::flcurve::stairs },
  4988. { 960, 1.0f, -0.123456f, (std::uint8_t) lynx::flcurve::smooth },
  4989. { 1920, 0.5f, 0.0f, (std::uint8_t) lynx::flcurve::hold },
  4990. { 2400, 0.75f, 0.7f, lynx::AutomationPoint::legacyCurve },
  4991. { 2880, 0.3f, 0.0f, 0 },
  4992. { 3840, 0.6f, 0.0f, 0 } };
  4993. a.lfo.on = true;
  4994. a.lfo.amp = { { 0, 1.0f, -0.25f, (std::uint8_t) lynx::flcurve::pulse }, { 960, 0.5f, 0.0f, 0 } };
  4995. juce::String e;
  4996. const auto text = lynx::ProjectFile::toJson (song);
  4997. const auto back = lynx::ProjectFile::fromJson (text, e);
  4998. return back && back->automations.size() == 1 && back->automations[0].points == a.points && back->automations[0].lfo.amp == a.lfo.amp
  4999. && back->automations[0].valueAt (700.0) == a.valueAt (700.0) && back->automations[0].valueAt (2600.0) == a.valueAt (2600.0);
  5000. }();
  5001. const auto projectOk = curveModesOk && reloaded && reloaded->channels.size() == original.channels.size()
  5002. && reloaded->channels[0].name == original.channels[0].name
  5003. && reloaded->patterns[0].notes.size() == original.patterns[0].notes.size()
  5004. && reloaded->patterns[0].notes[3].start == original.patterns[0].notes[3].start
  5005. && reloaded->mode == lynx::PlayMode::song && reloaded->playlist.size() == 2
  5006. && reloaded->clipGrid.has_value() && reloaded->clipGrid->globalQuant == lynx::LaunchQuant::bars2
  5007. && reloaded->clipGrid->scenes.size() == 3 && reloaded->clipGrid->scenes[0].name == "Intro"
  5008. && lynx::launcher::clipAt (*reloaded->clipGrid, 1, 2) != nullptr
  5009. && [&reloaded] {
  5010. auto grid = *reloaded->clipGrid;
  5011. const auto* slot = lynx::launcher::settingsAt (grid, 1, 2);
  5012. return slot != nullptr && slot->name == "Clip ação" && slot->mode == lynx::LaunchMode::toggle
  5013. && slot->quant == lynx::LaunchQuant::eighthTriplet && slot->legato && ! slot->loop;
  5014. }()
  5015. && [&reloaded, &original, savedGroove] { // round 190bv
  5016. auto grid = *reloaded->clipGrid;
  5017. const auto* kept = lynx::launcher::settingsAt (grid, 1, 2);
  5018. const auto* moved = lynx::launcher::settingsAt (grid, 2, 0);
  5019. const auto* clip = lynx::launcher::clipAt (grid, 2, 0);
  5020. return reloaded->grooves == original.grooves && reloaded->grooves.grooves.size() == 1
  5021. && reloaded->grooves.amount == 1.2f && reloaded->grooves.grooves[0].name == "Balanço"
  5022. && reloaded->grooves.grooves[0].points.size() == 2 && savedGroove != 0
  5023. && kept != nullptr && kept->groove == savedGroove
  5024. && lynx::launcher::clipAt (grid, 0, 1) == nullptr
  5025. && clip != nullptr && clip->pattern == 0 && clip->length == 1920
  5026. && moved != nullptr && moved->groove == savedGroove && moved->name == "Clip ação"
  5027. && moved->mode == lynx::LaunchMode::toggle && moved->legato && ! moved->loop
  5028. && reloaded->playlist[0].groove == savedGroove && reloaded->playlist[1].groove == 0; // (190fm)
  5029. }()
  5030. && reloaded->playlist[1].kind == lynx::ClipKind::automation && reloaded->playlist[1].automation == 0
  5031. && reloaded->automations.size() == 1 && reloaded->automations[0].target == automation.target
  5032. && reloaded->automations[0].points.size() == 2 && reloaded->automations[0].points[0].tension == 0.5f
  5033. && reloaded->automations[0].points[1].tick == 3840
  5034. && reloaded->loopStart == 960 && reloaded->loopEnd == 7680
  5035. && reloaded->playlistTracks.size() == 3 && reloaded->playlistTracks[2].colour == 0xFF2A6FDB
  5036. && reloaded->playlistTracks[1].colour == 0
  5037. && reloaded->playlistTracks[2].grouped && reloaded->playlistTracks[1].collapsed && ! reloaded->playlistTracks[1].grouped
  5038. && reloaded->channelGroups == original.channelGroups && reloaded->channels[1].group == 1 && reloaded->channels[0].group == -1
  5039. && reloaded->channels[1].cutOthersOnly && reloaded->channels[1].cutAtNoteEnd && ! reloaded->channels[0].cutOthersOnly
  5040. && ! reloaded->channels[0].cutAtNoteEnd
  5041. && reloaded->playlist[0].offset == 960 && reloaded->playlist[0].track == 2
  5042. && reloaded->mixer[3].effects.size() == 1
  5043. && reloaded->mixer[3].effects[0].kind == lynx::EffectKind::delay
  5044. && reloaded->mixer[3].effects[0].params[1] == 0.25f;
  5045. // round trip of the newer features: synth/sampler with modulation, EQs, utility, markers
  5046. auto rich = lynx::Song::makeDefault();
  5047. auto& synth = rich.channels[4].synth;
  5048. synth.osc[1] = { lynx::Waveform::square, -1, 7.0f, 0.4f, 5, -0.25f };
  5049. synth.filterType = 2;
  5050. synth.mono = true;
  5051. synth.portaBeats = 0.125f;
  5052. synth.am = true;
  5053. synth.filterEnv = { 3.0f, 0.01f, 0.02f, 0.3f, 0.25f, 0.4f };
  5054. synth.lfo[lynx::lfoPitch] = { 0.5f, 0.25f, true, 1, 0.1f, 0.2f };
  5055. auto& sampler = rich.channels[0].sampler;
  5056. sampler.cutoff = 1200.0f;
  5057. sampler.resonance = 0.3f;
  5058. sampler.filterType = 1;
  5059. sampler.pitchEnv = { -12.0f, 0.0f, 0.0f, 0.05f, 0.0f, 0.1f };
  5060. sampler.lfo[lynx::lfoVolume] = { 0.5f, 0.5f, false, 2, 0.0f, 0.0f };
  5061. rich.mixer[2].eq.gainDb = { 3.0f, -2.5f, 1.0f };
  5062. rich.mixer[2].eq.hz[1] = 2200.0f;
  5063. auto peqSlot = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  5064. peqSlot.params[(std::size_t) lynx::peq::param (2, 2)] = lynx::peq::gainValue (6.0);
  5065. peqSlot.params[(std::size_t) (lynx::peq::slopeParam + 0)] = lynx::peq::slopeValue (3);
  5066. rich.mixer[2].effects.push_back (peqSlot);
  5067. auto utilitySlot = lynx::makeEffectSlot (lynx::EffectKind::utility);
  5068. utilitySlot.params[1] = 0.2f;
  5069. rich.mixer[2].effects.push_back (utilitySlot);
  5070. auto vocodexSlot = lynx::makeEffectSlot (lynx::EffectKind::vocodex); // FL's raw state travels as base64
  5071. for (int i = 0; i < 300; ++i)
  5072. vocodexSlot.state.push_back ((std::uint8_t) (i * 37));
  5073. vocodexSlot.sidechain = 1;
  5074. vocodexSlot.sidechain2 = 2;
  5075. rich.mixer[3].effects.push_back (vocodexSlot);
  5076. rich.addMarker ({ 3840, "Refrão", 0, 4 });
  5077. rich.addMarker ({ 7680, {}, 7, 8 });
  5078. const auto richBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (rich), error);
  5079. auto paramsClose = [] (const lynx::EffectParams& a, const lynx::EffectParams& b) {
  5080. for (std::size_t i = 0; i < a.size(); ++i)
  5081. if (std::abs (a[i] - b[i]) > 1.0e-3f)
  5082. return false;
  5083. return true;
  5084. };
  5085. // round 190bu: a one-knob effect, the chain's Blend and its preset name travel in the project; a project without
  5086. // them reads as before (no goal, Blend 100 %) and writes none of the new keys
  5087. bool fx190buOk = false;
  5088. {
  5089. auto song = lynx::Song::makeDefault();
  5090. const auto plainJson = lynx::ProjectFile::toJson (song);
  5091. const auto* preset = lynx::chains::find ("Whisper Air");
  5092. if (preset != nullptr && song.mixer.size() > 2)
  5093. {
  5094. lynx::chains::apply (song, 1, *preset);
  5095. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::room, 0.62f));
  5096. song.mixer[2].effects.push_back (lynx::goals::make (lynx::goals::bass, 0.3f));
  5097. song.mixer[2].chainBlend = 0.4f;
  5098. const auto json = lynx::ProjectFile::toJson (song);
  5099. const auto back = lynx::ProjectFile::fromJson (json, error);
  5100. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  5101. auto same = back && back->mixer.size() == song.mixer.size();
  5102. for (std::size_t t = 1; same && t <= 2; ++t)
  5103. {
  5104. const auto& a = song.mixer[t];
  5105. const auto& b = back->mixer[t];
  5106. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  5107. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  5108. same = a.effects[i].kind == b.effects[i].kind && a.effects[i].goal == b.effects[i].goal
  5109. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f && a.effects[i].row == b.effects[i].row
  5110. && lynx::goals::active (b.effects[i]) == lynx::goals::active (a.effects[i]);
  5111. }
  5112. fx190buOk = same && lynx::chains::unchanged (*back, 1) && back->mixer[2].chainPreset.empty()
  5113. && ! plainJson.contains ("\"goal\"") && ! plainJson.contains ("chainBlend") && ! plainJson.contains ("chainPreset")
  5114. && json.contains ("\"goalAmount\"") && plainBack && plainBack->mixer[1].chainBlend == 1.0f
  5115. && lynx::ProjectFile::toJson (*back) == json;
  5116. // a user's chain preset file: the slots, Blend and name come back; the strip's level is not part of it
  5117. song.mixer[2].volume = 0.31f;
  5118. const auto file = lynx::ProjectFile::mixerTrackStateToJson (lynx::chains::stateOf (song.mixer[2], "Mine"));
  5119. const auto state = lynx::ProjectFile::mixerTrackStateFromJson (file, error);
  5120. fx190buOk = fx190buOk && state && state->effects.size() == 2 && state->effects[0].goal == lynx::goals::room
  5121. && lynx::goals::active (state->effects[1]) && std::abs (state->chainBlend - 0.4f) < 1.0e-6f && state->chainPreset == "Mine"
  5122. && state->volume == lynx::MixerTrack().volume;
  5123. }
  5124. }
  5125. const auto richOk = fx190buOk && richBack && richBack->channels[4].synth == synth && richBack->channels[0].sampler == sampler
  5126. && richBack->mixer[2].eq == rich.mixer[2].eq && richBack->mixer[2].effects.size() == 2
  5127. && richBack->mixer[2].effects[0].kind == lynx::EffectKind::parametricEq
  5128. && paramsClose (richBack->mixer[2].effects[0].params, peqSlot.params)
  5129. && richBack->mixer[2].effects[1].kind == lynx::EffectKind::utility
  5130. && paramsClose (richBack->mixer[2].effects[1].params, utilitySlot.params)
  5131. && richBack->mixer[3].effects.size() == 1 && richBack->mixer[3].effects[0].kind == lynx::EffectKind::vocodex
  5132. && richBack->mixer[3].effects[0].state == vocodexSlot.state && richBack->mixer[3].effects[0].sidechain2 == 2
  5133. && richBack->markers() == rich.markers();
  5134. // issue #96's per-plugin option: saved only when on; old projects (no field) read as off
  5135. bool hostKeysOk = false;
  5136. {
  5137. auto song = lynx::Song::makeDefault();
  5138. lynx::ChannelDef plugin;
  5139. plugin.instrument = lynx::InstrumentKind::plugin;
  5140. plugin.plugin.id = "x";
  5141. song.channels.push_back (plugin);
  5142. const auto channel = song.channels.size() - 1;
  5143. const auto off = lynx::ProjectFile::toJson (song);
  5144. song.channels[channel].plugin.allowHostKeys = true;
  5145. song.channels[channel].plugin.hostKeysFirst = true;
  5146. song.channels[channel].plugin.pinned = true; // (round 190ao: Pin on top)
  5147. song.channels[channel].plugin.velocityMode = lynx::prefs::pluginVelocityFixed; // (round 190ao: the plugin's own velocity)
  5148. song.channels[channel].plugin.fixedVelocity = 64;
  5149. const auto on = lynx::ProjectFile::toJson (song);
  5150. const auto offBack = lynx::ProjectFile::fromJson (off, error);
  5151. const auto onBack = lynx::ProjectFile::fromJson (on, error);
  5152. hostKeysOk = ! off.contains ("allowHostKeys") && on.contains ("allowHostKeys") && offBack && onBack
  5153. && ! offBack->channels[channel].plugin.allowHostKeys && onBack->channels[channel].plugin.allowHostKeys
  5154. && ! off.contains ("hostKeysFirst") && ! offBack->channels[channel].plugin.hostKeysFirst && onBack->channels[channel].plugin.hostKeysFirst
  5155. && ! off.contains ("pinnedOnTop") && ! offBack->channels[channel].plugin.pinned && onBack->channels[channel].plugin.pinned
  5156. && ! off.contains ("velocityMode") && ! off.contains ("fixedVelocity") && offBack->channels[channel].plugin.velocityMode == 0
  5157. && offBack->channels[channel].plugin.fixedVelocity == lynx::prefs::defaultFixedVelocity
  5158. && onBack->channels[channel].plugin.velocityMode == lynx::prefs::pluginVelocityFixed && onBack->channels[channel].plugin.fixedVelocity == 64;
  5159. }
  5160. // round 190ad: a new project has FL's plugin levels and keeps them through a save; a project saved before
  5161. // (no "pluginLevels") reads as LYNX's own law, and stays so when it opens
  5162. bool pluginLevelsOk = false;
  5163. {
  5164. const auto fresh = lynx::makeNewProject();
  5165. const auto saved = lynx::ProjectFile::toJson (fresh);
  5166. const auto back = lynx::ProjectFile::fromJson (saved, error);
  5167. auto old = lynx::Song::makeDefault(); // (what every earlier version made)
  5168. const auto oldSaved = lynx::ProjectFile::toJson (old);
  5169. const auto oldBack = lynx::ProjectFile::fromJson (oldSaved, error);
  5170. const auto stripped = lynx::ProjectFile::fromJson (saved.replace ("\"pluginLevels\"", "\"pluginLevelsGone\""), error);
  5171. pluginLevelsOk = fresh.flPluginLevels && saved.contains ("\"pluginLevels\"") && back && back->flPluginLevels
  5172. && ! old.flPluginLevels && ! oldSaved.contains ("pluginLevels") && oldBack && ! oldBack->flPluginLevels
  5173. && stripped && ! stripped->flPluginLevels;
  5174. }
  5175. // hardware output targets (REA round 156): saved only when set; old projects (no field) keep the defaults
  5176. bool hwOutOk = false;
  5177. {
  5178. auto song = lynx::Song::makeDefault();
  5179. const auto plain = lynx::ProjectFile::toJson (song);
  5180. song.mixer[0].outputChannel = lynx::outputNone;
  5181. song.mixer[1].outputChannel = 2;
  5182. song.mixer[1].outputMode = lynx::OutputMode::monoRight;
  5183. song.mixer[2].outputChannel = 6;
  5184. song.mixer[3].outputChannel = 4;
  5185. song.mixer[3].outputMode = lynx::OutputMode::monoSum;
  5186. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5187. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  5188. hwOutOk = back && back->mixer[0].outputChannel == lynx::outputNone && back->mixer[1].outputChannel == 2
  5189. && back->mixer[1].outputMode == lynx::OutputMode::monoRight && back->mixer[2].outputChannel == 6
  5190. && back->mixer[2].outputMode == lynx::OutputMode::stereo && back->mixer[3].outputMode == lynx::OutputMode::monoSum
  5191. && back->mixer[4].outputChannel == lynx::outputDefault && ! plain.contains ("\"output\"") && plainBack
  5192. && plainBack->mixer[0].outputChannel == lynx::outputDefault && plainBack->mixer[1].outputChannel == lynx::outputDefault;
  5193. }
  5194. // round 168j: FL's icons (channel / mixer track / playlist track), PDC Automatic / Compensate automations, Time
  5195. // settings, scale highlighting and data folder — saved only when set, old projects load with FL's defaults
  5196. bool flp168jOk = false;
  5197. {
  5198. auto song = lynx::Song::makeDefault();
  5199. const auto plain = lynx::ProjectFile::toJson (song);
  5200. song.channels[0].icon = 75;
  5201. song.mixer[2].icon = 71;
  5202. song.playlistTracks.resize (3);
  5203. song.playlistTracks[2].icon = 30;
  5204. song.autoPdc = false;
  5205. song.compensateAutomations = false;
  5206. song.timeSignatureMode = true;
  5207. song.scaleHighlight = { 10, 5 };
  5208. song.dataFolder = "D:\\Projects\\data";
  5209. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5210. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  5211. flp168jOk = back && back->channels[0].icon == 75 && back->mixer[2].icon == 71 && back->playlistTracks.size() >= 3
  5212. && back->playlistTracks[2].icon == 30 && ! back->autoPdc && ! back->compensateAutomations && back->timeSignatureMode
  5213. && back->scaleHighlight == song.scaleHighlight && back->dataFolder == song.dataFolder && plainBack && plainBack->autoPdc
  5214. && plainBack->compensateAutomations && ! plainBack->timeSignatureMode && plainBack->scaleHighlight == lynx::Song::ScaleHighlight {}
  5215. && plainBack->dataFolder.empty() && plainBack->channels[0].icon == 0 && ! plain.contains ("\"icon\"")
  5216. && ! plain.contains ("autoPdc") && ! plain.contains ("scaleHighlight");
  5217. }
  5218. // round 180d: clip fades take FL's S curve; a project saved before that keeps its straight fades, also after another
  5219. // save, and a clip made in it takes the S curve. FL's fade tensions and stretch mode and PITCH survive a save.
  5220. // issue #122: playlist tracks linked to inserts (audio) and channels (instrument) survive save, load and save
  5221. // again byte for byte (they were read before the mixer and fell back to Unassigned)
  5222. bool trackModes122Ok = false;
  5223. {
  5224. auto song = lynx::Song::makeDefault();
  5225. song.playlistTracks.resize (6);
  5226. song.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  5227. song.playlistTracks[1].mixerTrack = 3;
  5228. song.playlistTracks[4].mode = lynx::PlaylistTrackMode::audio;
  5229. song.playlistTracks[4].mixerTrack = (int) song.mixer.size() - 1;
  5230. song.playlistTracks[5].mode = lynx::PlaylistTrackMode::instrument;
  5231. song.playlistTracks[5].channel = 1;
  5232. song.playlistTracks[5].mixerTrack = 2;
  5233. const auto json = lynx::ProjectFile::toJson (song, false);
  5234. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  5235. const auto again = loaded ? lynx::ProjectFile::toJson (*loaded, false) : juce::String();
  5236. trackModes122Ok = loaded && json.contains ("playlistTrackModes") && again == json && loaded->playlistTracks.size() >= 6
  5237. && loaded->playlistTracks[1].mode == lynx::PlaylistTrackMode::audio && loaded->playlistTracks[1].mixerTrack == 3
  5238. && loaded->playlistTracks[4].mode == lynx::PlaylistTrackMode::audio
  5239. && loaded->playlistTracks[4].mixerTrack == (int) song.mixer.size() - 1
  5240. && loaded->playlistTracks[5].mode == lynx::PlaylistTrackMode::instrument && loaded->playlistTracks[5].channel == 1;
  5241. }
  5242. bool clipFades180dOk = false;
  5243. {
  5244. auto song = lynx::Song::makeDefault();
  5245. lynx::Clip faded;
  5246. faded.kind = lynx::ClipKind::audio;
  5247. faded.channel = 0;
  5248. faded.length = lynx::ppq * 8;
  5249. faded.fadeIn = lynx::ppq;
  5250. faded.fadeOutTension = -812.933f;
  5251. faded.fadeOut = lynx::ppq * 2;
  5252. lynx::Clip plainClip = faded;
  5253. plainClip.fadeIn = plainClip.fadeOut = 0;
  5254. plainClip.fadeOutTension = 0.0f;
  5255. plainClip.start = lynx::ppq * 16;
  5256. song.playlist = { faded, plainClip };
  5257. song.channels[0].sampler.flStretchMode = 5;
  5258. song.channels[0].sampler.flStretchPitch = 247;
  5259. const auto json = lynx::ProjectFile::toJson (song);
  5260. const auto current = lynx::ProjectFile::fromJson (json, error);
  5261. const auto oldJson = json.replace ("\"clipFadesPerClip\"", "\"clipFadesOther\"");
  5262. auto old = lynx::ProjectFile::fromJson (oldJson, error);
  5263. auto resaved = old;
  5264. if (resaved)
  5265. {
  5266. auto added = faded;
  5267. added.start = lynx::ppq * 32;
  5268. added.linearFades = 0;
  5269. resaved->playlist.push_back (added);
  5270. resaved = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*resaved), error);
  5271. }
  5272. clipFades180dOk = current && old && resaved && json.contains ("clipFadesPerClip") && ! oldJson.contains ("clipFadesPerClip")
  5273. && current->playlist.size() == 2 && ! current->playlist[0].linearFades
  5274. && current->playlist[0].fadeOutTension == -812.933f && ! current->playlist[1].linearFades
  5275. && current->channels[0].sampler.flStretchMode == 5 && current->channels[0].sampler.flStretchPitch == 247
  5276. && old->playlist.size() == 2 && old->playlist[0].linearFades && ! old->playlist[1].linearFades
  5277. && resaved->playlist.size() == 3 && resaved->playlist[0].linearFades && ! resaved->playlist[1].linearFades
  5278. && ! resaved->playlist[2].linearFades && resaved->playlist[0].fadeOutTension == -812.933f;
  5279. }
  5280. // FL's legacy Pattern Blocks (round 170f): the option and every arrangement's blocks are saved; a project without
  5281. // them has neither in its file and loads with the option off
  5282. bool blocksOk = false;
  5283. {
  5284. auto song = lynx::Song::makeDefault();
  5285. const auto plain = lynx::ProjectFile::toJson (song);
  5286. song.patternBlocksOn = true;
  5287. lynx::patternblocks::place (song, 0, 0);
  5288. lynx::patternblocks::place (song, 0, 4 * 4 * lynx::ppq);
  5289. lynx::patternblocks::setMuted (song, 1, true); // (round 190ht, issue #127: a muted block keeps its mute)
  5290. song.addArrangement ("Second");
  5291. lynx::patternblocks::place (song, 0, 2 * 4 * lynx::ppq);
  5292. song.selectArrangement (0);
  5293. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5294. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  5295. blocksOk = back && back->patternBlocksOn && back->blocks == song.blocks && song.blocks.size() == 2 && back->blocks[1].muted
  5296. && back->arrangements.size() == 2 && back->arrangements[1].blocks == song.arrangements[1].blocks
  5297. && song.arrangements[1].blocks.size() == 1 && back->songLength() == song.songLength() && plainBack
  5298. && ! plainBack->patternBlocksOn && plainBack->blocks.empty() && ! plain.contains ("blocks")
  5299. && ! plain.contains ("patternBlocks");
  5300. }
  5301. // FL's pattern clip takeover (issue #158): saved when on; a project saved before it (no key) loads with it off and
  5302. // keeps playing every overlapping clip of a pattern in full; new projects have it on
  5303. bool takeoverOk = false;
  5304. {
  5305. auto song = lynx::Song::makeDefault();
  5306. const auto plain = lynx::ProjectFile::toJson (song);
  5307. song.patternClipTakeover = true;
  5308. const auto json = lynx::ProjectFile::toJson (song);
  5309. const auto back = lynx::ProjectFile::fromJson (json, error);
  5310. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  5311. takeoverOk = back && back->patternClipTakeover && json.contains ("patternClipTakeover") && plainBack
  5312. && ! plainBack->patternClipTakeover && ! plain.contains ("patternClipTakeover")
  5313. && lynx::makeNewProject().patternClipTakeover;
  5314. }
  5315. // comping (round 177c): a comp's equal-power crossfades (Clip::fadeCurve) and the crossfade length are saved; a
  5316. // project without them has neither in its file
  5317. bool compOk = false;
  5318. {
  5319. auto song = lynx::Song::makeDefault();
  5320. const auto plain = lynx::ProjectFile::toJson (song);
  5321. lynx::ChannelDef take;
  5322. take.instrument = lynx::InstrumentKind::audioClip;
  5323. take.samplePath = "take.wav";
  5324. song.channels.push_back (take);
  5325. lynx::Clip a;
  5326. a.kind = lynx::ClipKind::audio;
  5327. a.channel = (int) song.channels.size() - 1;
  5328. a.length = lynx::ppq;
  5329. a.fadeOut = 20;
  5330. a.fadeCurve = 2;
  5331. auto b = a;
  5332. b.start = lynx::ppq - 20;
  5333. b.fadeOut = 0;
  5334. b.fadeIn = 20;
  5335. b.fadeCurve = 1;
  5336. // round 180d's FL fade fields (indices 17..20) and the comp curve (index 21) on one clip, all kept
  5337. auto c = a;
  5338. c.start = 4 * lynx::ppq;
  5339. c.fadeIn = 30;
  5340. c.fadeInTension = -0.75f;
  5341. c.fadeOutTension = 0.5f;
  5342. c.linearFades = 2;
  5343. c.flFadeFlags = 0x1234u;
  5344. c.fadeCurve = 3;
  5345. song.playlist = { a, b, c };
  5346. song.compCrossfadeMs = 12.5f;
  5347. song.playlistTracks.resize (2);
  5348. song.playlistTracks[0].compTrack = true;
  5349. song.playlistTracks[1].grouped = true;
  5350. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5351. const auto plainBack = lynx::ProjectFile::fromJson (plain, error);
  5352. const auto* both = back && back->playlist.size() == 3 ? &back->playlist[2] : nullptr;
  5353. compOk = back && back->playlist.size() == 3 && back->playlist[0].fadeCurve == 2 && back->playlist[1].fadeCurve == 1
  5354. && both != nullptr && both->fadeCurve == 3 && both->fadeInTension == -0.75f && both->fadeOutTension == 0.5f
  5355. && both->linearFades == 2 && both->flFadeFlags == 0x1234u && both->fadeIn == 30
  5356. && back->playlist[1].fadeIn == 20 && back->compCrossfadeMs == 12.5f && back->playlistTracks[0].compTrack && ! back->playlistTracks[1].compTrack && plainBack
  5357. && plainBack->compCrossfadeMs == lynx::Song::defaultCompCrossfadeMs && ! plain.contains ("compCrossfadeMs") && ! plain.contains ("playlistCompTracks");
  5358. }
  5359. // Misc › Mono / Porta / Slide on every generator (round 168l): kept in the file; a project saved before (an
  5360. // imported engine's flags in its synth settings) gets them back, a Max polyphony of 1 is not Mono
  5361. bool polyOk = false;
  5362. {
  5363. auto song = lynx::Song::makeDefault();
  5364. lynx::ChannelDef osc;
  5365. osc.instrument = lynx::InstrumentKind::threeosc;
  5366. osc.misc.mono = osc.misc.porta = true;
  5367. osc.misc.portaBeats = 0.25f;
  5368. song.channels.push_back (osc);
  5369. auto old = osc;
  5370. old.misc = {};
  5371. old.synth.mono = old.synth.porta = true;
  5372. old.synth.portaBeats = 0.5f;
  5373. song.channels.push_back (old);
  5374. old.maxPolyphony = 1;
  5375. song.channels.push_back (old);
  5376. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5377. const auto n = song.channels.size();
  5378. polyOk = back && back->channels.size() == n && back->channels[n - 3].misc.mono && back->channels[n - 3].misc.porta
  5379. && std::abs (back->channels[n - 3].misc.portaBeats - 0.25f) < 1e-6f && back->channels[n - 2].misc.mono
  5380. && back->channels[n - 2].misc.porta && std::abs (back->channels[n - 2].misc.portaBeats - 0.5f) < 1e-6f
  5381. && ! back->channels[n - 1].misc.mono && back->channels[n - 1].maxPolyphony == 1
  5382. && ! back->channels[4].misc.mono; // (the LYNX Synth keeps its own flags)
  5383. }
  5384. // FL's track latency (REA round 165f-mixer): manual ms, bypass mode and master compensation saved only when set
  5385. bool latencyOk = false;
  5386. {
  5387. auto song = lynx::Song::makeDefault();
  5388. const auto plain = lynx::ProjectFile::toJson (song);
  5389. song.mixer[1].latencyMs = -20.0f;
  5390. song.mixer[2].latencyMs = 12.5f;
  5391. song.mixer[2].latencyBypass = lynx::LatencyBypass::always;
  5392. song.mixer[3].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  5393. song.mixer[3].compensateMasterLatency = false;
  5394. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5395. latencyOk = back && back->mixer[1].latencyMs == -20.0f && back->mixer[2].latencyMs == 12.5f
  5396. && back->mixer[2].latencyBypass == lynx::LatencyBypass::always
  5397. && back->mixer[3].latencyBypass == lynx::LatencyBypass::whenRecordingOrStopped && ! back->mixer[3].compensateMasterLatency
  5398. && back->mixer[4].latencyMs == 0.0f && back->mixer[4].compensateMasterLatency
  5399. && ! plain.contains ("latencyMs") && ! plain.contains ("latencyBypass") && ! plain.contains ("compensateMaster");
  5400. }
  5401. // LYNX's pre-fader sends (round 190aq): saved only when one is used, in a list of its own ("preSends") that a
  5402. // version from before ignores (its sends then play post-fader, as FL's)
  5403. bool preSendOk = false;
  5404. {
  5405. auto song = lynx::Song::makeDefault();
  5406. song.setRoute (1, 3, true, 0.5f);
  5407. song.setRoute (1, 4, true);
  5408. song.setRoute (2, 3, true);
  5409. const auto plain = lynx::ProjectFile::toJson (song);
  5410. song.setSendPre (1, 3, true);
  5411. const auto json = lynx::ProjectFile::toJson (song);
  5412. const auto back = lynx::ProjectFile::fromJson (json, error);
  5413. preSendOk = back && back->sendPre (1, 3) && ! back->sendPre (1, 4) && ! back->sendPre (2, 3)
  5414. && std::abs (back->routeLevel (1, 3) - 0.5f) < 1.0e-4f && back->mixer[1].sends == song.mixer[1].sends
  5415. && ! plain.contains ("preSends") && json.contains ("preSends")
  5416. && json.replace ("\"preSends\"", "\"preSendsOld\"") != json;
  5417. // the same file without the list (what an older version reads): the sends are there, post-fader
  5418. if (const auto old = lynx::ProjectFile::fromJson (json.replace ("\"preSends\"", "\"unknownToOldVersions\""), error))
  5419. preSendOk = preSendOk && old->routes (1, 3) && ! old->sendPre (1, 3) && old->mixer[1].sends.size() == 2;
  5420. else
  5421. preSendOk = false;
  5422. }
  5423. // LYNX's "Low latency while recording" (round 190aq): a latency-adding effect on a monitored insert's path is
  5424. // bypassed in the engine only — PDC drops, the slot is marked, the song and the saved project stay as they are —
  5425. // and it is back when the option goes off
  5426. bool lowLatencyOk = false;
  5427. {
  5428. lynx::AudioEngine live (false);
  5429. live.editSong ([] (lynx::Song& s) {
  5430. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter)); // 1.5 ms look-ahead
  5431. s.mixer[1].inputChannel = 0;
  5432. s.mixer[1].monitor = lynx::InputMonitor::on;
  5433. });
  5434. const auto before = live.getLatencySamples();
  5435. const auto saved = lynx::ProjectFile::toJson (live.getSong());
  5436. const auto idle = live.lowLatencyBypassedCount() == 0; // the option is off: nothing is bypassed
  5437. auto o = live.getRecordOptions();
  5438. o.lowLatencyRecording = true;
  5439. live.setRecordOptions (o);
  5440. const auto during = live.getLatencySamples();
  5441. const auto marked = live.isSlotLowLatencyBypassed (1, 0) && live.lowLatencyBypassedLatency (1, 0) > 0 && live.lowLatencyBypassedCount() >= 1;
  5442. const auto untouched = live.getSong().mixer[1].effects[0].enabled && lynx::ProjectFile::toJson (live.getSong()) == saved;
  5443. // monitoring leaves "On" (nothing armed): the effect returns
  5444. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::whenArmed; });
  5445. const auto released = live.getLatencySamples() == before && ! live.isSlotLowLatencyBypassed (1, 0);
  5446. live.editSong ([] (lynx::Song& s) { s.mixer[1].monitor = lynx::InputMonitor::on; });
  5447. const auto again = live.getLatencySamples() == during && live.isSlotLowLatencyBypassed (1, 0);
  5448. o.lowLatencyRecording = false;
  5449. live.setRecordOptions (o);
  5450. lowLatencyOk = before > 0 && idle && during < before && marked && untouched && released && again
  5451. && live.getLatencySamples() == before && live.lowLatencyBypassedCount() == 0;
  5452. }
  5453. // The Browser's "Preview in time" (round 190aq): a loop whose name gives its tempo is stretched to the project's
  5454. // and starts on the beat; a one-shot plays as it always did; off, nothing changes
  5455. bool previewInTimeOk = false;
  5456. double previewPrepareMs = 0.0;
  5457. {
  5458. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-preview");
  5459. dir.deleteRecursively();
  5460. dir.createDirectory();
  5461. auto writeWav = [&dir] (const juce::String& name, int frames, bool loop) {
  5462. const auto wav = dir.getChildFile (name);
  5463. juce::WavAudioFormat format;
  5464. juce::AudioBuffer<float> audio (1, frames);
  5465. for (int i = 0; i < frames; ++i) // a click on every beat of 120 BPM over a tone, or a decaying hit
  5466. audio.setSample (0, i, loop ? (i % 24000 < 400 ? 0.8f : 0.0f) + 0.1f * std::sin (0.02f * (float) i)
  5467. : 0.6f * std::exp (-(float) i / 2000.0f) * std::sin (0.05f * (float) i));
  5468. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  5469. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  5470. {
  5471. out.release();
  5472. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  5473. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  5474. }
  5475. return wav;
  5476. };
  5477. const auto loop = writeWav ("selftest loop 120 bpm.wav", 96000, true); // 4 beats at 120 BPM
  5478. const auto hit = writeWav ("selftest hit.wav", 14400, false); // 0.3 s
  5479. lynx::AudioEngine player (false);
  5480. const auto projectBpm = player.getTransport().bpm.load();
  5481. // off (FL's preview): nothing is prepared, the file plays as it is
  5482. player.previewFile (loop);
  5483. const auto offOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  5484. player.setPreviewInTime (true);
  5485. player.previewFile (hit); // a one-shot: as it always played, at once
  5486. const auto hitOk = ! player.getPreviewTiming().pending && ! player.getPreviewTiming().inTime;
  5487. player.previewFile (loop);
  5488. const auto queued = player.getPreviewTiming().pending || std::abs (projectBpm - 120.0) < 0.2;
  5489. player.finishPreviewJobs();
  5490. const auto timing = player.getPreviewTiming();
  5491. previewPrepareMs = player.getLastPreviewPrepareMs();
  5492. const auto wanted = lynx::previewtempo::stretchRatio (120.0, projectBpm);
  5493. const auto stretchedOk = timing.inTime && ! timing.pending && timing.source == lynx::previewtempo::Source::name
  5494. && std::abs (timing.fileBpm - 120.0) < 1.0e-9 && std::abs (timing.ratio - wanted) < 1.0e-12
  5495. && std::abs ((double) timing.frames - 96000.0 * wanted) < 96000.0 * 0.01;
  5496. // the second click on the same file has its stretch ready
  5497. player.previewFile (loop);
  5498. const auto cachedOk = ! player.getPreviewTiming().pending && player.getPreviewTiming().inTime && player.getPreviewTiming().frames == timing.frames;
  5499. player.previewFile ({});
  5500. const auto stoppedOk = ! player.getPreviewTiming().inTime && player.getPreviewInTimeProgress() < 0.0;
  5501. // the start: on the next heard beat while the transport plays (sample exact), at once when it is stopped
  5502. auto firstSample = [] (bool playing, double startTick, int latency) {
  5503. lynx::Transport transport;
  5504. transport.sampleRate.store (48000.0);
  5505. transport.bpm.store (120.0); // 0.04 ticks per sample
  5506. transport.playing.store (playing);
  5507. transport.positionTicks.store (startTick);
  5508. lynx::PreviewPlayer p;
  5509. p.prepareToPlay (48000.0, 512);
  5510. p.setTransport (&transport);
  5511. p.setSyncLatency (latency);
  5512. auto dc = std::make_shared<lynx::SampleData>();
  5513. dc->sampleRate = 48000.0;
  5514. dc->left.assign (48000, 0.5f);
  5515. p.playBrowser (dc, 1.0f, true);
  5516. juce::AudioBuffer<float> block (2, 512);
  5517. juce::MidiBuffer midi;
  5518. for (int done = 0; done < 48000; done += 512)
  5519. {
  5520. p.processBlock (block, midi);
  5521. for (int i = 0; i < 512; ++i)
  5522. if (block.getSample (0, i) != 0.0f)
  5523. return done + i;
  5524. if (playing)
  5525. transport.positionTicks.store (transport.positionTicks.load() + 512 * transport.ticksPerSample());
  5526. }
  5527. return -1;
  5528. };
  5529. const auto beatOk = firstSample (true, 480.0, 0) == 12000 // half a beat to go: 480 ticks / 0.04
  5530. && firstSample (true, 480.0, 100) == 12100 // the song is heard 100 samples late (PDC)
  5531. && firstSample (true, 960.0, 0) == 0 // on a beat: now
  5532. && firstSample (false, 480.0, 0) == 0; // stopped: a free start
  5533. previewInTimeOk = loop.existsAsFile() && hit.existsAsFile() && offOk && hitOk && queued && stretchedOk && cachedOk && stoppedOk && beatOk;
  5534. dir.deleteRecursively();
  5535. }
  5536. // LYNX substitutes (round 98): a missing plugin's slot plays a built-in equivalent and the project keeps the
  5537. // original reference byte for byte (.flp record and LYNX plugin state)
  5538. bool substituteOk = false;
  5539. {
  5540. auto song = lynx::Song::makeDefault();
  5541. lynx::ForeignPlugin vv; // an .flp VST3 record (ValhallaVintageVerb's class ID), opaque state
  5542. vv.format = lynx::ForeignPlugin::Format::vst3;
  5543. const std::uint8_t cid[] = { 0x76, 0x54, 0x53, 0x56, 0x65, 0x65, 0x76, 0x33, 0x61, 0x6c, 0x68, 0x61, 0x6c, 0x6c, 0x61, 0x76 };
  5544. std::copy (std::begin (cid), std::end (cid), vv.classId.begin());
  5545. vv.hasClassId = true;
  5546. vv.name = "ValhallaVintageVerb";
  5547. vv.path = "C:\\x\\ValhallaVintageVerb.vst3";
  5548. for (int i = 0; i < 777; ++i)
  5549. vv.state.push_back ((std::uint8_t) (i * 13 + 1));
  5550. lynx::EffectSlot fromFlp;
  5551. fromFlp.kind = lynx::EffectKind::plugin;
  5552. fromFlp.plugin.foreign = vv;
  5553. lynx::EffectSlot fromLynx; // a LYNX reference whose plugin isn't installed here
  5554. fromLynx.kind = lynx::EffectKind::plugin;
  5555. fromLynx.plugin.id = "VST3-FabFilter Pro-Q 3-1a2b3c4d-5e6f7a8b";
  5556. fromLynx.plugin.name = "FabFilter Pro-Q 3";
  5557. fromLynx.plugin.state = "AAECAwQFBgcICQ==";
  5558. const auto flpRef = fromFlp.plugin, lynxRef = fromLynx.plugin;
  5559. song.mixer[1].effects = { fromFlp, fromLynx };
  5560. const auto substitutesOn = lynx::pluginSubstitutesEnabled();
  5561. const auto changed = offline.getPluginHost().applySubstitutes (song);
  5562. auto& fx = song.mixer[1].effects;
  5563. // only the LYNX reference is substituted here (an .flp record is the import's job); do the .flp one directly
  5564. const auto flpSubstituted = lynx::substituteEffectSlot (fx[0], lynx::pluginIdentity (vv));
  5565. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  5566. substituteOk = flpSubstituted && fx[0].kind == lynx::EffectKind::epochVerb
  5567. && (! substitutesOn || (changed == 1 && fx[1].kind == lynx::EffectKind::facetEq && fx[1].substituteFor == lynxRef))
  5568. && back && back->mixer[1].effects.size() == 2 && back->mixer[1].effects[0].kind == lynx::EffectKind::epochVerb
  5569. && back->mixer[1].effects[0].substituteFor == flpRef && back->mixer[1].effects[0].substituteFor.foreign.state == vv.state
  5570. && back->mixer[1].effects[1].kind == fx[1].kind && back->mixer[1].effects[1].substituteFor == fx[1].substituteFor;
  5571. }
  5572. // undo/redo
  5573. offline.editSong ([] (lynx::Song& s) { s.bpm = 99.0; });
  5574. offline.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  5575. offline.undo();
  5576. const auto afterUndo = offline.getSong().bpm;
  5577. offline.redo();
  5578. const auto undoOk = afterUndo == 99.0 && offline.getSong().bpm == 101.0 && offline.canUndo() && ! offline.canRedo()
  5579. && offline.isModified();
  5580. // Remote-owned steps still behave as ordinary native history when no RemoteControl instance is enabled.
  5581. // Only API undo/redo refuse device drift; remote reads, staging and publication never hold the audio-device callback lock.
  5582. const auto remoteHistoryResult = []() -> juce::String {
  5583. int checks = 0;
  5584. const auto require = [&] (bool condition, const char* message) {
  5585. ++checks;
  5586. if (! condition) throw std::runtime_error (message);
  5587. };
  5588. try
  5589. {
  5590. for (const auto session : { false, true })
  5591. {
  5592. lynx::AudioEngine history (false);
  5593. lynx::Song initial;
  5594. initial.channels.resize (1);
  5595. initial.channels[0].instrument = lynx::InstrumentKind::synth;
  5596. initial.mixer = lynx::Song::defaultMixer (1);
  5597. initial.bpm = 120.0;
  5598. history.setSong (std::move (initial));
  5599. history.setSessionHistory (session);
  5600. const auto editTempo = [&] (double bpm) {
  5601. require (history.editSongRemoteTransaction ([&] (lynx::Song& s) { s.bpm = bpm; }), "remote tempo edit was not committed");
  5602. };
  5603. const auto refused = [&] (const std::function<void()>& operation) {
  5604. const auto position = history.getHistoryPosition();
  5605. const auto before = lynx::ProjectFile::toJsonExact (history.getSong());
  5606. bool changed = false;
  5607. try { operation(); }
  5608. catch (const lynx::RemoteError& e) { changed = e.code == "changed" && ! e.uncertain; }
  5609. require (changed, "API history did not refuse untracked device changes");
  5610. require (history.getHistoryPosition() == position && lynx::ProjectFile::toJsonExact (history.getSong()) == before,
  5611. "refused API history changed the project or history position");
  5612. };
  5613. const auto withoutDeviceLock = [&] (const std::function<void()>& operation) {
  5614. juce::WaitableEvent locked, release;
  5615. bool timedOut = false;
  5616. std::thread callback ([&] {
  5617. const juce::ScopedLock lock (history.getDeviceManager().getAudioCallbackLock());
  5618. locked.signal();
  5619. timedOut = ! release.wait (3000);
  5620. });
  5621. const auto acquired = locked.wait (3000);
  5622. std::exception_ptr failure;
  5623. try { if (acquired) operation(); }
  5624. catch (...) { failure = std::current_exception(); }
  5625. release.signal();
  5626. callback.join();
  5627. // Check before rethrowing: an expected rejection must not conceal waiting for this lock.
  5628. require (acquired && ! timedOut, "remote read, edit or history publication waited for the audio-device callback lock");
  5629. if (failure) std::rethrow_exception (failure);
  5630. };
  5631. const auto baseline = lynx::ProjectFile::toJsonExact (history.getSong());
  5632. const auto baselineStamp = history.getSongStamp();
  5633. const auto baselinePosition = history.getHistoryPosition();
  5634. const auto unchanged = [&] {
  5635. return history.getSongStamp() == baselineStamp && history.getHistoryPosition() == baselinePosition
  5636. && lynx::ProjectFile::toJsonExact (history.getSong()) == baseline;
  5637. };
  5638. withoutDeviceLock ([&] {
  5639. require (lynx::ProjectFile::toJsonExact (history.snapshotForRemoteControl()) == baseline,
  5640. "remote snapshot changed the project");
  5641. require (history.remoteDeviceStateHash().isNotEmpty(), "remote snapshot did not hash device state");
  5642. });
  5643. require (unchanged(), "remote reads changed the project, revision or history");
  5644. bool staged = false;
  5645. withoutDeviceLock ([&] {
  5646. require (! history.editSongRemoteTransaction ([&] (lynx::Song&) { staged = true; }),
  5647. "remote no-op committed a history step");
  5648. });
  5649. require (staged && unchanged(), "remote no-op did not stage cleanly without changing history");
  5650. bool rejected = false;
  5651. try {
  5652. withoutDeviceLock ([&] {
  5653. history.editSongRemoteTransaction ([] (lynx::Song& next) {
  5654. next.bpm = 999.0;
  5655. throw lynx::RemoteError ("invalid", "selftest stage rejection");
  5656. });
  5657. });
  5658. }
  5659. catch (const lynx::RemoteError& e) { rejected = e.code == "invalid" && ! e.uncertain; }
  5660. require (rejected && unchanged(), "rejected staging changed the project, revision or history");
  5661. for (const auto cancelAfterStage : { false, true })
  5662. {
  5663. int calls = 0;
  5664. staged = false;
  5665. bool cancelledEdit = false;
  5666. try {
  5667. withoutDeviceLock ([&] {
  5668. history.editSongRemoteTransaction ([&] (lynx::Song& next) { staged = true; next.bpm = 999.0; },
  5669. [&] { return ++calls >= (cancelAfterStage ? 2 : 1); });
  5670. });
  5671. }
  5672. catch (const lynx::RemoteError& e) { cancelledEdit = e.code == "failed" && ! e.uncertain; }
  5673. require (cancelledEdit && staged == cancelAfterStage && unchanged(),
  5674. "cancelled edit changed the project, revision or history");
  5675. }
  5676. withoutDeviceLock ([&] { editTempo (130.0); });
  5677. require (history.getSong().bpm == 130.0 && history.getHistoryPosition() == baselinePosition + 1
  5678. && history.getSongStamp() > baselineStamp, "remote commit did not publish one history step");
  5679. history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.23f; }, false);
  5680. refused ([&] { history.undoRemoteControl(); });
  5681. withoutDeviceLock ([&] { history.undo(); });
  5682. require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0 && history.getRemoteHistoryError().isEmpty(),
  5683. "native undo refused device drift while remote control was disabled");
  5684. history.editSong ([] (lynx::Song& s) { s.channels[0].name = "Untracked change"; }, false);
  5685. refused ([&] { history.redoRemoteControl(); });
  5686. withoutDeviceLock ([&] { history.redo(); });
  5687. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
  5688. "native redo refused device drift while remote control was disabled");
  5689. withoutDeviceLock ([&] { editTempo (140.0); });
  5690. history.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.42f; }, false);
  5691. withoutDeviceLock ([&] { history.jumpToHistory (0); });
  5692. require (history.getHistoryPosition() == 0 && history.getSong().bpm == 120.0, "native history jump stopped at a remote step");
  5693. withoutDeviceLock ([&] { history.jumpToHistory (2); });
  5694. require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "native redo jump stopped at a remote step");
  5695. withoutDeviceLock ([&] { history.undoRemoteControl(); });
  5696. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0, "API undo failed with an unchanged device fence");
  5697. withoutDeviceLock ([&] { history.redoRemoteControl(); });
  5698. require (history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0, "API redo failed with an unchanged device fence");
  5699. int cancelledChecks = 0;
  5700. bool cancelled = false;
  5701. try { history.undoRemoteControl ([&] { return ++cancelledChecks >= 2; }); }
  5702. catch (const lynx::RemoteError& e) { cancelled = e.code == "failed" && ! e.uncertain; }
  5703. require (cancelled && history.getHistoryPosition() == 2 && history.getSong().bpm == 140.0,
  5704. "cancelled API history moved a step");
  5705. withoutDeviceLock ([&] { history.undo(); });
  5706. require (history.getHistoryPosition() == 1 && history.getSong().bpm == 130.0 && history.getRemoteHistoryError().isEmpty(),
  5707. "API cancellation leaked into native history");
  5708. }
  5709. return "OK (" + juce::String (checks) + " checks)";
  5710. }
  5711. catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
  5712. }();
  5713. // Hosted state access and processing share a per-instance lock, including fixed blocks and deferred resets.
  5714. const auto hostedStateLockResult = []() -> juce::String {
  5715. struct Probe final : juce::AudioPluginInstance
  5716. {
  5717. struct Parameter final : juce::HostedAudioProcessorParameter
  5718. {
  5719. explicit Parameter (Probe& p) : owner (p) {}
  5720. float getValue() const override { owner.access (owner.parameterReads); return value.load(); }
  5721. void setValue (float v) override { owner.access (owner.parameterWrites); value.store (v); }
  5722. float getDefaultValue() const override { return 0.0f; }
  5723. juce::String getName (int) const override { return "Value"; }
  5724. juce::String getLabel() const override { return {}; }
  5725. juce::String getParameterID() const override { return "value"; }
  5726. float getValueForText (const juce::String& text) const override { return text.getFloatValue(); }
  5727. Probe& owner;
  5728. std::atomic<float> value { 0.0f };
  5729. };
  5730. Probe() : AudioPluginInstance (BusesProperties().withInput ("Input", juce::AudioChannelSet::stereo(), true)
  5731. .withOutput ("Output", juce::AudioChannelSet::stereo(), true))
  5732. {
  5733. addHostedParameter (std::make_unique<Parameter> (*this));
  5734. }
  5735. const juce::String getName() const override { return "State lock probe"; }
  5736. void fillInPluginDescription (juce::PluginDescription& d) const override { d.name = getName(); }
  5737. void prepareToPlay (double, int) override {}
  5738. void releaseResources() override {}
  5739. void processBlock (juce::AudioBuffer<float>& audio, juce::MidiBuffer&) override { access (blocks); audio.clear(); }
  5740. void reset() override { access (resets, std::this_thread::get_id() == ui); } // (on the UI thread: the export reset)
  5741. double getTailLengthSeconds() const override { return 0.0; }
  5742. bool acceptsMidi() const override { return true; }
  5743. bool producesMidi() const override { return false; }
  5744. bool hasEditor() const override { return false; }
  5745. juce::AudioProcessorEditor* createEditor() override { return nullptr; }
  5746. int getNumPrograms() override { return 1; }
  5747. int getCurrentProgram() override { return 0; }
  5748. void setCurrentProgram (int) override {}
  5749. const juce::String getProgramName (int) override { return {}; }
  5750. void changeProgramName (int, const juce::String&) override {}
  5751. void getStateInformation (juce::MemoryBlock& state) override { access (captures); state.replaceAll ("state", 5); }
  5752. void setStateInformation (const void*, int) override { access (restores, true); }
  5753. // Round 190ha: only a restore and the export reset are exclusive with the audio side. A capture and the
  5754. // UI's parameter changes run beside processing, as on JUCE's own hosts (UI-thread calls never overlap
  5755. // each other here: they run in turn).
  5756. void access (std::atomic<int>& calls, bool exclusive = false)
  5757. {
  5758. ++calls;
  5759. if (exclusive)
  5760. {
  5761. ++exclusiveActive;
  5762. if (active.fetch_add (1) != 0) overlap = true;
  5763. }
  5764. else
  5765. {
  5766. ++active;
  5767. if (exclusiveActive.load() != 0) overlap = true;
  5768. }
  5769. juce::Thread::sleep (1); // widen the concurrent vendor-call window without using real plugins
  5770. --active;
  5771. if (exclusive) --exclusiveActive;
  5772. }
  5773. const std::thread::id ui = std::this_thread::get_id();
  5774. std::atomic<int> active { 0 }, exclusiveActive { 0 }, blocks { 0 }, resets { 0 }, captures { 0 }, restores { 0 };
  5775. std::atomic<int> parameterReads { 0 }, parameterWrites { 0 };
  5776. std::atomic<bool> overlap { false };
  5777. };
  5778. int checks = 0;
  5779. const auto require = [&] (bool condition, const char* message) {
  5780. ++checks;
  5781. if (! condition) throw std::runtime_error (message);
  5782. };
  5783. const auto exercise = [&] (auto& adapter, Probe& probe, const auto& render, const auto& reset) {
  5784. const auto saved = adapter.captureState();
  5785. require (saved.has_value(), "mock hosted state could not be captured");
  5786. juce::WaitableEvent start (true);
  5787. std::thread audio ([&] {
  5788. start.wait();
  5789. for (int i = 0; i < 32; ++i)
  5790. {
  5791. adapter.setParameter (0, i % 2 == 0 ? 0.25f : 0.75f);
  5792. (void) adapter.parameterValue (0);
  5793. reset();
  5794. render();
  5795. }
  5796. });
  5797. const juce::ScopeGuard joinAudio { [&] { if (audio.joinable()) audio.join(); } };
  5798. start.signal();
  5799. bool stateOk = true;
  5800. for (int i = 0; i < 32; ++i)
  5801. {
  5802. stateOk = adapter.captureState().has_value() && stateOk;
  5803. stateOk = adapter.restoreState (*saved) && stateOk;
  5804. adapter.setParameterFromUi (0, i % 2 == 0 ? 0.1f : 0.9f);
  5805. if (i % 8 == 0) adapter.resetForExport();
  5806. }
  5807. audio.join();
  5808. // Contended audio callbacks may all have bypassed while state was held.
  5809. // Exercise a successful callback after release before checking coverage.
  5810. adapter.setParameter (0, 0.5f);
  5811. (void) adapter.parameterValue (0);
  5812. reset();
  5813. render();
  5814. require (stateOk && probe.blocks > 0 && probe.resets > 0 && probe.captures > 0 && probe.restores > 0,
  5815. "mock did not exercise processing, resets and hosted state access");
  5816. require (probe.parameterReads > 0 && probe.parameterWrites > 0,
  5817. "mock did not exercise concurrent hosted parameter access");
  5818. require (! probe.overlap, "hosted processing/reset/parameters overlapped a state restore or the export reset");
  5819. require (! adapter.hasCrashed(), "mock hosted adapter crashed");
  5820. };
  5821. try
  5822. {
  5823. for (const auto fixed : { 0, 64 })
  5824. {
  5825. std::array<float, 128> left {}, right {};
  5826. auto instrument = std::make_unique<Probe>();
  5827. auto* instrumentProbe = instrument.get();
  5828. lynx::PluginInstrument voice (std::move (instrument), 128, fixed);
  5829. exercise (voice, *instrumentProbe, [&] { voice.render (left.data(), right.data(), 128, 1.0f, 1.0f); }, [&] { voice.panic(); });
  5830. auto effect = std::make_unique<Probe>();
  5831. auto* effectProbe = effect.get();
  5832. lynx::PluginEffect fx (std::move (effect), 128, fixed);
  5833. exercise (fx, *effectProbe, [&] { fx.process (left.data(), right.data(), 128, {}, 120.0); }, [&] { fx.transportReset(); });
  5834. }
  5835. return "OK (" + juce::String (checks) + " checks)";
  5836. }
  5837. catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
  5838. }();
  5839. const auto hostedStateContentionResult = lynx::pluginStateContentionSelfTest();
  5840. const auto generatorSmartResult = lynx::generatorSmartDisableSelfTest(); // (round 190ok, D2)
  5841. // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
  5842. // (Blend on: this checks that the take joins the pattern's notes; a new install starts with Blend off)
  5843. const auto notesBefore = offline.getSong().patterns[0].notes.size();
  5844. {
  5845. auto o = offline.getRecordOptions();
  5846. o.mode = lynx::RecordMode::overdub;
  5847. offline.setRecordOptions (o);
  5848. }
  5849. offline.setRecording (true);
  5850. offline.play();
  5851. offline.getTransport().positionTicks.store (960.0);
  5852. offline.sendLiveNote (2, 72, 0.9f, true, true);
  5853. offline.getTransport().positionTicks.store (1920.0);
  5854. offline.sendLiveNote (2, 72, 0.0f, false, true);
  5855. offline.setRecording (false);
  5856. offline.stop();
  5857. const auto& recorded = offline.getSong().patterns[0].notes;
  5858. const auto recordOk = recorded.size() == notesBefore + 1
  5859. && std::any_of (recorded.begin(), recorded.end(), [] (const lynx::Note& n) {
  5860. return n.key == 72 && n.channel == 2 && n.length == 960 && n.start >= 960 && n.start < 3840;
  5861. });
  5862. offline.undo();
  5863. const auto recordUndoOk = offline.getSong().patterns[0].notes.size() == notesBefore;
  5864. // FL's Tools › Cancel recording (round 187a): the pass's notes go, an edit made before it stays, recording turns
  5865. // off and playback goes on; nothing to redo
  5866. bool cancelRecordOk = false;
  5867. {
  5868. offline.editSong ([] (lynx::Song& s) { s.bpm = 123.0; });
  5869. const auto notesThen = offline.getSong().patterns[0].notes.size();
  5870. offline.setRecording (true);
  5871. offline.play();
  5872. offline.getTransport().positionTicks.store (960.0);
  5873. offline.sendLiveNote (2, 74, 0.9f, true, true);
  5874. offline.getTransport().positionTicks.store (1920.0);
  5875. offline.sendLiveNote (2, 74, 0.0f, false, true);
  5876. offline.sendLiveNote (2, 76, 0.9f, true, true); // (still held when the pass is cancelled)
  5877. const auto cancelled = offline.cancelRecording();
  5878. cancelRecordOk = cancelled && ! offline.isRecording() && offline.getTransport().playing.load()
  5879. && offline.getSong().patterns[0].notes.size() == notesThen && offline.getSong().bpm == 123.0 && ! offline.canRedo()
  5880. && ! offline.cancelRecording(); // (not recording: nothing to cancel)
  5881. offline.sendLiveNote (2, 76, 0.0f, false, false);
  5882. offline.stop();
  5883. }
  5884. // MIDI: exporting the pattern and importing it back gives the same notes
  5885. bool midiOk = false;
  5886. {
  5887. auto source = lynx::Song::makeDefault();
  5888. source.patterns[0].notes.push_back ({ 1000, 480, 4, 67, 0.5f });
  5889. source.patterns[0].sortNotes();
  5890. const auto midiFile = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest.mid");
  5891. juce::String midiError;
  5892. const auto saved = lynx::MidiFileIo::savePattern (source, 0, midiFile, midiError);
  5893. const auto song = saved ? lynx::MidiFileIo::loadSong (midiFile, midiError) : std::nullopt;
  5894. midiFile.deleteFile();
  5895. if (song && song->patterns.size() == 1 && song->patterns[0].notes.size() == source.patterns[0].notes.size()
  5896. && std::abs (song->bpm - source.bpm) < 0.01)
  5897. {
  5898. midiOk = true;
  5899. const auto& a = source.patterns[0].notes;
  5900. const auto& b = song->patterns[0].notes;
  5901. for (std::size_t i = 0; i < a.size(); ++i)
  5902. midiOk = midiOk && a[i].start == b[i].start && a[i].key == b[i].key && a[i].length == b[i].length;
  5903. }
  5904. }
  5905. // project package (REA round 118): a project with a sample exported as .zip, extracted and opened again,
  5906. // finds its sample inside the extracted folder
  5907. bool packageOk = false;
  5908. {
  5909. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-package");
  5910. dir.deleteRecursively();
  5911. dir.getChildFile ("src").createDirectory();
  5912. const auto wav = dir.getChildFile ("src/hit.wav");
  5913. {
  5914. juce::WavAudioFormat format;
  5915. juce::AudioBuffer<float> hit (1, 480);
  5916. for (int i = 0; i < 480; ++i)
  5917. hit.setSample (0, i, 0.5f * std::sin (0.1f * (float) i));
  5918. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  5919. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  5920. {
  5921. out.release();
  5922. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  5923. writer->writeFromAudioSampleBuffer (hit, 0, 480);
  5924. }
  5925. }
  5926. auto source = lynx::Song::makeDefault();
  5927. lynx::ChannelDef c;
  5928. c.name = "Hit";
  5929. c.instrument = lynx::InstrumentKind::sampler;
  5930. c.samplePath = wav.getFullPathName().toStdString();
  5931. source.channels.push_back (c);
  5932. lynx::ProjectPackage::Result packed;
  5933. juce::String packageError;
  5934. const auto zip = dir.getChildFile ("Beat.zip");
  5935. if (wav.existsAsFile() && lynx::ProjectPackage::exportZip (source, "Beat", zip, packed, packageError) && packed.files == 1)
  5936. {
  5937. const auto project = lynx::ProjectPackage::extractZip (zip, dir.getChildFile ("out"), packageError);
  5938. const auto song = project.existsAsFile() ? lynx::ProjectFile::load (project, packageError) : std::nullopt;
  5939. if (song && ! song->channels.empty())
  5940. {
  5941. const juce::File back (juce::String::fromUTF8 (song->channels.back().samplePath.c_str()));
  5942. packageOk = back.existsAsFile() && back.isAChildOf (project.getParentDirectory()) && back.getSize() == wav.getSize();
  5943. }
  5944. }
  5945. dir.deleteRecursively();
  5946. }
  5947. // D#92, round 180a: a non-ASCII folder and a dotted name save and load back; an unwritable place says so, and a
  5948. // relative path resolves as the start-up argument does
  5949. bool projectSaveOk = false;
  5950. {
  5951. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-save180a");
  5952. dir.deleteRecursively();
  5953. const auto folder = dir.getChildFile (juce::String::fromUTF8 ("M\xc3\xbasica nova"));
  5954. folder.createDirectory();
  5955. const auto named = lynx::ProjectFile::withProjectExtension (folder.getChildFile (juce::String::fromUTF8 ("Can\xc3\xa7\xc3\xa3o.v2")));
  5956. auto song = lynx::Song::makeDefault();
  5957. lynx::Note note;
  5958. note.length = 240;
  5959. note.key = 64;
  5960. song.patterns[0].notes.push_back (note);
  5961. juce::String error, blockedError;
  5962. const auto again = lynx::ProjectFile::save (song, named, error) ? lynx::ProjectFile::load (named, error) : std::nullopt;
  5963. const auto blocker = dir.getChildFile ("a file");
  5964. blocker.replaceWithText ("x");
  5965. const auto cwd = juce::File::getCurrentWorkingDirectory();
  5966. folder.setAsCurrentWorkingDirectory();
  5967. const auto relative = juce::File::getCurrentWorkingDirectory().getChildFile (named.getFileName());
  5968. cwd.setAsCurrentWorkingDirectory();
  5969. projectSaveOk = named.getFileName().endsWith (".v2.lynx") && again && again->patterns[0].notes.size() == song.patterns[0].notes.size()
  5970. && relative == named && ! lynx::ProjectFile::save (song, blocker.getChildFile ("x.lynx"), blockedError)
  5971. && blockedError.isNotEmpty() && lynx::ProjectFile::withProjectExtension (named) == named;
  5972. dir.deleteRecursively();
  5973. }
  5974. // Online Sessions (round 168a): a project sent as a .lynxpack (one sample used twice is stored once, the uids
  5975. // survive), a stand-in rendered through an ExportJob, the guest's part sent back and merged by the host
  5976. juce::String sessionResult = "ERROR";
  5977. {
  5978. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-session");
  5979. dir.deleteRecursively();
  5980. dir.getChildFile ("src").createDirectory();
  5981. const auto wav = dir.getChildFile ("src/hit.wav");
  5982. {
  5983. juce::WavAudioFormat format;
  5984. juce::AudioBuffer<float> hit (1, 4800);
  5985. for (int i = 0; i < 4800; ++i)
  5986. hit.setSample (0, i, 0.5f * std::sin (0.05f * (float) i) * (1.0f - (float) i / 4800.0f));
  5987. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  5988. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  5989. {
  5990. out.release();
  5991. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  5992. writer->writeFromAudioSampleBuffer (hit, 0, 4800);
  5993. }
  5994. }
  5995. auto host = lynx::Song::makeDefault();
  5996. host.mode = lynx::PlayMode::song;
  5997. const auto copyOfWav = dir.getChildFile ("src/hit copy.wav"); // the same bytes under another name: stored once
  5998. wav.copyFileTo (copyOfWav);
  5999. for (const auto& [name, file] : { std::pair<const char*, juce::File> { "Hit", wav }, { "Hit 2", copyOfWav } })
  6000. {
  6001. lynx::ChannelDef c;
  6002. c.name = name;
  6003. c.instrument = lynx::InstrumentKind::sampler;
  6004. c.samplePath = file.getFullPathName().toStdString();
  6005. host.channels.push_back (c);
  6006. }
  6007. const auto hitChannel = (int) host.channels.size() - 2;
  6008. lynx::Note hitNote;
  6009. hitNote.channel = hitChannel;
  6010. hitNote.length = 480;
  6011. host.patterns[0].notes.push_back (hitNote);
  6012. host.playlist.push_back ({ 0, 0, 0, host.patterns[0].effectiveLength (host.meter()), 0 });
  6013. lynx::uids::normalize (host);
  6014. const auto* guest = lynx::parts::invite (host, "Host", "Ana", 0xFF3D9BE9, false);
  6015. juce::String e;
  6016. std::vector<lynx::sessionpack::Rendered> rendered;
  6017. // (a sampler stands in for a plugin channel here: render() renders whatever it is given)
  6018. const std::vector<lynx::sessionpack::RenderItem> items { { false, hitChannel, false, "Hit", "Test" } };
  6019. const auto renderedOk = guest != nullptr && lynx::sessionpack::render (host, items, 44100.0, dir.getChildFile ("stems"), "Host", rendered, {}, e)
  6020. && rendered.size() == 1 && rendered[0].standIns.size() == 2
  6021. && juce::File (juce::String::fromUTF8 (rendered[0].standIns[0].path.c_str())).getSize() > 1000;
  6022. if (renderedOk)
  6023. lynx::sessionpack::apply (host, rendered);
  6024. lynx::sessionpack::Manifest m;
  6025. m.projectName = "Selftest";
  6026. m.from = *host.session.find (lynx::session::hostTag);
  6027. m.to = *host.session.find (2);
  6028. lynx::sessionpack::WriteResult written;
  6029. const auto pack = dir.getChildFile (juce::String ("Selftest") + lynx::sessionpack::extension);
  6030. const auto packOk = renderedOk && lynx::sessionpack::write (lynx::parts::guestCopy (host, 2), m, offline.getPluginHost(), pack, written, e)
  6031. && written.media == 3 && written.duplicates == 1; // the sample once (used twice), the stand-in pair
  6032. auto opened = packOk ? lynx::sessionpack::open (pack, dir.getChildFile ("received"), e) : std::nullopt;
  6033. bool openOk = false, mergeOk = false;
  6034. if (opened && opened->corrupt.isEmpty())
  6035. {
  6036. const auto& g = opened->song;
  6037. const juce::File sample (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].samplePath.c_str()));
  6038. openOk = g.session.me == 2 && g.projectId == host.projectId && g.channels[(std::size_t) hitChannel].uid == host.channels[(std::size_t) hitChannel].uid
  6039. && sample.existsAsFile() && sample.isAChildOf (opened->folder) && g.channels[(std::size_t) hitChannel].standIns.size() == 2
  6040. && juce::File (juce::String::fromUTF8 (g.channels[(std::size_t) hitChannel].standIns[1].path.c_str())).existsAsFile();
  6041. // the guest adds a channel and a pattern of his own, sends his part back
  6042. auto copy = g;
  6043. lynx::ChannelDef mine;
  6044. mine.name = "Ana's hit";
  6045. mine.instrument = lynx::InstrumentKind::sampler;
  6046. mine.samplePath = sample.getFullPathName().toStdString();
  6047. copy.channels.push_back (mine);
  6048. lynx::Pattern p;
  6049. p.name = "Ana";
  6050. lynx::Note note;
  6051. note.channel = (int) copy.channels.size() - 1;
  6052. note.length = 240;
  6053. note.key = 64;
  6054. p.notes.push_back (note);
  6055. copy.patterns.push_back (p);
  6056. lynx::uids::normalize (copy);
  6057. // its uids survive a save and a load
  6058. const auto saved = dir.getChildFile ("guest.lynx");
  6059. auto reloaded = lynx::ProjectFile::save (copy, saved, e) ? lynx::ProjectFile::load (saved, e) : std::nullopt;
  6060. lynx::sessionpack::Manifest back;
  6061. back.part = true;
  6062. back.from = *copy.session.self();
  6063. const auto partFile = dir.getChildFile (juce::String ("Ana part") + lynx::sessionpack::extension);
  6064. lynx::sessionpack::WriteResult partWritten;
  6065. auto part = reloaded && reloaded->channels.back().uid == copy.channels.back().uid && lynx::uids::tagOf (reloaded->channels.back().uid) == 2
  6066. ? lynx::sessionpack::write (lynx::parts::extract (*reloaded, 2), back, offline.getPluginHost(), partFile, partWritten, e)
  6067. : false;
  6068. auto partOpened = part ? lynx::sessionpack::open (partFile, dir.getChildFile ("parts"), e) : std::nullopt;
  6069. if (partOpened && partOpened->manifest.part && lynx::sessionpack::adoptMedia (partOpened->song, dir.getChildFile ("Session media/Ana"), e))
  6070. {
  6071. const auto report = lynx::parts::merge (host, partOpened->song, 2);
  6072. const auto& added = host.channels.back();
  6073. mergeOk = report.ok && report.channels >= 1 && added.name == "Ana's hit" && lynx::uids::tagOf (added.uid) == 2
  6074. && juce::File (juce::String::fromUTF8 (added.samplePath.c_str())).isAChildOf (dir.getChildFile ("Session media/Ana"))
  6075. && host.channels[(std::size_t) hitChannel].name == "Hit";
  6076. }
  6077. }
  6078. // a crafted package whose project points at a file elsewhere on this computer: opening it must not
  6079. // reach that file, or merging would copy it into the project and the next package would send it on
  6080. if (mergeOk)
  6081. {
  6082. const auto secret = dir.getChildFile ("secret.wav");
  6083. wav.copyFileTo (secret);
  6084. auto evil = lynx::Song::makeDefault();
  6085. lynx::ChannelDef c;
  6086. c.instrument = lynx::InstrumentKind::sampler;
  6087. c.samplePath = secret.getFullPathName().toStdString();
  6088. evil.channels.push_back (c);
  6089. lynx::ChannelDef keys; // (FL Keys' zones are read by the engine but are not in the media list)
  6090. keys.instrument = lynx::InstrumentKind::flkeys;
  6091. keys.zones.push_back ({});
  6092. keys.zones.back().path = c.samplePath;
  6093. evil.channels.push_back (keys);
  6094. lynx::ChannelDef patch; // (a Patcher's nodes are not in the media list either)
  6095. patch.instrument = lynx::InstrumentKind::patcher;
  6096. patch.patcher.nodes.resize (2);
  6097. patch.patcher.nodes[0].generator = true;
  6098. patch.patcher.nodes[0].channel = c;
  6099. patch.patcher.nodes[1].effect.samplePath = c.samplePath;
  6100. evil.channels.push_back (patch);
  6101. evil.mixer[1].recordTo = dir.getChildFile ("overwritten.wav").getFullPathName().toStdString();
  6102. const auto evilProject = dir.getChildFile ("evil.lynx");
  6103. lynx::sessionpack::Manifest em;
  6104. em.part = true;
  6105. juce::ZipFile::Builder b;
  6106. const auto json = lynx::sessionpack::manifestToJson (em);
  6107. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  6108. const auto evilPack = dir.getChildFile (juce::String ("Evil") + lynx::sessionpack::extension);
  6109. bool zipped = false;
  6110. if (lynx::ProjectFile::save (evil, evilProject, e))
  6111. {
  6112. b.addFile (evilProject, 0, "project.lynx");
  6113. juce::FileOutputStream out (evilPack);
  6114. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  6115. }
  6116. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil"), e) : std::nullopt;
  6117. const auto media = dir.getChildFile ("Session media/Evil");
  6118. mergeOk = evilOpened && lynx::sessionpack::adoptMedia (evilOpened->song, media, e)
  6119. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  6120. return juce::File (juce::String::fromUTF8 (ch.samplePath.c_str())) == secret
  6121. || std::any_of (ch.zones.begin(), ch.zones.end(), [&] (const lynx::SampleZone& z) { return juce::File (juce::String::fromUTF8 (z.path.c_str())) == secret; });
  6122. })
  6123. && evilOpened->song.channels.back().patcher.nodes.size() == 2
  6124. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[0].channel.samplePath.c_str())) != secret
  6125. && juce::File (juce::String::fromUTF8 (evilOpened->song.channels.back().patcher.nodes[1].effect.samplePath.c_str())) != secret
  6126. && evilOpened->song.mixer[1].recordTo.empty()
  6127. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  6128. if (! mergeOk && e.isEmpty())
  6129. e = "a received package reached a file outside it";
  6130. }
  6131. // ... nor through its own folder: "..", Windows' dotted names (". ." climbs like ".." there), and a manifest
  6132. // media entry outside the package (it must not even be read: "/dev/zero" would never end)
  6133. if (mergeOk)
  6134. {
  6135. const auto secret = dir.getChildFile ("secret.wav");
  6136. const auto folder = dir.getChildFile ("evil2").getChildFile ("Evil2"); // (where open() will unpack it)
  6137. const auto climb = folder.getFullPathName() + "/media/../../../secret.wav";
  6138. const auto dotted = folder.getFullPathName() + "/. ./.. ./secret.wav";
  6139. auto evil = lynx::Song::makeDefault();
  6140. for (const auto& path : { climb, dotted })
  6141. {
  6142. lynx::ChannelDef c;
  6143. c.instrument = lynx::InstrumentKind::sampler;
  6144. c.samplePath = path.toStdString();
  6145. evil.channels.push_back (c);
  6146. }
  6147. juce::MemoryBlock secretBytes;
  6148. secret.loadFileAsData (secretBytes);
  6149. lynx::sessionpack::Manifest em;
  6150. em.part = true;
  6151. em.media.push_back ({ "sha256-" + juce::String (lynx::sha256Hex ((const std::uint8_t*) secretBytes.getData(), secretBytes.getSize())),
  6152. "secret.wav", (juce::int64) secretBytes.getSize(), "../../secret.wav" });
  6153. const auto evilProject = dir.getChildFile ("evil2.lynx");
  6154. juce::ZipFile::Builder b;
  6155. const auto json = lynx::sessionpack::manifestToJson (em);
  6156. b.addEntry (new juce::MemoryInputStream (json.toRawUTF8(), json.getNumBytesAsUTF8(), true), 0, "manifest.json", {});
  6157. const auto evilPack = dir.getChildFile (juce::String ("Evil2") + lynx::sessionpack::extension);
  6158. bool zipped = false;
  6159. if (lynx::ProjectFile::save (evil, evilProject, e))
  6160. {
  6161. b.addFile (evilProject, 0, "project.lynx");
  6162. juce::FileOutputStream out (evilPack);
  6163. zipped = out.openedOk() && b.writeToStream (out, nullptr);
  6164. }
  6165. auto evilOpened = zipped ? lynx::sessionpack::open (evilPack, dir.getChildFile ("evil2"), e) : std::nullopt;
  6166. const auto media = dir.getChildFile ("Session media/Evil2");
  6167. mergeOk = evilOpened && evilOpened->folder == folder && evilOpened->corrupt.contains ("secret.wav")
  6168. && lynx::sessionpack::adoptMedia (evilOpened->song, media, e) && evilOpened->song.channels.size() >= 2
  6169. && std::none_of (evilOpened->song.channels.begin(), evilOpened->song.channels.end(), [&] (const lynx::ChannelDef& ch) {
  6170. const auto p = juce::String::fromUTF8 (ch.samplePath.c_str());
  6171. return p == climb || p == dotted || (juce::File::isAbsolutePath (p) && juce::File (p) == secret);
  6172. })
  6173. && media.findChildFiles (juce::File::findFiles, true).isEmpty();
  6174. if (! mergeOk && e.isEmpty())
  6175. e = "a received package climbed out of its folder";
  6176. }
  6177. if (! packOk && e.isEmpty())
  6178. e = "media " + juce::String (written.media) + ", duplicates " + juce::String (written.duplicates) + ", missing "
  6179. + written.missing.joinIntoString (";");
  6180. sessionResult = mergeOk ? juce::String ("OK")
  6181. : "ERROR (" + juce::String (renderedOk ? packOk ? openOk ? "merge" : "open" : "pack" : "render") + (e.isEmpty() ? "" : ": " + e) + ")";
  6182. dir.deleteRecursively();
  6183. }
  6184. // WavPack: a .wv from the FL packs (if installed) opens through the sample loader
  6185. juce::String wavpack = "NO_FL";
  6186. {
  6187. const auto roots = lynx::findFlStudioRoots();
  6188. const auto packs = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Packs");
  6189. const auto found = packs.isDirectory() ? packs.findChildFiles (juce::File::findFiles, true, "*.wv") : juce::Array<juce::File> {};
  6190. if (! found.isEmpty())
  6191. {
  6192. lynx::SampleLibrary library;
  6193. const auto sample = library.load (found.getFirst().getFullPathName());
  6194. float peakWv = 0.0f;
  6195. if (sample != nullptr)
  6196. for (std::size_t i = 0; i < sample->frames(); ++i)
  6197. peakWv = std::max (peakWv, std::abs (sample->leftData()[i]));
  6198. wavpack = sample != nullptr && sample->frames() > 0 && peakWv > 1e-4f ? "OK" : "ERROR";
  6199. }
  6200. }
  6201. // every built-in effect's editor and engine with extreme settings (round 111): a crash or NaN output fails here
  6202. const auto effectsOk = runEffectFuzz (4, {}); // (no mouse drags: nothing may open on screen)
  6203. // FL's Patcher (round 141): a mixer slot and a generator channel with their graphs survive save / load, and the
  6204. // generator one plays through the rack
  6205. bool patcherOk = false;
  6206. {
  6207. auto song = lynx::Song::makeDefault();
  6208. song.mixer.resize (4);
  6209. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  6210. lynx::PatchNode reverb, gain;
  6211. reverb.effect = lynx::makeEffectSlot (lynx::EffectKind::utility); // (exact defaults: params are saved to 4 decimals)
  6212. reverb.label = "Room";
  6213. reverb.x = 120.5f;
  6214. reverb.y = 40.0f;
  6215. gain.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  6216. gain.effect.enabled = false;
  6217. slot.patcher.nodes = { reverb, gain };
  6218. lynx::PatchWire a, b, c, control;
  6219. a.to = 0;
  6220. b.from = 0, b.to = 1, b.gain = 0.5f;
  6221. c.from = 1;
  6222. control.kind = lynx::PatchWire::Kind::control, control.from = 0, control.to = 1, control.toPort = 0, control.curve = { 0.0f, 0.25f, 1.0f };
  6223. slot.patcher.wires = { a, b, c, control };
  6224. slot.patcher.outputTracks = { 3 };
  6225. song.mixer[1].effects = { slot };
  6226. lynx::ChannelDef ch;
  6227. ch.name = "Patched";
  6228. ch.instrument = lynx::InstrumentKind::patcher;
  6229. lynx::PatchNode synth;
  6230. synth.generator = true;
  6231. synth.channel.instrument = lynx::InstrumentKind::synth;
  6232. synth.channel.name = "Synth";
  6233. ch.patcher.nodes = { synth };
  6234. lynx::PatchWire notes, out;
  6235. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  6236. out.from = 0;
  6237. ch.patcher.wires = { notes, out };
  6238. // round 162: the I/O nodes' MIDI pins and a MIDI Out node between them
  6239. lynx::PatchNode midiOutNode;
  6240. midiOutNode.generator = true;
  6241. midiOutNode.channel.instrument = lynx::InstrumentKind::midiOut;
  6242. lynx::midictl::writeMidiOut (midiOutNode.channel.pluginState, { 4, 0, 0, -1, -1 });
  6243. ch.patcher.nodes.push_back (midiOutNode);
  6244. lynx::PatchWire portIn, portOut;
  6245. portIn.kind = portOut.kind = lynx::PatchWire::Kind::midi;
  6246. portIn.fromPort = lynx::patchMidiPortPin (7), portIn.to = 1;
  6247. portOut.from = 1, portOut.to = lynx::patchToHost, portOut.toPort = 9;
  6248. ch.patcher.wires.push_back (portIn);
  6249. ch.patcher.wires.push_back (portOut);
  6250. ch.patcher.fromMidiPorts = { 2, 7 };
  6251. ch.patcher.toMidiPorts = { 9, 11 };
  6252. ch.patcher.fromNotesHidden = true;
  6253. song.channels.push_back (ch);
  6254. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  6255. patcherOk = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1
  6256. && back->mixer[1].effects[0].kind == lynx::EffectKind::patcher && back->mixer[1].effects[0].patcher == slot.patcher
  6257. && back->channels.back().instrument == lynx::InstrumentKind::patcher && back->channels.back().patcher.nodes.size() == 2
  6258. && back->channels.back().patcher.fromMidiPorts == ch.patcher.fromMidiPorts
  6259. && back->channels.back().patcher.toMidiPorts == ch.patcher.toMidiPorts && back->channels.back().patcher.fromNotesHidden
  6260. && back->channels.back().patcher.nodes[1].channel.pluginState == midiOutNode.channel.pluginState
  6261. && back->channels.back().patcher.nodes[0].generator
  6262. && back->channels.back().patcher.nodes[0].channel.instrument == lynx::InstrumentKind::synth
  6263. && back->channels.back().patcher.wires == ch.patcher.wires;
  6264. }
  6265. // Round 183c, Racks: (1) a plain Patcher's stored JSON loads and saves back byte for byte and never holds a
  6266. // "rack" key (FL's Patcher is untouched); (2) an Audio Effect Rack slot and an Instrument Rack channel survive save /
  6267. // load with their chains, zones, macros, mappings, variations and compiled cables
  6268. juce::String rackResult = "OK";
  6269. {
  6270. lynx::MixerTrack plain;
  6271. plain.name = "Plain Patcher";
  6272. auto fx = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  6273. lynx::PatchNode a, b;
  6274. a.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  6275. a.label = "A";
  6276. a.x = 120.5f;
  6277. b.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  6278. b.effect.enabled = false;
  6279. fx.patcher.nodes = { a, b };
  6280. lynx::PatchWire w1, w2, w3, wc;
  6281. w1.to = 0;
  6282. w2.from = 0, w2.to = 1, w2.gain = 0.5f;
  6283. w3.from = 1;
  6284. wc.kind = lynx::PatchWire::Kind::control, wc.from = 0, wc.to = 1, wc.toPort = 0, wc.curve = { 0.0f, 0.25f, 1.0f };
  6285. fx.patcher.wires = { w1, w2, w3, wc };
  6286. lynx::SurfaceControl knob;
  6287. knob.name = "Drive";
  6288. knob.value = 0.25f;
  6289. fx.patcher.surface = { knob };
  6290. lynx::PatchParam pp;
  6291. pp.node = 0, pp.param = 1, pp.name = "Balance";
  6292. fx.patcher.published = { pp };
  6293. plain.effects = { fx };
  6294. const auto first = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (plain), true);
  6295. const auto again = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (first))), true);
  6296. if (first != again || first.contains ("\"rack\"") || first.contains ("rackMixer"))
  6297. rackResult = "ERROR plain Patcher changed";
  6298. auto song = lynx::Song::makeDefault();
  6299. song.mixer.resize (3);
  6300. auto rackSlot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  6301. auto& doc = rackSlot.patcher;
  6302. lynx::PatchNode u;
  6303. u.effect = lynx::makeEffectSlot (lynx::EffectKind::utility);
  6304. const auto n0 = lynx::rack::addDevice (doc, 0, u);
  6305. lynx::rack::addChain (doc, "Wet");
  6306. lynx::rack::addDevice (doc, 1, u);
  6307. doc.rack[0].chains[1].select = { 10, 90, 30, 70 };
  6308. lynx::rack::setChainPan (doc, 1, -0.5f);
  6309. lynx::RackMapping m;
  6310. m.node = n0, m.param = 0, m.min = 0.2f, m.max = 0.9f;
  6311. lynx::rack::map (doc, 0, m);
  6312. lynx::RackMapping v;
  6313. v.target = lynx::RackMapping::Target::chainVolume, v.chain = 1, v.min = 0.0f, v.max = lynx::rack::unityVolume;
  6314. lynx::rack::map (doc, 1, v);
  6315. lynx::rack::setMacro (doc, 0, 64.0f);
  6316. lynx::rack::storeVariation (doc);
  6317. lynx::rack::setMacro (doc, 0, 100.0f);
  6318. lynx::rack::storeVariation (doc);
  6319. doc.rack[0].morphOn = true, doc.rack[0].morphA = 0, doc.rack[0].morphB = 1;
  6320. lynx::rack::setMorph (doc, 0.5f);
  6321. lynx::rack::compile (doc);
  6322. song.mixer[1].effects = { rackSlot };
  6323. lynx::ChannelDef inst;
  6324. inst.name = "Instrument Rack";
  6325. inst.instrument = lynx::InstrumentKind::patcher;
  6326. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  6327. lynx::PatchNode synth;
  6328. synth.generator = true;
  6329. synth.channel.instrument = lynx::InstrumentKind::synth;
  6330. synth.channel.name = "Synth";
  6331. lynx::rack::addDevice (inst.patcher, 0, synth);
  6332. inst.patcher.rack[0].chains[0].velocity = { 1, 127, 64, 127 };
  6333. lynx::rack::compile (inst.patcher);
  6334. song.channels.push_back (inst);
  6335. const auto json = lynx::ProjectFile::toJson (song);
  6336. const auto back = lynx::ProjectFile::fromJson (json, error);
  6337. // (the devices' parameters are stored to 4 decimals: the documents are compared as stored, the rack exactly)
  6338. const auto loaded = back && back->mixer.size() >= 2 && back->mixer[1].effects.size() == 1;
  6339. const auto& got = loaded ? back->mixer[1].effects[0].patcher : doc;
  6340. if (! loaded)
  6341. rackResult = "ERROR rack slot not loaded";
  6342. else if (got.rack != doc.rack)
  6343. rackResult = "ERROR rack model";
  6344. else if (got.wires != doc.wires)
  6345. rackResult = "ERROR rack cables";
  6346. else if (got.nodes.size() != doc.nodes.size())
  6347. rackResult = "ERROR rack devices";
  6348. else if (back->channels.back().patcher.rack != inst.patcher.rack || back->channels.back().patcher.wires != inst.patcher.wires
  6349. || back->channels.back().patcher.zones != inst.patcher.zones || back->channels.back().patcher.nodes.size() != inst.patcher.nodes.size())
  6350. rackResult = "ERROR instrument rack";
  6351. // the slot's insert as stored, once more: the same text (the stored form is stable)
  6352. else if (const auto once = juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (back->mixer[1]), true);
  6353. once != juce::JSON::toString (lynx::ProjectFile::mixerTrackToVar (lynx::ProjectFile::mixerTrackFromVar (juce::JSON::parse (once))), true))
  6354. rackResult = "ERROR rack stored form not stable";
  6355. }
  6356. // Round 190ec, Drum Rack: pads (Receive / Play / Choke / Audio To / sends), return chains and the views survive save /
  6357. // load with their compiled zones and cables
  6358. if (rackResult == "OK")
  6359. {
  6360. lynx::Song song;
  6361. song.mixer.resize (2);
  6362. lynx::ChannelDef ch;
  6363. ch.name = "Drums";
  6364. ch.instrument = lynx::InstrumentKind::patcher;
  6365. ch.patcher = lynx::rack::makeDrumRack();
  6366. lynx::PatchNode synth;
  6367. synth.generator = true;
  6368. synth.channel.instrument = lynx::InstrumentKind::synth;
  6369. const auto kick = lynx::rack::addPad (ch.patcher, 36, "Kick", synth);
  6370. const auto hat = lynx::rack::addPad (ch.patcher, 42, "Hat", synth);
  6371. lynx::rack::addPad (ch.patcher, -1, "Every note");
  6372. lynx::rack::addReturn (ch.patcher, "A Verb");
  6373. lynx::rack::setPlay (ch.patcher, kick, 64);
  6374. lynx::rack::setChoke (ch.patcher, hat, 2);
  6375. lynx::rack::setSend (ch.patcher, hat, 0, 0.25f, false);
  6376. lynx::rack::setAudioTo (ch.patcher, kick, 0);
  6377. lynx::rack::rackOf (ch.patcher)->showIO = true;
  6378. lynx::rack::rackOf (ch.patcher)->padScroll = 17;
  6379. song.channels.push_back (ch);
  6380. juce::String error;
  6381. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  6382. const auto& got = back && ! back->channels.empty() ? back->channels.back().patcher : lynx::PatcherDoc {};
  6383. if (! back || ! lynx::rack::isDrumRack (got))
  6384. rackResult = "ERROR drum rack not loaded";
  6385. else if (got.rack != ch.patcher.rack)
  6386. rackResult = "ERROR drum rack model";
  6387. else if (got.zones != ch.patcher.zones || got.wires != ch.patcher.wires)
  6388. rackResult = "ERROR drum rack cables";
  6389. }
  6390. // FL engines in a native project (round 142, issue #5): every engine this PC can make survives save / load and
  6391. // the instruments play through the rack
  6392. juce::String nativesResult = "OK";
  6393. int nativesMade = 0, nativesSilent = 0;
  6394. {
  6395. auto song = lynx::Song::makeDefault();
  6396. song.channels.clear();
  6397. song.patterns[0].notes.clear();
  6398. song.mixer.resize (3);
  6399. const auto& fl = lynx::flStudioAccess();
  6400. for (const auto& e : lynx::natives::instrumentEngines())
  6401. if (lynx::natives::available (e, fl))
  6402. if (auto c = lynx::natives::makeChannel (e.kind, fl))
  6403. {
  6404. c->mixerTrack = 1;
  6405. song.channels.push_back (*c);
  6406. }
  6407. for (const auto& e : lynx::natives::effectEngines())
  6408. if (auto fx = lynx::natives::makeSlot (e.kind, fl))
  6409. song.mixer[2].effects.push_back (*fx);
  6410. nativesMade = (int) (song.channels.size() + song.mixer[2].effects.size());
  6411. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  6412. auto same = back && back->channels.size() == song.channels.size() && back->mixer.size() >= 3
  6413. && back->mixer[2].effects.size() == song.mixer[2].effects.size();
  6414. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  6415. {
  6416. const auto& a = song.channels[i];
  6417. const auto& b = back->channels[i];
  6418. same = a.instrument == b.instrument && a.pluginState == b.pluginState && a.samplePath == b.samplePath && a.zones.size() == b.zones.size()
  6419. && a.modelParams.size() == b.modelParams.size();
  6420. if (! same)
  6421. nativesResult = "ERROR channel " + juce::String::fromUTF8 (a.name.c_str());
  6422. }
  6423. for (std::size_t i = 0; same && i < song.mixer[2].effects.size(); ++i)
  6424. {
  6425. const auto& a = song.mixer[2].effects[i];
  6426. const auto& b = back->mixer[2].effects[i];
  6427. same = a.kind == b.kind && a.state == b.state;
  6428. for (std::size_t p = 0; same && p < a.params.size(); ++p)
  6429. same = std::abs (a.params[p] - b.params[p]) < 1.0e-3f;
  6430. if (! same)
  6431. nativesResult = juce::String ("ERROR effect ") + lynx::effectInfo (a.kind).name;
  6432. }
  6433. if (! back)
  6434. nativesResult = "ERROR " + error;
  6435. // each instrument plays a note alone. The Granulizer and Wave Traveller play the channel's sample, and a new
  6436. // one has none (a PC without FL Studio, macOS / Linux: FL's presets are not there either), so they get a
  6437. // generated one: a second of a 220 Hz tone (round 167m, PR #19: Wave Traveller was "SILENT 1" on macOS)
  6438. const auto toneWav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-natives.wav");
  6439. {
  6440. juce::WavAudioFormat format;
  6441. juce::AudioBuffer<float> tone (1, 48000);
  6442. for (int i = 0; i < 48000; ++i)
  6443. tone.setSample (0, i, 0.5f * std::sin (juce::MathConstants<float>::twoPi * 220.0f * (float) i / 48000.0f));
  6444. toneWav.deleteFile();
  6445. std::unique_ptr<juce::OutputStream> out (toneWav.createOutputStream().release());
  6446. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  6447. {
  6448. out.release();
  6449. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  6450. writer->writeFromAudioSampleBuffer (tone, 0, 48000);
  6451. }
  6452. }
  6453. juce::StringArray silentNames;
  6454. for (std::size_t i = 0; same && i < song.channels.size(); ++i)
  6455. {
  6456. auto one = song;
  6457. one.channels = { song.channels[i] };
  6458. one.channels[0].mixerTrack = 1;
  6459. const auto kind = song.channels[i].instrument;
  6460. // A new Fruity Slicer has no sample and no slices, and FL's is silent then too (round 180c), so it is
  6461. // not one of the engines that must sound here (Linux / macOS CI: "SILENT 1 [Fruity Slicer]", 0.1.25)
  6462. if (kind == lynx::InstrumentKind::fruityslicer && one.channels[0].samplePath.empty())
  6463. continue;
  6464. if (kind == lynx::InstrumentKind::slicex && one.channels[0].samplePath.empty()) // (the same: no sample on its decks yet)
  6465. continue;
  6466. if (kind == lynx::InstrumentKind::directwave && one.channels[0].zones.empty()) // (FL's new DirectWave: no zones yet, round 190hz)
  6467. continue;
  6468. if ((kind == lynx::InstrumentKind::granulizer || kind == lynx::InstrumentKind::wavetraveller) && one.channels[0].samplePath.empty())
  6469. one.channels[0].samplePath = toneWav.getFullPathName().toStdString();
  6470. one.mixer[2].effects.clear();
  6471. // Drumaxx plays pad 1's key: FL's default kit has a pad at 48, LYNX's own bank kits (a PC without FL,
  6472. // macOS / Linux; round 168p) start at 36 (round 169d: "SILENT 1 [Drumaxx]" on the Linux / macOS CI)
  6473. auto key = 60;
  6474. if (kind == lynx::InstrumentKind::drumaxx)
  6475. {
  6476. const auto padKey = lynx::drumaxxParam (one.channels[0].pluginState, 4);
  6477. key = std::isfinite (padKey) && padKey >= 0.0f && padKey <= 127.0f ? (int) padKey : 48;
  6478. }
  6479. // FPC plays its pads' keys; a kit without a sample (FL's "Empty" kit: no FL Studio on this PC) is silent
  6480. // in FL too (round 190q)
  6481. if (kind == lynx::InstrumentKind::fpc)
  6482. {
  6483. const auto pads = lynx::fpcChannelPads (one.channels[0]);
  6484. if (pads.empty())
  6485. continue;
  6486. key = pads.front().key;
  6487. }
  6488. one.patterns[0].notes = { { 0, 1920, 0, key, 0.8f } };
  6489. lynx::AudioEngine player (false);
  6490. player.setSong (std::move (one));
  6491. player.dispatchPendingMessages();
  6492. if (! (player.renderOffline (1.0, 48000.0) > 1.0e-4f))
  6493. {
  6494. ++nativesSilent;
  6495. silentNames.add (juce::String::fromUTF8 (song.channels[i].name.c_str()));
  6496. }
  6497. }
  6498. toneWav.deleteFile();
  6499. if (nativesSilent > 0 && nativesResult == "OK")
  6500. nativesResult = "SILENT " + juce::String (nativesSilent) + " [" + silentNames.joinIntoString (", ") + "]";
  6501. }
  6502. const auto nativesOk = nativesResult == "OK";
  6503. // The metronome as FL 2026 plays it (round 165z-a2): FL's five sounds from its install, the downbeat at
  6504. // 0.9404 × the Tick two semitones up, into the Master ("---") by default; insert 2 as its track plays it through
  6505. // insert 2 (muted: silent); never in an export
  6506. juce::String metronomeResult = "OK";
  6507. int metronomeFlSounds = 0;
  6508. float metronomeMaster = 0.0f;
  6509. {
  6510. const auto& flData = lynx::flStudioAccess().roots.data;
  6511. const auto sounds = lynx::Metronome::loadSounds (flData.empty() ? juce::File() : lynx::platform::localFile (flData));
  6512. for (const auto& s : sounds)
  6513. metronomeFlSounds += s.fromFl ? 1 : 0;
  6514. auto renderClick = [] (int track, bool muteInsert, bool include) {
  6515. auto song = lynx::Song::makeDefault();
  6516. song.channels.clear();
  6517. song.playlist.clear();
  6518. for (auto& p : song.patterns)
  6519. p.notes.clear();
  6520. song.mixer[0].effects.clear(); // (the default Master limiter)
  6521. song.mixer[2].muted = muteInsert;
  6522. lynx::AudioEngine player (false);
  6523. player.setSong (std::move (song));
  6524. player.dispatchPendingMessages();
  6525. auto& t = player.getTransport();
  6526. t.metronome = true;
  6527. t.metronomeSound = 1; // Tick
  6528. t.metronomeTrack = track;
  6529. lynx::AudioEngine::RenderOptions o;
  6530. o.seconds = 0.25;
  6531. o.sampleRate = 44100.0;
  6532. o.pluginWarmUp = false;
  6533. o.includeMetronome = include;
  6534. return player.renderOffline (o);
  6535. };
  6536. metronomeMaster = renderClick (0, false, true);
  6537. const auto insert = renderClick (2, false, true);
  6538. const auto muted = renderClick (2, true, true);
  6539. const auto exported = renderClick (0, false, false);
  6540. // FL's Tick peaks at 1.0: its downbeat at most 0.9404 (the interpolation may land between peaks)
  6541. const auto expectHigh = metronomeFlSounds == lynx::metronome::soundCount ? lynx::metronome::downbeatGain + 1.0e-3f : 1.0f;
  6542. if (! (metronomeMaster > 0.5f && metronomeMaster < expectHigh))
  6543. metronomeResult = "ERROR master " + juce::String (metronomeMaster, 4);
  6544. else if (std::abs (insert - metronomeMaster) > 2.0e-3f)
  6545. metronomeResult = "ERROR insert " + juce::String (insert, 4);
  6546. else if (muted > 1.0e-4f)
  6547. metronomeResult = "ERROR muted insert " + juce::String (muted, 4);
  6548. else if (exported > 1.0e-4f)
  6549. metronomeResult = "ERROR in export " + juce::String (exported, 4);
  6550. }
  6551. const auto metronomeOk = metronomeResult == "OK";
  6552. // Settings › Audio "Driver settings…" with a fake driver panel (issue #13's crash, the panel's buffer kept)
  6553. const auto driverPanel = lynx::AudioEngine::driverPanelSelfTest();
  6554. // issue #134 (round 190c): the output device, its rate and its buffer changed under a playing project, on
  6555. // stand-in devices (a short run; --devicechangetest plays every instrument and effect)
  6556. const auto deviceChange = lynx::AudioEngine::deviceChangeSelfTest (10, false);
  6557. // round 190gh: export parity (B7) and MIDI device hot-plug (B8)
  6558. const auto exportParity = lynx::AudioEngine::exportParitySelfTest();
  6559. // round 190jb: exports with the live plugin instances (Surge XT when it is installed here; otherwise only noted)
  6560. juce::StringArray livePlugins;
  6561. #if JUCE_WINDOWS
  6562. livePlugins.add ("C:\\Program Files\\Common Files\\VST3\\Surge Synth Team\\Surge XT.vst3");
  6563. #elif JUCE_MAC
  6564. livePlugins.add ("/Library/Audio/Plug-Ins/VST3/Surge XT.vst3");
  6565. #else
  6566. livePlugins.add (juce::File::getSpecialLocation (juce::File::userHomeDirectory).getChildFile (".vst3/Surge XT.vst3").getFullPathName());
  6567. #endif
  6568. const auto exportLive = lynx::AudioEngine::exportLiveSelfTest ({}, livePlugins);
  6569. const auto midiHotplug = lynx::AudioEngine::midiHotplugSelfTest();
  6570. const auto midiOutPorts = lynx::AudioEngine::midiOutPortSelfTest(); // round 190jl
  6571. // Online Sessions P2 (round 169b): live sessions without a network (the JSON round trip of every entity, replicas
  6572. // through it, the invite code's keys)
  6573. const auto liveResult = lynx::livetest::selfTest (&rich);
  6574. // issue #67: every built-in effect's parameters, named and hidden (the Parametric EQ's FL law, processing, band
  6575. // mask...), at odd values, through a project save and reload: the same floats back
  6576. juce::String effectParamsResult = "OK";
  6577. {
  6578. auto song = lynx::Song::makeDefault();
  6579. song.mixer.resize (1);
  6580. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  6581. {
  6582. const auto kind = (lynx::EffectKind) k;
  6583. if (kind == lynx::EffectKind::plugin || kind == lynx::EffectKind::parallel)
  6584. continue;
  6585. auto fx = lynx::makeEffectSlot (kind);
  6586. for (std::size_t i = 0; i < fx.params.size(); ++i)
  6587. {
  6588. auto v = (float) ((double) ((i * 7919 + (std::size_t) k * 104729) % 65521) / 65521.0);
  6589. fx.params[i] = v == fx.params[i] ? 1.0f - v : v;
  6590. }
  6591. if (kind == lynx::EffectKind::fruitySend) // ("Send to" is written over the insert span)
  6592. fx.params[3] = 0.0f;
  6593. song.mixer.emplace_back();
  6594. song.mixer.back().name = "Insert " + std::to_string (song.mixer.size() - 1);
  6595. song.mixer.back().effects.push_back (fx);
  6596. }
  6597. // round 171b's Patcher round trip (coordinator): the Frequency Splitter, Fruity Delay 3 and Peak Controller
  6598. // nodes came back different (their FL defaults, e.g. the LFO speed 32750 / 65336, lost to 4 decimals)
  6599. {
  6600. auto patch = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  6601. for (const auto kind : { lynx::EffectKind::frequencySplitter, lynx::EffectKind::fruityDelay3, lynx::EffectKind::peakController,
  6602. lynx::EffectKind::reverb, lynx::EffectKind::hardwareInsert })
  6603. {
  6604. lynx::PatchNode node;
  6605. node.effect = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  6606. if (kind == lynx::EffectKind::peakController)
  6607. node.effect.params[7] = 32750.0f / 65336.0f;
  6608. node.x = 200.0f, node.y = 60.0f * (float) patch.patcher.nodes.size();
  6609. patch.patcher.nodes.push_back (node);
  6610. }
  6611. song.mixer.emplace_back();
  6612. song.mixer.back().name = "Patcher";
  6613. song.mixer.back().effects.push_back (patch);
  6614. }
  6615. juce::String why;
  6616. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  6617. if (back && back->mixer.size() == song.mixer.size())
  6618. {
  6619. const auto& a = song.mixer.back().effects[0].patcher.nodes;
  6620. const auto& b = back->mixer.back().effects[0].patcher.nodes;
  6621. for (std::size_t n = 0; n < a.size(); ++n)
  6622. if (n >= b.size() || ! (a[n].effect == b[n].effect))
  6623. effectParamsResult = juce::String ("ERROR Patcher node ") + lynx::effectInfo (a[n].effect.kind).name;
  6624. }
  6625. if (! back || back->mixer.size() != song.mixer.size())
  6626. effectParamsResult = "ERROR load " + why;
  6627. else
  6628. for (std::size_t t = 1; t + 1 < song.mixer.size() && effectParamsResult == "OK"; ++t)
  6629. if (back->mixer[t].effects.size() != 1 || back->mixer[t].effects[0].params != song.mixer[t].effects[0].params)
  6630. {
  6631. effectParamsResult = juce::String ("ERROR ") + lynx::effectInfo (song.mixer[t].effects[0].kind).name;
  6632. break;
  6633. }
  6634. }
  6635. // round 170j: the Themed plugin style (its resolution with and without art; every art draws)
  6636. const auto artResult = lynx::skin::artSelfTest();
  6637. // round 177b: a plugin's sidechain bus gets the slot's sidechain (one-click sidechain)
  6638. const auto sidechainResult = lynx::pluginSidechainSelfTest();
  6639. // round 190ap: the Versions panel's list of files, and its labels on disk beside them
  6640. const auto versionsResult = lynx::versionsSelfTest();
  6641. // round 190ap: a project opened with its plugins off creates none of them and saves their settings unchanged
  6642. const auto pluginsOffResult = lynx::pluginsOffSelfTest();
  6643. const auto missingFilesResult = lynx::missingFilesSelfTest(); // issue #165
  6644. // round 190cj: a dancer's own native window stays where the stage put it (it drifted off the screen: JUCE
  6645. // moved a transparent child window by the main window's client offset on every repaint)
  6646. juce::String danceWindowDetail;
  6647. const auto danceWindowResult = lynx::danceWindowSelfTest (&danceWindowDetail);
  6648. // issue #161: a click in a panel (a native child window that takes no focus on a click) of an inactive main
  6649. // window activates it (back from another app, Space played nothing until the Browser was clicked)
  6650. const auto clickActivationResult = lynx::nativechild::clickActivationSelfTest();
  6651. // round 190jy (queue item 44): the holes the native panels get under a docked editor drawn by the main window
  6652. const auto editorHolesResult = lynx::nativechild::editorHolesSelfTest();
  6653. // round 177b: automation lanes come back from a project (track, automation, height, folded)
  6654. juce::String lanesResult = "OK";
  6655. {
  6656. auto song = lynx::Song::makeDefault();
  6657. const auto lane = lynx::autolanes::addLane (song, 3, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Vol", 0.4f);
  6658. song.playlistTracks[3].lanes[0].height = 72;
  6659. song.playlistTracks[3].lanesFolded = true;
  6660. // (the same round's clip LFO and modulators ride along)
  6661. auto& lfo = song.automations[(std::size_t) lane].lfo;
  6662. lfo.on = true;
  6663. lfo.level = -40;
  6664. lfo.speed = 30000;
  6665. lfo.flags = 1 | 4;
  6666. lfo.phase = 123456789u;
  6667. lfo.amp = { { 0, 0.5f, 0.0f }, { 960, 1.0f, 0.0f } };
  6668. lynx::Modulator mod;
  6669. mod.name = "LFO 1";
  6670. mod.shape = lynx::ModShape::square;
  6671. mod.sync = false;
  6672. mod.hz = 2.5;
  6673. mod.routes = { { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  6674. song.modulators.push_back (mod);
  6675. juce::String why;
  6676. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  6677. if (! back || back->playlistTracks.size() < 4 || ! (back->playlistTracks[3].lanes == song.playlistTracks[3].lanes)
  6678. || ! back->playlistTracks[3].lanesFolded || back->automations.size() != song.automations.size()
  6679. || ! (back->automations[(std::size_t) lane].points == song.automations[(std::size_t) lane].points)
  6680. || ! (back->automations[(std::size_t) lane].lfo == lfo) || ! (back->modulators == song.modulators))
  6681. lanesResult = "ERROR " + why;
  6682. }
  6683. // round 190cg: the loop switch, folded tracks and the tempo lane's range come back from a project; a project
  6684. // without them loads as before (loop on, nothing folded, the whole range)
  6685. juce::String arrange190cgResult = "OK";
  6686. {
  6687. auto song = lynx::Song::makeDefault();
  6688. juce::String why;
  6689. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  6690. song.loopStart = 960;
  6691. song.loopEnd = 4800;
  6692. song.loopOff = true;
  6693. song.tempoViewLow = 80.0;
  6694. song.tempoViewHigh = 160.0;
  6695. song.playlistTracks.resize (std::max<std::size_t> (song.playlistTracks.size(), 6));
  6696. song.playlistTracks[2].folded = song.playlistTracks[5].folded = true;
  6697. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  6698. if (! plain || plain->loopOff || plain->tempoViewLow != 0.0 || plain->tempoViewHigh != 0.0
  6699. || std::any_of (plain->playlistTracks.begin(), plain->playlistTracks.end(), [] (const lynx::PlaylistTrack& t) { return t.folded; }))
  6700. arrange190cgResult = "ERROR defaults " + why;
  6701. else if (! back || ! back->loopOff || back->loopStart != 960 || back->loopEnd != 4800 || back->loopPlays() || back->tempoViewLow != 80.0
  6702. || back->tempoViewHigh != 160.0 || back->playlistTracks.size() < 6 || ! back->playlistTracks[2].folded
  6703. || ! back->playlistTracks[5].folded || back->playlistTracks[3].folded)
  6704. arrange190cgResult = "ERROR round trip " + why;
  6705. }
  6706. // round 190gz (issue #170): "Link Playlist tracks to mixer tracks" comes back from a project with its links; a
  6707. // project without it loads with it off (FL's tracks)
  6708. juce::String trackauto190gzResult = "OK";
  6709. {
  6710. auto song = lynx::Song::makeDefault();
  6711. juce::String why;
  6712. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  6713. lynx::Clip clip;
  6714. clip.kind = lynx::ClipKind::pattern;
  6715. clip.pattern = 0; // (the default pattern: Kick, Clap and Hat; a second one plays Kick alone)
  6716. song.playlist.push_back (clip);
  6717. auto& kick = song.patterns.emplace_back();
  6718. kick.name = "Kick";
  6719. kick.toggleStep (0, 0);
  6720. clip.pattern = (int) song.patterns.size() - 1;
  6721. clip.track = 1;
  6722. song.playlist.push_back (clip);
  6723. lynx::autolink::setOn (song, true);
  6724. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  6725. if (! plain || plain->linkTracksToMixer)
  6726. trackauto190gzResult = "ERROR defaults " + why;
  6727. // (round 190ib: Track 1 holds Kick, Clap and Hat, so they all go through insert 1 and Track 1 is its audio
  6728. // track; Track 2 only repeats Kick and stays unassigned)
  6729. // (a .lynx keeps the tracks up to the last one that differs from a plain track: Track 2 may not be written)
  6730. else if (! back || ! back->linkTracksToMixer || back->playlistTracks.empty() || back->playlistTracks[0].mode != lynx::PlaylistTrackMode::audio
  6731. || back->playlistTracks[0].mixerTrack != 1
  6732. || (back->playlistTracks.size() > 1 && back->playlistTracks[1].mode != lynx::PlaylistTrackMode::unassigned)
  6733. || back->channels[1].mixerTrack != 1 || back->channels[2].mixerTrack != 1)
  6734. {
  6735. trackauto190gzResult = "ERROR round trip " + why;
  6736. if (back && ! back->playlistTracks.empty() && back->channels.size() >= 3)
  6737. trackauto190gzResult << " tracks " << (int) back->playlistTracks.size() << " mode " << (int) back->playlistTracks[0].mode << " insert "
  6738. << back->playlistTracks[0].mixerTrack << " routes " << back->channels[0].mixerTrack << " "
  6739. << back->channels[1].mixerTrack << " " << back->channels[2].mixerTrack;
  6740. }
  6741. }
  6742. // round 190fm: the MIDI Tools generators' settings come back from a project; a project without them loads with
  6743. // Live's defaults (and saves none)
  6744. juce::String midigen190fmResult = "OK";
  6745. {
  6746. auto song = lynx::Song::makeDefault();
  6747. juce::String why;
  6748. const auto plainJson = lynx::ProjectFile::toJson (song);
  6749. const auto plain = lynx::ProjectFile::fromJson (plainJson, why);
  6750. song.midiGenerate.tool = lynx::midigen::Settings::stacks;
  6751. song.midiGenerate.rhythmOptions.pattern = 3;
  6752. song.midiGenerate.seedOptions.voices = 2;
  6753. song.midiGenerate.shapeOptions.levels[4] = 0.25f;
  6754. song.midiGenerate.shapeOptions.preset = lynx::midigen::ShapeOptions::custom;
  6755. song.midiGenerate.stacksOptions.sequence.push_back ({ 4, 3, 67, 1, 1, 0.5f, 2.0f });
  6756. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  6757. if (! plain || ! plain->midiGenerate.isDefault() || plainJson.contains ("midiGenerate"))
  6758. midigen190fmResult = "ERROR defaults " + why;
  6759. else if (! back || ! (back->midiGenerate == song.midiGenerate))
  6760. midigen190fmResult = "ERROR round trip " + why;
  6761. }
  6762. // round 190gi: audio clip envelopes come back from a project (an entry two clips share stays shared, an unused one
  6763. // is not written, the lane shown, FL's curve modes); a project without them writes neither "clipEnvelopes" nor a
  6764. // clip field 25 (older projects save byte-identical)
  6765. juce::String clipenv190giResult = "OK";
  6766. {
  6767. auto song = lynx::Song::makeDefault();
  6768. lynx::ChannelDef channel;
  6769. channel.instrument = lynx::InstrumentKind::audioClip;
  6770. channel.samplePath = "clipenv190gi.wav";
  6771. song.channels.push_back (channel);
  6772. lynx::Clip clip;
  6773. clip.kind = lynx::ClipKind::audio;
  6774. clip.channel = (int) song.channels.size() - 1;
  6775. clip.length = lynx::ppq * 4;
  6776. song.playlist.push_back (clip);
  6777. juce::String why;
  6778. const auto plainJson = lynx::ProjectFile::toJson (song);
  6779. lynx::ClipEnvelope e;
  6780. e.volume = { { 0, 1.0f, 0.0f, 0 }, { lynx::ppq * 4, 0.25f, 0.3f, 1 } };
  6781. e.pan = { { 0, 0.5f, 0.0f, 0 }, { lynx::ppq * 2, 0.0f, 0.0f, 0 } };
  6782. e.shown = lynx::clipenv::panLane;
  6783. song.clipEnvelopes.emplace_back(); // (no clip uses it: not written)
  6784. song.clipEnvelopes.push_back (e);
  6785. song.playlist.back().envelope = 1;
  6786. auto twin = song.playlist.back();
  6787. twin.start = lynx::ppq * 8;
  6788. song.playlist.push_back (twin);
  6789. const auto json = lynx::ProjectFile::toJson (song);
  6790. const auto back = lynx::ProjectFile::fromJson (json, why);
  6791. if (plainJson.contains ("clipEnvelopes") || ! json.contains ("clipEnvelopes"))
  6792. clipenv190giResult = "ERROR written " + why;
  6793. else if (! back || back->clipEnvelopes.size() != 1 || ! (back->clipEnvelopes[0] == e))
  6794. clipenv190giResult = "ERROR table " + why;
  6795. else
  6796. {
  6797. int withEnvelope = 0;
  6798. for (const auto& c : back->playlist)
  6799. withEnvelope += c.kind == lynx::ClipKind::audio && c.envelope == 0 ? 1 : 0;
  6800. if (withEnvelope != 2)
  6801. clipenv190giResult = "ERROR clips " + why;
  6802. }
  6803. }
  6804. // round 190gx: Beats' law in the .lynx — a new project's channels are Measured; a project saved before the law
  6805. // (no "beatsLaw190gx" mark, or a nine-number warpModes list) loads Classic; a Classic channel stays Classic
  6806. juce::String beatslaw190gxResult = "OK";
  6807. {
  6808. auto song = lynx::Song::makeDefault();
  6809. lynx::ChannelDef channel;
  6810. channel.instrument = lynx::InstrumentKind::audioClip;
  6811. channel.samplePath = "beatslaw190gx.wav";
  6812. channel.sampler.keepPitch = true;
  6813. channel.sampler.stretchMethod = lynx::StretchMethod::beats;
  6814. song.channels.push_back (channel);
  6815. const auto index = song.channels.size() - 1;
  6816. juce::String why;
  6817. const auto json = lynx::ProjectFile::toJson (song);
  6818. const auto lawOf = [&] (const juce::String& text) {
  6819. const auto back = lynx::ProjectFile::fromJson (text, why);
  6820. return back && back->channels.size() > index ? (int) back->channels[index].sampler.warpModes.beatsLaw : -1;
  6821. };
  6822. auto oldVar = juce::JSON::parse (json); // (the mark removed: a project saved before 190gx)
  6823. if (auto* o = oldVar.getDynamicObject())
  6824. o->removeProperty ("beatsLaw190gx");
  6825. const auto old = juce::JSON::toString (oldVar);
  6826. auto classic = song;
  6827. classic.channels[index].sampler.warpModes.beatsLaw = lynx::WarpModeSettings::beatsLawClassic;
  6828. auto nine = song;
  6829. nine.channels[index].sampler.warpModes.beatsLoop = 0; // (a 190fm project with a changed setting: nine numbers)
  6830. // (the list with its tenth number, the law, removed: what a 190fm build wrote)
  6831. auto nineVar = juce::JSON::parse (lynx::ProjectFile::toJson (nine));
  6832. bool trimmed = false;
  6833. if (auto* channels = nineVar.getProperty ("channels", {}).getArray(); channels != nullptr && (int) index < channels->size())
  6834. if (auto* modes = (*channels)[(int) index].getProperty ("samplerSettings", {}).getProperty ("warpModes", {}).getArray(); modes != nullptr && modes->size() == 11)
  6835. {
  6836. modes->removeLast (2); // (round 190ik's eleventh number too)
  6837. trimmed = true;
  6838. }
  6839. const auto nineJson = juce::JSON::toString (nineVar);
  6840. if (! json.contains ("beatsLaw190gx") || old.contains ("beatsLaw190gx"))
  6841. beatslaw190gxResult = "ERROR mark";
  6842. else if (lawOf (json) != lynx::WarpModeSettings::beatsLawPitchAware) // (round 190ik: the new default)
  6843. beatslaw190gxResult = "ERROR new " + why;
  6844. else if (lawOf (old) != lynx::WarpModeSettings::beatsLawClassic)
  6845. beatslaw190gxResult = "ERROR old " + why;
  6846. else if (lawOf (lynx::ProjectFile::toJson (classic)) != lynx::WarpModeSettings::beatsLawClassic)
  6847. beatslaw190gxResult = "ERROR classic kept " + why;
  6848. else if (! trimmed || lawOf (nineJson) != lynx::WarpModeSettings::beatsLawClassic)
  6849. beatslaw190gxResult = "ERROR nine-number list";
  6850. }
  6851. // round 190ik: the pitch-aware Beats law and the Texture / Complex Pro engines in the .lynx — a new project's channels
  6852. // use them; a project saved before 190ik (no "warpLaw190ik" mark, or a ten-number warpModes list) keeps Beats Measured
  6853. // and the Classic engines; a channel kept on an older law stays on it when saved again
  6854. juce::String warplaw190ikResult = "OK";
  6855. {
  6856. auto song = lynx::Song::makeDefault();
  6857. lynx::ChannelDef channel;
  6858. channel.instrument = lynx::InstrumentKind::audioClip;
  6859. channel.samplePath = "warplaw190ik.wav";
  6860. channel.sampler.keepPitch = true;
  6861. channel.sampler.stretchMethod = lynx::StretchMethod::texture;
  6862. song.channels.push_back (channel);
  6863. const auto index = song.channels.size() - 1;
  6864. juce::String why;
  6865. const auto lawsOf = [&] (const juce::String& text) {
  6866. const auto back = lynx::ProjectFile::fromJson (text, why);
  6867. if (! back || back->channels.size() <= index)
  6868. return std::pair<int, int> { -1, -1 };
  6869. const auto& w = back->channels[index].sampler.warpModes;
  6870. return std::pair<int, int> { (int) w.beatsLaw, (int) w.warpLaw };
  6871. };
  6872. const auto json = lynx::ProjectFile::toJson (song);
  6873. auto oldVar = juce::JSON::parse (json); // (the mark removed: a project saved by 0.1.28 / 0.1.29)
  6874. if (auto* o = oldVar.getDynamicObject())
  6875. o->removeProperty ("warpLaw190ik");
  6876. const auto old = juce::JSON::toString (oldVar);
  6877. auto kept = song; // a channel left on the older laws
  6878. kept.channels[index].sampler.warpModes.beatsLaw = lynx::WarpModeSettings::beatsLawMeasured;
  6879. kept.channels[index].sampler.warpModes.warpLaw = lynx::WarpModeSettings::warpLawClassic;
  6880. auto ten = song; // a changed setting saved by 0.1.28: a ten-number list
  6881. ten.channels[index].sampler.warpModes.textureFlux = 60.0f;
  6882. auto tenVar = juce::JSON::parse (lynx::ProjectFile::toJson (ten));
  6883. bool trimmed = false;
  6884. if (auto* channels = tenVar.getProperty ("channels", {}).getArray(); channels != nullptr && (int) index < channels->size())
  6885. if (auto* modes = (*channels)[(int) index].getProperty ("samplerSettings", {}).getProperty ("warpModes", {}).getArray(); modes != nullptr && modes->size() == 11)
  6886. {
  6887. modes->removeLast();
  6888. modes->set (9, 1); // (0.1.28 wrote Measured)
  6889. trimmed = true;
  6890. }
  6891. const auto tenJson = juce::JSON::toString (tenVar);
  6892. const std::pair<int, int> newest { lynx::WarpModeSettings::beatsLawPitchAware, lynx::WarpModeSettings::warpLawMeasured };
  6893. const std::pair<int, int> older { lynx::WarpModeSettings::beatsLawMeasured, lynx::WarpModeSettings::warpLawClassic };
  6894. if (! json.contains ("warpLaw190ik") || old.contains ("warpLaw190ik"))
  6895. warplaw190ikResult = "ERROR mark";
  6896. else if (lawsOf (json) != newest)
  6897. warplaw190ikResult = "ERROR new " + why;
  6898. else if (lawsOf (old) != older)
  6899. warplaw190ikResult = "ERROR old " + why;
  6900. else if (lawsOf (lynx::ProjectFile::toJson (kept)) != older)
  6901. warplaw190ikResult = "ERROR older laws kept " + why;
  6902. else if (! trimmed || lawsOf (tenJson) != std::pair<int, int> { lynx::WarpModeSettings::beatsLawMeasured, lynx::WarpModeSettings::warpLawClassic })
  6903. warplaw190ikResult = "ERROR ten-number list";
  6904. }
  6905. // round 190he (issue #152): a channel window's Scaling is saved with the channel; the default (125 %) writes
  6906. // nothing, so older projects and untouched channels read as before
  6907. juce::String editorScale190heResult = "OK";
  6908. {
  6909. auto song = lynx::Song::makeDefault();
  6910. song.channels[0].editorScale = 100;
  6911. song.channels[1].editorScale = 0;
  6912. juce::String why;
  6913. const auto json = lynx::ProjectFile::toJson (song);
  6914. const auto back = lynx::ProjectFile::fromJson (json, why);
  6915. auto outOfRange = juce::JSON::parse (json);
  6916. if (auto* chans = outOfRange.getProperty ("channels", {}).getArray(); chans != nullptr && ! chans->isEmpty())
  6917. if (auto* o = (*chans)[0].getDynamicObject())
  6918. o->setProperty ("editorScale", 9000);
  6919. const auto clamped = lynx::ProjectFile::fromJson (juce::JSON::toString (outOfRange), why);
  6920. if (! back || back->channels[0].editorScale != 100 || back->channels[1].editorScale != 0)
  6921. editorScale190heResult = "ERROR round trip " + why;
  6922. else if (json.indexOf ("editorScale") != json.lastIndexOf ("editorScale"))
  6923. editorScale190heResult = "ERROR written for a default channel";
  6924. else if (! clamped || clamped->channels[0].editorScale != lynx::editorscale::maxPercent)
  6925. editorScale190heResult = "ERROR not clamped";
  6926. }
  6927. // round 190he (coordinator's gate): a project saved before 190he (no "sfModBase190he") keeps the old 0.5 centre of
  6928. // a Modulation route on a Soundfont knob; a new song, saved and opened again, centres on the knob
  6929. juce::String sfModBase190heResult = "OK";
  6930. {
  6931. auto song = lynx::Song::makeDefault();
  6932. juce::String why;
  6933. const auto json = lynx::ProjectFile::toJson (song);
  6934. auto oldVar = juce::JSON::parse (json);
  6935. if (auto* o = oldVar.getDynamicObject())
  6936. o->removeProperty ("sfModBase190he");
  6937. const auto back = lynx::ProjectFile::fromJson (json, why);
  6938. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (oldVar), why);
  6939. auto resaved = old ? lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (*old), why) : std::optional<lynx::Song> {};
  6940. if (! json.contains ("sfModBase190he") || ! back || ! back->soundfontModBaseReal)
  6941. sfModBase190heResult = "ERROR new song " + why;
  6942. else if (! old || old->soundfontModBaseReal)
  6943. sfModBase190heResult = "ERROR old project " + why;
  6944. else if (! resaved || resaved->soundfontModBaseReal)
  6945. sfModBase190heResult = "ERROR old project saved again";
  6946. }
  6947. // round 190hq: tempo markers (B11) and the fader / route PDC switch (B13) in the .lynx, and the copy for an older
  6948. // LYNX (B20): an effect 0.1.27 does not know keeps its slot (as a switched-off Utility) and loses its automation,
  6949. // the later slots and their automation stay; the copy for 0.1.28 turns the markers into a plain tempo clip
  6950. juce::String community190hqResult = "OK";
  6951. {
  6952. auto song = lynx::Song::makeDefault();
  6953. song.mode = lynx::PlayMode::song;
  6954. lynx::tempomarkers::add (song, 4 * lynx::ppq, 90.0);
  6955. lynx::tempomarkers::add (song, 8 * lynx::ppq, 140.0, true);
  6956. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::anvilBus));
  6957. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay));
  6958. for (const auto slot : { 0, 1 })
  6959. {
  6960. lynx::Automation a;
  6961. a.name = slot == 0 ? "Anvil" : "Delay";
  6962. a.target = { lynx::AutomationTargetKind::effectParam, 1, slot, 1 };
  6963. a.points = { { 0, 0.2f }, { 1920, 0.8f } };
  6964. song.automations.push_back (a);
  6965. }
  6966. juce::String why;
  6967. const auto json = lynx::ProjectFile::toJson (song);
  6968. const auto back = lynx::ProjectFile::fromJson (json, why);
  6969. auto unmarked = juce::JSON::parse (json);
  6970. if (auto* o = unmarked.getDynamicObject())
  6971. o->removeProperty ("mixerLevelPdc190hq");
  6972. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (unmarked), why);
  6973. const auto marks = back ? lynx::tempomarkers::list (*back) : std::vector<lynx::tempomarkers::Mark> {};
  6974. const auto for127 = lynx::olderlynx::forRelease (song, "0.1.27");
  6975. const auto for128 = lynx::olderlynx::forRelease (song, "0.1.28");
  6976. const auto copy127 = for127.ok ? lynx::ProjectFile::fromJson (for127.json, why) : std::optional<lynx::Song> {};
  6977. const auto copy128 = for128.ok ? lynx::ProjectFile::fromJson (for128.json, why) : std::optional<lynx::Song> {};
  6978. const auto anvilLost = std::any_of (for127.lost.begin(), for127.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  6979. return juce::String (l.text).startsWith ("Anvil Bus");
  6980. });
  6981. auto targetOf = [] (const std::optional<lynx::Song>& s, const char* name) {
  6982. if (s)
  6983. for (const auto& a : s->automations)
  6984. if (a.name == name)
  6985. return a.target;
  6986. return lynx::AutomationTarget {};
  6987. };
  6988. if (! back || ! back->compensateMixerLevels || ! old || old->compensateMixerLevels)
  6989. community190hqResult = "ERROR mixer level PDC mark " + why;
  6990. 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
  6991. || std::abs (back->tempoAt (5.0 * lynx::ppq) - 102.5) > 0.5) // (90 at bar 2, ramping into the gliding 140 at bar 3)
  6992. community190hqResult = "ERROR tempo markers round trip";
  6993. else if (! copy127 || for127.json.contains ("anvilBus") || copy127->mixer[1].effects.size() != 2
  6994. || copy127->mixer[1].effects[0].kind != lynx::EffectKind::utility || copy127->mixer[1].effects[0].enabled
  6995. || copy127->mixer[1].effects[1].kind != lynx::EffectKind::delay || ! anvilLost)
  6996. community190hqResult = "ERROR copy for 0.1.27: slots " + why;
  6997. else if (targetOf (copy127, "Anvil").kind != lynx::AutomationTargetKind::none
  6998. || ! (targetOf (copy127, "Delay") == lynx::AutomationTarget { lynx::AutomationTargetKind::effectParam, 1, 1, 1 }))
  6999. community190hqResult = "ERROR copy for 0.1.27: automation";
  7000. else if (! juce::JSON::parse (for127.json)["savedBy"].toString().equalsIgnoreCase ("0.1.27") || for127.json.contains ("tempoMarkers")
  7001. || for127.json.contains ("mixerLevelPdc190hq") || for127.json.contains ("beatsLaw190gx"))
  7002. community190hqResult = "ERROR copy for 0.1.27: fields";
  7003. else if (! copy128 || for128.json.contains ("tempoMarkers") || ! for128.json.contains ("anvilBus") || lynx::tempomarkers::automationIndex (*copy128) >= 0
  7004. || std::abs (copy128->tempoAt (5.0 * lynx::ppq) - 102.5) > 0.5 || std::abs (copy128->tempoAt (12.0 * lynx::ppq) - 140.0) > 0.01)
  7005. community190hqResult = "ERROR copy for 0.1.28";
  7006. else if (lynx::olderlynx::forRelease (song, "0.1.9").ok)
  7007. community190hqResult = "ERROR unknown release accepted";
  7008. }
  7009. // 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
  7010. // an empty Sampler, MPE note curves, muted Pattern Blocks, clips transposed past ±12, clip slots' Start markers and
  7011. // 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
  7012. // out; a DirectWave state's 36-byte sample format record is completed (0.1.28 skipped it, and the loop with it)
  7013. juce::String rollup030Result = "OK";
  7014. {
  7015. auto song = lynx::Song::makeDefault();
  7016. lynx::ChannelDef tetra;
  7017. tetra.name = "FM";
  7018. tetra.instrument = lynx::InstrumentKind::tetra;
  7019. tetra.modelParams = { 0.5f, 0.25f };
  7020. song.channels.push_back (tetra);
  7021. lynx::ChannelDef wave;
  7022. wave.name = "Piano";
  7023. wave.instrument = lynx::InstrumentKind::directwave;
  7024. {
  7025. auto doc = lynx::dw::freshDoc();
  7026. lynx::dw::Node zone;
  7027. zone.id = 3;
  7028. zone.container = true;
  7029. lynx::dw::Node format;
  7030. format.id = 0x1F7;
  7031. format.body.assign (36, 0);
  7032. format.body[20] = 2; // loop mode
  7033. format.body[24] = 44; // loop A
  7034. format.body[28] = 200; // loop B
  7035. zone.kids.push_back (format);
  7036. for (auto& n : doc.top)
  7037. if (n.id == 1 && n.container)
  7038. {
  7039. n.kids.push_back (zone);
  7040. break;
  7041. }
  7042. wave.pluginState = lynx::dw::writeDoc (doc);
  7043. }
  7044. song.channels.push_back (wave);
  7045. lynx::Note curved;
  7046. curved.key = 60;
  7047. curved.length = lynx::ppq;
  7048. lynx::NoteCurves curves;
  7049. curves.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { 96.0f, 200.0f } };
  7050. curved.curves = curves;
  7051. song.patterns[0].notes.push_back (curved);
  7052. song.patternBlocksOn = true;
  7053. lynx::patternblocks::place (song, 0, 0);
  7054. lynx::patternblocks::place (song, 0, 4 * lynx::ppq);
  7055. lynx::patternblocks::setMuted (song, 1, true);
  7056. lynx::Clip up;
  7057. up.track = 1;
  7058. up.length = 4 * lynx::ppq;
  7059. up.pitch = 24.0f;
  7060. song.playlist.push_back (up);
  7061. lynx::Clip slotClip;
  7062. slotClip.length = 4 * lynx::ppq;
  7063. if (const auto id = lynx::launcher::setClip (song, 0, 0, slotClip); id >= 0)
  7064. {
  7065. song.clipGrid->slots[(std::size_t) id].startMarker = lynx::ppq;
  7066. song.clipGrid->slots[(std::size_t) id].ownScale = true;
  7067. }
  7068. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::voiceShift)); // (a new one: revision 1)
  7069. auto ridgeSlot = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  7070. ridgeSlot.params[(std::size_t) lynx::mixsuite::ridge::k4Pink] = 1.0f;
  7071. song.mixer[2].effects.push_back (ridgeSlot);
  7072. auto hushSlot = lynx::makeEffectSlot (lynx::EffectKind::hushDeEsser); // (a new one: the measured timing, round 190iq)
  7073. hushSlot.params[(std::size_t) lynx::mixsuite::hush::allround] = 1.0f;
  7074. song.mixer[3].effects.push_back (hushSlot);
  7075. lynx::Automation coloured;
  7076. coloured.name = "Cutoff";
  7077. coloured.colour = 0xFFC03030u;
  7078. coloured.points = { { 0, 0.2f }, { 1920, 0.8f } };
  7079. song.automations.push_back (coloured);
  7080. lynx::mixsnap::take (song);
  7081. // rollup step 3 (round 190jk): Helix (190ja), the effects' hidden revisions (190is / 190it), a warped Texture
  7082. // channel with its offline transposition and tempo automation (190ik), a deactivated clip slot (190im)
  7083. lynx::ChannelDef helix;
  7084. helix.name = "WT";
  7085. helix.instrument = lynx::InstrumentKind::helix;
  7086. helix.modelParams = { 0.5f };
  7087. song.channels.push_back (helix);
  7088. lynx::ChannelDef loop;
  7089. loop.name = "Loop";
  7090. loop.instrument = lynx::InstrumentKind::sampler;
  7091. loop.sampler.stretchBeats = 8.0f;
  7092. loop.sampler.keepPitch = true;
  7093. loop.sampler.stretchMethod = lynx::StretchMethod::texture;
  7094. loop.sampler.stretchPitch = 5.0f;
  7095. song.channels.push_back (loop);
  7096. lynx::Automation tempoClip;
  7097. tempoClip.name = "Tempo";
  7098. tempoClip.target.kind = lynx::AutomationTargetKind::tempo;
  7099. tempoClip.points = { { 0, 0.4f }, { 1920, 0.6f } };
  7100. song.automations.push_back (tempoClip);
  7101. if (song.clipGrid)
  7102. for (auto& slot : song.clipGrid->slots)
  7103. slot.active = false;
  7104. auto echoSlot = lynx::makeEffectSlot (lynx::EffectKind::echoform); // (new: voicings revision 1)
  7105. echoSlot.params[(std::size_t) lynx::echosuite::echoform::voicing] = 1.0f;
  7106. song.mixer[4].effects.push_back (echoSlot);
  7107. auto haloSlot = lynx::makeEffectSlot (lynx::EffectKind::halo); // (new: revision 1 of the Measured law)
  7108. haloSlot.params[(std::size_t) lynx::verbs::halo::engineLaw] = 1.0f;
  7109. song.mixer[5].effects.push_back (haloSlot);
  7110. song.mixer[6].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::latticeMod));
  7111. auto luxeSlot = lynx::makeEffectSlot (lynx::EffectKind::luxeVerb);
  7112. luxeSlot.params[(std::size_t) lynx::luxeVerbSpaceDucking] = 0.5f;
  7113. song.mixer[7].effects.push_back (luxeSlot);
  7114. // rollup step 4 (round 190jt): Facet's automatic threshold (190jh), a MIDI Out channel (190jl), a hosted VST3's
  7115. // automated parameter (190jg), a nested Playlist folder (190jf), the Limiter's CURVE view (190jd)
  7116. auto facetSlot = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  7117. facetSlot.params[(std::size_t) lynx::facet::autoThresholdParam0 + 2] = 1.0f;
  7118. song.mixer[8].effects.push_back (facetSlot);
  7119. auto limiterSlot = lynx::makeEffectSlot (lynx::EffectKind::fruityLimiter);
  7120. limiterSlot.displayView = 1;
  7121. song.mixer[9].effects.push_back (limiterSlot);
  7122. lynx::ChannelDef midiOut;
  7123. midiOut.name = "Hardware";
  7124. midiOut.instrument = lynx::InstrumentKind::midiOut;
  7125. song.channels.push_back (midiOut);
  7126. lynx::ChannelDef hosted;
  7127. hosted.name = "Hosted";
  7128. hosted.instrument = lynx::InstrumentKind::plugin;
  7129. hosted.plugin.id = "VST3-Test Synth-1a2b3c4d-5e6f7a8b";
  7130. hosted.plugin.name = "Test Synth";
  7131. song.channels.push_back (hosted);
  7132. lynx::Automation pluginKnob;
  7133. pluginKnob.name = "Test Synth - Cutoff";
  7134. pluginKnob.target.kind = lynx::AutomationTargetKind::channelParam;
  7135. pluginKnob.target.index = (int) song.channels.size() - 1;
  7136. pluginKnob.target.param = 3;
  7137. pluginKnob.points = { { 0, 0.1f }, { 1920, 0.9f } };
  7138. song.automations.push_back (pluginKnob);
  7139. if (song.playlistTracks.size() < 4)
  7140. song.playlistTracks.resize (4);
  7141. song.playlistTracks[1].grouped = true;
  7142. song.playlistTracks[2].grouped = true;
  7143. song.playlistTracks[2].nest = 1;
  7144. // rollup step 5 (round 190kh): Hush's Single Vocal revision (190js), a slide note on an FL native generator (190jv)
  7145. song.mixer[10].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::hushDeEsser)); // (new: Single Vocal, revision 1)
  7146. lynx::ChannelDef slider;
  7147. slider.name = "Slides";
  7148. slider.instrument = lynx::InstrumentKind::sampler;
  7149. song.channels.push_back (slider);
  7150. if (song.patterns.empty())
  7151. song.patterns.emplace_back();
  7152. {
  7153. lynx::Note slide;
  7154. slide.start = 0;
  7155. slide.length = lynx::ppq;
  7156. slide.channel = (int) song.channels.size() - 1;
  7157. slide.key = 64;
  7158. slide.slide = true;
  7159. song.patterns[0].notes.push_back (slide);
  7160. }
  7161. // rollup step 6 (round 190km): Live's Crossfade Assign and a return track (190kc), the Simple Controls tab's own
  7162. // mapping (190ke), a Newtone slot whose state is version 3 (natives190kj: + the key and the notes' velocity)
  7163. song.mixer[11].crossfade = lynx::CrossfadeAssign::a;
  7164. song.crossfader = -0.5f;
  7165. song.mixer[12].liveReturn = true;
  7166. song.mixer[12].returnPre = true;
  7167. song.mixer[13].smartControls = "custom";
  7168. {
  7169. auto newtoneSlot = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  7170. lynx::newtonefx::Track nt;
  7171. nt.frames = 48000;
  7172. nt.key = 9;
  7173. lynx::newtonefx::Note n;
  7174. n.origEnd = n.curEnd = 24000;
  7175. n.origPitch = 69.0;
  7176. n.velocity = 0.8;
  7177. n.validEnd = 20000;
  7178. nt.pitches = { n };
  7179. nt.notes = 1;
  7180. newtoneSlot.state = lynx::newtonefx::writeNative (nt);
  7181. song.mixer[14].effects.push_back (newtoneSlot);
  7182. }
  7183. // rollup step 7 (round 190lc): a Peak Controller on a LYNX shape (190kl), Crest's console law (190kt), a locked
  7184. // insert beside a solo (190kn), an imported take lane (qafix190kq), a plugin that records no notes from its
  7185. // window (190ks)
  7186. {
  7187. auto peakSlot = lynx::makeEffectSlot (lynx::EffectKind::peakController);
  7188. peakSlot.params[(std::size_t) lynx::peakshapes::extraShapeParam] = (float) lynx::peakshapes::expFall / lynx::peakshapes::idScale;
  7189. song.mixer[15].effects.push_back (peakSlot);
  7190. auto crestSlot = lynx::makeEffectSlot (lynx::EffectKind::crestCompressor);
  7191. crestSlot.params[(std::size_t) lynx::dyn::crest::busLaw] = 1.0f;
  7192. song.mixer[16].effects.push_back (crestSlot);
  7193. // rollup step 8: a new Crest (round 190kw's revision 1), a Crest on round 190ky's FET law, a Ridge Strip with
  7194. // round 190lb's 4K G filters, an Echoform on round 190kw's Timeless 3 line law in a locked slot (round
  7195. // 190ld), and a Playlist track's solo lock (round 190ld)
  7196. song.mixer[16].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::crestCompressor));
  7197. auto fetSlot = lynx::makeEffectSlot (lynx::EffectKind::crestCompressor);
  7198. fetSlot.params[(std::size_t) lynx::dyn::crest::revision] = 0.0f;
  7199. fetSlot.params[(std::size_t) lynx::dyn::crest::fetLaw] = lynx::dyn::crest::fetLawValue (0);
  7200. song.mixer[16].effects.push_back (fetSlot);
  7201. auto k4gSlot = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  7202. k4gSlot.params[(std::size_t) lynx::mixsuite::ridge::k4gLaw] = 1.0f;
  7203. song.mixer[16].effects.push_back (k4gSlot);
  7204. auto lineSlot = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  7205. lineSlot.params[(std::size_t) lynx::echosuite::echoform::lineLaw] = 1.0f;
  7206. lineSlot.lockState = true;
  7207. song.mixer[16].effects.push_back (lineSlot);
  7208. // (round 190mo: track 4 is the fifth; the song had four tracks here, so this wrote one byte past the
  7209. // vector's end: the heap corruption of the Linux self-test, "corrupted size vs. prev_size" later on)
  7210. if (song.playlistTracks.size() < 5)
  7211. song.playlistTracks.resize (5);
  7212. song.playlistTracks[4].soloLock = true;
  7213. song.mixer[1].lockState = true; // (the default mixer has inserts 1…16)
  7214. song.mixer[2].solo = true;
  7215. song.playlistTracks[3].takeLane = true;
  7216. for (auto& c : song.channels)
  7217. if (c.name == "Hosted")
  7218. c.plugin.recordOwnNotes = false;
  7219. }
  7220. // rollup step 9 (round 190lu): a new Ember (round 190kw / 190lg's Saturn laws), a Prism on round 190lg's Pro-MB
  7221. // law, round 190lf's L2 law on the Limiter, cell law on Glow Leveler, direct sound on Reeverb 2, zero law on Quell
  7222. // and H-Delay loop law on Echoform, round 190ln's all-pass dispersion on Facet, and a note on an audio clip
  7223. // channel (round 190lq: FL's law in a marked project)
  7224. {
  7225. auto& m16 = song.mixer[16].effects;
  7226. m16.push_back (lynx::makeEffectSlot (lynx::EffectKind::ember)); // [5]
  7227. auto prism = lynx::makeEffectSlot (lynx::EffectKind::prismMultiband);
  7228. prism.params[(std::size_t) lynx::dyn::prism::revision] = 1.0f;
  7229. m16.push_back (prism); // [6]
  7230. auto l2 = lynx::makeEffectSlot (lynx::EffectKind::limiter);
  7231. l2.params[(std::size_t) lynx::limiterlaw::lawParam] = lynx::limiterlaw::l2LawValue;
  7232. m16.push_back (l2); // [7]
  7233. auto glow = lynx::makeEffectSlot (lynx::EffectKind::glowLeveler);
  7234. glow.params[(std::size_t) lynx::mixsuite::glow::cellLaw] = 1.0f;
  7235. m16.push_back (glow); // [8]
  7236. auto verb = lynx::makeEffectSlot (lynx::EffectKind::reeverb2);
  7237. verb.params[(std::size_t) lynx::reeverb2DirectLaw] = 1.0f;
  7238. m16.push_back (verb); // [9]
  7239. auto quell = lynx::makeEffectSlot (lynx::EffectKind::quellDenoiser);
  7240. quell.params[(std::size_t) lynx::voicetools::quell::zeroLaw] = 1.0f;
  7241. m16.push_back (quell); // [10]
  7242. auto disperser = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  7243. disperser.params[(std::size_t) lynx::facet::dispersionCountParam] = 0.25f;
  7244. m16.push_back (disperser); // [11]
  7245. auto hybrid = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  7246. hybrid.params[(std::size_t) lynx::echosuite::echoform::hybridLaw] = 1.0f;
  7247. m16.push_back (hybrid); // [12]
  7248. lynx::ChannelDef clipChannel;
  7249. clipChannel.name = "Clip";
  7250. clipChannel.instrument = lynx::InstrumentKind::audioClip;
  7251. song.channels.push_back (clipChannel);
  7252. lynx::Note hit;
  7253. hit.length = lynx::ppq / 4;
  7254. hit.channel = (int) song.channels.size() - 1;
  7255. hit.key = 67;
  7256. song.patterns[0].notes.push_back (hit);
  7257. }
  7258. // rollup step 10 (round 190me): a new Apex Limiter and Sentry Gate (round 190lp's revision 1), a LuxeVerb on its
  7259. // Space engine (revision 1, round 190kw / 190lz), an Echoform on round 190ly's ValhallaDelay law, a new Spiral Echo
  7260. // on the Measured law (round 190ly's rate law) and a scene follow action (round 190lr)
  7261. {
  7262. auto& m16 = song.mixer[16].effects; // (after step 9's [5] … [12]: the song has inserts 0 … 16)
  7263. m16.push_back (lynx::makeEffectSlot (lynx::EffectKind::apexLimiter)); // [13]
  7264. m16.push_back (lynx::makeEffectSlot (lynx::EffectKind::sentryGate)); // [14]
  7265. auto luxe = lynx::makeEffectSlot (lynx::EffectKind::luxeVerb);
  7266. luxe.params[(std::size_t) lynx::luxeVerbSpaceFirst] = 1.0f;
  7267. m16.push_back (luxe); // [15]
  7268. auto valhalla = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  7269. valhalla.params[(std::size_t) lynx::echosuite::echoform::valhallaLaw] = 1.0f;
  7270. m16.push_back (valhalla); // [16]
  7271. auto spiral = lynx::makeEffectSlot (lynx::EffectKind::spiralEcho);
  7272. spiral.params[(std::size_t) lynx::echosuite::spiral::law] = 1.0f;
  7273. m16.push_back (spiral); // [17]
  7274. if (! song.clipGrid)
  7275. song.clipGrid.emplace();
  7276. if (song.clipGrid->scenes.empty())
  7277. song.clipGrid->scenes.emplace_back();
  7278. song.clipGrid->scenes[0].follow.enabled = true;
  7279. }
  7280. // rollup step 11 (round 190mn): a new Horizon (round 190mb / 190mj's revision and FutureVerb law), a Nebula on the
  7281. // Supermassive tone, an Orbit on the SpaceModulator laws (190mb / 190mj), round 190mg's Waves laws (Prism C4,
  7282. // Compressor Renaissance, Quell NS1, Gemini splice, LYNX Tune Waves Tune, Facet PuigTec) and a note repeat (190ma)
  7283. {
  7284. auto& m16 = song.mixer[16].effects; // (after step 10's [13] … [17])
  7285. m16.push_back (lynx::makeEffectSlot (lynx::EffectKind::horizon)); // [18]
  7286. auto nebula = lynx::makeEffectSlot (lynx::EffectKind::nebula);
  7287. nebula.params[(std::size_t) lynx::verbs::nebula::toneLaw] = 1.0f;
  7288. m16.push_back (nebula); // [19]
  7289. auto orbit = lynx::makeEffectSlot (lynx::EffectKind::orbit);
  7290. orbit.params[(std::size_t) lynx::echosuite::orbit::smLaw] = 1.0f;
  7291. orbit.params[(std::size_t) lynx::echosuite::orbit::voiceLaw] = 1.0f;
  7292. m16.push_back (orbit); // [20]
  7293. auto c4 = lynx::makeEffectSlot (lynx::EffectKind::prismMultiband);
  7294. c4.params[(std::size_t) lynx::dyn::prism::c4Law] = lynx::dyn::prism::c4LawValue (false);
  7295. m16.push_back (c4); // [21]
  7296. auto ren = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  7297. ren.params[(std::size_t) lynx::compressorRenLaw] = 1.0f;
  7298. m16.push_back (ren); // [22]
  7299. auto ns1 = lynx::makeEffectSlot (lynx::EffectKind::quellDenoiser);
  7300. ns1.params[(std::size_t) lynx::voicetools::quell::ns1Law] = 1.0f;
  7301. m16.push_back (ns1); // [23]
  7302. auto splice = lynx::makeEffectSlot (lynx::EffectKind::geminiDoubler);
  7303. splice.params[(std::size_t) lynx::voicetools::gemini::spliceLaw] = 1.0f;
  7304. m16.push_back (splice); // [24]
  7305. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  7306. tune.params[(std::size_t) lynx::lynxtune::wavesLaw] = 1.0f;
  7307. m16.push_back (tune); // [25]
  7308. auto puig = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  7309. puig.params[(std::size_t) lynx::facet::puigLawParam] = lynx::facet::puigLawValue (2);
  7310. m16.push_back (puig); // [26]
  7311. lynx::Note repeated;
  7312. repeated.length = lynx::ppq;
  7313. repeated.channel = 0;
  7314. repeated.key = 60;
  7315. repeated.repeat = 9;
  7316. song.patterns[0].notes.push_back (repeated);
  7317. }
  7318. // rollup step 12 (round 190mu): round 190mm's Waves laws (Facet's Waves design law, Compressor's Vox / API-2500 /
  7319. // RChannel EQ, Prism's C6 floating bands, Hush's Renaissance law, Low Lifter's bass law, Aether's Vitamin law,
  7320. // Ridge's omni law), round 190mk's Multiband display SPEED and a zipped channel
  7321. {
  7322. auto& m16 = song.mixer[16].effects; // (after step 11's [18] … [26])
  7323. auto req = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  7324. req.params[(std::size_t) lynx::facet::wavesLawParam] = 1.0f;
  7325. req.params[(std::size_t) lynx::facet::wavesBandParam0] = lynx::facet::waveCodeValue (lynx::facet::WaveCode::reqBell);
  7326. m16.push_back (req); // [27]
  7327. auto vox = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  7328. vox.params[8] = 1.0f;
  7329. vox.params[(std::size_t) lynx::compressorVoxLaw] = 1.0f;
  7330. m16.push_back (vox); // [28]
  7331. auto api = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  7332. api.params[(std::size_t) lynx::compressorApiLaw] = 1.0f;
  7333. m16.push_back (api); // [29]
  7334. auto rchannel = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  7335. rchannel.params[(std::size_t) lynx::compressorRenLaw] = 1.0f;
  7336. rchannel.params[(std::size_t) lynx::compressorChannelLaw] = 1.0f;
  7337. m16.push_back (rchannel); // [30]
  7338. auto c6 = lynx::makeEffectSlot (lynx::EffectKind::prismMultiband);
  7339. c6.params[(std::size_t) lynx::dyn::prism::c4Law] = lynx::dyn::prism::c4LawValue (false);
  7340. c6.params[(std::size_t) lynx::dyn::prism::c6Param (1, lynx::dyn::prism::c6On)] = 1.0f;
  7341. m16.push_back (c6); // [31]
  7342. auto rdeesser = lynx::makeEffectSlot (lynx::EffectKind::hushDeEsser);
  7343. rdeesser.params[(std::size_t) lynx::mixsuite::hush::essLaw] = 1.0f;
  7344. m16.push_back (rdeesser); // [32]
  7345. auto maxx = lynx::makeEffectSlot (lynx::EffectKind::flLowLifter);
  7346. maxx.params[(std::size_t) lynx::lowlifter::bassLaw] = 1.0f;
  7347. m16.push_back (maxx); // [33]
  7348. auto vitamin = lynx::makeEffectSlot (lynx::EffectKind::aether);
  7349. vitamin.params[(std::size_t) lynx::mixsuite::aether::vitLaw] = 1.0f;
  7350. m16.push_back (vitamin); // [34]
  7351. auto scheps = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  7352. scheps.params[(std::size_t) lynx::mixsuite::ridge::omniLaw] = 1.0f;
  7353. m16.push_back (scheps); // [35]
  7354. auto multiband = lynx::makeEffectSlot (lynx::EffectKind::fruityMultiband);
  7355. multiband.displayView = 100;
  7356. m16.push_back (multiband); // [36]
  7357. song.channels[0].zipped = true;
  7358. }
  7359. // rollup step 13 (round 190na): round 190mt's Waves laws (Facet's API-560 law, Compressor's RVox type and gate,
  7360. // Ridge's G-Channel EQ law) and round 190mv's FL Current mixer track (round 190mr's window layout: below)
  7361. int currentAt = -1;
  7362. {
  7363. auto& m16 = song.mixer[16].effects; // (after step 12's [27] … [36])
  7364. auto api560 = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  7365. api560.params[(std::size_t) lynx::facet::api560LawParam] = 1.0f;
  7366. api560.params[(std::size_t) lynx::facet::api560GainParam0 + 3] = lynx::facet::api560GainValue (6.0);
  7367. m16.push_back (api560); // [37]
  7368. auto rch = lynx::makeEffectSlot (lynx::EffectKind::compressor);
  7369. rch.params[(std::size_t) lynx::compressorRenLaw] = 1.0f;
  7370. rch.params[(std::size_t) lynx::compressorRVoxType] = 1.0f;
  7371. rch.params[(std::size_t) lynx::compressorRchGate] = 1.0f;
  7372. m16.push_back (rch); // [38]
  7373. auto sslG = lynx::makeEffectSlot (lynx::EffectKind::ridgeStrip);
  7374. sslG.params[(std::size_t) lynx::mixsuite::ridge::gEqLaw] = 1.0f;
  7375. sslG.params[(std::size_t) lynx::mixsuite::ridge::gHfKHz] = 0.5f;
  7376. m16.push_back (sslG); // [39]
  7377. currentAt = lynx::mixerops::addCurrentTrack (song);
  7378. if (currentAt >= 0)
  7379. song.mixer[(std::size_t) currentAt].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::facetEq));
  7380. }
  7381. // rollup step 14 (round 190nf): round 190nb's Kilohearts law on Effector, round 190mx's launched pattern clip that
  7382. // plays its pattern's events (the grid's slot clip above plays pattern 1)
  7383. {
  7384. auto khs = lynx::makeEffectSlot (lynx::EffectKind::effector);
  7385. khs.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::resonator);
  7386. khs.params[(std::size_t) lynx::khsdsp::valueParam] = 0.5f;
  7387. song.mixer[16].effects.push_back (khs); // [40]
  7388. lynx::PatternEvents knob;
  7389. knob.target.kind = lynx::AutomationTargetKind::channelVolume;
  7390. knob.target.index = 0;
  7391. knob.events = { { 0, 0.2f }, { lynx::ppq, 0.8f } };
  7392. song.patterns[0].events.push_back (knob);
  7393. }
  7394. const auto copy = lynx::olderlynx::forRelease (song, "0.1.28");
  7395. juce::String why;
  7396. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  7397. const auto said = [&copy] (const char* start) {
  7398. return std::any_of (copy.lost.begin(), copy.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  7399. };
  7400. const auto parsed = juce::JSON::parse (copy.json);
  7401. const auto* channels = parsed["channels"].getArray();
  7402. bool fmEmpty = false, notesCut = true, waveDone = false, wtEmpty = false, loopKnob = false;
  7403. if (channels != nullptr)
  7404. for (const auto& c : *channels)
  7405. {
  7406. if (c["name"].toString() == "FM")
  7407. fmEmpty = c["instrument"].toString() == "sampler" && ! c.hasProperty ("modelParams");
  7408. if (c["name"].toString() == "WT")
  7409. wtEmpty = c["instrument"].toString() == "sampler" && ! c.hasProperty ("modelParams");
  7410. if (c["name"].toString() == "Loop")
  7411. loopKnob = std::abs ((double) c["samplerSettings"]["pitch"] - 5.0) < 1.0e-6 && ! c["samplerSettings"].hasProperty ("stretchPitch")
  7412. && (! c["samplerSettings"]["warpModes"].isArray() || c["samplerSettings"]["warpModes"].size() <= 10);
  7413. if (c["name"].toString() == "Piano")
  7414. {
  7415. juce::MemoryOutputStream bytes;
  7416. if (juce::Base64::convertFromBase64 (bytes, c["pluginState"].toString()))
  7417. {
  7418. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  7419. if (const auto st = lynx::dw::parseState (std::vector<std::uint8_t> (b, b + bytes.getDataSize())))
  7420. for (const auto& prog : st->programs)
  7421. for (const auto& z : prog.zones)
  7422. waveDone = waveDone || (z.loopMode == 2 && z.loopA == 44 && z.loopB == 200 && z.bits == 32);
  7423. if (const auto doc = lynx::dw::readDoc (std::vector<std::uint8_t> (b, b + bytes.getDataSize())))
  7424. for (const auto& n : doc->top)
  7425. for (const auto& z : n.kids)
  7426. for (const auto& r : z.kids)
  7427. if (r.id == 0x1F7)
  7428. waveDone = waveDone && r.body.size() == 40;
  7429. }
  7430. }
  7431. }
  7432. if (const auto* patterns = parsed["patterns"].getArray())
  7433. for (const auto& pt : *patterns)
  7434. if (const auto* notes = pt["notes"].getArray())
  7435. for (const auto& n : *notes)
  7436. notesCut = notesCut && n.size() <= 19;
  7437. if (! copy.ok || ! back)
  7438. rollup030Result = "ERROR copy " + why;
  7439. else if (! fmEmpty || ! said ("Tetra is not in this release"))
  7440. rollup030Result = "ERROR Tetra channel";
  7441. else if (! waveDone)
  7442. rollup030Result = "ERROR DirectWave short record";
  7443. else if (! notesCut || ! said ("{0} note(s) lose their MPE curves"))
  7444. rollup030Result = "ERROR note curves";
  7445. else if (back->blocks.size() != 1 || back->blocks[0].start != 0 || ! said ("{0} muted Pattern Block(s)"))
  7446. rollup030Result = "ERROR muted blocks";
  7447. else if (std::none_of (back->playlist.begin(), back->playlist.end(), [] (const lynx::Clip& c) { return c.pitch == 12.0f; })
  7448. || ! said ("{0} clip(s) transposed"))
  7449. rollup030Result = "ERROR clip pitch";
  7450. else if (copy.json.contains ("startMarker") || copy.json.contains ("clipScale") || ! said ("{0} clip slot(s) launch") || ! said ("Clip scales"))
  7451. rollup030Result = "ERROR clip slots";
  7452. else if (! said ("Voice Shift's Measured law") || ! said ("Ridge Strip's 4K Pink EQ") || ! said ("Hush De-esser's Allround mode")
  7453. || parsed["mixer"][1]["effects"][0]["params"].size() > lynx::voiceshift::revision
  7454. || parsed["mixer"][3]["effects"][0]["params"].size() > lynx::mixsuite::hush::timing)
  7455. rollup030Result = "ERROR effects";
  7456. else if (copy.json.contains ("mixSnapshots") || ! said ("Mix snapshots") || ! said ("Automation clip colours")
  7457. || std::any_of (back->automations.begin(), back->automations.end(), [] (const lynx::Automation& a) { return a.colour != 0; }))
  7458. rollup030Result = "ERROR view items";
  7459. else if (! wtEmpty || ! said ("Helix is not in this release"))
  7460. rollup030Result = "ERROR Helix channel";
  7461. else if (! said ("Echoform's echo voicings") || ! said ("Epoch Verb, Atrium, Foil Plate and Halo") || ! said ("Lattice Mod plays")
  7462. || ! said ("LuxeVerb's Space ducking")
  7463. || parsed["mixer"][4]["effects"][0]["params"].size() > lynx::echosuite::echoform::revision
  7464. || parsed["mixer"][5]["effects"][0]["params"].size() > lynx::verbs::halo::revision
  7465. || parsed["mixer"][6]["effects"][0]["params"].size() > lynx::echosuite::lattice::revision
  7466. || parsed["mixer"][7]["effects"][0]["params"].size() > lynx::luxeVerbSpaceDucking)
  7467. rollup030Result = "ERROR step-3 effects";
  7468. else if (! loopKnob || ! said ("Texture and Complex Pro play") || ! said ("Complex Pro and Texture transpositions") || ! said ("Warped samples do not follow"))
  7469. rollup030Result = juce::String ("ERROR warp engines ") + (loopKnob ? "" : "knob ") + (said ("Texture and Complex Pro play") ? "" : "engines ")
  7470. + (said ("Complex Pro and Texture transpositions") ? "" : "transpose ") + (said ("Warped samples do not follow") ? "" : "tempo");
  7471. else if (copy.json.contains ("\"inactive\"") || ! said ("{0} deactivated clip slot(s)"))
  7472. rollup030Result = "ERROR deactivated slots";
  7473. else if (! said ("Facet EQ's automatic dynamic thresholds") || parsed["mixer"][8]["effects"][0]["params"].size() > lynx::facet::autoThresholdParam0)
  7474. rollup030Result = "ERROR Facet automatic threshold";
  7475. else if (! said ("MIDI Out channels and plugins' MIDI output") || ! said ("Automation of hosted CLAP and VST3 plugins"))
  7476. rollup030Result = juce::String ("ERROR engine notes ") + (said ("MIDI Out channels") ? "" : "midi-out ") + (said ("Automation of hosted") ? "" : "timed");
  7477. else if (copy.json.contains ("playlistTrackNest") || copy.json.contains ("displayView") || ! said ("{0} track(s) in nested Playlist folders")
  7478. || ! said ("Fruity Limiter's CURVE view"))
  7479. rollup030Result = "ERROR step-4 view items";
  7480. else if (! said ("Hush De-esser's Single Vocal mode") || ! said ("Slide notes on FL's native generators"))
  7481. rollup030Result = juce::String ("ERROR step-5 engine notes ") + (said ("Hush De-esser's Single Vocal") ? "" : "hush ") + (said ("Slide notes") ? "" : "slides");
  7482. else if (! said ("The crossfader (Live's Crossfade Assign)") || ! said ("Live return tracks show") || ! said ("The Simple Controls tab's")
  7483. || copy.json.contains ("\"crossfade") || copy.json.contains ("liveReturn") || copy.json.contains ("returnPre")
  7484. || copy.json.contains ("smartControls") || copy.json.contains ("engineRev"))
  7485. rollup030Result = "ERROR step-6 mixer items";
  7486. else if (const auto nts = [&parsed] {
  7487. juce::MemoryOutputStream bytes;
  7488. std::vector<std::uint8_t> st;
  7489. if (juce::Base64::convertFromBase64 (bytes, parsed["mixer"][14]["effects"][0]["state"].toString()))
  7490. st.assign (static_cast<const std::uint8_t*> (bytes.getData()), static_cast<const std::uint8_t*> (bytes.getData()) + bytes.getDataSize());
  7491. return st;
  7492. }();
  7493. ! said ("Newtone's detected key") || lynx::newtonefx::nativeVersionOf (nts) != 2 || ! lynx::newtonefx::parseNative (nts)
  7494. || lynx::newtonefx::parseNative (nts)->pitches.size() != 1 || lynx::newtonefx::parseNative (nts)->pitches[0].curEnd != 24000)
  7495. rollup030Result = "ERROR step-6 Newtone state";
  7496. else if (! said ("The Peak Controller's LYNX LFO shapes") || ! said ("Crest Compressor's console law") || ! said ("Mixer lock states")
  7497. || ! said ("{0} imported take lane(s)")
  7498. || parsed["mixer"][15]["effects"][0]["params"].size() > lynx::peakshapes::extraShapeParam
  7499. || parsed["mixer"][16]["effects"][0]["params"].size() > lynx::dyn::crest::busLaw
  7500. || copy.json.contains ("lockState") || copy.json.contains ("playlistTakeLanes") || copy.json.contains ("recordOwnNotes"))
  7501. rollup030Result = "ERROR step-7 items";
  7502. else if (const auto& m16 = parsed["mixer"][16]["effects"];
  7503. ! said ("Crest Compressor's styles play their earlier laws") || ! said ("Crest Compressor's FET law")
  7504. || ! said ("Ridge Strip's measured SSL 4K G / 4K E filters") || ! said ("Echoform's Timeless 3 line law")
  7505. || ! said ("Lock states of effect slots and Playlist tracks") || copy.json.contains ("playlistTrackSoloLocks")
  7506. || m16[1]["params"].size() > lynx::dyn::crest::busLaw || m16[2]["params"].size() > lynx::dyn::crest::busLaw
  7507. || m16[3]["params"].size() > lynx::mixsuite::ridge::k4Pink || m16[4]["params"].size() > lynx::echosuite::echoform::revision)
  7508. rollup030Result = "ERROR step-8 items";
  7509. else if (const auto& m16 = parsed["mixer"][16]["effects"];
  7510. ! said ("Ember's Saturn styles") || ! said ("Prism Multiband's Pro-MB band law") || ! said ("The Limiter's L2 law")
  7511. || ! said ("Glow Leveler's cell law") || ! said ("Reeverb 2's measured direct sound") || ! said ("Quell's zero law")
  7512. || ! said ("Facet EQ's all-pass dispersion") || ! said ("Echoform's H-Delay loop law")
  7513. || ! said ("Notes on audio clip channels play cut") || copy.json.contains ("clipNotes190lq") || copy.json.contains ("clipNoteLegacy")
  7514. || m16[5]["params"].size() > lynx::mixsuite::ember::revision || m16[6]["params"].size() > lynx::dyn::prism::revision
  7515. || m16[7]["params"].size() > lynx::limiterlaw::lawParam || m16[8]["params"].size() > lynx::mixsuite::glow::cellLaw
  7516. || m16[9]["params"].size() > lynx::reeverb2DirectLaw || m16[10]["params"].size() > lynx::voicetools::quell::zeroLaw
  7517. || m16[11]["params"].size() > lynx::facet::autoThresholdParam0 || m16[12]["params"].size() > lynx::echosuite::echoform::revision)
  7518. rollup030Result = "ERROR step-9 items";
  7519. else if (const auto& m16 = parsed["mixer"][16]["effects"];
  7520. ! said ("Apex Limiter's styles") || ! said ("Sentry Gate plays its earlier") || ! said ("LuxeVerb's Space engine plays")
  7521. || ! said ("Echoform's ValhallaDelay loop law") || ! said ("Spiral Echo's Measured loop") || ! said ("{0} scene follow action")
  7522. || m16[13]["params"].size() > lynx::apex::pRevision || m16[14]["params"].size() > (int) lynx::dyn::sentry::revision
  7523. || m16[15]["params"].size() > lynx::luxeVerbSpaceDucking || m16[16]["params"].size() > lynx::echosuite::echoform::revision
  7524. || m16[17]["params"].size() > (int) lynx::echosuite::spiral::rateLaw || parsed["clipGrid"]["scenes"][0].hasProperty ("follow"))
  7525. rollup030Result = "ERROR step-10 items";
  7526. else if (const auto& m16 = parsed["mixer"][16]["effects"];
  7527. ! said ("Horizon plays its earlier") || ! said ("Nebula's classic modes") || ! said ("Orbit plays its own voices")
  7528. || ! said ("Prism Multiband's C4 law") || ! said ("Compressor's Renaissance law") || ! said ("Quell's NS1 law")
  7529. || ! said ("Gemini Doubler's splice law") || ! said ("LYNX Tune's Waves Tune") || ! said ("Facet EQ's PuigTec law")
  7530. || ! said ("{0} note(s) play once instead of repeating")
  7531. || m16[18]["params"].size() > lynx::verbs::horizon::revision || m16[19]["params"].size() > lynx::verbs::nebula::toneLaw
  7532. || m16[20]["params"].size() > (int) lynx::echosuite::orbit::smLaw || m16[21]["params"].size() > (int) lynx::dyn::prism::revision
  7533. || m16[22]["params"].size() > lynx::compressorRenLaw || m16[23]["params"].size() > (int) lynx::voicetools::quell::zeroLaw
  7534. || m16[24]["params"].size() > (int) lynx::voicetools::gemini::spliceLaw || m16[25]["params"].size() > (int) lynx::lynxtune::wavesLaw
  7535. || m16[26]["params"].size() > lynx::facet::autoThresholdParam0)
  7536. rollup030Result = "ERROR step-11 items";
  7537. else if (const auto& m16 = parsed["mixer"][16]["effects"];
  7538. ! said ("Facet EQ's Waves design law") || ! said ("Compressor's Vox law") || ! said ("Compressor's bus law")
  7539. || ! said ("Compressor's channel EQ") || ! said ("Prism Multiband's floating bands") || ! said ("Hush De-esser's Renaissance law")
  7540. || ! said ("Low Lifter's bass law") || ! said ("Aether's Vitamin law") || ! said ("Ridge Strip's omni law")
  7541. || ! said ("Fruity Multiband Compressor's display SPEED") || ! said ("{0} zipped channel(s)")
  7542. || m16[27]["params"].size() > lynx::facet::autoThresholdParam0 || m16[28]["params"].size() > lynx::compressorRenLaw
  7543. || m16[29]["params"].size() > lynx::compressorRenLaw || m16[30]["params"].size() > lynx::compressorRenLaw
  7544. || m16[31]["params"].size() > (int) lynx::dyn::prism::revision || m16[32]["params"].size() > (int) lynx::mixsuite::hush::timing
  7545. || m16[33]["params"].size() > (int) lynx::lowlifter::bassLaw || m16[34]["params"].size() > (int) lynx::mixsuite::aether::vitLaw
  7546. || m16[35]["params"].size() > (int) lynx::mixsuite::ridge::k4Pink || m16[36].hasProperty ("displayView")
  7547. || copy.json.contains ("\"zipped\""))
  7548. rollup030Result = "ERROR step-12 items";
  7549. else if (const auto& m16 = parsed["mixer"][16]["effects"];
  7550. ! said ("Facet EQ's API-560 law") || ! said ("Compressor's RVox type") || ! said ("Compressor's gate")
  7551. || ! said ("Ridge Strip's G-Channel EQ law") || ! said ("The Current mixer track shows as an ordinary insert")
  7552. || m16[37]["params"].size() > lynx::facet::autoThresholdParam0 || m16[38]["params"].size() > lynx::compressorRenLaw
  7553. || m16[39]["params"].size() > (int) lynx::mixsuite::ridge::k4Pink || currentAt < 0
  7554. || parsed["mixer"][currentAt].hasProperty ("current") || parsed["mixer"][currentAt]["effects"].size() != 1)
  7555. rollup030Result = "ERROR step-13 items";
  7556. else if (const auto laid = lynx::olderlynx::forRelease (lynx::ProjectFile::withWindowLayout (lynx::ProjectFile::toJson (lynx::Song::makeDefault()),
  7557. { 0, "rollup step 13" }), "0.1.28");
  7558. ! laid.ok || laid.json.contains ("windowLayout")
  7559. || std::none_of (laid.lost.begin(), laid.lost.end(), [] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith ("The window layout saved"); }))
  7560. rollup030Result = "ERROR step-13 window layout";
  7561. else if (const auto& m16 = parsed["mixer"][16]["effects"];
  7562. ! said ("Effector's Kilohearts laws") || ! said ("Launched pattern clips play without their pattern's events")
  7563. || m16[40]["params"].size() > lynx::khsdsp::lawParam || parsed["patterns"][0]["events"].size() != 1)
  7564. rollup030Result = juce::String ("ERROR step-14 items (") + (said ("Effector's Kilohearts laws") ? "" : "no Kilohearts line, ")
  7565. + (said ("Launched pattern clips play without their pattern's events") ? "" : "no launched-clip line, ")
  7566. + "Effector params " + juce::String (m16[40]["params"].size()) + ", events " + juce::String (parsed["patterns"][0]["events"].size()) + ")";
  7567. else if (const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.28");
  7568. ! plain.ok || std::any_of (plain.lost.begin(), plain.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  7569. const auto t = juce::String (l.text);
  7570. return t.startsWith ("Tetra") || t.contains ("MPE") || t.contains ("Pattern Block") || t.contains ("Voice Shift")
  7571. || t.contains ("Ridge") || t.contains ("Hush") || t.startsWith ("Automation clip colours") || t.startsWith ("Mix snapshots")
  7572. || t.startsWith ("Helix") || t.contains ("Echoform") || t.contains ("Halo") || t.contains ("Lattice") || t.contains ("LuxeVerb")
  7573. || t.contains ("Texture") || t.contains ("Beats'") || t.startsWith ("Warped") || t.contains ("deactivated")
  7574. || t.contains ("Facet") || t.contains ("MIDI Out") || t.contains ("hosted CLAP") || t.contains ("nested Playlist")
  7575. || t.contains ("CURVE") || t.startsWith ("Slide notes") || t.contains ("crossfader") || t.contains ("return tracks")
  7576. || t.contains ("Controls tab") || t.startsWith ("Harmor") || t.startsWith ("Newtone")
  7577. || t.contains ("Peak Controller") || t.contains ("console law") || t.startsWith ("Mixer lock") || t.contains ("take lane")
  7578. || t.contains ("Crest") || t.startsWith ("Lock states") || t.startsWith ("Ember") || t.startsWith ("Prism")
  7579. || t.contains ("L2 law") || t.startsWith ("Glow") || t.startsWith ("Reeverb 2") || t.startsWith ("Quell")
  7580. || t.contains ("audio clip channels") || t.startsWith ("Apex") || t.startsWith ("Sentry") || t.startsWith ("Spiral")
  7581. || t.contains ("scene follow") || t.startsWith ("Horizon") || t.startsWith ("Nebula") || t.startsWith ("Orbit")
  7582. || t.startsWith ("Compressor's") || t.startsWith ("Gemini") || t.startsWith ("LYNX Tune") || t.contains ("Repeat")
  7583. || t.startsWith ("Low Lifter") || t.startsWith ("Aether") || t.startsWith ("Ridge Strip's omni") || t.startsWith ("Hush De-esser's Renaissance")
  7584. || t.startsWith ("Fruity Multiband") || t.contains ("zipped") || t.contains ("Current mixer track") || t.contains ("window layout")
  7585. || t.startsWith ("Effector's Kilohearts") || t.startsWith ("Launched pattern clips");
  7586. }))
  7587. rollup030Result = "ERROR a plain project reports a loss it does not have";
  7588. }
  7589. // 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
  7590. // 0.1.31 rounds save (190ni LYNX Model, 190nh Kilohearts part-2 laws, 190ne track clips, 190nc Solo / Cue); round
  7591. // 190nb's laws (0.1.30 has them) stay; the copy for 0.1.28 runs this step first; a plain project loses nothing
  7592. juce::String rollup031Result = "OK";
  7593. {
  7594. auto song = lynx::Song::makeDefault();
  7595. lynx::ChannelDef model;
  7596. model.name = "Bars";
  7597. model.instrument = lynx::InstrumentKind::lynxModel;
  7598. model.modelParams = { 0.0f, 0.5f, 0.3f };
  7599. song.channels.push_back (model);
  7600. auto comb = lynx::makeEffectSlot (lynx::EffectKind::effector);
  7601. comb.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::comb);
  7602. comb.params[(std::size_t) lynx::khsdsp::valueParam] = 0.4f;
  7603. auto resonator = lynx::makeEffectSlot (lynx::EffectKind::effector);
  7604. resonator.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::resonator);
  7605. resonator.params[(std::size_t) lynx::khsdsp::valueParam] = 0.5f;
  7606. song.mixer[3].effects.push_back (comb); // [0]
  7607. song.mixer[3].effects.push_back (resonator); // [1]
  7608. song.patterns[0].trackClip = true;
  7609. if (song.playlistTracks.empty())
  7610. song.playlistTracks.resize (1);
  7611. song.playlistTracks[0].ownClips = true;
  7612. lynx::launcher::ensureGrid (song);
  7613. song.clipGrid->cue.cueMode = true;
  7614. song.clipGrid->cue.out = 2;
  7615. song.mixer[2].cue = true;
  7616. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  7617. const auto older = lynx::olderlynx::forRelease (song, "0.1.28");
  7618. juce::String why;
  7619. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  7620. const auto count = [] (const lynx::olderlynx::Copy& c, const char* start) {
  7621. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  7622. };
  7623. const auto parsed = juce::JSON::parse (copy.json);
  7624. const auto& fx = parsed["mixer"][3]["effects"];
  7625. juce::String bars;
  7626. if (const auto* channels = parsed["channels"].getArray())
  7627. for (const auto& c : *channels)
  7628. if (c["name"].toString() == "Bars")
  7629. bars = c["instrument"].toString() + (c.hasProperty ("modelParams") ? "+params" : "");
  7630. const char* lines[] = { "LYNX Model is not in this release", "Effector's newer Kilohearts laws", "{0} track clip(s) show as ordinary patterns",
  7631. "Live's Solo/Cue settings" };
  7632. if (! copy.ok || ! back)
  7633. rollup031Result = "ERROR copy " + copy.error + why;
  7634. else if (! parsed["savedBy"].toString().equalsIgnoreCase ("0.1.30") || lynx::olderlynx::releases()[0] != "0.1.30")
  7635. rollup031Result = "ERROR release list / stamp";
  7636. else if (bars != "sampler")
  7637. rollup031Result = "ERROR LYNX Model channel: " + bars;
  7638. else if (fx[0]["params"].size() > lynx::khsdsp::lawParam || fx[1]["params"].size() <= lynx::khsdsp::lawParam
  7639. || lynx::khsdsp::lawOf ((float) (double) fx[1]["params"][lynx::khsdsp::lawParam]) != lynx::khsdsp::Law::resonator)
  7640. rollup031Result = "ERROR Kilohearts laws (comb params " + juce::String (fx[0]["params"].size()) + ")";
  7641. else if (copy.json.contains ("\"trackClip\"") || copy.json.contains ("playlistOwnClips") || parsed["clipGrid"].hasProperty ("cue")
  7642. || parsed["mixer"][2].hasProperty ("cue"))
  7643. rollup031Result = "ERROR 0.1.31 keys left in the copy";
  7644. else if (std::any_of (std::begin (lines), std::end (lines), [&] (const char* l) { return count (copy, l) != 1 || count (older, l) != 1; }))
  7645. rollup031Result = "ERROR loss lines (each once, in both copies)";
  7646. else if (! older.ok || older.json.contains ("lynxmodel") || juce::JSON::parse (older.json)["mixer"][3]["effects"][1]["params"].size() > lynx::khsdsp::lawParam
  7647. || count (older, "Effector's Kilohearts laws") != 1)
  7648. rollup031Result = "ERROR copy for 0.1.28 after the 0.1.30 step";
  7649. else if (const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30"); ! plain.ok || ! plain.lost.empty())
  7650. rollup031Result = "ERROR a plain project loses something in the copy for 0.1.30";
  7651. }
  7652. // 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 —
  7653. // 190ns's Created date (#231, ProjectInfo.created: 0.1.30 reads it), its linked audio track ⇄ insert names and
  7654. // colours (#235: the same mixerTrack / name / colour fields; only the syncing is new), 190nq's "(target deleted)"
  7655. // automation names (#226: text) — and 190np's onboarding, 190nq's ruler / fade switches and 190nr's installed-files
  7656. // list live in the profile, never in a project. Checked: the copy keeps them, reports no loss and has every key of
  7657. // the project (the copy keeps every key the project has, none dropped or renamed)
  7658. juce::String rollup031s2Result = "OK";
  7659. {
  7660. auto song = lynx::Song::makeDefault();
  7661. song.info.created = 1763600000.0;
  7662. if (song.mixer.size() < 3)
  7663. song.mixer.resize (3);
  7664. song.playlistTracks.resize (std::max<std::size_t> (2, song.playlistTracks.size()));
  7665. auto& vox = song.playlistTracks[1];
  7666. vox.mode = lynx::PlaylistTrackMode::audio;
  7667. vox.mixerTrack = 2;
  7668. vox.name = song.mixer[2].name = "Vox";
  7669. vox.colour = song.mixer[2].colour = 0xff8040c0;
  7670. song.patterns[0].name = lynx::mixerops::targetDeletedName ("BEAT BUS - Send level");
  7671. const auto keysOf = [] (const juce::var& v) {
  7672. std::set<juce::String> keys;
  7673. std::function<void (const juce::var&, const juce::String&)> walk = [&] (const juce::var& x, const juce::String& path) {
  7674. if (auto* o = x.getDynamicObject())
  7675. for (const auto& p : o->getProperties())
  7676. {
  7677. if (path.isEmpty() && (p.name.toString() == "savedBy" || p.name.toString() == "copiedFrom")) // (the copy's stamp)
  7678. continue;
  7679. keys.insert (path + "/" + p.name.toString());
  7680. walk (p.value, path + "/" + p.name.toString());
  7681. }
  7682. else if (auto* a = x.getArray())
  7683. for (const auto& e : *a)
  7684. walk (e, path + "[]");
  7685. };
  7686. walk (v, {});
  7687. return keys;
  7688. };
  7689. const auto original = juce::JSON::parse (lynx::ProjectFile::toJson (song));
  7690. for (const auto* release : { "0.1.30", "0.1.28" })
  7691. {
  7692. const auto copy = lynx::olderlynx::forRelease (song, release);
  7693. juce::String why;
  7694. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  7695. if (! copy.ok || ! back)
  7696. rollup031s2Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  7697. else if (back->info.created != song.info.created)
  7698. rollup031s2Result = juce::String ("ERROR Created date in the copy for ") + release;
  7699. else if (back->playlistTracks.size() < 2 || back->playlistTracks[1].mixerTrack != 2 || back->playlistTracks[1].colour != vox.colour
  7700. || back->playlistTracks[1].name != "Vox" || back->mixer[2].colour != vox.colour || back->mixer[2].name != "Vox")
  7701. rollup031s2Result = juce::String ("ERROR linked track / insert in the copy for ") + release;
  7702. else if (back->patterns[0].name != song.patterns[0].name)
  7703. rollup031s2Result = juce::String ("ERROR automation name in the copy for ") + release;
  7704. else if (! copy.lost.empty())
  7705. rollup031s2Result = juce::String ("ERROR loss lines in the copy for ") + release + ": " + juce::String (copy.lost.front().text);
  7706. else if (const auto kept = keysOf (juce::JSON::parse (copy.json)), all = keysOf (original); juce::String (release) == "0.1.30" && kept != all)
  7707. {
  7708. juce::StringArray diff;
  7709. for (const auto& k : all)
  7710. if (kept.count (k) == 0)
  7711. diff.add ("-" + k);
  7712. for (const auto& k : kept)
  7713. if (all.count (k) == 0)
  7714. diff.add ("+" + k);
  7715. rollup031s2Result = "ERROR keys differ in the copy for 0.1.30: " + diff.joinIntoString (" ").substring (0, 300);
  7716. }
  7717. if (rollup031s2Result != "OK")
  7718. break;
  7719. }
  7720. }
  7721. // 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
  7722. // else — 190nu's key markers' keys ("markerKeys" beside each pattern's marker list; the markers and their names
  7723. // stay) and 190nw's tracker view settings (root "tracker"; the notes are the patterns' own) — each with its one
  7724. // line, in both copies; 190nx (offline switch, --demo) and 190nt (site) save nothing in a project
  7725. juce::String rollup031s3Result = "OK";
  7726. {
  7727. using namespace lynx::keyregions;
  7728. auto song = lynx::Song::makeDefault();
  7729. auto& p = song.patterns[(std::size_t) song.currentPattern];
  7730. p.markers.push_back ({ 2 * lynx::ppq, "Verse", 0, 4 });
  7731. addKeyMarker (p, 0, { State::key, { 9, flScaleNamed ("Minor Harmonic") } });
  7732. addKeyMarker (p, 4 * lynx::ppq, { State::key, { 2, flScaleNamed ("Other Dorian") } });
  7733. for (int c = 0; c < 2; ++c)
  7734. song.channels.emplace_back().name = "S3-" + std::to_string (c);
  7735. lynx::uids::normalize (song);
  7736. song.tracker.rowsPerBeat = 6;
  7737. song.tracker.showPan = true;
  7738. song.tracker.groups.push_back ({ "Pair", { song.channels[song.channels.size() - 2].uid, song.channels.back().uid } });
  7739. const auto keysOf = [] (const juce::var& v) {
  7740. std::set<juce::String> keys;
  7741. std::function<void (const juce::var&, const juce::String&)> walk = [&] (const juce::var& x, const juce::String& path) {
  7742. if (auto* o = x.getDynamicObject())
  7743. for (const auto& prop : o->getProperties())
  7744. {
  7745. if (path.isEmpty() && (prop.name.toString() == "savedBy" || prop.name.toString() == "copiedFrom")) // (the copy's stamp)
  7746. continue;
  7747. keys.insert (path + "/" + prop.name.toString());
  7748. walk (prop.value, path + "/" + prop.name.toString());
  7749. }
  7750. else if (auto* a = x.getArray())
  7751. for (const auto& e : *a)
  7752. walk (e, path + "[]");
  7753. };
  7754. walk (v, {});
  7755. return keys;
  7756. };
  7757. const auto json = lynx::ProjectFile::toJson (song);
  7758. auto expected = keysOf (juce::JSON::parse (json));
  7759. for (auto it = expected.begin(); it != expected.end();)
  7760. it = it->startsWith ("/tracker") || it->contains ("/markerKeys") ? expected.erase (it) : std::next (it);
  7761. const char* lines[] = { "key marker(s) in the Piano roll", "The tracker's view settings" };
  7762. for (const auto* release : { "0.1.30", "0.1.28" })
  7763. {
  7764. const auto copy = lynx::olderlynx::forRelease (song, release);
  7765. juce::String why;
  7766. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  7767. const auto count = [&copy] (const char* l) {
  7768. return (int) std::count_if (copy.lost.begin(), copy.lost.end(), [l] (const lynx::olderlynx::Loss& x) { return juce::String (x.text).contains (l); });
  7769. };
  7770. if (! copy.ok || ! back)
  7771. rollup031s3Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  7772. else if (copy.json.contains ("markerKeys") || copy.json.contains ("\"tracker\""))
  7773. rollup031s3Result = juce::String ("ERROR 0.1.31 keys left in the copy for ") + release;
  7774. else if (std::any_of (std::begin (lines), std::end (lines), [&] (const char* l) { return count (l) != 1; }))
  7775. rollup031s3Result = juce::String ("ERROR loss lines in the copy for ") + release + " (" + juce::String ((int) copy.lost.size()) + ")";
  7776. else if (const auto& bp = back->patterns[(std::size_t) back->currentPattern];
  7777. bp.markers.size() != p.markers.size() || bp.notes != p.notes
  7778. || std::any_of (bp.markers.begin(), bp.markers.end(), [] (const lynx::Marker& m) { return keyOf (m).has_value(); }))
  7779. rollup031s3Result = juce::String ("ERROR markers / notes in the copy for ") + release;
  7780. else if (juce::String (release) == "0.1.30" && (copy.lost.size() != 2 || keysOf (juce::JSON::parse (copy.json)) != expected))
  7781. rollup031s3Result = "ERROR the copy for 0.1.30 drops more than the two (" + juce::String ((int) copy.lost.size()) + " lines)";
  7782. if (rollup031s3Result != "OK")
  7783. break;
  7784. }
  7785. }
  7786. // round chord2_190nu (discussion #105): the Piano roll's key markers come back from a project (their keys beside the
  7787. // marker list, so older releases keep the markers), the copy for 0.1.30 / 0.1.28 drops the keys with a line, and
  7788. // a MIDI file carries them as key signatures (with the exact scale in a "Key: ..." marker meta event)
  7789. juce::String keys190nuResult = "OK";
  7790. {
  7791. using namespace lynx::keyregions;
  7792. auto song = lynx::Song::makeDefault();
  7793. auto& p = song.patterns[(std::size_t) song.currentPattern];
  7794. const auto bar = 4 * lynx::ppq;
  7795. const lynx::projectkey::Key dorian { 2, flScaleNamed ("Other Dorian") }, harmonic { 0, flScaleNamed ("Minor Harmonic") };
  7796. p.markers.push_back ({ bar / 2, "Verse", 0, 4 });
  7797. addKeyMarker (p, 0, { State::key, dorian });
  7798. addKeyMarker (p, bar, { State::key, harmonic });
  7799. addKeyMarker (p, 2 * bar, { State::none, {} });
  7800. lynx::Note n;
  7801. n.key = 62;
  7802. n.length = lynx::ppq;
  7803. p.notes.push_back (n);
  7804. p.lengthTicks = 3 * bar; // (a MIDI file gets the key changes within the pattern's length)
  7805. juce::String why;
  7806. const auto json = lynx::ProjectFile::toJson (song);
  7807. const auto back = lynx::ProjectFile::fromJson (json, why);
  7808. bool oldShape = true; // (every marker array as 0.1.30 reads it: 4 or 5 items)
  7809. const auto parsedJson = juce::JSON::parse (json); // (kept: operator[] refers into it)
  7810. if (auto* patterns = parsedJson["patterns"].getArray())
  7811. for (const auto& pv : *patterns)
  7812. if (auto* ms = pv["markers"].getArray())
  7813. for (const auto& m : *ms)
  7814. oldShape = oldShape && m.isArray() && (m.size() == 4 || m.size() == 5);
  7815. const auto for130 = lynx::olderlynx::forRelease (song, "0.1.30");
  7816. const auto for128 = lynx::olderlynx::forRelease (song, "0.1.28");
  7817. const auto copy130 = for130.ok ? lynx::ProjectFile::fromJson (for130.json, why) : std::optional<lynx::Song> {};
  7818. 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)"); });
  7819. const auto file = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-keys190nu.mid");
  7820. juce::String midiError;
  7821. const auto saved = lynx::MidiFileIo::savePattern (song, song.currentPattern, file, midiError);
  7822. const auto parsed = saved ? lynx::MidiFileIo::parseFile (file, midiError) : std::nullopt;
  7823. const auto loaded = saved ? lynx::MidiFileIo::loadSong (file, midiError) : std::nullopt;
  7824. file.deleteFile();
  7825. const auto& bp = back ? back->patterns[(std::size_t) back->currentPattern] : p;
  7826. if (! back || bp.markers != p.markers)
  7827. keys190nuResult = "ERROR project round trip " + why;
  7828. else if (! oldShape)
  7829. keys190nuResult = "ERROR marker arrays an older release skips";
  7830. else if (! copy130 || for130.json.contains ("markerKeys") || ! said || ! for128.ok || for128.json.contains ("markerKeys"))
  7831. keys190nuResult = "ERROR copy for 0.1.30 / 0.1.28";
  7832. else if (const auto& cp = copy130->patterns[(std::size_t) copy130->currentPattern];
  7833. cp.markers.size() != 4 || cp.markers[0].name != "D Other Dorian" || cp.markers[0].action != lynx::Marker::keyScale || keyOf (cp.markers[0]))
  7834. keys190nuResult = "ERROR the copy's markers";
  7835. else if (! parsed || parsed->keys.size() != 2 || parsed->keys[0].tick != 0 || parsed->keys[0].flScale != dorian.flScale || parsed->keys[0].root != 2
  7836. || parsed->keys[1].tick != bar || parsed->keys[1].flScale != harmonic.flScale)
  7837. keys190nuResult = "ERROR MIDI key signatures " + midiError;
  7838. else if (! loaded || ! (lynx::projectkey::get (*loaded) == dorian) || ! (stateAt (loaded->patterns[0], bar).value == harmonic))
  7839. keys190nuResult = "ERROR MIDI file opened as a project " + midiError;
  7840. }
  7841. // 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
  7842. // or reverse grains play) and the Kilohearts Nonlinear Filter law (code 49, its own loss line); the copy for 0.1.28
  7843. // still turns Helix into an empty Sampler after it; a Helix channel of revision 4 at the block's defaults loses nothing
  7844. juce::String helix4khs190ocResult = "OK";
  7845. {
  7846. auto song = lynx::Song::makeDefault();
  7847. if (song.mixer.size() < 3)
  7848. song.mixer.resize (3);
  7849. lynx::ChannelDef plain, swarm;
  7850. plain.name = "Plain", swarm.name = "Swarm";
  7851. plain.instrument = swarm.instrument = lynx::InstrumentKind::helix;
  7852. const auto d = lynx::helixDefaults();
  7853. plain.modelParams = swarm.modelParams = d;
  7854. swarm.modelParams[(std::size_t) (lynx::wt::ext4Base + lynx::wt::ext4::grainUnison)] = 5.0f;
  7855. swarm.modelParams[(std::size_t) (lynx::wt::ext4Base + lynx::wt::ext4::grainReverse)] = 0.4f;
  7856. song.channels.push_back (plain);
  7857. song.channels.push_back (swarm);
  7858. auto nlf = lynx::makeEffectSlot (lynx::EffectKind::effector);
  7859. nlf.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::nonlinearFilter);
  7860. nlf.params[(std::size_t) lynx::khsdsp::valueParam + 2] = 0.5f;
  7861. song.mixer[2].effects.push_back (nlf);
  7862. const auto copy = lynx::olderlynx::forRelease (song, "0.1.30");
  7863. const auto older = lynx::olderlynx::forRelease (song, "0.1.28");
  7864. const auto count = [] (const lynx::olderlynx::Copy& c, const char* start) {
  7865. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  7866. };
  7867. const auto parsed = juce::JSON::parse (copy.json);
  7868. int helixCut = 0, revisions3 = 0;
  7869. juce::String lossDetail;
  7870. for (const auto& l : copy.lost)
  7871. if (juce::String (l.text).startsWith ("Helix's unison"))
  7872. lossDetail = l.detail;
  7873. if (const auto* channels = parsed["channels"].getArray())
  7874. for (const auto& c : *channels)
  7875. if (c["instrument"].toString() == "helix")
  7876. {
  7877. auto values = juce::StringArray::fromTokens (c["modelParams"].toString(), " ", "");
  7878. values.removeEmptyStrings();
  7879. helixCut += values.size() == lynx::wt::ext4Base ? 1 : 0;
  7880. revisions3 += values.size() > lynx::wt::extBase && values[lynx::wt::extBase].getFloatValue() == 3.0f ? 1 : 0;
  7881. }
  7882. if (! copy.ok || ! older.ok)
  7883. helix4khs190ocResult = "ERROR copy " + copy.error + older.error;
  7884. else if (helixCut != 2 || revisions3 != 2)
  7885. helix4khs190ocResult = "ERROR Helix block in the copy (cut " + juce::String (helixCut) + ", revision 3 " + juce::String (revisions3) + ")";
  7886. else if (count (copy, "Helix's unison") != 1 || ! lossDetail.contains ("Swarm") || lossDetail.contains ("Plain"))
  7887. helix4khs190ocResult = "ERROR Helix loss line: " + lossDetail;
  7888. else if (parsed["mixer"][2]["effects"][0]["params"].size() > lynx::khsdsp::lawParam || count (copy, "Effector's Kilohearts Nonlinear Filter") != 1
  7889. || count (copy, "Effector's newer Kilohearts laws") != 0)
  7890. helix4khs190ocResult = "ERROR Nonlinear Filter law in the copy";
  7891. else if (older.json.contains ("\"helix\"") || count (older, "Helix is not in this release") != 1)
  7892. helix4khs190ocResult = "ERROR copy for 0.1.28 after the 0.1.30 step";
  7893. }
  7894. // 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:
  7895. // 190oc's Helix round-4 block and Effector law 49 (each one line), 190od's slide of the note properties (#236: the
  7896. // key goes; one line counting only slide notes that move something), 190od's #239 colours and icons by name and a
  7897. // #238 "no colour" channel (ordinary project data: kept as they are), 190nz's clipboard (no project data), 190oa's
  7898. // main (monitor) volume and Gross Beat's scratch offset (merge 4; its window places are not in a copy: the copy is
  7899. // the song's JSON without the window layout). The 0.1.30 copy keeps every key but "slideNoteProps" and "mainVolume";
  7900. // a project whose slide notes move nothing, or saved before #236, gets no slide line
  7901. juce::String rollup031s4Result = "OK";
  7902. {
  7903. auto song = lynx::Song::makeDefault();
  7904. if (song.mixer.size() < 3)
  7905. song.mixer.resize (3);
  7906. song.slideNoteProps = true;
  7907. lynx::ChannelDef bass, lead, swarm, plain;
  7908. bass.name = "Bass 808", lead.name = "Lead", swarm.name = "Swarm", plain.name = "No colour";
  7909. swarm.instrument = lynx::InstrumentKind::helix;
  7910. swarm.modelParams = lynx::helixDefaults();
  7911. swarm.modelParams[(std::size_t) (lynx::wt::ext4Base + lynx::wt::ext4::specUnison)] = 4.0f;
  7912. for (auto* c : { &bass, &lead, &swarm, &plain })
  7913. song.channels.push_back (*c);
  7914. const int bassIndex = (int) song.channels.size() - 4, leadIndex = bassIndex + 1;
  7915. auto nlf = lynx::makeEffectSlot (lynx::EffectKind::effector);
  7916. nlf.params[(std::size_t) lynx::khsdsp::lawParam] = lynx::khsdsp::lawValue (lynx::khsdsp::Law::nonlinearFilter);
  7917. song.mixer[2].effects.push_back (nlf);
  7918. // merge 4 (190oa): the toolbar's main (monitor) volume off 0 dB and Gross Beat's scratch offset set (DF-21, DP-8)
  7919. song.mainVolume = 0.5f;
  7920. auto gross = lynx::makeEffectSlot (lynx::EffectKind::grossBeat);
  7921. gross.params[8] = 0.25f;
  7922. song.mixer[2].effects.push_back (gross);
  7923. lynx::autolook::Rules rules;
  7924. rules.on = true;
  7925. rules.list.push_back ({ "bass", lynx::autolook::Match::contains, 0xFF2266AAu, 7, lynx::autolook::everything });
  7926. const auto coloured = lynx::autolook::applyAll (song, rules);
  7927. auto& p = song.patterns[(std::size_t) song.currentPattern];
  7928. const auto note = [] (int channel, juce::int64 start, int key, float velocity, float pan, bool slide) {
  7929. lynx::Note n;
  7930. n.channel = channel, n.start = start, n.length = lynx::ppq, n.key = key, n.velocity = velocity, n.pan = pan, n.slide = slide;
  7931. return n;
  7932. };
  7933. p.notes.push_back (note (bassIndex, 0, 36, 0.78f, 0.0f, false));
  7934. p.notes.push_back (note (bassIndex, lynx::ppq / 2, 43, 0.3f, 0.0f, true)); // moves the velocity
  7935. p.notes.push_back (note (bassIndex, lynx::ppq, 41, 0.78f, -0.5f, true)); // moves the pan
  7936. p.notes.push_back (note (leadIndex, 0, 60, 0.78f, 0.0f, false));
  7937. p.notes.push_back (note (leadIndex, lynx::ppq / 2, 64, 0.78f, 0.0f, true)); // pitch only: sounds the same in 0.1.30
  7938. p.sortNotes(); // (the order a project reads back in)
  7939. lynx::uids::normalize (song);
  7940. const auto keysOf = [] (const juce::var& v) {
  7941. std::set<juce::String> keys;
  7942. std::function<void (const juce::var&, const juce::String&)> walk = [&] (const juce::var& x, const juce::String& path) {
  7943. if (auto* o = x.getDynamicObject())
  7944. for (const auto& prop : o->getProperties())
  7945. {
  7946. if (path.isEmpty() && (prop.name.toString() == "savedBy" || prop.name.toString() == "copiedFrom"))
  7947. continue;
  7948. keys.insert (path + "/" + prop.name.toString());
  7949. walk (prop.value, path + "/" + prop.name.toString());
  7950. }
  7951. else if (auto* a = x.getArray())
  7952. for (const auto& e : *a)
  7953. walk (e, path + "[]");
  7954. };
  7955. walk (v, {});
  7956. return keys;
  7957. };
  7958. auto expected = keysOf (juce::JSON::parse (lynx::ProjectFile::toJson (song)));
  7959. const auto hadKey = expected.erase ("/slideNoteProps") == 1 && expected.erase ("/mainVolume") == 1;
  7960. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* start) {
  7961. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  7962. };
  7963. const char* slideLine = "{0} slide note(s) move only the pitch";
  7964. if (coloured != 1 || ! hadKey)
  7965. rollup031s4Result = "ERROR set-up (coloured " + juce::String (coloured) + ")";
  7966. for (const auto* release : { "0.1.30", "0.1.28" })
  7967. {
  7968. if (rollup031s4Result != "OK")
  7969. break;
  7970. const auto copy = lynx::olderlynx::forRelease (song, release);
  7971. juce::String why;
  7972. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  7973. juce::String slideDetail;
  7974. for (const auto& l : copy.lost)
  7975. if (juce::String (l.text).startsWith (slideLine))
  7976. slideDetail = l.detail;
  7977. const auto is130 = juce::String (release) == "0.1.30";
  7978. if (! copy.ok || ! back)
  7979. rollup031s4Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  7980. else if (copy.json.contains ("slideNoteProps") || back->slideNoteProps)
  7981. rollup031s4Result = juce::String ("ERROR slideNoteProps left in the copy for ") + release;
  7982. else if (countOf (copy, slideLine) != 1 || slideDetail != "2")
  7983. rollup031s4Result = juce::String ("ERROR the slide line in the copy for ") + release + " (" + slideDetail + ")";
  7984. else if (countOf (copy, "Effector's Kilohearts Nonlinear Filter") != 1 || (is130 && countOf (copy, "Helix's unison") != 1)
  7985. || (! is130 && countOf (copy, "Helix is not in this release") != 1))
  7986. rollup031s4Result = juce::String ("ERROR 190oc's lines in the copy for ") + release;
  7987. else if (countOf (copy, "The main (monitor) volume") != 1 || countOf (copy, "Gross Beat's scratch offset") != 1
  7988. || copy.json.contains ("mainVolume") || juce::JSON::parse (copy.json)["mixer"][2]["effects"][1]["params"].size() != 8)
  7989. rollup031s4Result = juce::String ("ERROR 190oa's main volume / Gross Beat offset in the copy for ") + release;
  7990. else if (back->patterns[(std::size_t) back->currentPattern].notes != p.notes)
  7991. rollup031s4Result = juce::String ("ERROR the notes in the copy for ") + release;
  7992. else if (back->channels[(std::size_t) bassIndex].colour != 0xFF2266AAu || back->channels[(std::size_t) bassIndex].icon != 7
  7993. || back->channels[(std::size_t) bassIndex + 3].colour != 0 || back->channels[(std::size_t) leadIndex].colour != song.channels[(std::size_t) leadIndex].colour)
  7994. rollup031s4Result = juce::String ("ERROR #239 / #238 colours in the copy for ") + release;
  7995. else if (is130 && (copy.lost.size() != 5 || keysOf (juce::JSON::parse (copy.json)) != expected))
  7996. rollup031s4Result = "ERROR the copy for 0.1.30 drops more than step 4's five (" + juce::String ((int) copy.lost.size()) + " lines)";
  7997. }
  7998. // slide notes that move nothing, and a project saved before #236 (key off): no slide line
  7999. if (rollup031s4Result == "OK")
  8000. {
  8001. auto still = song;
  8002. auto& sp = still.patterns[(std::size_t) still.currentPattern];
  8003. 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());
  8004. auto before = song;
  8005. before.slideNoteProps = false;
  8006. const auto a = lynx::olderlynx::forRelease (still, "0.1.30"), b = lynx::olderlynx::forRelease (before, "0.1.30");
  8007. if (! a.ok || ! b.ok || countOf (a, slideLine) != 0 || countOf (b, slideLine) != 0)
  8008. rollup031s4Result = "ERROR a slide line where nothing moves";
  8009. }
  8010. }
  8011. // 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
  8012. // (plain markers at their starts, one view line); 190ol's Simple time signature changes (ordinary signature markers
  8013. // 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
  8014. // dropped, one view line naming both); gap190og's transport mappings (the Overdub key mapping dropped with a line,
  8015. // the Play one kept); 190ob's tracker volume automation (a channel Volume multiplier clip: kept point for point);
  8016. // 190on's stacked lanes and palette are profile settings and 190og's .flm export keeps no settings (the song is the
  8017. // same after an export). The 0.1.30 copy keeps every key but the three dropped ones and has exactly three lines
  8018. juce::String rollup031s5Result = "OK";
  8019. {
  8020. auto song = lynx::Song::makeDefault();
  8021. if (song.mixer.size() < 3)
  8022. song.mixer.resize (3);
  8023. // 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:
  8024. // a signature marker)
  8025. lynx::sections::add (song, "Intro");
  8026. lynx::sections::add (song, "Verse");
  8027. lynx::signatureedit::set (song, 0, 5, 1);
  8028. lynx::signatureedit::set (song, song.barAt (0).tick + 8 * 5 * lynx::ppq * 4, 7, 8);
  8029. std::vector<lynx::Marker> signatures;
  8030. for (const auto& m : song.markers())
  8031. if (m.isSignature())
  8032. signatures.push_back (m);
  8033. // 190oh: a plugin channel with DPI aware off, an insert plugin with Scale editor dimensions on
  8034. lynx::ChannelDef synth;
  8035. synth.name = "Old Synth";
  8036. synth.instrument = lynx::InstrumentKind::plugin;
  8037. synth.plugin.id = "VST3:old-synth";
  8038. synth.plugin.name = "Old Synth";
  8039. synth.plugin.dpiAware = false;
  8040. synth.smartDisable = true; // (merge 6, 190ok D2: dropped without a line)
  8041. song.channels.push_back (synth);
  8042. const auto synthIndex = (int) song.channels.size() - 1;
  8043. lynx::EffectSlot fx;
  8044. fx.kind = lynx::EffectKind::plugin;
  8045. fx.plugin.id = "VST3:tiny-eq";
  8046. fx.plugin.name = "Tiny EQ";
  8047. fx.plugin.scaleEditorDimensions = true;
  8048. song.mixer[2].effects.push_back (fx);
  8049. auto ember = lynx::makeEffectSlot (lynx::EffectKind::ember); // (merge 6, 190ok D3: engine revision 2 -> 1 in the copies)
  8050. song.mixer[2].effects.push_back (ember);
  8051. // gap190og: a key mapped to Arrangement Overdub (newer) and one to Play (0.1.30 has it)
  8052. lynx::RemoteMapping overdub, play;
  8053. overdub.source = play.source = lynx::RemoteMapping::Source::key;
  8054. overdub.key = 'O', overdub.action = lynx::RemoteAction::overdub;
  8055. play.key = 'P', play.action = lynx::RemoteAction::play;
  8056. song.remoteMappings = { overdub, play };
  8057. // 190ob: the tracker import's volume automation (the channel's Levels "Volume multiplier", 5000 = 100 %)
  8058. lynx::Automation volume;
  8059. volume.name = "Old Synth volume (ch 1)";
  8060. volume.target.kind = lynx::AutomationTargetKind::channelAdjust;
  8061. volume.target.index = synthIndex;
  8062. volume.target.param = lynx::leveladjust::volume;
  8063. volume.points = { { 0, 0.5f }, { lynx::ppq, 0.25f }, { 2 * lynx::ppq, 0.4f } };
  8064. song.automations.push_back (volume);
  8065. lynx::uids::normalize (song);
  8066. const auto json = lynx::ProjectFile::toJson (song);
  8067. const auto keysOf = [] (const juce::var& v) {
  8068. std::set<juce::String> keys;
  8069. std::function<void (const juce::var&, const juce::String&)> walk = [&] (const juce::var& x, const juce::String& path) {
  8070. if (auto* o = x.getDynamicObject())
  8071. for (const auto& prop : o->getProperties())
  8072. {
  8073. if (path.isEmpty() && (prop.name.toString() == "savedBy" || prop.name.toString() == "copiedFrom"))
  8074. continue;
  8075. keys.insert (path + "/" + prop.name.toString());
  8076. walk (prop.value, path + "/" + prop.name.toString());
  8077. }
  8078. else if (auto* a = x.getArray())
  8079. for (const auto& e : *a)
  8080. walk (e, path + "[]");
  8081. };
  8082. walk (v, {});
  8083. return keys;
  8084. };
  8085. auto expected = keysOf (juce::JSON::parse (json));
  8086. const auto hadKeys = expected.erase ("/arrangements[]/sections") == 1 && expected.erase ("/channels[]/plugin/dpiAware") == 1
  8087. && expected.erase ("/mixer[]/effects[]/plugin/scaleEditorDimensions") == 1 && expected.erase ("/channels[]/smartDisable") == 1;
  8088. const auto countOf = [] (const lynx::olderlynx::Copy& c, const char* start) {
  8089. return (int) std::count_if (c.lost.begin(), c.lost.end(), [start] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).startsWith (start); });
  8090. };
  8091. const auto detailOf = [] (const lynx::olderlynx::Copy& c, const char* start) {
  8092. for (const auto& l : c.lost)
  8093. if (juce::String (l.text).startsWith (start))
  8094. return juce::String (l.detail);
  8095. return juce::String();
  8096. };
  8097. if (! hadKeys || song.sections().size() != 2 || song.beatsPerBar != 5 || song.beatUnit != 1 || signatures.size() != 1 || signatures[0].numerator != 7)
  8098. rollup031s5Result = "ERROR set-up (" + juce::String ((int) signatures.size()) + " signature changes)";
  8099. // (190og: the .flm export reads the song and keeps nothing in it)
  8100. if (rollup031s5Result == "OK")
  8101. {
  8102. const auto flm = lynx::exportFlm (song);
  8103. if (flm.bytes.empty() || lynx::ProjectFile::toJson (song) != json)
  8104. rollup031s5Result = "ERROR the .flm export (" + juce::String ((int) flm.bytes.size()) + " bytes)";
  8105. }
  8106. for (const auto* release : { "0.1.30", "0.1.28" })
  8107. {
  8108. if (rollup031s5Result != "OK")
  8109. break;
  8110. const auto copy = lynx::olderlynx::forRelease (song, release);
  8111. juce::String why;
  8112. const auto back = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why) : std::optional<lynx::Song> {};
  8113. const auto is130 = juce::String (release) == "0.1.30";
  8114. std::vector<lynx::Marker> backSignatures;
  8115. int sectionMarkers = 0;
  8116. if (back)
  8117. for (const auto& m : back->markers())
  8118. if (m.isSignature())
  8119. backSignatures.push_back (m);
  8120. else if (m.name == "Intro" || m.name == "Verse")
  8121. ++sectionMarkers;
  8122. const auto bars = song.barsBetween (0, 400 * lynx::ppq);
  8123. const auto backBars = back ? back->barsBetween (0, 400 * lynx::ppq) : std::vector<lynx::Bar> {};
  8124. 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 {};
  8125. const auto backEmberRev = back && back->mixer.size() > 2 && ! back->mixer[2].effects.empty() ? back->mixer[2].effects.back().engineRev : -1;
  8126. if (! copy.ok || ! back)
  8127. rollup031s5Result = juce::String ("ERROR copy ") + release + " " + copy.error + why;
  8128. else if (copy.json.contains ("\"sections\"") || ! back->sections().empty() || sectionMarkers != 2
  8129. || countOf (copy, "{0} song section(s) of the Sections lane") != 1)
  8130. rollup031s5Result = juce::String ("ERROR 190ol's sections in the copy for ") + release;
  8131. else if (backSignatures.size() != signatures.size()
  8132. || ! std::equal (signatures.begin(), signatures.end(), backSignatures.begin(), [] (const lynx::Marker& a, const lynx::Marker& b) {
  8133. return a.tick == b.tick && a.numerator == b.numerator && a.denominator == b.denominator;
  8134. })
  8135. || back->beatsPerBar != song.beatsPerBar || back->beatUnit != song.beatUnit
  8136. || ! std::equal (bars.begin(), bars.end(), backBars.begin(), backBars.end(), [] (const lynx::Bar& a, const lynx::Bar& b) {
  8137. return a.tick == b.tick && a.length == b.length && a.number == b.number;
  8138. }))
  8139. rollup031s5Result = juce::String ("ERROR 190ol's time signature changes in the copy for ") + release;
  8140. else if (copy.json.contains ("dpiAware") || copy.json.contains ("scaleEditorDimensions") || ! back->channels[(std::size_t) synthIndex].plugin.dpiAware
  8141. || backFx.scaleEditorDimensions || backFx.name != "Tiny EQ"
  8142. || countOf (copy, "FL's wrapper GUI settings") != 1 || ! detailOf (copy, "FL's wrapper GUI settings").contains ("Old Synth")
  8143. || ! detailOf (copy, "FL's wrapper GUI settings").contains ("Tiny EQ"))
  8144. rollup031s5Result = juce::String ("ERROR 190oh's wrapper GUI settings in the copy for ") + release + " (" + detailOf (copy, "FL's wrapper GUI settings") + ")";
  8145. else if (back->remoteMappings.size() != 1 || back->remoteMappings[0].action != lynx::RemoteAction::play
  8146. || countOf (copy, "{0} key / MIDI mapping(s) of Overdub") != 1 || detailOf (copy, "{0} key / MIDI mapping(s) of Overdub") != "1")
  8147. rollup031s5Result = juce::String ("ERROR gap190og's transport mappings in the copy for ") + release;
  8148. else if (copy.json.contains ("smartDisable") || back->channels[(std::size_t) synthIndex].smartDisable || song.mixer[2].effects.back().engineRev != 2
  8149. || backEmberRev != (is130 ? 1 : 0))
  8150. rollup031s5Result = juce::String ("ERROR 190ok's smart disable / engine revision in the copy for ") + release + " (rev " + juce::String (backEmberRev) + ")";
  8151. else if (back->automations != song.automations)
  8152. rollup031s5Result = juce::String ("ERROR 190ob's volume automation in the copy for ") + release;
  8153. else if (is130 && (copy.lost.size() != 3 || keysOf (juce::JSON::parse (copy.json)) != expected))
  8154. rollup031s5Result = "ERROR the copy for 0.1.30 drops more than step 5's three (" + juce::String ((int) copy.lost.size()) + " lines)";
  8155. }
  8156. // a project without any of them: no step-5 line (the default song)
  8157. if (rollup031s5Result == "OK")
  8158. {
  8159. const auto plain = lynx::olderlynx::forRelease (lynx::Song::makeDefault(), "0.1.30");
  8160. if (! plain.ok || ! plain.lost.empty())
  8161. rollup031s5Result = "ERROR lines for a project with none of step 5's data (" + juce::String ((int) plain.lost.size()) + ")";
  8162. }
  8163. }
  8164. // round 190ol (research190oe P1 / P6): the Sections lane in .lynx (both arrangements, and a project without sections
  8165. // keeps its JSON with no "sections" key), a section move as one undo step that restores the song bit for bit, the
  8166. // 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
  8167. // song's metronome table (core/SignatureEdit.h)
  8168. juce::String sections190olResult = "OK";
  8169. {
  8170. const auto bar = 4 * (std::int64_t) lynx::ppq;
  8171. auto song = lynx::Song::makeDefault();
  8172. song.playlistTracks.resize (juce::jmax<std::size_t> (2, song.playlistTracks.size()));
  8173. lynx::Clip c;
  8174. c.pattern = 0;
  8175. c.track = 0;
  8176. c.length = 2 * bar;
  8177. song.playlist = { c };
  8178. c.start = 2 * bar;
  8179. c.track = 1;
  8180. song.playlist.push_back (c);
  8181. song.sections() = { { 0, 2 * bar, "Intro", 0, 1 }, { 2 * bar, 2 * bar, "Verse", 0xFF336699u, 2 } };
  8182. song.addArrangement ("Second", true);
  8183. song.sections().push_back ({ 4 * bar, bar, "Outro", 0, 3 });
  8184. song.selectArrangement (0);
  8185. juce::String why;
  8186. const auto json = lynx::ProjectFile::toJson (song);
  8187. const auto back = lynx::ProjectFile::fromJson (json, why);
  8188. if (! back || back->arrangements.size() != 2 || back->arrangements[0].sections != song.arrangements[0].sections
  8189. || back->arrangements[1].sections != song.arrangements[1].sections || back->sections().size() != 2 || back->sections()[1].colour != 0xFF336699u)
  8190. sections190olResult = "ERROR round trip " + why;
  8191. else if (lynx::ProjectFile::toJson (lynx::Song::makeDefault()).contains ("\"sections\""))
  8192. sections190olResult = "ERROR a project without sections writes the key";
  8193. // one undo step, bit for bit
  8194. if (sections190olResult == "OK")
  8195. {
  8196. lynx::AudioEngine e (false);
  8197. e.setSong (song);
  8198. const auto before = lynx::ProjectFile::toJson (e.getSong());
  8199. e.editSong ([] (lynx::Song& s) { lynx::sections::move (s, 1, 0); });
  8200. const auto moved = e.getSong().sections().size() == 2 && e.getSong().sections()[0].name == "Verse";
  8201. e.undo();
  8202. if (! moved || lynx::ProjectFile::toJson (e.getSong()) != before)
  8203. sections190olResult = juce::String ("ERROR undo of a section move (moved ") + (moved ? "yes" : "no") + ")";
  8204. }
  8205. // the copies for older LYNX: plain markers at the sections' starts, "sections" gone, one line
  8206. for (const auto* release : { "0.1.30", "0.1.28" })
  8207. {
  8208. if (sections190olResult != "OK")
  8209. break;
  8210. const auto copy = lynx::olderlynx::forRelease (song, release);
  8211. const auto lines = std::count_if (copy.lost.begin(), copy.lost.end(), [] (const lynx::olderlynx::Loss& l) {
  8212. return juce::String (l.text).contains ("Sections lane");
  8213. });
  8214. juce::String why2;
  8215. const auto old = copy.ok ? lynx::ProjectFile::fromJson (copy.json, why2) : std::nullopt;
  8216. if (! copy.ok || copy.json.contains ("\"sections\"") || lines != 1 || ! old)
  8217. sections190olResult = juce::String ("ERROR the copy for ") + release;
  8218. else if (old->arrangements[0].markers.size() != 2 || old->arrangements[0].markers[1].name != "Verse" || old->arrangements[0].markers[1].tick != 2 * bar
  8219. || old->arrangements[1].markers.size() != 3 || ! old->arrangements[0].sections.empty())
  8220. sections190olResult = juce::String ("ERROR the markers in the copy for ") + release;
  8221. }
  8222. // P6: the metronome follows 4/4 -> 7/8 (bar 3) -> 4/4 (bar 5)
  8223. if (sections190olResult == "OK")
  8224. {
  8225. auto meter = lynx::Song::makeDefault();
  8226. const auto seven = 7 * (std::int64_t) lynx::ppq / 2;
  8227. lynx::signatureedit::set (meter, 2 * bar, 7, 8);
  8228. lynx::signatureedit::set (meter, 2 * bar + 2 * seven, 4, 4);
  8229. lynx::AudioEngine e (false);
  8230. e.setSong (meter);
  8231. e.dispatchPendingMessages();
  8232. const auto& t = e.getTransport();
  8233. if (t.signatureCount.load() != 3 || t.signatureTick[1].load() != 2 * bar || t.signatureLength[1].load() != seven
  8234. || t.signatureBeat[1].load() != (std::int64_t) lynx::ppq / 2 || t.signatureTick[2].load() != 2 * bar + 2 * seven
  8235. || t.signatureLength[2].load() != bar || meter.barAt (2 * bar + 2 * seven).number != 5)
  8236. sections190olResult = "ERROR the metronome's signature table (" + juce::String (t.signatureCount.load()) + " entries)";
  8237. }
  8238. }
  8239. // round 190dr: the Session mixer's sections come back from a project (a project without them: Live's defaults);
  8240. // a device dragged to another track and a Warp switch are one undo step each in a real engine
  8241. juce::String livescr190drResult = "OK";
  8242. {
  8243. auto song = lynx::Song::makeDefault();
  8244. lynx::launcher::ensureGrid (song);
  8245. juce::String why;
  8246. const auto plain = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  8247. song.clipGrid->mixerView.io = false;
  8248. song.clipGrid->mixerView.trackOptions = true;
  8249. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), why);
  8250. if (! plain || ! plain->clipGrid || ! (plain->clipGrid->mixerView == lynx::SessionMixerView {}))
  8251. livescr190drResult = "ERROR view defaults " + why;
  8252. else if (! back || ! back->clipGrid || back->clipGrid->mixerView.io || ! back->clipGrid->mixerView.trackOptions || ! back->clipGrid->mixerView.shown)
  8253. livescr190drResult = "ERROR view round trip " + why;
  8254. lynx::AudioEngine e (false);
  8255. e.editSong ([] (lynx::Song& s) {
  8256. if (s.mixer.size() < 4)
  8257. s.mixer.resize (4);
  8258. s.mixer[2].effects.clear();
  8259. s.mixer[3].effects.clear();
  8260. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  8261. {
  8262. lynx::EffectSlot fx;
  8263. fx.kind = kind;
  8264. s.mixer[2].effects.push_back (fx);
  8265. }
  8266. lynx::Automation a;
  8267. a.target = { lynx::AutomationTargetKind::effectMix, 2, 1, 0 };
  8268. s.automations.push_back (a);
  8269. }, false);
  8270. const auto id = e.getSong().mixer[2].effects[1].instance.id;
  8271. const auto automations = e.getSong().automations.size();
  8272. e.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  8273. const auto& moved = e.getSong();
  8274. if (livescr190drResult == "OK"
  8275. && (moved.mixer[2].effects.size() != 1 || moved.mixer[3].effects.size() != 1 || moved.mixer[3].effects[0].instance.id != id
  8276. || moved.automations.size() != automations || moved.automations.back().target.index != 3 || moved.automations.back().target.slot != 0))
  8277. livescr190drResult = "ERROR device move";
  8278. e.undo();
  8279. const auto& undone = e.getSong();
  8280. if (livescr190drResult == "OK"
  8281. && (undone.mixer[2].effects.size() != 2 || undone.mixer[3].effects.size() != 0 || undone.mixer[2].effects[1].instance.id != id
  8282. || undone.automations.back().target.index != 2 || undone.automations.back().target.slot != 1))
  8283. livescr190drResult = "ERROR device move undo";
  8284. e.editSong ([] (lynx::Song& s) {
  8285. s.channels.resize (std::max<std::size_t> (s.channels.size(), 1));
  8286. s.channels[0].sampler.stretchBeats = 16.0f;
  8287. lynx::Clip c;
  8288. c.kind = lynx::ClipKind::audio;
  8289. c.channel = 0;
  8290. c.offset = 4 * lynx::ppq;
  8291. c.length = 8 * lynx::ppq;
  8292. lynx::launcher::setClip (s, 0, 0, c);
  8293. }, false);
  8294. e.editSong ([] (lynx::Song& s) { lynx::clipsample::setWarp (s, 0, false, 4.0); });
  8295. const auto* off = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  8296. 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)))
  8297. livescr190drResult = "ERROR warp off";
  8298. e.undo();
  8299. const auto* on = e.getSong().clipGrid ? lynx::launcher::clipAt (*e.getSong().clipGrid, 0, 0) : nullptr;
  8300. if (livescr190drResult == "OK" && (e.getSong().channels[0].sampler.stretchBeats != 16.0f || on == nullptr || on->length != 8 * lynx::ppq))
  8301. livescr190drResult = "ERROR warp undo";
  8302. }
  8303. // round 190ef: the map modes' storage (.lynx round trip of key / MIDI mappings and a link's Min / Max; an older
  8304. // reader keeps the plain link), and in a real engine: a link's range, MIDI Map Mode catching the control instead
  8305. // of moving anything, a slot's MIDI mapping firing on its press and release
  8306. juce::String livewf190efResult = "OK";
  8307. {
  8308. using namespace lynx::remotemap;
  8309. auto song = lynx::Song::makeDefault();
  8310. lynx::launcher::ensureGrid (song);
  8311. const lynx::AutomationTarget vol { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 };
  8312. assignMidi (song, Target::parameter (vol), { 0, 20, -1 });
  8313. assignMidi (song, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, 2 });
  8314. assignKey (song, Target::sceneLaunch (0), 'S');
  8315. assignKey (song, Target::parameter ({ lynx::AutomationTargetKind::tempo, 0, 0, 0 }), 'T');
  8316. setRange (song, rows (song, Mode::midi)[0], 0.25f, 0.75f);
  8317. setRange (song, rows (song, Mode::key)[1], 0.9f, 0.1f);
  8318. juce::String why;
  8319. const auto json = lynx::ProjectFile::toJson (song);
  8320. const auto back = lynx::ProjectFile::fromJson (json, why);
  8321. if (! back || back->remoteMappings != song.remoteMappings || back->midiLinks != song.midiLinks)
  8322. livewf190efResult = "ERROR round trip " + why;
  8323. auto parsed = juce::JSON::parse (json);
  8324. if (auto* o = parsed.getDynamicObject())
  8325. {
  8326. o->removeProperty ("remoteMappings");
  8327. o->removeProperty ("midiLinkSettings");
  8328. }
  8329. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  8330. if (livewf190efResult == "OK" && (! older || ! older->remoteMappings.empty() || older->midiLinks.size() != 1 || older->midiLinks[0].max != 1.0f))
  8331. livewf190efResult = "ERROR older reader";
  8332. const auto plain = lynx::ProjectFile::toJson (lynx::Song::makeDefault());
  8333. if (livewf190efResult == "OK" && plain.contains ("remoteMappings"))
  8334. livewf190efResult = "ERROR written without mappings";
  8335. lynx::AudioEngine e (false);
  8336. e.editSong ([vol] (lynx::Song& s) {
  8337. if (s.mixer.size() < 3)
  8338. s.mixer.resize (3);
  8339. lynx::MidiLink l { 20, 0, vol };
  8340. l.min = 0.25f;
  8341. l.max = 0.75f;
  8342. s.midiLinks = { l };
  8343. lynx::launcher::ensureGrid (s);
  8344. assignMidi (s, Target::slot (0, 0), { 0, 21, -1 });
  8345. });
  8346. e.injectControllerForTest (20, 0, 127);
  8347. const auto top = e.currentTargetValue (vol);
  8348. e.injectControllerForTest (20, 0, 0);
  8349. const auto bottom = e.currentTargetValue (vol);
  8350. if (livewf190efResult == "OK" && (std::abs (top - 0.75f) > 0.01f || std::abs (bottom - 0.25f) > 0.01f))
  8351. livewf190efResult = "ERROR range " + juce::String (bottom) + " " + juce::String (top);
  8352. std::vector<Fire> fired;
  8353. e.onRemoteFire = [&fired] (const Fire& f) { fired.push_back (f); };
  8354. e.injectControllerForTest (21, 0, 127);
  8355. e.injectControllerForTest (21, 0, 127); // (still down: no new press)
  8356. e.injectControllerForTest (21, 0, 0);
  8357. if (livewf190efResult == "OK"
  8358. && (fired.size() != 2 || fired[0].edge != Edge::press || fired[1].edge != Edge::release || ! (fired[0].target == Target::slot (0, 0))))
  8359. livewf190efResult = "ERROR slot fire " + juce::String ((int) fired.size());
  8360. e.setMapMode (Mode::midi);
  8361. fired.clear();
  8362. e.injectControllerForTest (20, 0, 127);
  8363. e.injectControllerForTest (21, 0, 127);
  8364. const auto caught = e.takeMapCapture();
  8365. if (livewf190efResult == "OK" && (std::abs (e.currentTargetValue (vol) - 0.25f) > 0.01f || ! fired.empty()))
  8366. livewf190efResult = "ERROR mappings acted in MIDI Map Mode";
  8367. else if (livewf190efResult == "OK" && (! caught || caught->number != 21 || caught->channel != 0 || e.takeMapCapture().has_value()))
  8368. livewf190efResult = "ERROR map capture";
  8369. e.setMapMode (Mode::off);
  8370. e.onRemoteFire = nullptr;
  8371. }
  8372. // round 190em: a scene's time signature denominator (.lynx round trip; an older file without it reads n/4; a
  8373. // 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
  8374. // armed track, the selected scene's slot, the tempo from a phrase played while stopped (8 notes at 148 BPM), the
  8375. // new clip launched and the transport started
  8376. juce::String livewf190emResult = "OK";
  8377. {
  8378. auto song = lynx::Song::makeDefault();
  8379. auto& grid = lynx::launcher::ensureGrid (song);
  8380. grid.scenes.resize (3);
  8381. lynx::session::setSceneSignature (song, 1, 6, 8);
  8382. lynx::session::setSceneTempo (song, 1, 100.0);
  8383. juce::String why;
  8384. const auto json = lynx::ProjectFile::toJson (song);
  8385. const auto back = lynx::ProjectFile::fromJson (json, why);
  8386. if (! back || ! back->clipGrid || back->clipGrid->scenes != song.clipGrid->scenes || back->clipGrid->scenes[1].beatUnit != 8)
  8387. livewf190emResult = "ERROR round trip " + why;
  8388. {
  8389. // a captured clip's blank label (ClipGridSlot::blankName) survives the round trip
  8390. auto withClip = song;
  8391. lynx::Clip c;
  8392. c.pattern = 0;
  8393. c.length = 4 * lynx::ppq;
  8394. if (withClip.patterns.empty())
  8395. withClip.patterns.emplace_back();
  8396. const auto slot = lynx::launcher::setClip (withClip, 0, 0, c);
  8397. if (slot >= 0)
  8398. withClip.clipGrid->slots[(std::size_t) slot].blankName = true;
  8399. const auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (withClip), why);
  8400. const auto* keptClip = again && again->clipGrid ? lynx::launcher::clipAt (*again->clipGrid, 0, 0) : nullptr;
  8401. const auto* kept = keptClip != nullptr ? &again->clipGrid->slots[(std::size_t) keptClip->gridSlot] : nullptr;
  8402. if (livewf190emResult == "OK" && (slot < 0 || kept == nullptr || ! kept->blankName))
  8403. livewf190emResult = "ERROR blank clip name round trip";
  8404. }
  8405. auto parsed = juce::JSON::parse (json);
  8406. if (auto* scenes = parsed.getProperty ("clipGrid", {}).getProperty ("scenes", {}).getArray(); scenes != nullptr && scenes->size() > 1)
  8407. if (auto* o = (*scenes)[1].getDynamicObject())
  8408. o->removeProperty ("beatUnit");
  8409. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), why);
  8410. if (livewf190emResult == "OK" && (! older || ! older->clipGrid || older->clipGrid->scenes.size() < 2 || older->clipGrid->scenes[1].beatUnit != 4
  8411. || older->clipGrid->scenes[1].beatsPerBar != 6))
  8412. livewf190emResult = "ERROR older reader";
  8413. if (livewf190emResult == "OK" && lynx::ProjectFile::toJson (lynx::Song::makeDefault()).contains ("beatUnit"))
  8414. livewf190emResult = "ERROR beatUnit written by default";
  8415. // round 190fg: the song meter's denominator round-trips through .lynx; a file without it reads n/4
  8416. {
  8417. auto six = lynx::Song::makeDefault();
  8418. six.beatsPerBar = 6;
  8419. six.beatUnit = 8;
  8420. const auto text = lynx::ProjectFile::toJson (six);
  8421. juce::String why2;
  8422. const auto back = lynx::ProjectFile::fromJson (text, why2);
  8423. auto json = juce::JSON::parse (text);
  8424. if (auto* o = json.getDynamicObject())
  8425. o->removeProperty ("beatUnit");
  8426. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (json), why2);
  8427. if (livewf190emResult == "OK" && (! back || back->beatsPerBar != 6 || back->beatUnit != 8 || ! old || old->beatsPerBar != 6 || old->beatUnit != 4))
  8428. livewf190emResult = "ERROR song meter round trip";
  8429. }
  8430. lynx::AudioEngine e (false);
  8431. e.editSong ([] (lynx::Song& s) {
  8432. s.bpm = 120.0;
  8433. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  8434. auto& g = lynx::launcher::ensureGrid (s);
  8435. g.scenes.resize (3);
  8436. lynx::session::setSceneSignature (s, 2, 6, 8);
  8437. lynx::session::setSceneTempo (s, 2, 90.0);
  8438. }, false);
  8439. e.launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, 2 });
  8440. // (round 190fg: the song takes the scene's 6 / 8 as it is: six eighths a bar, 3 quarters long)
  8441. if (livewf190emResult == "OK" && (e.getSong().beatsPerBar != 6 || e.getSong().beatUnit != 8 || e.getSong().barTicks() != 3 * lynx::ppq
  8442. || e.getSong().bpm != 90.0))
  8443. livewf190emResult = "ERROR scene launch " + juce::String (e.getSong().beatsPerBar) + "/" + juce::String (e.getSong().beatUnit) + " "
  8444. + juce::String (e.getSong().bpm);
  8445. e.stop();
  8446. e.editSong ([] (lynx::Song& s) {
  8447. s.bpm = 120.0;
  8448. s.beatsPerBar = 4;
  8449. s.beatUnit = 4;
  8450. }, false);
  8451. e.setGridTrackArmed (2, true, true);
  8452. const auto now = juce::Time::getMillisecondCounterHiRes();
  8453. const auto beat = 60000.0 / 148.0;
  8454. for (int i = 0; i < 8; ++i)
  8455. {
  8456. const auto at = now - 9.0 * beat + i * beat;
  8457. e.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  8458. e.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  8459. }
  8460. int placed = -1;
  8461. bool into = true;
  8462. const auto r = e.captureMidiToSlot (2, 1, placed, into);
  8463. const auto& g = *e.getSong().clipGrid;
  8464. const auto* clip = lynx::launcher::clipAt (g, 2, 1);
  8465. if (livewf190emResult == "OK" && (r.notes != 8 || placed != 1 || into || clip == nullptr || clip->length != 8 * lynx::ppq))
  8466. livewf190emResult = "ERROR capture " + juce::String (r.notes) + " " + juce::String (placed) + (clip == nullptr ? " no clip" : " " + juce::String ((int) clip->length));
  8467. else if (livewf190emResult == "OK" && std::abs (e.getSong().bpm - 148.0) > 0.5)
  8468. livewf190emResult = "ERROR tempo " + juce::String (e.getSong().bpm, 2);
  8469. else if (livewf190emResult == "OK" && ! e.getTransport().playing.load())
  8470. livewf190emResult = "ERROR the capture did not start the transport";
  8471. e.stop();
  8472. }
  8473. const auto mixerBasics = lynx::mixerbasics::run();
  8474. // issue #142: every font has a typeface, and one without does not crash (fonts get theirs through the
  8475. // look and feel, as in the app)
  8476. auto& lookBefore = juce::LookAndFeel::getDefaultLookAndFeel();
  8477. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8478. const auto fontsResult = lynx::theme::fontSelfTest();
  8479. auto paintCachesResult = lynx::theme::paintCacheSelfTest(); // (round 190gr)
  8480. if (paintCachesResult.startsWith ("OK")) // (round 190ki: the Pattern toolbar's cached FL tiles, the pixels of painting them straight)
  8481. {
  8482. const auto tiles = lynx::flTileCacheSelfTest();
  8483. paintCachesResult = tiles == "OK" ? paintCachesResult + ", FL tiles exact at x1 / x2" : tiles;
  8484. }
  8485. // round 190ne (0.1.31, core/TrackClips.h): track clips. A .lynx round trip keeps the flags and an older file opens
  8486. // unchanged; in a real engine a track clip goes with its last clip in the same undo step (Undo brings both back),
  8487. // ordinary patterns stay; the copy for 0.1.28 drops the flags with a loss line; an .flp export merges identical
  8488. // track clips.
  8489. juce::String trackclips190neResult = "OK";
  8490. {
  8491. auto song = lynx::Song::makeDefault();
  8492. if (song.patterns.empty())
  8493. song.patterns.emplace_back().name = "Pattern 1";
  8494. lynx::ChannelDef synth;
  8495. synth.name = "Lead";
  8496. song.channels.push_back (synth);
  8497. const auto channel = (int) song.channels.size() - 1;
  8498. lynx::trackmodes::makeInstrumentTrack (song, 2, channel);
  8499. lynx::trackclips::setOwnClips (song, 2, true);
  8500. const auto a = lynx::trackclips::newClip (song, 2, 4 * lynx::ppq);
  8501. song.patterns[(std::size_t) a].notes.push_back ({});
  8502. song.patterns[(std::size_t) a].notes.back().channel = channel;
  8503. song.patterns[(std::size_t) a].notes.back().key = 60;
  8504. song.patterns[(std::size_t) a].notes.back().length = lynx::ppq;
  8505. const auto b = lynx::trackclips::newClip (song, 2, 4 * lynx::ppq);
  8506. song.patterns[(std::size_t) b].notes = song.patterns[(std::size_t) a].notes;
  8507. for (const auto p : { a, a, b })
  8508. {
  8509. lynx::Clip c;
  8510. c.pattern = p;
  8511. c.track = 2;
  8512. c.start = (std::int64_t) song.playlist.size() * 4 * lynx::ppq;
  8513. c.length = 4 * lynx::ppq;
  8514. song.playlist.push_back (c);
  8515. }
  8516. juce::String why;
  8517. const auto json = lynx::ProjectFile::toJson (song);
  8518. const auto back = lynx::ProjectFile::fromJson (json, why);
  8519. if (! back || back->patterns != song.patterns || back->playlistTracks.size() <= 2 || ! back->playlistTracks[2].ownClips
  8520. || ! back->patterns[(std::size_t) a].trackClip || back->playlist.size() != song.playlist.size())
  8521. trackclips190neResult = "ERROR round trip " + why;
  8522. // an older project (no flags): opens unchanged, nothing becomes a track clip
  8523. const auto plain = lynx::Song::makeDefault();
  8524. const auto plainJson = lynx::ProjectFile::toJson (plain);
  8525. if (trackclips190neResult == "OK" && (plainJson.contains ("trackClip") || plainJson.contains ("playlistOwnClips")))
  8526. trackclips190neResult = "ERROR flags written for a project without track clips";
  8527. if (const auto reread = lynx::ProjectFile::fromJson (plainJson, why); trackclips190neResult == "OK"
  8528. && (! reread || lynx::trackclips::count (*reread) != 0 || lynx::ProjectFile::toJson (*reread) != plainJson))
  8529. trackclips190neResult = "ERROR an older project changed";
  8530. // the copy for 0.1.28: no flags, one loss line
  8531. const auto copy = lynx::olderlynx::forRelease (song, "0.1.28");
  8532. const auto said = [&copy] (const char* text) {
  8533. return std::any_of (copy.lost.begin(), copy.lost.end(), [text] (const lynx::olderlynx::Loss& l) { return juce::String (l.text).contains (text); });
  8534. };
  8535. if (trackclips190neResult == "OK" && (! copy.ok || copy.json.contains ("\"trackClip\"") || copy.json.contains ("playlistOwnClips") || ! said ("track clip(s) show as ordinary patterns")))
  8536. trackclips190neResult = "ERROR copy for 0.1.28";
  8537. // .flp export: clips a and b hold the same notes: one pattern in FL, every clip kept
  8538. lynx::flpexport::Report flpReport;
  8539. const auto flp = flp::parseProject (lynx::flpexport::exportFlp (song, {}, flpReport));
  8540. auto other = song; // (b with other notes: nothing to merge)
  8541. other.patterns[(std::size_t) b].notes.front().key += 1;
  8542. const auto flpOther = flp::parseProject (lynx::flpexport::exportFlp (other, {}, flpReport));
  8543. if (trackclips190neResult == "OK" && flp.patterns.size() + 1 != flpOther.patterns.size())
  8544. trackclips190neResult = "ERROR flp merge " + juce::String ((int) flp.patterns.size()) + " / " + juce::String ((int) flpOther.patterns.size());
  8545. // a real engine: delete the last clip of b -> b goes in the same undo step; Undo brings it back
  8546. lynx::AudioEngine e (false);
  8547. e.editSong ([&song] (lynx::Song& s) { s = song; });
  8548. const auto before = e.getSong().patterns.size();
  8549. e.editSong ([] (lynx::Song& s) { s.playlist.pop_back(); }); // (the only clip of b)
  8550. if (trackclips190neResult == "OK" && (e.getSong().patterns.size() + 1 != before || e.getSong().playlist.size() != 2))
  8551. trackclips190neResult = "ERROR auto-delete " + juce::String ((int) e.getSong().patterns.size());
  8552. e.undo();
  8553. if (trackclips190neResult == "OK" && (e.getSong().patterns.size() != before || e.getSong().playlist.size() != 3))
  8554. trackclips190neResult = "ERROR undo of the auto-delete";
  8555. // an ordinary pattern without clips stays (FL)
  8556. e.editSong ([] (lynx::Song& s) { s.patterns.emplace_back().name = "Kept"; });
  8557. e.editSong ([] (lynx::Song& s) { s.playlist.erase (s.playlist.begin()); }); // (a's first clip: a still has one)
  8558. if (trackclips190neResult == "OK" && (e.getSong().patterns.size() != before + 1 || e.getSong().patterns.back().name != "Kept"))
  8559. trackclips190neResult = "ERROR an ordinary pattern or a linked clip went";
  8560. }
  8561. // round 190nw (0.1.31): the tracker. Its settings are saved only when changed (an older project's file stays the
  8562. // 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
  8563. // real engine (one note, one Sampler channel, its sample written) and its notes render.
  8564. juce::String tracker190nwResult = "OK", tracker190obResult = "OK";
  8565. {
  8566. auto song = lynx::Song::makeDefault();
  8567. juce::String why;
  8568. const auto plainJson = lynx::ProjectFile::toJson (song);
  8569. if (plainJson.contains ("\"tracker\""))
  8570. tracker190nwResult = "ERROR settings written for a project that never changed them";
  8571. if (const auto reread = lynx::ProjectFile::fromJson (plainJson, why); tracker190nwResult == "OK" && (! reread || lynx::ProjectFile::toJson (*reread) != plainJson))
  8572. tracker190nwResult = "ERROR an older project changed";
  8573. for (int c = 0; c < 2; ++c)
  8574. song.channels.emplace_back().name = "T" + std::to_string (c);
  8575. lynx::uids::normalize (song);
  8576. song.tracker.rowsPerBeat = 8;
  8577. song.tracker.showPan = true;
  8578. song.tracker.groups.push_back ({ "Drums", { song.channels[song.channels.size() - 2].uid, song.channels.back().uid } });
  8579. const auto json = lynx::ProjectFile::toJson (song);
  8580. const auto back = lynx::ProjectFile::fromJson (json, why);
  8581. if (tracker190nwResult == "OK" && (! back || ! (back->tracker == song.tracker)))
  8582. tracker190nwResult = "ERROR round trip " + why;
  8583. for (const auto* release : { "0.1.30", "0.1.28" })
  8584. {
  8585. const auto copy = lynx::olderlynx::forRelease (song, release);
  8586. 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"); });
  8587. if (tracker190nwResult == "OK" && (! copy.ok || copy.json.contains ("\"tracker\"") || ! said))
  8588. tracker190nwResult = "ERROR copy for " + juce::String (release);
  8589. }
  8590. // a ProTracker module of one note, through the engine's import (its sample written beside it)
  8591. const auto folder = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-selftest-190nw-" + juce::String (juce::Time::currentTimeMillis()));
  8592. folder.createDirectory();
  8593. std::vector<std::uint8_t> mod (1084 + 1024 + 128, 0);
  8594. std::memcpy (mod.data(), "selftest", 8);
  8595. mod[20 + 22] = 0, mod[20 + 23] = 64, mod[20 + 25] = 64, mod[20 + 29] = 1; // sample 1: 128 bytes, volume 64, no loop
  8596. for (int k = 1; k < 31; ++k)
  8597. mod[(std::size_t) (20 + k * 30 + 29)] = 1;
  8598. mod[950] = 1, mod[951] = 127;
  8599. std::memcpy (mod.data() + 1080, "M.K.", 4);
  8600. mod[1084] = 0x01, mod[1085] = 0xAC, mod[1086] = 0x10; // row 0: C-2 (428), sample 1
  8601. for (int i = 0; i < 128; ++i)
  8602. mod[(std::size_t) (1084 + 1024 + i)] = (std::uint8_t) (std::int8_t) std::lround (90.0 * std::sin (i * 0.39));
  8603. const auto modFile = folder.getChildFile ("one note.mod");
  8604. modFile.replaceWithData (mod.data(), mod.size());
  8605. lynx::AudioEngine e (false);
  8606. juce::String error;
  8607. if (tracker190nwResult == "OK" && ! e.importFlpFile (modFile, error))
  8608. tracker190nwResult = "ERROR module import: " + error;
  8609. const auto& imported = e.getSong();
  8610. if (tracker190nwResult == "OK" && (imported.channels.size() != 1 || imported.patterns.empty() || imported.patterns.front().notes.size() != 1
  8611. || ! folder.getChildFile ("one note samples").getChildFile ("01-01.wav").existsAsFile()))
  8612. tracker190nwResult = "ERROR module import: " + juce::String ((int) imported.channels.size()) + " channel(s), "
  8613. + juce::String (imported.patterns.empty() ? 0 : (int) imported.patterns.front().notes.size()) + " note(s)";
  8614. if (tracker190nwResult == "OK")
  8615. {
  8616. const auto peak = e.renderOffline (1.0, 44100.0, nullptr);
  8617. if (peak < 0.01f)
  8618. tracker190nwResult = "ERROR the imported note is silent (peak " + juce::String (peak) + ")";
  8619. }
  8620. // round 190ob: the same note, its sample looping, with a volume set on row 1 (C10, no note): its channel's
  8621. // Volume multiplier automation comes in, is saved and read back the same, and the note still sounds
  8622. if (tracker190obResult == "OK")
  8623. {
  8624. mod[1084 + 16 + 2] = 0x0C, mod[1084 + 16 + 3] = 0x10;
  8625. mod[20 + 28] = 0, mod[20 + 29] = 64; // (the sample loops whole: the note still sounds on row 1)
  8626. const auto volumeFile = folder.getChildFile ("one note volume.mod");
  8627. volumeFile.replaceWithData (mod.data(), mod.size());
  8628. lynx::AudioEngine ve (false);
  8629. if (! ve.importFlpFile (volumeFile, error))
  8630. tracker190obResult = "ERROR module import: " + error;
  8631. else
  8632. {
  8633. const auto& vs = ve.getSong();
  8634. const auto automation = std::find_if (vs.automations.begin(), vs.automations.end(), [] (const lynx::Automation& a) {
  8635. return a.target.kind == lynx::AutomationTargetKind::channelAdjust && a.target.param == lynx::leveladjust::volume && a.target.index == 0;
  8636. });
  8637. if (automation == vs.automations.end() || automation->points.size() < 2)
  8638. tracker190obResult = "ERROR no volume automation";
  8639. else if (const auto reread = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (vs), why); ! reread || reread->automations != vs.automations)
  8640. tracker190obResult = "ERROR the automation changed on the .lynx round trip " + why;
  8641. else if (ve.renderOffline (1.0, 44100.0, nullptr) < 0.001f)
  8642. tracker190obResult = "ERROR the note is silent";
  8643. }
  8644. }
  8645. folder.deleteRecursively();
  8646. }
  8647. const auto motionOverlayResult = lynx::ui::MotionOverlay::selfTest(); // (round 190ip)
  8648. // round 190bm (0.1.25 showed the Mixer and the Playlist black): their cached pictures shown on native and
  8649. // software targets against straight paints (ui/PictureCheck.h; --picturetest runs more sizes and scales)
  8650. juce::String picturesResult = "OK";
  8651. {
  8652. lynx::AudioEngine pictureEngine (false);
  8653. auto pictureFailures = 0;
  8654. juce::String lines;
  8655. {
  8656. lynx::PlaylistComponent playlist (pictureEngine);
  8657. playlist.setBounds (0, 0, 1200, 700);
  8658. playlist.setVisible (true);
  8659. lines << lynx::ui::picturecheck::run (playlist, "Playlist 1200 x 700", { 1.0f, 1.5f }, pictureFailures, {});
  8660. }
  8661. {
  8662. lynx::MixerComponent mixer (pictureEngine);
  8663. mixer.setBounds (0, 0, 1200, 500);
  8664. mixer.setVisible (true);
  8665. lines << lynx::ui::picturecheck::run (mixer, "Mixer 1200 x 500", { 1.0f, 1.5f }, pictureFailures, {});
  8666. }
  8667. if (pictureFailures > 0 || ! lines.contains (": ok"))
  8668. picturesResult = "ERROR " + lines.trim().replace ("\n", "; ");
  8669. }
  8670. // round 190ci (the 0.1.26 release candidate ended when an FPC channel was added): every built-in generator and
  8671. // effect, its editor built as the Channel Rack / mixer opens it and painted once. The report file names the
  8672. // plugin being opened, so a run that dies there says which one.
  8673. const auto editorsResult = lynx::pluginthumbs::checkEditors ([&reportPath] (const juce::String& key) {
  8674. if (reportPath.isNotEmpty())
  8675. juce::File (reportPath).replaceWithText ("(opening the editor of " + key + ")\n");
  8676. });
  8677. // round 190ci: a fault leaves a crash file, also on a stack Windows cannot walk (that FPC fault left none)
  8678. const auto faultResult = faultReportSelfTest();
  8679. const auto stemsResult = stemsSinglePassSelfTest(); // round 190gj
  8680. const auto exportFormatsResult = lynx::shortexport::formatsCheck(); // AIFF and M4A (owner decision D5)
  8681. const auto renderAgainResult = lynx::renderagain::check(); // round 190ou: offline renders made again
  8682. juce::LookAndFeel::setDefaultLookAndFeel (&lookBefore);
  8683. const auto ok = editorsResult.startsWith ("OK") && ! faultResult.startsWith ("ERROR") && stemsResult == "OK" && exportFormatsResult.startsWith ("OK")
  8684. && 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
  8685. && sessionResult == "OK" && liveResult.startsWith ("OK")
  8686. && 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"
  8687. && sidechainResult == "OK" && lanesResult == "OK" && arrange190cgResult == "OK" && livescr190drResult == "OK" && livewf190efResult == "OK" && livewf190emResult == "OK" && trackclips190neResult == "OK" && tracker190nwResult == "OK" && tracker190obResult == "OK" && versionsResult == "OK" && pluginsOffResult == "OK" && missingFilesResult == "OK"
  8688. && midigen190fmResult == "OK" && clipenv190giResult == "OK" && beatslaw190gxResult == "OK" && warplaw190ikResult == "OK" && editorScale190heResult == "OK" && sfModBase190heResult == "OK" && trackauto190gzResult == "OK" && community190hqResult == "OK" && rollup030Result == "OK" && rollup031Result == "OK" && rollup031s2Result == "OK"
  8689. && keys190nuResult == "OK" && rollup031s3Result == "OK"
  8690. && helix4khs190ocResult == "OK" && rollup031s4Result == "OK" && sections190olResult == "OK" && rollup031s5Result == "OK"
  8691. && renderAgainResult.startsWith ("OK")
  8692. && remoteHistoryResult.startsWith ("OK") && hostedStateLockResult.startsWith ("OK")
  8693. && hostedStateContentionResult.startsWith ("OK")
  8694. && generatorSmartResult.startsWith ("OK")
  8695. && danceWindowResult == "OK" && clickActivationResult == "OK" && motionOverlayResult.startsWith ("OK")
  8696. && editorHolesResult.startsWith ("OK");
  8697. juce::String report;
  8698. report << "connections=" << offline.getNumGraphConnections() << "\n"
  8699. << "peak=" << peak << "\n"
  8700. << "stems_single_pass=" << stemsResult << "\n"
  8701. << "export_formats=" << exportFormatsResult << "\n"
  8702. << "project=" << (projectOk ? "OK" : "ERROR " + error) << "\n"
  8703. << "playlist_track_modes_roundtrip=" << (trackModes122Ok ? "OK" : "ERROR") << "\n"
  8704. << "project_features=" << (richOk ? "OK" : "ERROR") << "\n"
  8705. << "hardware_outputs=" << (hwOutOk ? "OK" : "ERROR") << "\n"
  8706. << "plugin_host_keys_option=" << (hostKeysOk ? "OK" : "ERROR") << "\n"
  8707. << "plugin_levels_new_project=" << (pluginLevelsOk ? "OK" : "ERROR") << "\n"
  8708. << "flp168j_fields=" << (flp168jOk ? "OK" : "ERROR") << "\n"
  8709. << "clip_fades_180d=" << (clipFades180dOk ? "OK" : "ERROR") << "\n"
  8710. << "pattern_blocks=" << (blocksOk ? "OK" : "ERROR") << "\n"
  8711. << "pattern_clip_takeover=" << (takeoverOk ? "OK" : "ERROR") << "\n"
  8712. << "comp_crossfades=" << (compOk ? "OK" : "ERROR") << "\n"
  8713. << "channel_polyphony=" << (polyOk ? "OK" : "ERROR") << "\n"
  8714. << "track_latency=" << (latencyOk ? "OK" : "ERROR") << "\n"
  8715. << "pre_fader_sends=" << (preSendOk ? "OK" : "ERROR") << "\n"
  8716. << "low_latency_recording=" << (lowLatencyOk ? "OK" : "ERROR") << "\n"
  8717. << "preview_in_time=" << (previewInTimeOk ? "OK" : "ERROR") << " (2 s loop prepared in " << juce::String (previewPrepareMs, 1) << " ms)\n"
  8718. << "plugin_substitutes=" << (substituteOk ? "OK" : "ERROR") << "\n"
  8719. << "patcher=" << (patcherOk ? "OK" : "ERROR") << "\n"
  8720. << "racks=" << rackResult << "\n"
  8721. << "native_engines=" << nativesResult << " (" << nativesMade << " made)\n"
  8722. << "undo=" << (undoOk ? "OK" : "ERROR") << "\n"
  8723. << "mixer_basics=" << mixerBasics << "\n"
  8724. << "remote_history=" << remoteHistoryResult << "\n"
  8725. << "hosted_state_lock=" << hostedStateLockResult << "\n"
  8726. << "hosted_state_contention=" << hostedStateContentionResult << "\n"
  8727. << "generator_smart_disable=" << generatorSmartResult << "\n"
  8728. << "fonts=" << fontsResult << "\n"
  8729. << "paint_caches=" << paintCachesResult << "\n"
  8730. << "motion_overlay=" << motionOverlayResult << "\n"
  8731. << "cached_pictures=" << picturesResult << "\n"
  8732. << "plugin_editors=" << editorsResult << "\n"
  8733. << "fault_report=" << faultResult << "\n"
  8734. << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
  8735. << "cancel_recording=" << (cancelRecordOk ? "OK" : "ERROR") << "\n"
  8736. << "midi=" << (midiOk ? "OK" : "ERROR") << "\n"
  8737. << "package=" << (packageOk ? "OK" : "ERROR") << "\n"
  8738. << "projectSave=" << (projectSaveOk ? "OK" : "ERROR") << "\n"
  8739. << "online_session=" << sessionResult << "\n"
  8740. << "live_session=" << liveResult << "\n"
  8741. << "wavpack=" << wavpack << "\n"
  8742. << "effects=" << (effectsOk ? "OK" : "NONFINITE") << "\n"
  8743. << "effect_params_saved=" << effectParamsResult << "\n"
  8744. << "driver_panel=" << driverPanel << "\n"
  8745. << "device_change=" << deviceChange << "\n"
  8746. << "export_parity=" << exportParity << "\n"
  8747. << "export_live=" << exportLive << "\n"
  8748. << "midi_hotplug=" << midiHotplug << "\n"
  8749. << "midi_out_ports=" << midiOutPorts.replace ("\n", " | ").trimCharactersAtEnd (" |") << "\n"
  8750. << "plugin_art=" << artResult << "\n"
  8751. << "plugin_sidechain=" << sidechainResult << "\n"
  8752. << "versions_panel=" << versionsResult << "\n"
  8753. << "plugins_off=" << pluginsOffResult << "\n"
  8754. << "missing_files_rows=" << missingFilesResult << "\n"
  8755. << "dance_window=" << danceWindowResult << "\n"
  8756. << "dance_window_detail=" << danceWindowDetail << "\n"
  8757. << "click_activation=" << clickActivationResult << "\n"
  8758. << "editor_holes=" << editorHolesResult << "\n"
  8759. << "lanes_saved=" << lanesResult << "\n"
  8760. << "arrange190cg_saved=" << arrange190cgResult << "\n"
  8761. << "livescr190dr=" << livescr190drResult << "\n"
  8762. << "livewf190ef=" << livewf190efResult << "\n"
  8763. << "livewf190em=" << livewf190emResult << "\n"
  8764. << "trackclips190ne=" << trackclips190neResult << "\n"
  8765. << "tracker190nw=" << tracker190nwResult << "\n"
  8766. << "tracker190ob=" << tracker190obResult << "\n"
  8767. << "midigen190fm_saved=" << midigen190fmResult << "\n"
  8768. << "trackauto190gz_saved=" << trackauto190gzResult << "\n"
  8769. << "clipenv190gi_saved=" << clipenv190giResult << "\n"
  8770. << "beatslaw190gx_saved=" << beatslaw190gxResult << "\n"
  8771. << "warplaw190ik_saved=" << warplaw190ikResult << "\n"
  8772. << "editor_scale190he_saved=" << editorScale190heResult << "\n"
  8773. << "sf_mod_base190he=" << sfModBase190heResult << "\n"
  8774. << "community190hq_saved=" << community190hqResult << "\n"
  8775. << "rollup030_copy_for_0128=" << rollup030Result << "\n"
  8776. << "rollup031_copy_for_0130=" << rollup031Result << "\n"
  8777. << "rollup031s2_copy_for_0130=" << rollup031s2Result << "\n"
  8778. << "keys190nu_key_markers=" << keys190nuResult << "\n"
  8779. << "rollup031s3_copy_for_0130=" << rollup031s3Result << "\n"
  8780. << "helix4_khs190oc_copy_for_0130=" << helix4khs190ocResult << "\n"
  8781. << "rollup031s4_copy_for_0130=" << rollup031s4Result << "\n"
  8782. << "rollup031s5_copy_for_0130=" << rollup031s5Result << "\n"
  8783. << "sections190ol=" << sections190olResult << "\n"
  8784. << "renderagain190ou=" << renderAgainResult << "\n"
  8785. << "metronome=" << metronomeResult << " (FL sounds " << metronomeFlSounds << "/" << lynx::metronome::soundCount
  8786. << ", downbeat peak " << juce::String (metronomeMaster, 4) << ")\n";
  8787. // issue #138 (round 190c): a short note at the very start of the Playlist against the same note at bar 2, through
  8788. // the Export window's path (its own thread while the message loop runs: the report is finished from there)
  8789. if (reportPath.isNotEmpty())
  8790. juce::File (reportPath).replaceWithText (report + "(short_export running)\n");
  8791. lynx::shortexport::run (false, 1, {}, {}, [this, report, ok, reportPath] (juce::String shortExport) {
  8792. const auto all = ok && shortExport.startsWith ("OK");
  8793. const auto text = report + "short_export=" + shortExport + "\nresult=" + (all ? "OK" : "FAILED") + "\n";
  8794. if (reportPath.isNotEmpty())
  8795. juce::File (reportPath).replaceWithText (text);
  8796. setApplicationReturnValue (all ? 0 : 1);
  8797. if (selfTestTemp != juce::File())
  8798. selfTestTemp.deleteRecursively(); // (round 190mo: this run's own temp folder)
  8799. quit();
  8800. });
  8801. }
  8802. // Every built-in effect in its native editor: random / extreme parameters, mouse drags over the editor, the editor
  8803. // painted, audio rendered at 44.1 / 48 / 96 kHz. Returns false when an effect output NaN / inf (muted by the
  8804. // renderer's guard). The report lists each effect. Used by --fxfuzz and (a short run) by --selftest.
  8805. bool runEffectFuzz (int rounds, const juce::String& reportPath, bool drags = false)
  8806. {
  8807. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8808. lynx::setNativeEditorDemo (true);
  8809. juce::String report;
  8810. auto allFinite = true;
  8811. {
  8812. lynx::AudioEngine offline (false);
  8813. juce::Random random (111);
  8814. const auto value = [&] { const auto r = random.nextInt (6); return r == 0 ? 0.0f : r == 1 ? 1.0f : random.nextFloat(); };
  8815. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  8816. {
  8817. const auto kind = (lynx::EffectKind) k;
  8818. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher) // (the Patcher's editor is a graph window)
  8819. continue;
  8820. const auto before = lynx::RackRenderer::nonFiniteEffectBlocks();
  8821. const auto& info = lynx::effectInfo (kind);
  8822. // (FL engines: a fresh instance as the menus make it, from the user's FL installation; round 142)
  8823. auto fx = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  8824. int dragged = 0; // parameter changes made by the mouse drags
  8825. for (int round = 0; round < rounds; ++round)
  8826. {
  8827. if (round > 0)
  8828. for (std::size_t p = 0; p < info.params.size(); ++p)
  8829. fx.params[p] = round == 1 ? 0.0f : round == 2 ? 1.0f : value();
  8830. auto song = lynx::Song::makeDefault(); // its demo beat feeds the effect
  8831. song.mixer.resize (2);
  8832. song.mixer[0].name = "Master";
  8833. song.mixer[1].name = "Insert 1";
  8834. song.mixer[1].effects.assign (1, fx);
  8835. for (auto& channel : song.channels)
  8836. channel.mixerTrack = 1;
  8837. offline.setSong (std::move (song));
  8838. offline.dispatchPendingMessages();
  8839. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  8840. for (int page = 0; page < pages; ++page)
  8841. {
  8842. auto editor = kind == lynx::EffectKind::facetEq ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  8843. : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  8844. if (editor == nullptr || editor->getWidth() <= 0 || editor->getHeight() <= 0)
  8845. continue;
  8846. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  8847. const auto paint = [&] {
  8848. juce::Graphics g (image);
  8849. editor->paintEntireComponent (g, false);
  8850. };
  8851. paint();
  8852. // drags from a grid of points, as a user moving every control (plain left button)
  8853. if (round >= 3 && drags)
  8854. {
  8855. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  8856. const auto step = juce::jmax (12, juce::jmin (editor->getWidth(), editor->getHeight()) / 8);
  8857. for (int y = step / 2; y < editor->getHeight(); y += step)
  8858. for (int x = step / 2; x < editor->getWidth(); x += step)
  8859. {
  8860. auto* target = editor->getComponentAt (x, y);
  8861. if (target == nullptr)
  8862. continue;
  8863. const auto at = target->getLocalPoint (editor.get(), juce::Point<float> ((float) x, (float) y));
  8864. const auto now = juce::Time::getCurrentTime();
  8865. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods) {
  8866. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, at, now, 1, false);
  8867. };
  8868. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  8869. const juce::Component::SafePointer<juce::Component> alive (target);
  8870. target->mouseDown (event (at, down));
  8871. const auto dy = (float) (random.nextBool() ? 400 : -400), dx = (float) (random.nextInt (401) - 200);
  8872. if (alive != nullptr)
  8873. target->mouseDrag (event (at + juce::Point<float> (dx * 0.5f, dy * 0.5f), down));
  8874. if (alive != nullptr)
  8875. target->mouseDrag (event (at + juce::Point<float> (dx, dy), down));
  8876. if (alive != nullptr)
  8877. target->mouseUp (event (at + juce::Point<float> (dx, dy), juce::ModifierKeys()));
  8878. juce::PopupMenu::dismissAllActiveMenus();
  8879. offline.dispatchPendingMessages();
  8880. }
  8881. paint();
  8882. }
  8883. }
  8884. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  8885. offline.renderOffline (0.05, rate);
  8886. if (round == 0 || round >= 3) // keep what the drags set for the next round
  8887. if (offline.getSong().mixer.size() > 1 && ! offline.getSong().mixer[1].effects.empty())
  8888. {
  8889. const auto& now = offline.getSong().mixer[1].effects[0];
  8890. for (std::size_t p = 0; p < fx.params.size(); ++p)
  8891. dragged += now.params[p] != fx.params[p] ? 1 : 0;
  8892. dragged += now.state != fx.state ? 1 : 0;
  8893. fx = now;
  8894. }
  8895. }
  8896. const auto broken = lynx::RackRenderer::nonFiniteEffectBlocks() - before;
  8897. allFinite = allFinite && broken == 0;
  8898. report << info.name << ": " << (broken == 0 ? juce::String ("OK") : "non-finite output in " + juce::String ((juce::int64) broken) + " blocks")
  8899. << " (" << dragged << " changes by mouse)\n";
  8900. if (reportPath.isNotEmpty())
  8901. juce::File (reportPath).replaceWithText (report + "(running)\n"); // what was reached, if it crashes
  8902. }
  8903. }
  8904. lynx::setNativeEditorDemo (false);
  8905. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  8906. report << "result=" << (allFinite ? "OK" : "NONFINITE") << "\n";
  8907. if (reportPath.isNotEmpty())
  8908. juce::File (reportPath).replaceWithText (report);
  8909. return allFinite;
  8910. }
  8911. // --opentest (round 157a): see the command line. Runs on the message loop (the editors' timers, animations and
  8912. // native windows are real); one step per timer tick.
  8913. void runOpenTest (const juce::String& reportPath, bool visible, std::function<void (bool)> done)
  8914. {
  8915. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  8916. struct OpenTest final : juce::Timer
  8917. {
  8918. juce::String reportPath, report;
  8919. bool visible = false, ok = true;
  8920. std::function<void (bool)> done;
  8921. std::unique_ptr<lynx::AudioEngine> engine;
  8922. std::vector<std::pair<juce::String, std::function<void()>>> steps;
  8923. std::size_t next = 0;
  8924. std::atomic<std::int64_t> lastStep { 0 };
  8925. std::atomic<bool> finished { false };
  8926. std::thread watchdog;
  8927. juce::String current;
  8928. std::mutex currentLock;
  8929. int opened = 0, painted = 0;
  8930. // LYNX_OPENTEST_TIMEOUT (seconds): longer for sanitizer builds
  8931. const std::int64_t timeoutMs = 1000 * juce::jmax (5, juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_TIMEOUT", "20").getIntValue());
  8932. static std::int64_t now() { return (std::int64_t) juce::Time::getMillisecondCounter(); }
  8933. void write (const juce::String& tail = {}) { juce::File (reportPath).replaceWithText (report + tail); }
  8934. ~OpenTest() override
  8935. {
  8936. finished = true;
  8937. if (watchdog.joinable())
  8938. watchdog.join();
  8939. }
  8940. void start()
  8941. {
  8942. lastStep = now();
  8943. // the UI hang watch runs during the whole test (5 s): a slow step leaves its stack next to the report
  8944. const auto folder = juce::File (reportPath).getParentDirectory().getChildFile ("opentest-hang");
  8945. folder.deleteRecursively();
  8946. folder.createDirectory();
  8947. lynx::crashguard::startHangWatch (folder.getFullPathName().replaceCharacter ('\\', '/').toStdString(), 5000);
  8948. watchdog = std::thread ([this] {
  8949. while (! finished)
  8950. {
  8951. std::this_thread::sleep_for (std::chrono::milliseconds (200));
  8952. if (now() - lastStep.load() > timeoutMs)
  8953. {
  8954. juce::String at;
  8955. {
  8956. const std::lock_guard<std::mutex> l (currentLock);
  8957. at = current;
  8958. }
  8959. juce::File (reportPath).replaceWithText (report + "HANG at " + at + " (no progress for " + juce::String (timeoutMs / 1000) + " s; stack in opentest-hang)\nresult=HANG\n");
  8960. lynx::crashguard::exitNow (3);
  8961. }
  8962. }
  8963. });
  8964. startTimer (30);
  8965. }
  8966. // every LYNX window but none of the main one (there is none here): moved off-screen, painted once into an image
  8967. void touchWindows (bool resize, bool large)
  8968. {
  8969. auto& desktop = juce::Desktop::getInstance();
  8970. for (int i = desktop.getNumComponents(); --i >= 0;)
  8971. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible())
  8972. {
  8973. if (! visible && c->getScreenX() > -3000)
  8974. c->setTopLeftPosition (-6000, -6000);
  8975. if (resize)
  8976. if (auto* w = dynamic_cast<juce::ResizableWindow*> (c))
  8977. {
  8978. const auto b = w->getBounds();
  8979. w->setSize (large ? b.getWidth() * 2 : juce::jmax (40, b.getWidth() / 3), large ? b.getHeight() * 2 : juce::jmax (40, b.getHeight() / 3));
  8980. }
  8981. if (c->getWidth() > 0 && c->getHeight() > 0 && c->getWidth() < 8000 && c->getHeight() < 8000)
  8982. {
  8983. juce::Image image (juce::Image::ARGB, c->getWidth(), c->getHeight(), true);
  8984. juce::Graphics g (image);
  8985. c->paintEntireComponent (g, false);
  8986. ++painted;
  8987. // LYNX_OPENTEST_SHOTS=folder: each window as first painted (before the resizes), for a look
  8988. if (const auto shots = juce::SystemStats::getEnvironmentVariable ("LYNX_OPENTEST_SHOTS", {}); shots.isNotEmpty() && ! resize)
  8989. {
  8990. juce::FileOutputStream out (juce::File (shots).getChildFile (juce::String (painted).paddedLeft ('0', 4) + ".png"));
  8991. if (out.openedOk())
  8992. {
  8993. out.setPosition (0), out.truncate();
  8994. juce::PNGImageFormat().writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  8995. }
  8996. }
  8997. }
  8998. }
  8999. }
  9000. void timerCallback() override
  9001. {
  9002. if (next >= steps.size())
  9003. {
  9004. stopTimer();
  9005. lynx::NativeEffectWindows::closeAll();
  9006. lynx::closeChannelSettings();
  9007. // the UI hang watch itself: the message thread spins past the stall time; the watcher must write the stack
  9008. {
  9009. const auto before = lynx::crashguard::lastHangFile();
  9010. for (const auto until = now() + 7000; now() < until;)
  9011. lastStep = now(); // (busy: no heartbeat; the test's own watchdog stays quiet)
  9012. for (const auto until = now() + 1500; now() < until && lynx::crashguard::lastHangFile() == before;)
  9013. std::this_thread::sleep_for (std::chrono::milliseconds (20));
  9014. lynx::crashguard::stopHangWatch();
  9015. const juce::File hang (juce::String::fromUTF8 (lynx::crashguard::lastHangFile().c_str()));
  9016. const auto text = hang.loadFileAsString();
  9017. const auto frames = juce::StringArray::fromLines (text).size() - 2;
  9018. #if JUCE_WINDOWS
  9019. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && text.contains ("LYNX.exe+0x") && frames >= 3;
  9020. #else
  9021. const auto hangOk = lynx::crashguard::lastHangFile() != before && hang.existsAsFile() && frames >= 3;
  9022. #endif
  9023. report << "hang watch: " << (hangOk ? "OK" : "FAIL") << " (" << hang.getFileName() << ", " << frames << " lines"
  9024. << (before.empty() ? juce::String() : "; a step stalled > 5 s earlier: " + juce::String::fromUTF8 (before.c_str())) << ")\n";
  9025. ok = ok && hangOk;
  9026. }
  9027. report << "windows opened: " << opened << ", paints: " << painted << "\nresult=" << (ok ? "OK" : "FAIL") << "\n";
  9028. write();
  9029. finished = true;
  9030. if (done)
  9031. done (ok);
  9032. return;
  9033. }
  9034. auto& [label, fn] = steps[next++];
  9035. {
  9036. const std::lock_guard<std::mutex> l (currentLock);
  9037. current = label;
  9038. }
  9039. fn();
  9040. lastStep = now();
  9041. lynx::crashguard::heartbeat();
  9042. }
  9043. };
  9044. auto* test = new OpenTest();
  9045. test->reportPath = reportPath;
  9046. test->visible = visible;
  9047. test->engine = std::make_unique<lynx::AudioEngine> (false);
  9048. test->done = [test, done] (bool ok) {
  9049. juce::MessageManager::callAsync ([test, done, ok] {
  9050. delete test;
  9051. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  9052. done (ok);
  9053. });
  9054. };
  9055. auto& engine = *test->engine;
  9056. lynx::setNativeEditorDemo (true); // live displays animate without an audio device
  9057. const auto songWith = [] (const lynx::EffectSlot& fx) {
  9058. auto song = lynx::Song::makeDefault();
  9059. song.mixer.resize (2);
  9060. song.mixer[0].name = "Master";
  9061. song.mixer[1].name = "Insert 1";
  9062. song.mixer[1].effects.assign (1, fx);
  9063. for (auto& channel : song.channels)
  9064. channel.mixerTrack = 1;
  9065. return song;
  9066. };
  9067. // an older project's slot: its parameter list cut to `count` and read back by the project reader (the
  9068. // parameters a newer LYNX added after them take their defaults)
  9069. const auto oldState = [songWith] (const lynx::EffectSlot& fx, std::size_t count) -> std::optional<lynx::Song> {
  9070. auto json = juce::JSON::parse (lynx::ProjectFile::toJson (songWith (fx)));
  9071. if (auto* mixer = json["mixer"].getArray(); mixer != nullptr && mixer->size() > 1)
  9072. if (auto* effects = (*mixer)[1]["effects"].getArray(); effects != nullptr && ! effects->isEmpty())
  9073. if (auto* params = (*effects)[0]["params"].getArray())
  9074. params->removeRange ((int) count, params->size());
  9075. juce::String error;
  9076. return lynx::ProjectFile::fromJson (juce::JSON::toString (json), error);
  9077. };
  9078. auto& steps = test->steps;
  9079. juce::Random random (157);
  9080. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  9081. {
  9082. const auto kind = (lynx::EffectKind) k;
  9083. if (! lynx::NativeEffectWindows::canOpen (kind) || kind == lynx::EffectKind::patcher)
  9084. continue;
  9085. const auto& info = lynx::effectInfo (kind);
  9086. const auto base = lynx::natives::newEffect (kind, lynx::flStudioAccess()).value_or (lynx::makeEffectSlot (kind));
  9087. const auto n = info.params.size();
  9088. std::vector<std::pair<juce::String, std::function<std::optional<lynx::Song>()>>> variants;
  9089. variants.push_back ({ "default", [=] { return std::optional<lynx::Song> (songWith (base)); } });
  9090. for (const auto value : { 0.0f, 1.0f })
  9091. variants.push_back ({ value == 0.0f ? "all 0" : "all 1", [=] {
  9092. auto fx = base;
  9093. for (std::size_t p = 0; p < n; ++p) fx.params[p] = value;
  9094. return std::optional<lynx::Song> (songWith (fx));
  9095. } });
  9096. const auto seed = random.nextInt64();
  9097. variants.push_back ({ "random", [=] {
  9098. juce::Random r (seed);
  9099. auto fx = base;
  9100. for (std::size_t p = 0; p < n; ++p) fx.params[p] = r.nextFloat();
  9101. return std::optional<lynx::Song> (songWith (fx));
  9102. } });
  9103. std::vector<std::size_t> cuts { n / 2 };
  9104. 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)
  9105. if (c < n) cuts.push_back (c);
  9106. for (const auto c : cuts)
  9107. variants.push_back ({ "old project (" + juce::String ((int) c) + " of " + juce::String ((int) n) + " params)", [=] { return oldState (base, c); } });
  9108. for (const auto& [variant, makeSong] : variants)
  9109. {
  9110. const auto label = juce::String::fromUTF8 (info.name) + " / " + variant;
  9111. steps.push_back ({ label + ": open", [test, &engine, label, makeSong = makeSong] {
  9112. auto song = makeSong();
  9113. if (! song)
  9114. {
  9115. test->report << "FAIL " << label << ": project reader refused the state\n";
  9116. test->ok = false;
  9117. return;
  9118. }
  9119. engine.setSong (std::move (*song));
  9120. engine.dispatchPendingMessages();
  9121. lynx::NativeEffectWindows::open (engine, 1, 0);
  9122. ++test->opened;
  9123. test->touchWindows (false, false);
  9124. } });
  9125. steps.push_back ({ label + ": run", [test, &engine] {
  9126. for (const auto rate : { 44100.0, 48000.0, 96000.0 })
  9127. engine.renderOffline (0.03, rate);
  9128. test->touchWindows (false, false);
  9129. } });
  9130. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  9131. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  9132. steps.push_back ({ label + ": close", [test, label] {
  9133. lynx::NativeEffectWindows::closeAll();
  9134. test->report << label << ": OK\n";
  9135. test->write ("(running)\n");
  9136. } });
  9137. }
  9138. }
  9139. // instruments: the channel window the Channel rack opens (Patcher: its graph window, not here)
  9140. for (int k = 0; k <= (int) lynx::InstrumentKind::soundfont; ++k)
  9141. {
  9142. const auto kind = (lynx::InstrumentKind) k;
  9143. if (kind == lynx::InstrumentKind::plugin || kind == lynx::InstrumentKind::patcher)
  9144. continue;
  9145. for (const auto* variant : { "default", "old project (saved and read back)", "odd settings" })
  9146. {
  9147. if (juce::String (variant) == "odd settings" && kind != lynx::InstrumentKind::soundfont)
  9148. continue;
  9149. const auto label = "instrument " + juce::String (k) + " / " + variant;
  9150. steps.push_back ({ label + ": open", [test, &engine, kind, label, variant = juce::String (variant), old = juce::String (variant) != "default"] {
  9151. auto song = lynx::Song::makeDefault();
  9152. auto channel = lynx::natives::makeChannel (kind, lynx::flStudioAccess());
  9153. lynx::ChannelDef def;
  9154. def.instrument = kind;
  9155. def.name = "Test";
  9156. song.channels.push_back (channel ? *channel : def);
  9157. if (kind == lynx::InstrumentKind::soundfont && variant != "default")
  9158. {
  9159. // a real font when FL's is there; NaN / huge / truncated settings
  9160. const auto& roots = lynx::flStudioAccess().roots;
  9161. if (! roots.data.empty())
  9162. song.channels.back().samplePath = (juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  9163. .getChildFile ("Patches/Soundfonts/STR_Ensemble.sf2"))
  9164. .getFullPathName().toStdString();
  9165. if (variant == "odd settings")
  9166. song.channels.back().modelParams = { NAN, 1.0e9f, -1.0e9f, 0.5f, 7.0f };
  9167. }
  9168. if (old)
  9169. {
  9170. juce::String error;
  9171. if (auto again = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error))
  9172. song = std::move (*again);
  9173. }
  9174. const auto index = (int) song.channels.size() - 1;
  9175. engine.setSong (std::move (song));
  9176. engine.dispatchPendingMessages();
  9177. lynx::openChannelSettings (engine, index);
  9178. ++test->opened;
  9179. test->touchWindows (false, false);
  9180. } });
  9181. steps.push_back ({ label + ": run", [test, &engine] {
  9182. engine.renderOffline (0.03, 48000.0);
  9183. test->touchWindows (false, false);
  9184. } });
  9185. steps.push_back ({ label + ": small", [test] { test->touchWindows (true, false); } });
  9186. steps.push_back ({ label + ": large", [test] { test->touchWindows (true, true); } });
  9187. steps.push_back ({ label + ": close", [test, label] {
  9188. lynx::closeChannelSettings();
  9189. test->report << label << ": OK\n";
  9190. test->write ("(running)\n");
  9191. } });
  9192. }
  9193. }
  9194. test->start();
  9195. }
  9196. void runPluginOptionsTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath)
  9197. {
  9198. struct Test final : juce::Timer
  9199. {
  9200. juce::String reportPath, report;
  9201. juce::File shots;
  9202. std::unique_ptr<lynx::AudioEngine> engine;
  9203. std::unique_ptr<juce::DocumentWindow> mainWindow, other; // LYNX's main window stand-in; another secondary window
  9204. bool instrument = false, ok = true;
  9205. int channelIndex = -1, phase = 0;
  9206. juce::uint32 phaseStart = 0;
  9207. juce::AudioPluginInstance* instance = nullptr;
  9208. std::function<void (bool)> done;
  9209. void step (const juce::String& line)
  9210. {
  9211. report << line << "\n";
  9212. juce::File (reportPath).replaceWithText (report);
  9213. }
  9214. void expect (const juce::String& name, bool value)
  9215. {
  9216. step (name + "=" + juce::String ((int) value));
  9217. ok = ok && value;
  9218. }
  9219. void next (int to)
  9220. {
  9221. phase = to;
  9222. phaseStart = juce::Time::getMillisecondCounter();
  9223. }
  9224. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  9225. lynx::PluginRef* ref (lynx::Song& song) const
  9226. {
  9227. if (instrument)
  9228. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  9229. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  9230. }
  9231. const lynx::PluginRef& refNow() const { return *ref (const_cast<lynx::Song&> (engine->getSong())); }
  9232. juce::AudioPluginInstance* find()
  9233. {
  9234. if (instrument)
  9235. {
  9236. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  9237. return &p->getInstance();
  9238. }
  9239. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  9240. return &p->getInstance();
  9241. return nullptr;
  9242. }
  9243. void openWindow()
  9244. {
  9245. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  9246. : std::shared_ptr<void> (engine->getEffect (1, 0));
  9247. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  9248. { engine.get(), [this] (lynx::Song& song) { return ref (song); }, instrument, instrument ? -1 : 1,
  9249. instrument ? -1 : 0, {}, {} });
  9250. }
  9251. void shot (const char* name, bool settingsPage = false)
  9252. {
  9253. if (shots != juce::File() && instance != nullptr)
  9254. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  9255. }
  9256. // the plugin window is in front of the other secondary window
  9257. bool pluginInFront()
  9258. {
  9259. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  9260. #if JUCE_WINDOWS
  9261. return plug != nullptr && lynx::nativechild::isAbove (plug, other->getWindowHandle());
  9262. #else
  9263. auto& desktop = juce::Desktop::getInstance();
  9264. for (int i = 0; i < desktop.getNumComponents(); ++i)
  9265. if (auto* c = desktop.getComponent (i); c->getWindowHandle() == plug)
  9266. return c->isAlwaysOnTop() || desktop.getComponent (desktop.getNumComponents() - 1) == c;
  9267. return false;
  9268. #endif
  9269. }
  9270. void timerCallback() override
  9271. {
  9272. if (phase == 0) // waiting for the engine to host the plugin
  9273. {
  9274. instance = find();
  9275. if (instance == nullptr)
  9276. {
  9277. if (elapsed() > 20000)
  9278. finish ("not hosted");
  9279. return;
  9280. }
  9281. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  9282. openWindow();
  9283. next (1);
  9284. return;
  9285. }
  9286. if (phase == 1 && elapsed() >= 800) // Pin on top: off for a new plugin
  9287. {
  9288. expect ("pin_off_by_default", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  9289. shot ("pin-off");
  9290. const auto history = engine->getHistoryPosition();
  9291. lynx::PluginWindows::setPinnedOnTop (*instance, true);
  9292. expect ("pin_set", lynx::PluginWindows::isPinnedOnTop (*instance) && refNow().pinned);
  9293. expect ("pin_no_undo_step_project_modified", engine->getHistoryPosition() == history && engine->isModified());
  9294. // another secondary window brought in front of it
  9295. other = std::make_unique<juce::DocumentWindow> ("Another LYNX window", juce::Colours::darkslategrey, juce::DocumentWindow::closeButton);
  9296. other->setUsingNativeTitleBar (true);
  9297. other->setBounds (mainWindow->getX() + 60, mainWindow->getY() + 60, 420, 300);
  9298. other->setVisible (true);
  9299. lynx::keepAboveMainWindow (*other);
  9300. lynx::forceForegroundForTest (*other);
  9301. other->toFront (true);
  9302. next (2);
  9303. return;
  9304. }
  9305. if (phase == 2 && elapsed() >= 1200)
  9306. {
  9307. expect ("pinned_stays_in_front_of_a_clicked_window", pluginInFront());
  9308. shot ("pin-on");
  9309. // closed and opened again: the pin comes back from the project
  9310. lynx::PluginWindows::close (*instance);
  9311. openWindow();
  9312. next (3);
  9313. return;
  9314. }
  9315. if (phase == 3 && elapsed() >= 600)
  9316. {
  9317. expect ("pin_remembered_when_reopened", lynx::PluginWindows::isPinnedOnTop (*instance));
  9318. lynx::PluginWindows::setPinnedOnTop (*instance, false);
  9319. expect ("pin_cleared", ! lynx::PluginWindows::isPinnedOnTop (*instance) && ! refNow().pinned);
  9320. other->toFront (true);
  9321. next (4);
  9322. return;
  9323. }
  9324. if (phase == 4 && elapsed() >= 1000)
  9325. {
  9326. #if JUCE_WINDOWS
  9327. expect ("unpinned_goes_behind_a_clicked_window", ! pluginInFront());
  9328. #endif
  9329. other = nullptr;
  9330. // the wrapper settings page: LYNX's Velocity row in the MIDI group (instruments), default = follow
  9331. expect ("velocity_follows_midi_settings_by_default", refNow().velocityMode == lynx::prefs::pluginVelocityFollow
  9332. && refNow().fixedVelocity == lynx::prefs::defaultFixedVelocity);
  9333. shot ("wrapper-velocity-default", true);
  9334. engine->editSong ([this] (lynx::Song& song) {
  9335. if (auto* r = ref (song))
  9336. {
  9337. r->velocityMode = lynx::prefs::pluginVelocityFixed;
  9338. r->fixedVelocity = 96;
  9339. }
  9340. });
  9341. next (5);
  9342. return;
  9343. }
  9344. if (phase == 5 && elapsed() >= 400)
  9345. {
  9346. expect ("velocity_change_keeps_the_running_plugin", find() == instance);
  9347. shot ("wrapper-velocity-fixed", true);
  9348. engine->undo();
  9349. expect ("velocity_undo", refNow().velocityMode == lynx::prefs::pluginVelocityFollow && find() == instance);
  9350. // the preset menu's "Play a note when a preset loads": off by default, a user setting
  9351. expect ("audition_off_by_default", ! lynx::pluginpresetui::auditionOnLoad());
  9352. lynx::pluginpresetui::setAuditionOnLoad (true);
  9353. expect ("audition_menu_opened", lynx::PluginWindows::showPresetMenu (*instance));
  9354. next (6);
  9355. return;
  9356. }
  9357. if (phase == 6 && elapsed() >= 500) // the menu, as drawn
  9358. {
  9359. auto found = false;
  9360. auto& desktop = juce::Desktop::getInstance();
  9361. for (int c = desktop.getNumComponents(); --c >= 0 && ! found;)
  9362. if (auto* menu = desktop.getComponent (c); dynamic_cast<juce::TopLevelWindow*> (menu) == nullptr && menu->isVisible()
  9363. && menu->getHeight() > 60 && shots != juce::File())
  9364. {
  9365. const auto image = menu->createComponentSnapshot (menu->getLocalBounds(), true, 1.0f);
  9366. juce::FileOutputStream out (shots.getChildFile ("preset-menu-audition.png"));
  9367. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  9368. }
  9369. step ("shot_preset-menu-audition=" + juce::String ((int) found));
  9370. juce::PopupMenu::dismissAllActiveMenus();
  9371. // a preset loaded while the song is stopped: the note waits a moment, sounds, ends
  9372. const auto asked = engine->auditionPreset (*instance);
  9373. expect ("audition_only_for_channel_instruments", asked == instrument);
  9374. expect ("audition_waits_first", ! instrument || engine->auditionState() == 1);
  9375. next (7);
  9376. return;
  9377. }
  9378. if (phase == 7 && elapsed() >= 300)
  9379. {
  9380. expect ("audition_sounds", ! instrument || engine->auditionState() == 2);
  9381. next (8);
  9382. return;
  9383. }
  9384. if (phase == 8 && elapsed() >= 700)
  9385. {
  9386. expect ("audition_ends", engine->auditionState() == 0);
  9387. engine->getTransport().playing.store (true); // the song plays: no audition
  9388. expect ("no_audition_while_playing", ! engine->auditionPreset (*instance) && engine->auditionState() == 0);
  9389. engine->getTransport().playing.store (false);
  9390. lynx::pluginpresetui::setAuditionOnLoad (false);
  9391. expect ("audition_setting_off_again", ! lynx::pluginpresetui::auditionOnLoad());
  9392. finish ({});
  9393. }
  9394. }
  9395. void finish (const juce::String& failure)
  9396. {
  9397. stopTimer();
  9398. if (failure.isNotEmpty())
  9399. step ("failed=" + failure);
  9400. ok = ok && failure.isEmpty();
  9401. step (ok ? "result=OK" : "result=FAILED");
  9402. lynx::PluginWindows::closeAll();
  9403. done (ok);
  9404. }
  9405. };
  9406. auto* test = new Test();
  9407. test->reportPath = reportPath;
  9408. if (shotsPath.isNotEmpty())
  9409. {
  9410. test->shots = juce::File (shotsPath);
  9411. test->shots.createDirectory();
  9412. }
  9413. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9414. test->done = [this, test] (bool ok) {
  9415. setApplicationReturnValue (ok ? 0 : 1);
  9416. juce::MessageManager::callAsync ([this, test] {
  9417. lynx::setMainWindowForOwnership (nullptr);
  9418. test->other = nullptr;
  9419. test->mainWindow = nullptr;
  9420. test->engine = nullptr;
  9421. delete test;
  9422. quit();
  9423. });
  9424. };
  9425. test->engine = std::make_unique<lynx::AudioEngine> (false);
  9426. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  9427. test->mainWindow->setBounds (20, 20, 300, 200);
  9428. test->mainWindow->setVisible (true);
  9429. lynx::setMainWindowForOwnership (test->mainWindow.get());
  9430. auto& host = test->engine->getPluginHost();
  9431. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  9432. std::optional<juce::PluginDescription> chosen;
  9433. for (const auto& type : host.getKnownPlugins().getTypes())
  9434. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  9435. {
  9436. chosen = type;
  9437. break;
  9438. }
  9439. if (! chosen)
  9440. {
  9441. test->step ("result=FAILED (no plugin)");
  9442. test->done (false);
  9443. return;
  9444. }
  9445. test->instrument = chosen->isInstrument;
  9446. lynx::PluginRef ref;
  9447. ref.id = chosen->createIdentifierString().toStdString();
  9448. ref.name = chosen->name.toStdString();
  9449. test->engine->editSong ([&] (lynx::Song& song) {
  9450. if (test->instrument)
  9451. {
  9452. lynx::ChannelDef c;
  9453. c.name = ref.name;
  9454. c.instrument = lynx::InstrumentKind::plugin;
  9455. c.plugin = ref;
  9456. test->channelIndex = (int) song.channels.size();
  9457. song.channels.push_back (c);
  9458. }
  9459. else
  9460. {
  9461. while (song.mixer.size() < 2)
  9462. song.mixer.emplace_back();
  9463. lynx::EffectSlot slot;
  9464. slot.kind = lynx::EffectKind::plugin;
  9465. slot.plugin = ref;
  9466. song.mixer[1].effects.push_back (slot);
  9467. }
  9468. });
  9469. test->engine->markSaved();
  9470. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  9471. test->next (0);
  9472. test->startTimerHz (20);
  9473. }
  9474. void runReloadTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& shotsPath, bool waitKill)
  9475. {
  9476. struct Test final : juce::Timer
  9477. {
  9478. juce::String reportPath, report;
  9479. juce::File shots;
  9480. std::unique_ptr<lynx::AudioEngine> engine;
  9481. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  9482. bool instrument = false, waitKill = false, ok = true;
  9483. int channelIndex = -1, phase = 0, round = 0;
  9484. juce::uint32 phaseStart = 0;
  9485. int firstPid = 0, pid = 0, historyBefore = 0;
  9486. bool modifiedBefore = false;
  9487. float captured = -1.0f;
  9488. juce::AudioPluginInstance* instance = nullptr;
  9489. std::vector<lynx::ChannelDef> channelsBefore;
  9490. std::function<void (bool)> done;
  9491. lynx::AudioEngine::HostedSlot where() const { return instrument ? lynx::AudioEngine::HostedSlot { channelIndex, -1, -1 } : lynx::AudioEngine::HostedSlot { -1, 1, 0 }; }
  9492. void step (const juce::String& line)
  9493. {
  9494. report << line << "\n";
  9495. juce::File (reportPath).replaceWithText (report);
  9496. }
  9497. void expect (const juce::String& name, bool value)
  9498. {
  9499. step (name + "=" + juce::String ((int) value));
  9500. ok = ok && value;
  9501. }
  9502. void next (int to)
  9503. {
  9504. phase = to;
  9505. phaseStart = juce::Time::getMillisecondCounter();
  9506. }
  9507. int elapsed() const { return (int) (juce::Time::getMillisecondCounter() - phaseStart); }
  9508. juce::AudioPluginInstance* find()
  9509. {
  9510. if (instrument)
  9511. {
  9512. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  9513. return &p->getInstance();
  9514. }
  9515. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  9516. return &p->getInstance();
  9517. return nullptr;
  9518. }
  9519. // a few blocks through the plugin (the offline engine has no audio thread): they carry parameter changes to
  9520. // the plugin's process and its values back
  9521. void pump (int blocks)
  9522. {
  9523. std::vector<float> l (512), r (512);
  9524. lynx::EffectParams none {};
  9525. for (int b = 0; b < blocks; ++b)
  9526. {
  9527. std::fill (l.begin(), l.end(), 0.0f);
  9528. std::fill (r.begin(), r.end(), 0.0f);
  9529. if (instrument)
  9530. {
  9531. if (auto in = engine->getChannelInstrument (channelIndex))
  9532. in->render (l.data(), r.data(), 512, 1.0f, 1.0f);
  9533. }
  9534. else if (auto fx = engine->getEffect (1, 0))
  9535. fx->process (l.data(), r.data(), 512, none, 120.0);
  9536. }
  9537. }
  9538. juce::AudioProcessorParameter* firstParam()
  9539. {
  9540. if (instance != nullptr)
  9541. for (auto* candidate : instance->getParameters())
  9542. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  9543. return candidate;
  9544. return nullptr;
  9545. }
  9546. void openWindow()
  9547. {
  9548. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  9549. : std::shared_ptr<void> (engine->getEffect (1, 0));
  9550. lynx::PluginWindows::WrapperContext context { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  9551. if (instrument)
  9552. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  9553. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  9554. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  9555. }, instrument, instrument ? -1 : 1, instrument ? -1 : 0, {}, {} };
  9556. context.reload = [] {}; // (the test reloads by itself; with it the window shows the notice)
  9557. lynx::PluginWindows::open (owner, *instance, instance->getName(), std::move (context));
  9558. }
  9559. void shot (const char* name, bool settingsPage = false)
  9560. {
  9561. if (shots != juce::File() && instance != nullptr)
  9562. step (juce::String ("shot_") + name + "=" + juce::String ((int) lynx::PluginWindows::saveWindowShot (*instance, shots.getChildFile (juce::String (name) + ".png"), settingsPage)));
  9563. }
  9564. void timerCallback() override
  9565. {
  9566. if (phase == 0) // waiting for the engine to host the plugin
  9567. {
  9568. instance = find();
  9569. if (instance == nullptr)
  9570. {
  9571. if (elapsed() > 20000)
  9572. finish ("not hosted");
  9573. return;
  9574. }
  9575. pid = firstPid = lynx::sandboxedPluginProcessId (*instance);
  9576. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName + " pid=" + juce::String (pid));
  9577. expect ("separate_process", lynx::isSandboxedPlugin (*instance) && pid != 0);
  9578. expect ("running", ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  9579. // a setting that is captured (what a save or a backup does), then one that is not
  9580. if (auto* param = firstParam())
  9581. {
  9582. param->setValue (param->getValue() > 0.5f ? 0.13f : 0.87f);
  9583. pump (4);
  9584. engine->capturePluginStates();
  9585. captured = param->getValue();
  9586. param->setValue (captured > 0.5f ? 0.31f : 0.69f);
  9587. pump (4);
  9588. step ("param=" + param->getName (64) + " captured=" + juce::String (captured, 4) + " then=" + juce::String (param->getValue(), 4));
  9589. }
  9590. else
  9591. {
  9592. engine->capturePluginStates();
  9593. step ("param=none");
  9594. }
  9595. channelsBefore = engine->getSong().channels;
  9596. historyBefore = engine->getHistoryPosition();
  9597. modifiedBefore = engine->isModified();
  9598. if (shots != juce::File())
  9599. openWindow();
  9600. next (1);
  9601. return;
  9602. }
  9603. if (phase == 1 && elapsed() >= 600) // the plugin's process goes
  9604. {
  9605. shot (round == 0 ? "window-running" : "window-reloaded");
  9606. if (waitKill && round == 0)
  9607. {
  9608. juce::File (reportPath + ".pid").replaceWithText (juce::String (pid));
  9609. step ("waiting_for_kill pid=" + juce::String (pid));
  9610. }
  9611. else
  9612. lynx::crashSandboxedPluginForTest (*instance);
  9613. next (2);
  9614. return;
  9615. }
  9616. if (phase == 2) // LYNX notices
  9617. {
  9618. if (! engine->hostedPluginDown (where()))
  9619. {
  9620. pump (1); // (as the audio thread would: a block that gets no answer marks it too)
  9621. if (elapsed() > (waitKill && round == 0 ? 120000 : 10000))
  9622. finish ("the plugin never went down");
  9623. return;
  9624. }
  9625. step ("down_after_ms=" + juce::String (elapsed()));
  9626. const auto down = engine->downHostedPlugins();
  9627. expect ("listed_down", down.size() == 1 && down.front() == where());
  9628. expect ("listed_by_name", engine->downHostedPlugins (nameInSong()).size() == 1 && engine->downHostedPlugins ("no such plugin").empty());
  9629. next (3);
  9630. return;
  9631. }
  9632. if (phase == 3 && elapsed() >= 1500) // nothing reloads by itself
  9633. {
  9634. expect ("still_down_without_asking", engine->hostedPluginDown (where()) && find() == instance
  9635. && lynx::sandboxedPluginProcessId (*instance) == pid);
  9636. shot (round == 0 ? "reload-notice" : "reload-notice-again");
  9637. if (shots != juce::File() && round == 0)
  9638. {
  9639. lynx::PluginWindows::close (*instance);
  9640. lynx::PluginWindows::promptReload (*engine, where(), {});
  9641. next (4);
  9642. return;
  9643. }
  9644. next (5);
  9645. return;
  9646. }
  9647. if (phase == 4 && elapsed() >= 500) // the prompt a click on the channel / slot shows
  9648. {
  9649. auto found = false;
  9650. for (int c = juce::Desktop::getInstance().getNumComponents(); --c >= 0;)
  9651. if (auto* alert = dynamic_cast<juce::AlertWindow*> (juce::Desktop::getInstance().getComponent (c)))
  9652. {
  9653. const auto image = alert->createComponentSnapshot (alert->getLocalBounds(), true, 1.0f);
  9654. juce::FileOutputStream out (shots.getChildFile ("reload-prompt.png"));
  9655. found = out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  9656. alert->exitModalState (0); // Close: nothing reloads
  9657. break;
  9658. }
  9659. step ("shot_reload-prompt=" + juce::String ((int) found));
  9660. next (45);
  9661. return;
  9662. }
  9663. if (phase == 45 && elapsed() >= 300)
  9664. {
  9665. expect ("still_down_after_close", engine->hostedPluginDown (where()));
  9666. next (5);
  9667. return;
  9668. }
  9669. if (phase == 5) // Reload, as the notice's button / the prompt / the menu item do
  9670. {
  9671. auto* old = instance;
  9672. const auto running = lynx::PluginWindows::reload (*engine, { where() });
  9673. instance = find();
  9674. const auto newPid = instance != nullptr ? lynx::sandboxedPluginProcessId (*instance) : 0;
  9675. expect ("reloaded", running == 1 && instance != nullptr && ! engine->hostedPluginDown (where()) && engine->downHostedPlugins().empty());
  9676. expect ("new_process", newPid != 0 && newPid != pid);
  9677. step ("pid=" + juce::String (newPid) + " same_object=" + juce::String ((int) (instance == old)));
  9678. expect ("old_window_closed", ! lynx::PluginWindows::isOpen (*old) || instance == old);
  9679. pid = newPid;
  9680. if (instance != nullptr)
  9681. {
  9682. pump (4);
  9683. if (auto* param = firstParam(); param != nullptr && captured >= 0.0f)
  9684. {
  9685. step ("param_after_reload=" + juce::String (param->getValue(), 4));
  9686. expect ("state_captured_last", std::abs (param->getValue() - captured) < 0.02f);
  9687. }
  9688. }
  9689. expect ("song_untouched", engine->getSong().channels == channelsBefore);
  9690. expect ("no_undo_step", engine->getHistoryPosition() == historyBefore && engine->isModified() == modifiedBefore);
  9691. if (instance == nullptr)
  9692. {
  9693. finish ("no instance after the reload");
  9694. return;
  9695. }
  9696. if (shots != juce::File())
  9697. openWindow();
  9698. if (round == 0) // once more: a plugin that crashes again waits for the user again
  9699. {
  9700. round = 1;
  9701. next (1);
  9702. return;
  9703. }
  9704. next (6);
  9705. return;
  9706. }
  9707. if (phase == 6 && elapsed() >= 400) // an edit and its undo keep the reloaded plugin
  9708. {
  9709. shot ("window-reloaded-twice");
  9710. auto* before = find();
  9711. engine->editSong ([] (lynx::Song& song) { song.bpm += 1.0f; });
  9712. engine->undo();
  9713. expect ("undo_keeps_the_reloaded_plugin", find() == before && ! engine->hostedPluginDown (where()));
  9714. lynx::PluginWindows::closeAll();
  9715. finish ({});
  9716. }
  9717. }
  9718. std::string nameInSong() const
  9719. {
  9720. const auto& song = engine->getSong();
  9721. return instrument ? song.channels[(size_t) channelIndex].plugin.name : song.mixer[1].effects[0].plugin.name;
  9722. }
  9723. void finish (const juce::String& failure)
  9724. {
  9725. stopTimer();
  9726. if (failure.isNotEmpty())
  9727. step ("failed=" + failure);
  9728. ok = ok && failure.isEmpty();
  9729. step (ok ? "result=OK" : "result=FAILED");
  9730. lynx::PluginWindows::closeAll();
  9731. done (ok);
  9732. }
  9733. };
  9734. lynx::setPluginSandboxAlerts (true); // (the deaths are recorded as in the app; no box: there is no main component)
  9735. auto* test = new Test();
  9736. test->reportPath = reportPath;
  9737. test->waitKill = waitKill;
  9738. if (shotsPath.isNotEmpty())
  9739. {
  9740. test->shots = juce::File (shotsPath);
  9741. test->shots.createDirectory();
  9742. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  9743. }
  9744. juce::File (reportPath + ".pid").deleteFile();
  9745. test->done = [this, test] (bool ok) {
  9746. setApplicationReturnValue (ok ? 0 : 1);
  9747. juce::MessageManager::callAsync ([this, test] {
  9748. lynx::setMainWindowForOwnership (nullptr);
  9749. test->mainWindow = nullptr;
  9750. test->engine = nullptr;
  9751. delete test;
  9752. quit();
  9753. });
  9754. };
  9755. test->engine = std::make_unique<lynx::AudioEngine> (false);
  9756. if (shotsPath.isNotEmpty())
  9757. {
  9758. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  9759. test->mainWindow->setBounds (20, 20, 300, 200);
  9760. test->mainWindow->setVisible (true);
  9761. lynx::setMainWindowForOwnership (test->mainWindow.get());
  9762. }
  9763. auto& host = test->engine->getPluginHost();
  9764. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  9765. std::optional<juce::PluginDescription> chosen;
  9766. for (const auto& type : host.getKnownPlugins().getTypes())
  9767. if (juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  9768. {
  9769. chosen = type;
  9770. break;
  9771. }
  9772. if (! chosen)
  9773. {
  9774. test->step ("result=FAILED (no plugin)");
  9775. test->done (false);
  9776. return;
  9777. }
  9778. test->instrument = chosen->isInstrument;
  9779. lynx::PluginRef ref;
  9780. ref.separateProcess = true;
  9781. ref.id = chosen->createIdentifierString().toStdString();
  9782. ref.name = chosen->name.toStdString();
  9783. test->engine->editSong ([&] (lynx::Song& song) {
  9784. if (test->instrument)
  9785. {
  9786. lynx::ChannelDef c;
  9787. c.name = ref.name;
  9788. c.instrument = lynx::InstrumentKind::plugin;
  9789. c.plugin = ref;
  9790. test->channelIndex = (int) song.channels.size();
  9791. song.channels.push_back (c);
  9792. }
  9793. else
  9794. {
  9795. while (song.mixer.size() < 2)
  9796. song.mixer.emplace_back();
  9797. lynx::EffectSlot slot;
  9798. slot.kind = lynx::EffectKind::plugin;
  9799. slot.plugin = ref;
  9800. song.mixer[1].effects.push_back (slot);
  9801. }
  9802. });
  9803. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  9804. test->next (0);
  9805. test->startTimerHz (20);
  9806. }
  9807. void runPlugWinTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only, int seconds)
  9808. {
  9809. struct Test final : juce::Timer
  9810. {
  9811. juce::String reportPath, report;
  9812. std::unique_ptr<lynx::AudioEngine> engine;
  9813. bool instrument = false;
  9814. int phase = 0, ticks = 0, seconds = 15, dockStep = 0;
  9815. juce::uint32 phaseStartMs = 0; // (phase 1 counts real time: the timer's ticks ran faster than 20 Hz here)
  9816. juce::AudioPluginInstance* instance = nullptr;
  9817. juce::AudioProcessorParameter* checked = nullptr;
  9818. std::unique_ptr<juce::DocumentWindow> mainWindow; // stands for LYNX's main window (window ownership)
  9819. lynx::Workspace* workspace = nullptr; // LYNX_PLUGWIN_DOCK=1: the real main window's desktop (issue #116)
  9820. int channelIndex = -1; // an instrument: its channel (added after the song's own channels)
  9821. int stepMs = 3000; // dock mode: each state held that long (screenshots)
  9822. bool keysDone = false;
  9823. bool dockOk = true;
  9824. std::function<void (bool)> done;
  9825. // LYNX_PLUGWIN_DROP=<sample> (issue #174): a Sample browser window beside the plugin window with that file
  9826. // selected. The report gives the row's and the editor's places on screen with what LYNX sees there (for a
  9827. // real drag by xdotool / SendInput in that time), and, before the plugin is removed, whether the plugin took
  9828. // the file (its saved state names it).
  9829. juce::File dropFile;
  9830. std::unique_ptr<juce::DocumentWindow> dropWindow;
  9831. lynx::BrowserComponent* dropBrowser = nullptr;
  9832. int dropStage = 0;
  9833. juce::uint32 dropReadyMs = 0; // (the Browser may take long to list a big library: the time counts from here)
  9834. void dropTick (int elapsedMs)
  9835. {
  9836. if (dropStage == 0 && elapsedMs >= 1000)
  9837. {
  9838. lynx::externaldrag::install();
  9839. auto content = lynx::BrowserComponent::makeSampleBrowserContent (*engine, [this] (lynx::BrowserComponent& b) { dropBrowser = &b; });
  9840. dropWindow = std::make_unique<juce::DocumentWindow> ("LYNX test sample browser", juce::Colours::darkgrey, 0);
  9841. dropWindow->setContentOwned (content.release(), false);
  9842. dropWindow->setBounds (20, 240, 340, 520);
  9843. dropWindow->setVisible (true);
  9844. if (dropBrowser != nullptr)
  9845. {
  9846. dropBrowser->showFilterForSnapshot (dropFile.getParentDirectory(), lynx::browserview::ContentFilter::all);
  9847. step ("drop_locate=" + juce::String ((int) dropBrowser->locateFile (dropFile)));
  9848. }
  9849. dropStage = 1;
  9850. }
  9851. else if (dropStage == 1 && elapsedMs >= 2500)
  9852. {
  9853. using namespace lynx::externaldrag;
  9854. const auto row = dropBrowser != nullptr ? dropBrowser->selectedRowScreenBounds() : juce::Rectangle<int>();
  9855. const auto from = row.getCentre();
  9856. // (physical pixels too: SendInput / xdotool work in those)
  9857. auto physical = [] (juce::Point<int> p) {
  9858. const auto q = juce::Desktop::getInstance().getDisplays().logicalToPhysical (p);
  9859. return " phys=" + juce::String (q.x) + "," + juce::String (q.y);
  9860. };
  9861. step ("drop_source=" + juce::String (from.x) + "," + juce::String (from.y) + " place=" + placeName (placeAt (from)) + physical (from));
  9862. if (const auto pid = lynx::sandboxedPluginProcessId (*instance); pid != 0)
  9863. step ("drop_target_pid=" + juce::String (pid)); // (its window is the other process's)
  9864. else if (auto* editor = instance->getActiveEditor())
  9865. {
  9866. const auto to = editor->getScreenBounds().getCentre();
  9867. step ("drop_target=" + juce::String (to.x) + "," + juce::String (to.y) + " place=" + placeName (placeAt (to)) + physical (to));
  9868. }
  9869. const auto files = filesOf (juce::String (lynx::BrowserComponent::dragDescription) + "|" + dropFile.getFullPathName(), nullptr);
  9870. step ("drop_files=" + files.joinIntoString (";"));
  9871. dropStage = 2;
  9872. dropReadyMs = juce::Time::getMillisecondCounter();
  9873. }
  9874. }
  9875. void dropResult()
  9876. {
  9877. juce::MemoryBlock state;
  9878. instance->getStateInformation (state);
  9879. const auto name = dropFile.getFileNameWithoutExtension().toStdString();
  9880. auto holds = [&name] (const juce::MemoryBlock& block) {
  9881. const auto* bytes = static_cast<const char*> (block.getData());
  9882. return ! name.empty() && std::search (bytes, bytes + block.getSize(), name.begin(), name.end()) != bytes + block.getSize();
  9883. };
  9884. auto received = holds (state);
  9885. // (JUCE's VST3 host keeps the plugin's own state base64-encoded inside an XML of its own)
  9886. auto xml = juce::AudioProcessor::getXmlFromBinary (state.getData(), (int) state.getSize());
  9887. if (xml == nullptr)
  9888. xml = juce::parseXML (state.toString());
  9889. if (! received && xml != nullptr)
  9890. for (auto* e : xml->getChildIterator())
  9891. {
  9892. juce::MemoryBlock inner;
  9893. if (inner.fromBase64Encoding (e->getAllSubText().trim()) && holds (inner))
  9894. received = true;
  9895. }
  9896. step ("drop_received=" + juce::String ((int) received));
  9897. }
  9898. // issue #116 (with LYNX_DOCKED_PLUGINS=1 and LYNX_PLUGWIN_DOCK=1), FL's f116 sequence for every floating
  9899. // panel: the docked plugin window goes behind a clicked panel and comes back in front when clicked; a
  9900. // panel called by its key comes in front too; Detached reopens it as a window of its own, which stays above
  9901. // every panel clicked (it is owned by the main window).
  9902. const std::array<lynx::workspace::Panel, 4> dockPanels { lynx::workspace::Panel::channelRack, lynx::workspace::Panel::playlist,
  9903. lynx::workspace::Panel::pianoRoll, lynx::workspace::Panel::mixer };
  9904. const int dockSteps = 2 * 4 + 18; // (the last one reports dock_result)
  9905. int danceChannel = -1; // issue #116 slice 4: a dance channel's dancer over the docked plugin
  9906. lynx::MainComponent* ui = nullptr; // dock mode: the real main window's contents
  9907. struct ScaleSpy final : juce::ComponentPeer::ScaleFactorListener
  9908. {
  9909. int calls = 0;
  9910. double last = 0.0;
  9911. void nativeScaleFactorChanged (double s) override { ++calls; last = s; }
  9912. } scaleSpy;
  9913. juce::ComponentPeer* spiedPeer = nullptr;
  9914. void* panelHandle (lynx::workspace::Panel p) const { return workspace->getFrame (p).getWindowHandle(); }
  9915. void dockCheck (int at)
  9916. {
  9917. using lynx::workspace::Panel;
  9918. auto* main = mainWindow->getWindowHandle();
  9919. auto* plug = lynx::PluginWindows::hostWindowHandle (*instance);
  9920. auto expect = [this] (const juce::String& name, bool value) {
  9921. step (name + "=" + juce::String ((int) value));
  9922. dockOk = dockOk && value;
  9923. };
  9924. auto id = [] (Panel p) { return juce::String (lynx::workspace::panelId (p)); };
  9925. if (at == 0)
  9926. {
  9927. expect ("docked", lynx::PluginWindows::isDocked (*instance));
  9928. expect ("plugin_native_child", plug != nullptr && lynx::nativechild::parentOf (plug) == main);
  9929. for (auto p : dockPanels)
  9930. {
  9931. auto* h = panelHandle (p);
  9932. expect (id (p) + "_visible", workspace->isPanelVisible (p));
  9933. expect (id (p) + "_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  9934. expect ("plugin_above_" + id (p) + "_when_opened", lynx::nativechild::isAbove (plug, h));
  9935. }
  9936. expect ("browser_plain", ! workspace->isNativePanel (Panel::browser));
  9937. }
  9938. if (at < 2 * 4)
  9939. {
  9940. const auto p = dockPanels[at / 2];
  9941. if (at % 2 == 0)
  9942. {
  9943. workspace->activate (p); // a click on the panel
  9944. expect (id (p) + "_above_plugin_after_its_click", lynx::nativechild::isAbove (panelHandle (p), plug));
  9945. // the plugin stays above the panels nobody clicked
  9946. for (auto other : dockPanels)
  9947. if (other != p)
  9948. expect ("plugin_above_" + id (other) + "_after_" + id (p) + "_click", lynx::nativechild::isAbove (plug, panelHandle (other)));
  9949. }
  9950. else
  9951. {
  9952. lynx::PluginWindows::open ({}, *instance, {}); // (open again = a click on the plugin)
  9953. expect ("plugin_above_" + id (p) + "_after_plugin_click", lynx::nativechild::isAbove (plug, panelHandle (p)));
  9954. }
  9955. return;
  9956. }
  9957. if (at == 8)
  9958. {
  9959. // a layout change elsewhere (a panel resized, the Browser shown) keeps the plugin in front; a panel
  9960. // called by its key comes in front of it
  9961. workspace->hide (Panel::browser);
  9962. workspace->show (Panel::browser);
  9963. for (auto p : dockPanels)
  9964. expect ("plugin_above_" + id (p) + "_after_layout_change", lynx::nativechild::isAbove (plug, panelHandle (p)));
  9965. workspace->show (Panel::mixer);
  9966. expect ("mixer_above_plugin_after_show", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  9967. }
  9968. else if (at == 9)
  9969. {
  9970. // the setup wizard (Options › Setup wizard; first start) in front of the native panels and the plugin
  9971. ui->showSetupWizard();
  9972. }
  9973. else if (at == 10)
  9974. {
  9975. auto* overlay = ui->setupOverlayForTest();
  9976. auto* h = overlay != nullptr ? overlay->getWindowHandle() : nullptr;
  9977. expect ("setup_overlay_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  9978. expect ("setup_overlay_above_plugin", lynx::nativechild::isAbove (h, plug));
  9979. for (auto p : dockPanels)
  9980. expect ("setup_overlay_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  9981. workspace->activate (Panel::playlist); // (a panel brought in front by code: the overlay stays in front)
  9982. lynx::PluginWindows::open ({}, *instance, {});
  9983. expect ("setup_overlay_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::playlist)));
  9984. }
  9985. else if (at == 11)
  9986. {
  9987. ui->closeSetupWizardForSnapshot();
  9988. expect ("setup_overlay_closed", ui->setupOverlayForTest() == nullptr);
  9989. // drops: JUCE's list of windows in the native stacking order once a drag starts
  9990. workspace->activate (Panel::mixer);
  9991. workspace->hide (Panel::browser);
  9992. workspace->show (Panel::browser);
  9993. lynx::matchWindowOrderToScreen();
  9994. auto children = lynx::nativechild::attachedChildren (main);
  9995. auto& desktop = juce::Desktop::getInstance();
  9996. int last = -1;
  9997. bool ordered = children.size() >= 5;
  9998. for (auto* c : children)
  9999. if (c->isVisible())
  10000. {
  10001. int at2 = -1;
  10002. for (int k = 0; k < desktop.getNumComponents(); ++k)
  10003. if (desktop.getComponent (k) == c)
  10004. at2 = k;
  10005. ordered = ordered && at2 > last;
  10006. last = at2;
  10007. }
  10008. expect ("drop_order_matches_screen", ordered);
  10009. }
  10010. else if (at == 12)
  10011. {
  10012. // the main window's scale changes (a display with another scale): every native child placed again in
  10013. // physical pixels, the docked editor's window told (JUCE tells child windows nothing by itself)
  10014. for (int i = 0; i < juce::ComponentPeer::getNumPeers(); ++i)
  10015. if (auto* peer = juce::ComponentPeer::getPeer (i); peer != nullptr && peer->getNativeHandle() == plug)
  10016. spiedPeer = peer;
  10017. if (spiedPeer != nullptr)
  10018. spiedPeer->addScaleFactorListener (&scaleSpy);
  10019. lynx::nativechild::notifyScaleListenersForTest (*mainWindow);
  10020. juce::Desktop::getInstance().setGlobalScaleFactor (1.25f); // and LYNX's own UI zoom
  10021. }
  10022. else if (at == 13)
  10023. {
  10024. bool placed = true;
  10025. for (auto* c : lynx::nativechild::attachedChildren (main))
  10026. placed = placed && (! c->isVisible() || lynx::nativechild::placedPhysically (*c));
  10027. expect ("native_children_placed_at_125", placed);
  10028. expect ("docked_editor_told_the_scale", scaleSpy.calls > 0 && spiedPeer != nullptr
  10029. && std::abs (scaleSpy.last - spiedPeer->getPlatformScaleFactor()) < 0.001);
  10030. if (spiedPeer != nullptr && juce::ComponentPeer::isValidPeer (spiedPeer))
  10031. spiedPeer->removeScaleFactorListener (&scaleSpy);
  10032. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  10033. lynx::PluginWindows::setDetached (*instance, true);
  10034. }
  10035. else if (at == 14)
  10036. {
  10037. expect ("detached_reopened", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance));
  10038. expect ("detached_owned_by_main", plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  10039. expect ("detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  10040. for (auto p : dockPanels)
  10041. workspace->activate (p);
  10042. }
  10043. else if (at == 15)
  10044. {
  10045. // (an owned top-level window: above the main window and so above all its child windows)
  10046. expect ("detached_stays_above_clicked_panels", plug != nullptr && lynx::nativechild::ownerOf (plug) == main
  10047. && lynx::nativechild::parentOf (plug) != main && lynx::PluginWindows::isOpen (*instance));
  10048. lynx::PluginWindows::setDetached (*instance, false);
  10049. }
  10050. else if (at == 16)
  10051. {
  10052. // issue #116 slice 4: a Fruity Dance dancer standing on the docked plugin window, in front of it
  10053. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  10054. juce::Rectangle<int> over;
  10055. for (auto* c : lynx::nativechild::attachedChildren (main))
  10056. if (c->getWindowHandle() == plug)
  10057. over = ui->getLocalArea (nullptr, c->getScreenBounds());
  10058. expect ("dance_stage", stage != nullptr && ! over.isEmpty());
  10059. lynx::dance::Settings s;
  10060. s.move = lynx::dance::held; // (a still pose: the pixels tested below stay where they are)
  10061. s.x = over.getCentreX();
  10062. s.y = over.getCentreY() + 70;
  10063. const auto state = lynx::dance::toState (s);
  10064. engine->editSongStructural ([this, state] (lynx::Song& song) {
  10065. lynx::ChannelDef c;
  10066. c.name = "Fruity Dance";
  10067. c.instrument = lynx::InstrumentKind::fruitydance;
  10068. c.pluginState = state;
  10069. danceChannel = (int) song.channels.size();
  10070. song.channels.push_back (c);
  10071. });
  10072. engine->dispatchPendingMessages();
  10073. if (stage != nullptr)
  10074. stage->update();
  10075. }
  10076. else if (at == 17)
  10077. {
  10078. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  10079. auto* w = stage != nullptr ? stage->windowOf (danceChannel) : nullptr;
  10080. auto* h = w != nullptr ? w->getWindowHandle() : nullptr;
  10081. expect ("dancer_window_native_child", h != nullptr && h != main && lynx::nativechild::parentOf (h) == main);
  10082. expect ("dancer_window_layered", lynx::nativechild::isLayered (h));
  10083. expect ("dancer_above_plugin", lynx::nativechild::isAbove (h, plug));
  10084. for (auto p : dockPanels)
  10085. expect ("dancer_above_" + id (p), lynx::nativechild::isAbove (h, panelHandle (p)));
  10086. // panels and the plugin brought in front (clicks, keys): the dancer stays in front of them
  10087. workspace->activate (Panel::mixer);
  10088. workspace->show (Panel::pianoRoll);
  10089. lynx::PluginWindows::open ({}, *instance, {});
  10090. expect ("dancer_stays_in_front", lynx::nativechild::isAbove (h, plug) && lynx::nativechild::isAbove (h, panelHandle (Panel::mixer))
  10091. && lynx::nativechild::isAbove (h, panelHandle (Panel::pianoRoll)));
  10092. // the mouse: the dancer's body takes it, its window's transparent pixels let it through
  10093. if (w != nullptr)
  10094. {
  10095. const auto picture = w->createComponentSnapshot (w->getLocalBounds(), true, 1.0f);
  10096. const auto body = stage->bodyOf (danceChannel) - (w->getScreenPosition() - stage->getScreenPosition());
  10097. juce::Point<int> solid { -1, -1 }, clear { -1, -1 };
  10098. for (int y = body.getCentreY() - 10; y < body.getBottom() && solid.x < 0; ++y)
  10099. for (int x = body.getX(); x < body.getRight() && solid.x < 0; ++x)
  10100. if (picture.getBounds().contains (x, y) && picture.getPixelAt (x, y).getAlpha() == 255)
  10101. solid = { x, y };
  10102. for (int y = 0; y < picture.getHeight() && clear.x < 0; y += 2)
  10103. for (int x = 0; x < picture.getWidth() && clear.x < 0; x += 2)
  10104. if (picture.getPixelAt (x, y).getAlpha() == 0 && ! body.expanded (8).contains (x, y))
  10105. clear = { x, y };
  10106. step ("dancer_window=" + w->getBounds().toString() + " solid=" + solid.toString() + " clear=" + clear.toString());
  10107. auto* atSolid = lynx::nativechild::windowAt (*w, solid);
  10108. auto* atClear = lynx::nativechild::windowAt (*w, clear);
  10109. expect ("dancer_takes_its_body_clicks", solid.x >= 0 && atSolid == h);
  10110. expect ("dancer_lets_clicks_through", clear.x >= 0 && atClear != nullptr && atClear != h);
  10111. expect ("stage_leaves_the_mouse", ! stage->hitTest (stage->bodyOf (danceChannel).getCentreX(), stage->bodyOf (danceChannel).getCentreY()));
  10112. }
  10113. }
  10114. else if (at == 18)
  10115. {
  10116. // no dance channel: no dancer window (nothing drawn, no cost)
  10117. auto* stage = dynamic_cast<lynx::DanceStage*> (ui->danceStageForTest());
  10118. engine->editSongStructural ([this] (lynx::Song& song) {
  10119. if (danceChannel >= 0 && danceChannel < (int) song.channels.size())
  10120. song.channels.erase (song.channels.begin() + danceChannel);
  10121. });
  10122. engine->dispatchPendingMessages();
  10123. if (stage != nullptr)
  10124. stage->update();
  10125. expect ("dancer_window_gone", stage != nullptr && stage->windowCount() == 0);
  10126. }
  10127. else if (at == 19 || at == 20)
  10128. {
  10129. // round 190ev (issue #152, "flickering windows"): on Windows a docked panel no longer fades by its
  10130. // window's alpha (each fade switched its drawing surface twice and the panel flashed); it shows and
  10131. // hides at once, as FL's docked windows. Elsewhere round 190i's fade stays.
  10132. auto& frame = workspace->getFrame (Panel::mixer);
  10133. if (at == 19)
  10134. {
  10135. workspace->show (Panel::mixer);
  10136. expect ("mixer_above_plugin_when_shown", lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  10137. workspace->hide (Panel::mixer);
  10138. expect ("mixer_hides_at_once", ! frame.isVisible() && workspace->nativeFadeDirection (Panel::mixer) == 0
  10139. && frame.getAlpha() == 1.0f && ! lynx::nativechild::isLayered (frame.getWindowHandle()));
  10140. }
  10141. else
  10142. {
  10143. workspace->show (Panel::mixer);
  10144. expect ("mixer_shows_at_once", frame.isVisible() && frame.getAlpha() == 1.0f && workspace->nativeFadeDirection (Panel::mixer) == 0
  10145. && ! lynx::nativechild::isLayered (frame.getWindowHandle())
  10146. && lynx::nativechild::isAbove (panelHandle (Panel::mixer), plug));
  10147. }
  10148. }
  10149. else if (at >= 21 && at <= 23)
  10150. {
  10151. // round 190ev (issue #152, "the Channel rack almost never comes to the front"): LYNX's own editor
  10152. // windows (here a channel's settings) are docked like FL's plugin windows, so a click on the rack
  10153. // brings the rack in front of them and a click on one brings it back; a click inside a docked
  10154. // plugin's own view (a native window JUCE never hears of) brings that plugin window in front.
  10155. auto docked = [] {
  10156. auto& desktop = juce::Desktop::getInstance();
  10157. for (int i = 0; i < desktop.getNumComponents(); ++i)
  10158. if (auto* c = desktop.getComponent (i); c != nullptr && c->isVisible() && (bool) c->getProperties()["lynxDockedWindow"])
  10159. return c;
  10160. return (juce::Component*) nullptr;
  10161. };
  10162. auto* rack = panelHandle (Panel::channelRack);
  10163. if (at == 21)
  10164. {
  10165. lynx::openChannelSettings (*engine, 0);
  10166. auto* ed = docked();
  10167. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  10168. expect ("editor_docked", h != nullptr && lynx::nativechild::parentOf (h) == main && lynx::nativechild::ownerOf (h) == nullptr);
  10169. expect ("editor_above_rack_when_opened", h != nullptr && lynx::nativechild::isAbove (h, rack));
  10170. workspace->activate (Panel::channelRack); // a click on the rack
  10171. expect ("rack_above_editor_after_its_click", h != nullptr && lynx::nativechild::isAbove (rack, h));
  10172. // a real click (a message to the editor's own window) on its title bar, at a point where the editor
  10173. // can be seen. Round 190fc (0.1.27 RC M1): JUCE takes a button-down only where the system says its
  10174. // window is the one under the point (HWNDComponentPeer::contains asks WindowFromPoint), so the old
  10175. // fixed point (60, 8) was dropped whenever the rack, raised just above, covered it there: the
  10176. // check read 0 while real clicks (on what can be seen) raise the editor.
  10177. if (h != nullptr && ed != nullptr)
  10178. {
  10179. juce::Point<int> at (-1, -1);
  10180. for (int x = 30; x < ed->getWidth() - 40 && at.x < 0; x += 12)
  10181. if (lynx::nativechild::windowAt (*ed, { x, 8 }) == h)
  10182. at = { x, 8 };
  10183. step (juce::String ("editor_title_visible_at=") + juce::String (at.x));
  10184. if (at.x >= 0)
  10185. {
  10186. const auto scale = ed->getPeer() != nullptr ? ed->getPeer()->getPlatformScaleFactor() * (double) ed->getDesktopScaleFactor() : 1.0;
  10187. lynx::nativechild::postClickForTest (h, (at.toDouble() * scale).roundToInt());
  10188. }
  10189. }
  10190. }
  10191. else if (at == 22)
  10192. {
  10193. auto* ed = docked();
  10194. auto* h = ed != nullptr ? ed->getWindowHandle() : nullptr;
  10195. expect ("editor_above_rack_after_its_click", h != nullptr && lynx::nativechild::isAbove (h, rack));
  10196. workspace->activate (Panel::channelRack);
  10197. expect ("rack_above_plugin_after_its_click", lynx::nativechild::isAbove (rack, plug));
  10198. auto* view = lynx::nativechild::innermostChild (plug);
  10199. step (juce::String ("plugin_view_window=") + (view != nullptr ? "1" : "0"));
  10200. if (view != nullptr) // a click in the plugin's own view, near its top-left corner
  10201. lynx::nativechild::postClickForTest (view, { 2, 2 });
  10202. }
  10203. else
  10204. {
  10205. if (lynx::nativechild::innermostChild (plug) != nullptr)
  10206. expect ("plugin_above_rack_after_click_in_its_view", lynx::nativechild::isAbove (plug, rack));
  10207. lynx::closeChannelSettings();
  10208. // FL's Tools > Macros > Switch all plugin editors to > Detached (round 190i)
  10209. lynx::PluginWindows::setAllDetached (*engine, true);
  10210. }
  10211. }
  10212. else if (at == 24)
  10213. {
  10214. expect ("macro_detached_the_open_editor", lynx::PluginWindows::isOpen (*instance) && ! lynx::PluginWindows::isDocked (*instance)
  10215. && plug != nullptr && lynx::nativechild::ownerOf (plug) == main);
  10216. expect ("macro_detached_saved", find() == instance && engineRef() != nullptr && engineRef()->detached);
  10217. lynx::PluginWindows::setAllDetached (*engine, false); // ... > Attached
  10218. }
  10219. else
  10220. {
  10221. expect ("docked_again", lynx::PluginWindows::isDocked (*instance) && engineRef() != nullptr && ! engineRef()->detached);
  10222. step (juce::String ("dock_result=") + (dockOk ? "OK" : "FAILED"));
  10223. }
  10224. }
  10225. const lynx::PluginRef* engineRef() const
  10226. {
  10227. const auto& song = engine->getSong();
  10228. if (instrument)
  10229. return channelIndex < 0 || channelIndex >= (int) song.channels.size() ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  10230. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  10231. }
  10232. void step (const juce::String& line)
  10233. {
  10234. report << line << "\n";
  10235. juce::File (reportPath).replaceWithText (report);
  10236. }
  10237. juce::AudioPluginInstance* find()
  10238. {
  10239. if (instrument)
  10240. {
  10241. if (auto* p = dynamic_cast<lynx::PluginInstrument*> (engine->getChannelInstrument (channelIndex).get()))
  10242. return &p->getInstance();
  10243. }
  10244. else if (auto* p = dynamic_cast<lynx::PluginEffect*> (engine->getEffect (1, 0).get()))
  10245. return &p->getInstance();
  10246. return nullptr;
  10247. }
  10248. void timerCallback() override
  10249. {
  10250. ++ticks;
  10251. if (phase == 0) // waiting for the engine to host the plugin
  10252. {
  10253. instance = find();
  10254. if (instance == nullptr)
  10255. {
  10256. if (ticks > 200)
  10257. {
  10258. step ("result=FAILED (not hosted)");
  10259. stopTimer();
  10260. done (false);
  10261. }
  10262. return;
  10263. }
  10264. step ("hosted=" + instance->getName() + " format=" + instance->getPluginDescription().pluginFormatName);
  10265. step ("programs=" + juce::String (instance->getNumPrograms()));
  10266. for (int p = 0; p < juce::jmin (5, instance->getNumPrograms()); ++p)
  10267. step ("program" + juce::String (p) + "=" + instance->getProgramName (p));
  10268. step ("save_formats=" + lynx::pluginpresetui::saveWildcard (*instance));
  10269. // preset round trip: save, change the first parameter, load, compare
  10270. juce::AudioProcessorParameter* param = nullptr;
  10271. for (auto* candidate : instance->getParameters())
  10272. if (candidate->isAutomatable() && ! candidate->isMetaParameter() && candidate != instance->getBypassParameter())
  10273. {
  10274. param = candidate;
  10275. break;
  10276. }
  10277. if (param != nullptr)
  10278. {
  10279. step ("param=" + param->getName (64));
  10280. checked = param;
  10281. const auto file = lynx::pluginpresetui::folderFor (instance->getName()).getChildFile ("plugwintest.lynxpreset");
  10282. juce::String error;
  10283. const auto before = param->getValue();
  10284. const auto saved = lynx::pluginpresetui::save (*instance, file, "plugwintest", error);
  10285. param->setValueNotifyingHost (before > 0.5f ? 0.1f : 0.9f);
  10286. const auto changed = param->getValue();
  10287. const auto loaded = saved && lynx::pluginpresetui::load (*instance, file, error);
  10288. step ("preset_roundtrip saved=" + juce::String ((int) saved) + " loaded=" + juce::String ((int) loaded) + " param0 before="
  10289. + juce::String (before, 4) + " changed=" + juce::String (changed, 4) + " after=" + juce::String (param->getValue(), 4)
  10290. + (error.isNotEmpty() ? " error=" + error : juce::String()));
  10291. for (const auto* ext : { "fxp", "fxb", "vstpreset" })
  10292. {
  10293. juce::String e2;
  10294. const auto f2 = file.withFileExtension (ext);
  10295. const auto ok2 = lynx::pluginpresetui::save (*instance, f2, "plugwintest", e2) && lynx::pluginpresetui::load (*instance, f2, e2);
  10296. step (juce::String ("preset_") + ext + "=" + juce::String ((int) ok2) + (e2.isNotEmpty() ? " (" + e2 + ")" : juce::String()));
  10297. f2.deleteFile();
  10298. }
  10299. step ("browser_lists=" + juce::String (lynx::pluginpresetui::userPresets (instance->getName()).size()));
  10300. }
  10301. std::shared_ptr<void> owner = instrument ? std::shared_ptr<void> (engine->getChannelInstrument (channelIndex))
  10302. : std::shared_ptr<void> (engine->getEffect (1, 0));
  10303. lynx::PluginWindows::open (owner, *instance, instance->getName(),
  10304. { engine.get(), [this] (lynx::Song& song) -> lynx::PluginRef* {
  10305. if (instrument)
  10306. return channelIndex < 0 || channelIndex >= (int) song.channels.size()
  10307. ? nullptr : &song.channels[(size_t) channelIndex].plugin;
  10308. return song.mixer.size() < 2 || song.mixer[1].effects.empty() ? nullptr : &song.mixer[1].effects[0].plugin;
  10309. }, instrument });
  10310. owner.reset();
  10311. step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  10312. phase = 1;
  10313. ticks = 0;
  10314. phaseStartMs = juce::Time::getMillisecondCounter();
  10315. return;
  10316. }
  10317. if (phase == 1 && ticks >= 30 && ! keysDone && juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_KEYS", {}).isNotEmpty() && instance->getActiveEditor() != nullptr)
  10318. keysDone = ! lynx::pluginKeysTestTick (*instance->getActiveEditor(),
  10319. [this] (bool on) {
  10320. engine->editSong ([this, on] (lynx::Song& song) {
  10321. (instrument ? song.channels[(size_t) channelIndex].plugin : song.mixer[1].effects[0].plugin).hostKeysFirst = on;
  10322. });
  10323. },
  10324. [this] (const juce::String& line) { step (line); });
  10325. const auto elapsedMs = (int) (juce::Time::getMillisecondCounter() - phaseStartMs);
  10326. if (phase == 1 && ticks == 20 && checked != nullptr)
  10327. step ("param_after_1s=" + juce::String (checked->getValue(), 4));
  10328. // round 190in: LYNX_PLUGWIN_MENU=<png>: FL's ▸ wrapper menu of the open window (two columns for a channel)
  10329. if (const auto menuShot = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_MENU", {}); phase == 1 && ticks == 10 && menuShot.isNotEmpty())
  10330. if (const auto menu = lynx::PluginWindows::wrapperMenuForSnapshot (*instance))
  10331. {
  10332. juce::PopupMenu left, right;
  10333. auto* to = &left;
  10334. for (juce::PopupMenu::MenuItemIterator it (*menu); it.next();)
  10335. {
  10336. to->addItem (it.getItem());
  10337. if (it.getItem().shouldBreakAfter)
  10338. to = &right;
  10339. }
  10340. juce::StringArray names { "Plugin" };
  10341. std::vector<juce::PopupMenu> menus { left };
  10342. if (right.getNumItems() > 0)
  10343. {
  10344. names.add ("Channel");
  10345. menus.push_back (right);
  10346. }
  10347. LynxApplication::saveMenus (names, menus, menuShot);
  10348. step ("wrapper_menu_items=" + juce::String (left.getNumItems()) + "+" + juce::String (right.getNumItems()));
  10349. }
  10350. // (3 s apart: time for screenshots of each state)
  10351. if (phase == 1 && workspace != nullptr && dockStep < dockSteps && elapsedMs >= (dockStep + 1) * stepMs)
  10352. dockCheck (dockStep++);
  10353. if (phase == 1 && dropFile.existsAsFile())
  10354. dropTick (elapsedMs);
  10355. // (with LYNX_PLUGWIN_DROP: `seconds` after the drop places were reported, time for the drag)
  10356. const auto dropDone = ! dropFile.existsAsFile()
  10357. || (dropStage == 2 && (int) (juce::Time::getMillisecondCounter() - dropReadyMs) >= seconds * 1000);
  10358. if (phase == 1 && elapsedMs >= seconds * 1000 && dropDone && (workspace == nullptr || dockStep >= dockSteps)) // remove the plugin from the song
  10359. {
  10360. if (dropFile.existsAsFile())
  10361. dropResult();
  10362. engine->editSong ([this] (lynx::Song& song) {
  10363. if (instrument)
  10364. {
  10365. if (channelIndex >= 0 && channelIndex < (int) song.channels.size())
  10366. song.channels.erase (song.channels.begin() + channelIndex);
  10367. }
  10368. else
  10369. song.mixer[1].effects.clear();
  10370. });
  10371. step ("removed");
  10372. phase = 2;
  10373. ticks = 0;
  10374. return;
  10375. }
  10376. if (phase == 2 && ticks >= 40)
  10377. {
  10378. const auto open = lynx::PluginWindows::isOpen (*instance);
  10379. step ("window_open_after_remove=" + juce::String ((int) open));
  10380. step (open || ! dockOk ? "result=FAILED" : "result=OK");
  10381. stopTimer();
  10382. lynx::PluginWindows::closeAll();
  10383. done (! open && dockOk);
  10384. }
  10385. }
  10386. };
  10387. // round 190in: LYNX_PLUGWIN_ZOOM=<percent>: LYNX's interface zoom for the run (the wrapper's header at 150 %)
  10388. if (const auto zoom = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_ZOOM", {}).getIntValue(); zoom >= 50 && zoom <= 300)
  10389. juce::Desktop::getInstance().setGlobalScaleFactor ((float) zoom / 100.0f);
  10390. auto* test = new Test();
  10391. test->reportPath = reportPath;
  10392. test->seconds = seconds;
  10393. if (const auto drop = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DROP", {}); drop.isNotEmpty())
  10394. test->dropFile = juce::File (drop);
  10395. test->done = [this, test] (bool ok) {
  10396. setApplicationReturnValue (ok ? 0 : 1);
  10397. juce::MessageManager::callAsync ([this, test] {
  10398. lynx::setMainWindowForOwnership (nullptr);
  10399. lynx::PluginWindows::setDockWorkspace (nullptr);
  10400. test->dropWindow = nullptr; // (its Browser before the engine)
  10401. test->workspace = nullptr;
  10402. test->mainWindow = nullptr; // (dock mode: the main component with it, before the engine)
  10403. test->engine = nullptr;
  10404. delete test;
  10405. quit();
  10406. });
  10407. };
  10408. test->engine = std::make_unique<lynx::AudioEngine> (false);
  10409. test->mainWindow = std::make_unique<juce::DocumentWindow> ("LYNX test main window", juce::Colours::darkgrey, 0);
  10410. test->mainWindow->setBounds (20, 20, 300, 200);
  10411. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_DOCK", {}) == "1" && lynx::nativechild::dockingEnabled())
  10412. {
  10413. // the real main window's contents (it docks plugin windows in its own desktop), so the panels are real
  10414. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  10415. auto* ui = new lynx::MainComponent (*test->engine, false);
  10416. test->mainWindow->setUsingNativeTitleBar (true);
  10417. test->mainWindow->setContentOwned (ui, false);
  10418. test->mainWindow->setBounds (20, 20, 1500, 900);
  10419. test->workspace = &ui->workspaceForTest();
  10420. test->ui = ui;
  10421. if (const auto ms = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_STEP_MS", {}).getIntValue(); ms > 0)
  10422. test->stepMs = ms;
  10423. }
  10424. test->mainWindow->setVisible (true);
  10425. lynx::setMainWindowForOwnership (test->mainWindow.get());
  10426. if (test->workspace != nullptr)
  10427. {
  10428. using lynx::workspace::Panel;
  10429. for (auto p : { Panel::playlist, Panel::mixer, Panel::pianoRoll, Panel::channelRack })
  10430. test->workspace->show (p);
  10431. test->step ("dock_test=2 rack_visible=" + juce::String ((int) test->workspace->isPanelVisible (Panel::channelRack)));
  10432. }
  10433. auto& host = test->engine->getPluginHost();
  10434. test->step ("plugins_in_file=" + juce::String (host.addPluginFile (juce::File (pluginPath))));
  10435. std::optional<juce::PluginDescription> chosen;
  10436. for (const auto& type : host.getKnownPlugins().getTypes())
  10437. if ((juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName() || type.fileOrIdentifier == pluginPath)
  10438. && (only.isEmpty() || type.name == only))
  10439. {
  10440. chosen = type;
  10441. break;
  10442. }
  10443. if (! chosen)
  10444. {
  10445. test->step ("result=FAILED (no plugin)");
  10446. test->done (false);
  10447. return;
  10448. }
  10449. test->instrument = chosen->isInstrument;
  10450. lynx::PluginRef ref;
  10451. ref.separateProcess = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGWIN_SEPARATE", {}) == "1"; // (issue #96's other-process check)
  10452. ref.id = chosen->createIdentifierString().toStdString();
  10453. ref.name = chosen->name.toStdString();
  10454. test->engine->editSong ([&] (lynx::Song& song) {
  10455. if (test->instrument)
  10456. {
  10457. lynx::ChannelDef c;
  10458. c.name = ref.name;
  10459. c.instrument = lynx::InstrumentKind::plugin;
  10460. c.plugin = ref;
  10461. test->channelIndex = (int) song.channels.size();
  10462. song.channels.push_back (c);
  10463. }
  10464. else
  10465. {
  10466. while (song.mixer.size() < 2)
  10467. song.mixer.emplace_back();
  10468. lynx::EffectSlot slot;
  10469. slot.kind = lynx::EffectKind::plugin;
  10470. slot.plugin = ref;
  10471. song.mixer[1].effects.push_back (slot);
  10472. }
  10473. });
  10474. test->step ("plugin=" + chosen->name + " instrument=" + juce::String ((int) test->instrument));
  10475. test->startTimerHz (20);
  10476. }
  10477. void runEditorCrashTest (const juce::String& pluginPath, const juce::String& reportPath)
  10478. {
  10479. struct CrashTest final : juce::Timer
  10480. {
  10481. juce::String reportPath, report;
  10482. std::unique_ptr<lynx::PluginHost> host;
  10483. juce::AudioPluginInstance* plugin = nullptr;
  10484. std::shared_ptr<juce::AudioPluginInstance> keep; // a window whose plugin nobody else holds is closed as orphaned
  10485. std::function<void (bool)> done;
  10486. int ticks = 0, crashesBefore = 0;
  10487. void step (const juce::String& line)
  10488. {
  10489. report << line << "\n";
  10490. juce::File (reportPath).replaceWithText (report); // at each step: a crash leaves the last one
  10491. }
  10492. void timerCallback() override
  10493. {
  10494. ++ticks;
  10495. const auto crashes = lynx::PluginWindows::editorCrashCount() - crashesBefore;
  10496. const auto open = lynx::PluginWindows::isOpen (*plugin);
  10497. if ((crashes > 0 && ! open) || ticks >= 50) // 100 ms ticks: up to 5 s
  10498. {
  10499. stopTimer();
  10500. step ("editor_crashes=" + juce::String (crashes) + " window_open=" + juce::String ((int) open) + " ticks=" + juce::String (ticks));
  10501. bool traced = false;
  10502. if (crashes > 0)
  10503. {
  10504. const auto last = lynx::PluginWindows::editorCrashes().back();
  10505. traced = last.traceFile.existsAsFile() && last.traceFile.loadFileAsString().contains ("LYNX Test Crash");
  10506. step ("plugin=" + last.plugin + " detail=" + last.detail + " trace=" + last.traceFile.getFileName() + " traced="
  10507. + juce::String ((int) traced));
  10508. last.traceFile.deleteFile();
  10509. }
  10510. // still alive: one more message through the loop after the fault
  10511. juce::MessageManager::callAsync ([this, ok = crashes == 1 && ! open && traced] {
  10512. step ("message_loop_after_fault=1");
  10513. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  10514. done (ok);
  10515. });
  10516. }
  10517. }
  10518. };
  10519. auto* test = new CrashTest();
  10520. test->reportPath = reportPath;
  10521. test->done = [this, test] (bool ok)
  10522. {
  10523. setApplicationReturnValue (ok ? 0 : 1);
  10524. juce::MessageManager::callAsync ([this, test] { lynx::PluginWindows::closeAll(); delete test; quit(); });
  10525. };
  10526. #if ! JUCE_WINDOWS
  10527. test->step ("result=SKIPPED (Windows only: on macOS / Linux a plugin fault is a signal, see docs/analise/REA_rodada174a.md)");
  10528. test->done (true);
  10529. return;
  10530. #else
  10531. _putenv_s ("LYNX_TEST_CRASH", "editor");
  10532. test->host = std::make_unique<lynx::PluginHost> (false);
  10533. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  10534. std::shared_ptr<juce::AudioPluginInstance> instance;
  10535. for (const auto& type : test->host->getKnownPlugins().getTypes())
  10536. {
  10537. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName())
  10538. continue;
  10539. juce::String error;
  10540. instance = std::shared_ptr<juce::AudioPluginInstance> (lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error).release());
  10541. test->step ("plugin=" + type.name + (instance == nullptr ? " error=" + error : juce::String()));
  10542. break;
  10543. }
  10544. if (instance == nullptr || ! instance->hasEditor())
  10545. {
  10546. test->step ("result=FAILED (no plugin with an editor)");
  10547. test->done (false);
  10548. return;
  10549. }
  10550. lynx::preparePlugin (*instance, 48000.0, 512);
  10551. test->plugin = instance.get();
  10552. test->keep = instance;
  10553. test->crashesBefore = lynx::PluginWindows::editorCrashCount();
  10554. lynx::PluginWindows::open (instance, *instance, instance->getName()); // (the window keeps the plugin alive)
  10555. test->step ("window_open=" + juce::String ((int) lynx::PluginWindows::isOpen (*instance)));
  10556. test->startTimer (100);
  10557. #endif
  10558. }
  10559. void runEditorTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only)
  10560. {
  10561. struct EditorTest final : juce::Timer
  10562. {
  10563. juce::String reportPath, report;
  10564. std::unique_ptr<lynx::PluginHost> host;
  10565. std::unique_ptr<juce::AudioPluginInstance> plugin;
  10566. std::unique_ptr<juce::DocumentWindow> window;
  10567. std::function<void (bool)> done;
  10568. void step (const juce::String& line)
  10569. {
  10570. report << line << "\n";
  10571. juce::File (reportPath).replaceWithText (report); // written at each step: a crash leaves the last one
  10572. }
  10573. void timerCallback() override
  10574. {
  10575. stopTimer();
  10576. window = nullptr;
  10577. step ("step=closed");
  10578. plugin = nullptr;
  10579. step ("result=OK");
  10580. done (true);
  10581. }
  10582. };
  10583. auto* test = new EditorTest();
  10584. test->reportPath = reportPath;
  10585. test->done = [this, test] (bool ok)
  10586. {
  10587. setApplicationReturnValue (ok ? 0 : 1);
  10588. juce::MessageManager::callAsync ([this, test] { delete test; quit(); });
  10589. };
  10590. test->host = std::make_unique<lynx::PluginHost> (false);
  10591. test->step ("plugins_in_file=" + juce::String (test->host->addPluginFile (juce::File (pluginPath))));
  10592. test->step ("exe=" + juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
  10593. for (const auto& type : test->host->getKnownPlugins().getTypes())
  10594. {
  10595. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  10596. || (only.isNotEmpty() && type.name != only))
  10597. continue;
  10598. juce::String error;
  10599. test->plugin = lynx::createRightInstance (test->host->getFormats(), type, 48000.0, 512, error);
  10600. test->step ("plugin=" + type.name + (test->plugin == nullptr ? " error=" + error : juce::String()));
  10601. break;
  10602. }
  10603. if (test->plugin == nullptr)
  10604. {
  10605. test->step ("result=FAILED");
  10606. test->done (false);
  10607. return;
  10608. }
  10609. lynx::preparePlugin (*test->plugin, 48000.0, 512);
  10610. test->step ("step=create_editor");
  10611. test->window = std::make_unique<juce::DocumentWindow> (test->plugin->getName(), juce::Colours::black, juce::DocumentWindow::closeButton);
  10612. test->window->setUsingNativeTitleBar (true);
  10613. if (auto* editor = test->plugin->createEditorIfNeeded())
  10614. test->window->setContentOwned (editor, true);
  10615. else
  10616. test->step ("no_editor");
  10617. test->step ("step=show");
  10618. test->window->centreWithSize (test->window->getWidth(), test->window->getHeight());
  10619. test->window->setVisible (true);
  10620. test->step ("step=shown");
  10621. test->startTimer (4000);
  10622. }
  10623. void runFitTest (const juce::String& reportPath, int percent)
  10624. {
  10625. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  10626. struct FitTest final : juce::Timer
  10627. {
  10628. juce::String path, report;
  10629. bool ok = true;
  10630. int step = 0, percent = 150;
  10631. std::unique_ptr<juce::DocumentWindow> tall, big;
  10632. std::function<void()> done;
  10633. // `whole`: the window must fit entirely (a resizable one); else its title bar and close button must be on the screen
  10634. void check (const juce::String& what, juce::Component& w, bool whole)
  10635. {
  10636. juce::BorderSize<int> frame;
  10637. if (auto* peer = w.getPeer())
  10638. if (const auto f = peer->getFrameSizeIfPresent())
  10639. frame = *f;
  10640. auto outer = frame.addedTo (w.getBounds());
  10641. const auto* display = juce::Desktop::getInstance().getDisplays().getDisplayForRect (outer);
  10642. const auto area = display != nullptr ? display->userArea : outer;
  10643. #if JUCE_LINUX
  10644. // round 164: a compositor that draws the frame itself (WSLg's Weston) reports its invisible shadow in
  10645. // the frame (59 px on top, 38 around at 100%): only what is visible is checked, give or take 4 px
  10646. const auto shadow = frame.getLeft() >= 16 ? frame.getLeft() : 0;
  10647. outer = outer.reduced (shadow);
  10648. const auto slack = shadow > 0 ? 4 : 0;
  10649. #else
  10650. const auto slack = 0;
  10651. #endif
  10652. const auto passed = outer.getY() >= area.getY() - slack && outer.getRight() <= area.getRight() + slack && outer.getX() >= area.getX() - slack
  10653. && (! whole || outer.getBottom() <= area.getBottom() + 1 + slack);
  10654. report << (passed ? "ok " : "FAIL ") << what << " window=" << outer.toString() << " (frame " << frame.getTop() << ","
  10655. << frame.getLeft() << ") screen=" << area.toString() << "\n";
  10656. ok = ok && passed;
  10657. }
  10658. void start()
  10659. {
  10660. report << "scale=" << percent << "%\n";
  10661. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  10662. // a tool window taller than the screen, centred (its title bar would be above the screen)
  10663. tall = std::make_unique<juce::DocumentWindow> ("LYNX fit test - tall", lynx::theme::colour::bg2, juce::DocumentWindow::closeButton);
  10664. tall->setUsingNativeTitleBar (true);
  10665. auto* content = new juce::Component();
  10666. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  10667. content->setSize (500, area.getHeight() + 200);
  10668. tall->setContentOwned (content, true);
  10669. tall->setCentrePosition (area.getCentre());
  10670. tall->setVisible (true);
  10671. lynx::keepAboveMainWindow (*tall);
  10672. // LYNX_FITTEST_MS: how long each window stays (default 700 ms; longer to take screenshots of them)
  10673. startTimer (juce::jlimit (300, 60000, juce::SystemStats::getEnvironmentVariable ("LYNX_FITTEST_MS", "700").getIntValue()));
  10674. }
  10675. void timerCallback() override
  10676. {
  10677. ++step;
  10678. if (step == 1)
  10679. {
  10680. check ("tall tool window: title bar and close button on the screen", *tall, false);
  10681. tall.reset();
  10682. // round 164: a fixed-size LYNX tool window whose content is taller than the screen: it scrolls
  10683. auto content = std::make_unique<juce::Component>();
  10684. const auto screen = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  10685. content->setSize (520, screen.getHeight() + 300);
  10686. lynx::openToolWindow (std::move (content), "LYNX fit test - fixed size", "fittest-fixed");
  10687. return;
  10688. }
  10689. if (step == 2)
  10690. {
  10691. if (auto* w = lynx::findToolWindow ("fittest-fixed"))
  10692. {
  10693. check ("fixed-size tool window taller than the screen: fits (its content scrolls)", *w, true);
  10694. const auto scrolls = w->getContentComponent() != nullptr && w->getContentComponent()->getNumChildComponents() > 0
  10695. && dynamic_cast<juce::Viewport*> (w->getContentComponent()->getChildComponent (0)) != nullptr;
  10696. report << (scrolls ? "ok " : "FAIL ") << "its content is in a scrolling viewport\n";
  10697. ok = ok && scrolls;
  10698. }
  10699. else
  10700. {
  10701. report << "FAIL fixed-size tool window not found\n";
  10702. ok = false;
  10703. }
  10704. lynx::closeAllToolWindows();
  10705. // a resizable window that fits at 100%, then the zoom goes up (the main window's case)
  10706. juce::Desktop::getInstance().setGlobalScaleFactor (1.0f);
  10707. big = std::make_unique<juce::DocumentWindow> ("LYNX fit test - zoom", lynx::theme::colour::bg2, juce::DocumentWindow::allButtons);
  10708. big->setUsingNativeTitleBar (true);
  10709. big->setResizable (true, false);
  10710. big->setResizeLimits (400, 300, 10000, 10000);
  10711. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  10712. big->setBounds (area.getX() + 40, area.getY() + 60, area.getWidth() * 9 / 10 - 40, area.getHeight() * 9 / 10 - 60);
  10713. big->setVisible (true);
  10714. return;
  10715. }
  10716. if (step == 3)
  10717. {
  10718. juce::Desktop::getInstance().setGlobalScaleFactor ((float) percent / 100.0f);
  10719. juce::Timer::callAfterDelay (200, [] { lynx::fitAllWindowsOnScreen(); });
  10720. return;
  10721. }
  10722. if (step == 4)
  10723. {
  10724. check ("resizable window after the zoom change: fits the screen", *big, true);
  10725. big.reset();
  10726. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  10727. juce::File (path).replaceWithText (report);
  10728. stopTimer();
  10729. if (done)
  10730. done();
  10731. }
  10732. }
  10733. };
  10734. static std::unique_ptr<FitTest> test;
  10735. test = std::make_unique<FitTest>();
  10736. test->path = reportPath;
  10737. test->percent = juce::jlimit (50, 300, percent);
  10738. test->done = [this] { juce::MessageManager::callAsync ([this] { test.reset(); quit(); }); };
  10739. test->start();
  10740. }
  10741. void runFocusTest (const juce::String& reportPath)
  10742. {
  10743. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  10744. struct FocusTest final : juce::Timer
  10745. {
  10746. juce::String reportPath, report;
  10747. bool ok = true;
  10748. int stepIndex = 0;
  10749. std::unique_ptr<lynx::AudioEngine> engine;
  10750. lynx::MainComponent* ui = nullptr;
  10751. std::unique_ptr<juce::DocumentWindow> main;
  10752. std::function<void()> done;
  10753. void line (const juce::String& text)
  10754. {
  10755. report << text << "\n";
  10756. juce::File (reportPath).replaceWithText (report);
  10757. }
  10758. void check (const juce::String& what, bool passed)
  10759. {
  10760. line ((passed ? "ok " : "FAIL ") + what);
  10761. ok = ok && passed;
  10762. }
  10763. juce::ComponentPeer* mainPeer() const { return main != nullptr ? main->getPeer() : nullptr; }
  10764. bool focusInMain() const
  10765. {
  10766. auto* f = juce::Component::getCurrentlyFocusedComponent();
  10767. return f != nullptr && main->isParentOf (f);
  10768. }
  10769. // a click (press and release) at the middle of the panel's content, through the native window it is in
  10770. static void click (juce::Component& frame, bool right)
  10771. {
  10772. auto* peer = frame.getPeer();
  10773. if (peer == nullptr)
  10774. return;
  10775. const auto at = peer->getComponent().getLocalPoint (&frame, frame.getLocalBounds().getCentre().toFloat());
  10776. const auto button = right ? juce::ModifierKeys::rightButtonModifier : juce::ModifierKeys::leftButtonModifier;
  10777. const auto now = juce::Time::currentTimeMillis();
  10778. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (button), 1.0f, 0.0f, now);
  10779. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  10780. }
  10781. bool space()
  10782. {
  10783. auto* peer = mainPeer(); // (the system sends the key to the window with the focus: the main one)
  10784. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  10785. }
  10786. juce::TextEditor* firstField (juce::Component& c)
  10787. {
  10788. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && t->getWantsKeyboardFocus())
  10789. return t;
  10790. for (auto* child : c.getChildren())
  10791. if (auto* t = firstField (*child))
  10792. return t;
  10793. return nullptr;
  10794. }
  10795. // the user tabs away and comes back with a click in `panel`
  10796. void backWithClickIn (lynx::workspace::Panel panel, bool right)
  10797. {
  10798. auto& frame = ui->workspaceForTest().getFrame (panel);
  10799. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  10800. auto* peer = mainPeer();
  10801. line (name + ": native child window=" + juce::String ((int) lynx::nativechild::isAttached (frame)));
  10802. check (name + ": the main window has the keys before", ui->hasKeyboardFocus (true));
  10803. peer->handleFocusLoss(); // (another app is in front: the main window lost the system focus)
  10804. check (name + ": nothing in LYNX has the keys while it is in the background", ! focusInMain());
  10805. // the cause: JUCE answers the system's "activate?" from the panel's own component, which takes no focus on a click
  10806. line (name + ": JUCE's answer alone would activate the window=" + juce::String ((int) frame.getMouseClickGrabsKeyboardFocus()));
  10807. const auto activates = lynx::nativechild::clickActivatesWindow (frame, false);
  10808. check (name + ": a click in it activates the inactive main window", activates);
  10809. #if JUCE_WINDOWS
  10810. if (lynx::nativechild::isAttached (frame))
  10811. check (name + ": its native window answers WM_MOUSEACTIVATE with MA_ACTIVATE",
  10812. lynx::nativechild::mouseActivateAnswerForTest (frame, true) == 1 /* MA_ACTIVATE */);
  10813. #endif
  10814. if (activates)
  10815. peer->handleFocusGain(); // (the system activates the main window and gives it the focus)
  10816. click (frame, right);
  10817. }
  10818. void spacePlays (lynx::workspace::Panel panel, bool right)
  10819. {
  10820. const auto name = juce::String (lynx::workspace::panelId (panel)) + (right ? " (right click)" : "");
  10821. check (name + ": the main window has the keys after the click", ui->hasKeyboardFocus (true));
  10822. auto& transport = engine->getTransport();
  10823. if (transport.playing.load())
  10824. engine->stop();
  10825. const auto used = space();
  10826. check (name + ": Space starts playback", used && transport.playing.load());
  10827. engine->stop();
  10828. }
  10829. void timerCallback() override
  10830. {
  10831. using lynx::workspace::Panel;
  10832. auto& ws = ui->workspaceForTest();
  10833. switch (stepIndex++)
  10834. {
  10835. case 0:
  10836. line ("docking=" + juce::String ((int) lynx::nativechild::dockingEnabled()));
  10837. ws.show (Panel::playlist);
  10838. ws.show (Panel::pianoRoll);
  10839. ui->grabKeyboardFocus();
  10840. break;
  10841. case 1: backWithClickIn (Panel::playlist, false); break;
  10842. case 2: spacePlays (Panel::playlist, false); ui->grabKeyboardFocus(); break;
  10843. case 3: backWithClickIn (Panel::pianoRoll, false); break;
  10844. case 4: spacePlays (Panel::pianoRoll, false); ui->grabKeyboardFocus(); break;
  10845. case 5: backWithClickIn (Panel::playlist, true); break;
  10846. case 6:
  10847. juce::PopupMenu::dismissAllActiveMenus(); // (the right click's menu)
  10848. spacePlays (Panel::playlist, true);
  10849. break;
  10850. case 7:
  10851. {
  10852. // a text field (the Browser's search box) keeps the keys through a switch to another app and back:
  10853. // nothing in LYNX takes them from it (no periodic grab); inside the active window the click's
  10854. // activation answer is unchanged, and a click in the Playlist ends the typing as before (issue #9,
  10855. // as FL ends typing in its search field)
  10856. auto* field = firstField (*ui);
  10857. line ("text field found=" + juce::String ((int) (field != nullptr)));
  10858. if (field != nullptr)
  10859. {
  10860. auto& frame = ws.getFrame (Panel::playlist);
  10861. field->grabKeyboardFocus();
  10862. check ("the text field has the keys", field->hasKeyboardFocus (false));
  10863. mainPeer()->handleFocusLoss();
  10864. mainPeer()->handleFocusGain(); // (back with Alt+Tab, or a click that activates the window)
  10865. check ("the text field gets the keys back with the window", field->hasKeyboardFocus (false));
  10866. check ("active window: a click in a panel does not activate it again", ! lynx::nativechild::clickActivatesWindow (frame, true));
  10867. click (frame, false);
  10868. check ("a click in the Playlist ends the typing: the main window has the keys", ui->hasKeyboardFocus (true) && ! field->hasKeyboardFocus (false));
  10869. }
  10870. line (ok ? "result=OK" : "result=FAILED");
  10871. stopTimer();
  10872. done();
  10873. break;
  10874. }
  10875. default:
  10876. break;
  10877. }
  10878. }
  10879. };
  10880. auto* test = new FocusTest();
  10881. test->reportPath = reportPath;
  10882. startFocusTestWindow (*test);
  10883. test->startTimer (600);
  10884. }
  10885. // --simplekeytest (round 190fc, 0.1.27 RC H2): in the Simple layout Space often did nothing after a click in the
  10886. // window (the dock, a track header, the grid, the Lyrics button) or after a demo opened from Welcome › Start from. The
  10887. // main window in the Simple layout; each step clicks as the system would (through the native window under the point)
  10888. // and presses Space where the system sends it (the native window of the component with the focus): playback must
  10889. // start, except while a text field the user clicked into has the keys (it types). Shows a window (Windows: GUI lock).
  10890. void runSimpleKeyTest (const juce::String& reportPath)
  10891. {
  10892. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  10893. struct KeyTest final : juce::Timer
  10894. {
  10895. juce::String reportPath, report;
  10896. bool ok = true;
  10897. int stepIndex = 0, instrumentTrack = 0;
  10898. std::unique_ptr<lynx::AudioEngine> engine;
  10899. lynx::MainComponent* ui = nullptr;
  10900. std::unique_ptr<juce::DocumentWindow> main;
  10901. std::function<void()> done;
  10902. void line (const juce::String& text)
  10903. {
  10904. report << text << "\n";
  10905. juce::File (reportPath).replaceWithText (report);
  10906. }
  10907. void check (const juce::String& what, bool passed)
  10908. {
  10909. line ((passed ? "ok " : "FAIL ") + what);
  10910. ok = ok && passed;
  10911. }
  10912. static juce::String describe (juce::Component* c)
  10913. {
  10914. if (c == nullptr)
  10915. return "nothing";
  10916. juce::String path;
  10917. for (auto* p = c; p != nullptr && path.length() < 160; p = p->getParentComponent())
  10918. {
  10919. auto name = p->getComponentID().isNotEmpty() ? p->getComponentID() : p->getName();
  10920. if (name.isEmpty())
  10921. name = juce::String (typeid (*p).name()).fromLastOccurrenceOf ("::", false, false).substring (0, 28);
  10922. path << (path.isEmpty() ? "" : " < ") << name;
  10923. }
  10924. return path;
  10925. }
  10926. // the first showing component with this ID in the main window or a native child window of it
  10927. juce::Component* find (const juce::String& id)
  10928. {
  10929. std::function<juce::Component* (juce::Component&)> in = [&] (juce::Component& root) -> juce::Component* {
  10930. if (root.getComponentID() == id && root.isShowing())
  10931. return &root;
  10932. for (auto* c : root.getChildren())
  10933. if (auto* f = in (*c))
  10934. return f;
  10935. return nullptr;
  10936. };
  10937. if (auto* f = in (*main))
  10938. return f;
  10939. if (auto* peer = main->getPeer())
  10940. for (auto* attached : lynx::nativechild::attachedChildren (peer->getNativeHandle()))
  10941. if (auto* f = in (*attached))
  10942. return f;
  10943. return nullptr;
  10944. }
  10945. // a click (press and release) at `local` in `c`, through the native window it is in
  10946. juce::String lastHit;
  10947. void click (juce::Component& c, juce::Point<int> local)
  10948. {
  10949. auto* peer = c.getPeer();
  10950. if (peer == nullptr)
  10951. return;
  10952. const auto at = peer->getComponent().getLocalPoint (&c, local.toFloat());
  10953. lastHit = describe (peer->getComponent().getComponentAt (at.roundToInt()));
  10954. line (" click at " + local.toString() + " in " + describe (&c).upToFirstOccurrenceOf (" < ", false, false) + " -> " + lastHit);
  10955. const auto now = juce::Time::currentTimeMillis();
  10956. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, now);
  10957. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, at, juce::ModifierKeys(), 1.0f, 0.0f, now + 40);
  10958. }
  10959. void click (juce::Component& c) { click (c, c.getLocalBounds().getCentre()); }
  10960. // Space where the system sends it: the native window of the focused component (else the main one)
  10961. bool space()
  10962. {
  10963. // Windows: posted to the window with the system's focus, as a real key goes (the system's own routing)
  10964. if (lynx::nativechild::pressSpaceForTest (main->getWindowHandle()))
  10965. return true;
  10966. auto* focused = juce::Component::getCurrentlyFocusedComponent();
  10967. auto* peer = focused != nullptr && focused->getPeer() != nullptr ? focused->getPeer() : main->getPeer();
  10968. return peer != nullptr && peer->handleKeyPress (juce::KeyPress (juce::KeyPress::spaceKey, juce::ModifierKeys(), ' '));
  10969. }
  10970. void spacePlays (const juce::String& after)
  10971. {
  10972. line (" keys at: " + describe (juce::Component::getCurrentlyFocusedComponent()));
  10973. auto& transport = engine->getTransport();
  10974. if (transport.playing.load())
  10975. engine->stop();
  10976. space();
  10977. check ("Space plays after " + after, transport.playing.load());
  10978. engine->stop();
  10979. }
  10980. void timerCallback() override
  10981. {
  10982. auto* simple = ui->getSimpleWorkflowForSnapshot();
  10983. auto& playlist = ui->getPlaylistForSnapshot();
  10984. switch (stepIndex++)
  10985. {
  10986. case 0:
  10987. ui->setLayoutStyle (lynx::layoutstyle::Style::simple);
  10988. ui->grabKeyboardFocus();
  10989. break;
  10990. case 1:
  10991. check ("the Simple workflow is up", simple != nullptr);
  10992. if (simple == nullptr)
  10993. return finish();
  10994. spacePlays ("the layout came up");
  10995. simple->showWelcome();
  10996. break;
  10997. case 2:
  10998. if (auto* demo = find ("tour.welcome.demo"))
  10999. click (*demo); // Welcome › Open a demo song: the Start from list
  11000. else
  11001. check ("Welcome > Open a demo song found", false);
  11002. break;
  11003. case 3:
  11004. {
  11005. if (! simple->isStartFromShowing()) // (X11: a child window just mapped may miss the first click)
  11006. if (auto* demo = find ("tour.welcome.demo"))
  11007. {
  11008. line (" the first click was not taken: once more");
  11009. click (*demo);
  11010. }
  11011. check ("Start from is up", simple->isStartFromShowing());
  11012. if (auto* start = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot()))
  11013. check ("a demo song opens from it", start->openForSnapshot (1));
  11014. break;
  11015. }
  11016. case 4:
  11017. check ("Start from closed with the demo open", ! simple->isStartFromShowing() && ! engine->getSong().playlist.empty());
  11018. spacePlays ("a demo opened from Welcome > Start from");
  11019. instrumentTrack = [] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  11020. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  11021. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  11022. return t;
  11023. return 0;
  11024. } (engine->getSong());
  11025. line ("instrument track: " + juce::String (instrumentTrack));
  11026. playlist.selectTrack (instrumentTrack);
  11027. simple->trackSelected (instrumentTrack);
  11028. break;
  11029. case 5:
  11030. if (auto* dock = simple->dockForSnapshot(); dock != nullptr && dock->isShowing())
  11031. {
  11032. click (*dock, { dock->getWidth() - 6, dock->getHeight() - 6 }); // (its empty corner)
  11033. spacePlays ("a click in the dock");
  11034. }
  11035. else
  11036. check ("the dock shows", false);
  11037. break;
  11038. case 6:
  11039. if (auto* tab = find ("simple.dock.keyboard"))
  11040. {
  11041. click (*tab);
  11042. spacePlays ("a click on a dock tab (Keyboard)");
  11043. }
  11044. if (auto* tab = find ("simple.dock.editor"))
  11045. {
  11046. click (*tab);
  11047. spacePlays ("a click on a dock tab (Editor)");
  11048. }
  11049. break;
  11050. case 7:
  11051. if (auto* lyrics = find ("simple.lyrics"))
  11052. {
  11053. click (*lyrics);
  11054. spacePlays ("a click on the Lyrics button");
  11055. }
  11056. else
  11057. check ("the Lyrics button found", false);
  11058. break;
  11059. case 8:
  11060. {
  11061. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  11062. click (playlist, { juce::jmax (4, playlist.headerWidth / 2), lane.getCentreY() });
  11063. spacePlays ("a click on a track header");
  11064. click (playlist, lane.getCentre() + juce::Point<int> (40, 0));
  11065. spacePlays ("a click in the Playlist grid");
  11066. break;
  11067. }
  11068. case 9:
  11069. {
  11070. // a text field the user clicks into keeps its typing keys; a click outside gives Space back
  11071. // a dock knob clicked keeps the arrow keys, and Space still plays from it
  11072. for (auto tab : { lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::instrument })
  11073. {
  11074. juce::Component* knob = nullptr;
  11075. std::function<void (juce::Component&)> seek = [&] (juce::Component& c) {
  11076. if (knob == nullptr && c.isShowing() && (bool) c.getProperties().getWithDefault ("lynxClickKeepsKeys", false))
  11077. knob = &c;
  11078. for (auto* child : c.getChildren())
  11079. seek (*child);
  11080. };
  11081. if (auto* dock = simple->dockForSnapshot())
  11082. {
  11083. dock->setTab (tab);
  11084. seek (*dock);
  11085. }
  11086. if (knob != nullptr)
  11087. {
  11088. click (*knob);
  11089. spacePlays ("a click on a dock knob");
  11090. break;
  11091. }
  11092. }
  11093. if (auto* dock = simple->dockForSnapshot())
  11094. dock->setTab (lynx::SimpleDock::Tab::instrument);
  11095. juce::TextEditor* field = nullptr;
  11096. std::function<void (juce::Component&)> look = [&] (juce::Component& c) {
  11097. if (auto* t = dynamic_cast<juce::TextEditor*> (&c); t != nullptr && t->isShowing() && field == nullptr)
  11098. field = t;
  11099. for (auto* child : c.getChildren())
  11100. look (*child);
  11101. };
  11102. if (auto* dock = simple->dockForSnapshot())
  11103. look (*dock);
  11104. line ("text field in the dock found=" + juce::String ((int) (field != nullptr)));
  11105. if (field != nullptr)
  11106. {
  11107. click (*field);
  11108. const auto before = field->getText();
  11109. space();
  11110. check ("Space types into the text field the user clicked", field->getText() != before && ! engine->getTransport().playing.load());
  11111. engine->stop();
  11112. field->clear();
  11113. const auto lane = playlist.trackRowForSnapshot (instrumentTrack).withTrimmedLeft (playlist.headerWidth);
  11114. click (playlist, lane.getCentre() + juce::Point<int> (60, 0));
  11115. spacePlays ("a click in the grid after typing");
  11116. }
  11117. // H1: the first-song tour's card in front of the native panels, taking no keys (started on the demo
  11118. // as it is: Help's question about a new project is a dialog)
  11119. if (auto* tour = simple->tourForSnapshot())
  11120. tour->start();
  11121. break;
  11122. }
  11123. case 10:
  11124. {
  11125. auto* tour = simple->tourForSnapshot();
  11126. auto* card = tour != nullptr ? tour->cardForSnapshot() : nullptr;
  11127. check ("the tour runs", tour != nullptr && tour->isRunning() && card != nullptr && card->isVisible());
  11128. if (card == nullptr)
  11129. return finish();
  11130. auto& frame = ui->workspaceForTest().getFrame (lynx::workspace::Panel::playlist);
  11131. const auto native = lynx::nativechild::dockingEnabled() && lynx::nativechild::isAttached (frame);
  11132. line ("playlist native child window=" + juce::String ((int) native) + ", tour card native child window="
  11133. + juce::String ((int) lynx::nativechild::isAttached (*card)));
  11134. if (native)
  11135. {
  11136. check ("the tour card is a native child window of the main window (not under the panels)", lynx::nativechild::isAttached (*card));
  11137. #if JUCE_WINDOWS
  11138. check ("the tour card is above the Playlist's native window", lynx::nativechild::isAbove (card->getWindowHandle(), frame.getWindowHandle()));
  11139. juce::Component* layer = nullptr;
  11140. for (auto* c : lynx::nativechild::attachedChildren (main->getPeer()->getNativeHandle()))
  11141. if (c != nullptr && c->getComponentID() == "tour.layer")
  11142. layer = c;
  11143. check ("the ring's layer is above the Playlist too", layer != nullptr && lynx::nativechild::isAbove (layer->getWindowHandle(), frame.getWindowHandle()));
  11144. check ("the ring's layer lets clicks through to the Playlist",
  11145. layer != nullptr && lynx::nativechild::windowAt (*layer, layer->getLocalBounds().getCentre()) != layer->getWindowHandle());
  11146. #endif
  11147. }
  11148. check ("the tour card took no keys", ! card->hasKeyboardFocus (true));
  11149. spacePlays ("the tour came up");
  11150. if (auto* next = card->findChildWithID ("tour.next"); next != nullptr && next->isShowing())
  11151. {
  11152. click (*next);
  11153. check ("a click on the card took no keys", ! card->hasKeyboardFocus (true));
  11154. spacePlays ("a click on the tour card");
  11155. }
  11156. finish();
  11157. break;
  11158. }
  11159. default:
  11160. break;
  11161. }
  11162. }
  11163. void finish()
  11164. {
  11165. line (ok ? "result=OK" : "result=FAILED");
  11166. stopTimer();
  11167. done();
  11168. }
  11169. };
  11170. auto* test = new KeyTest();
  11171. test->reportPath = reportPath;
  11172. startFocusTestWindow (*test);
  11173. // Windows: kept above other apps' windows for its few seconds (JUCE takes a button-down only where the system finds
  11174. // its window under the point, and the test clicks through LYNX's own peers, not the system's input)
  11175. #if JUCE_WINDOWS
  11176. test->main->setAlwaysOnTop (true); // (Linux: JUCE makes the X11 window again for it; the private X server has no other windows)
  11177. #endif
  11178. test->startTimer (700);
  11179. }
  11180. template <typename Test>
  11181. void startFocusTestWindow (Test& t)
  11182. {
  11183. auto* test = &t;
  11184. test->engine = std::make_unique<lynx::AudioEngine> (false);
  11185. test->main = std::make_unique<juce::DocumentWindow> ("LYNX focus test", lynx::theme::window, juce::DocumentWindow::allButtons);
  11186. test->main->setUsingNativeTitleBar (true);
  11187. test->ui = new lynx::MainComponent (*test->engine, false);
  11188. test->main->setContentOwned (test->ui, true);
  11189. test->main->setResizable (true, true);
  11190. test->main->centreWithSize (1280, 760);
  11191. test->main->setVisible (true);
  11192. lynx::setMainWindowForOwnership (test->main.get());
  11193. test->done = [this, test] {
  11194. setApplicationReturnValue (test->ok ? 0 : 1);
  11195. juce::MessageManager::callAsync ([this, test] {
  11196. lynx::setMainWindowForOwnership (nullptr);
  11197. test->main = nullptr;
  11198. delete test;
  11199. quit();
  11200. });
  11201. };
  11202. }
  11203. void runWindowTest (const juce::String& reportPath)
  11204. {
  11205. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11206. struct WindowTest final : juce::Timer
  11207. {
  11208. juce::String reportPath, report;
  11209. bool ok = true;
  11210. int stepIndex = 0;
  11211. std::unique_ptr<lynx::AudioEngine> engine;
  11212. lynx::MainComponent* ui = nullptr;
  11213. std::unique_ptr<juce::DocumentWindow> main, pluginLike;
  11214. juce::TextEditor* pluginField = nullptr;
  11215. std::unique_ptr<juce::AlertWindow> nameDialog;
  11216. std::function<void()> done;
  11217. void line (const juce::String& text)
  11218. {
  11219. report << text << "\n";
  11220. juce::File (reportPath).replaceWithText (report);
  11221. }
  11222. void check (const juce::String& what, bool passed)
  11223. {
  11224. line ((passed ? "ok " : "FAIL ") + what);
  11225. ok = ok && passed;
  11226. }
  11227. bool isAbove (juce::Component* w) { return w != nullptr && lynx::isAboveMainWindow (*w); }
  11228. bool focusIn (juce::Component* w)
  11229. {
  11230. auto* f = juce::Component::getCurrentlyFocusedComponent();
  11231. return w != nullptr && f != nullptr && (f == w || w->isParentOf (f));
  11232. }
  11233. void timerCallback() override
  11234. {
  11235. switch (stepIndex++)
  11236. {
  11237. case 0:
  11238. line ("foreground=" + juce::String (juce::Process::isForegroundProcess() ? 1 : 0));
  11239. ui->openQuickAddForTest();
  11240. break;
  11241. case 1:
  11242. {
  11243. auto* w = lynx::findToolWindow ("quickadd");
  11244. check ("quick-add palette open", w != nullptr);
  11245. check ("quick-add palette active", w != nullptr && w->isActiveWindow());
  11246. check ("quick-add palette owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  11247. check ("quick-add palette above the main window", isAbove (w));
  11248. auto* f = juce::Component::getCurrentlyFocusedComponent();
  11249. check ("quick-add search box has the keyboard focus", focusIn (w) && dynamic_cast<juce::TextEditor*> (f) != nullptr && f->hasKeyboardFocus (false) && w->isActiveWindow());
  11250. lynx::closeAllToolWindows();
  11251. lynx::openAudioEditor (*engine);
  11252. break;
  11253. }
  11254. case 2:
  11255. {
  11256. auto* w = lynx::findToolWindow ("audioeditor");
  11257. check ("audio editor open", w != nullptr);
  11258. check ("audio editor active", w != nullptr && w->isActiveWindow());
  11259. check ("audio editor owned by the main window", w != nullptr && lynx::isOwnedByMainWindow (*w));
  11260. check ("audio editor above the main window", isAbove (w));
  11261. lynx::forceForegroundForTest (*main); // the user clicks the main window
  11262. break;
  11263. }
  11264. case 3:
  11265. {
  11266. auto* w = lynx::findToolWindow ("audioeditor");
  11267. check ("audio editor stays above the main window after clicking it", isAbove (w));
  11268. lynx::closeAllToolWindows();
  11269. // a plugin editor's window: its own controls keep the keyboard focus
  11270. pluginLike = std::make_unique<juce::DocumentWindow> ("Plugin", juce::Colours::black, juce::DocumentWindow::closeButton);
  11271. pluginLike->setUsingNativeTitleBar (true);
  11272. auto* field = new juce::TextEditor();
  11273. field->setSize (300, 120);
  11274. pluginLike->setContentOwned (field, true);
  11275. pluginLike->centreWithSize (300, 120);
  11276. pluginLike->setVisible (true);
  11277. lynx::keepAboveMainWindow (*pluginLike);
  11278. pluginLike->toFront (true);
  11279. field->grabKeyboardFocus();
  11280. pluginField = field;
  11281. break;
  11282. }
  11283. case 4:
  11284. check ("plugin window active", pluginLike->isActiveWindow());
  11285. check ("plugin window keeps the keyboard focus", pluginField->hasKeyboardFocus (false) && pluginLike->isActiveWindow());
  11286. check ("plugin window above the main window", isAbove (pluginLike.get()));
  11287. pluginLike = nullptr;
  11288. lynx::forceForegroundForTest (*main);
  11289. juce::Component::unfocusAllComponents();
  11290. break;
  11291. case 5:
  11292. check ("main window takes the keyboard focus back when it is active", ui->hasKeyboardFocus (true));
  11293. // round 165q: a name dialog (F4's next empty pattern, Rename and color...) opens ready to type
  11294. nameDialog = lynx::makeNameAndColourDialog ("Rename pattern", "Pattern 2", 0xff808080u);
  11295. nameDialog->enterModalState (true, nullptr, false);
  11296. lynx::keepAboveMainWindow (*nameDialog);
  11297. break;
  11298. case 6:
  11299. {
  11300. auto* f = juce::Component::getCurrentlyFocusedComponent();
  11301. auto* field = dynamic_cast<juce::TextEditor*> (f);
  11302. check ("name dialog: its text field has the keyboard focus", field != nullptr && focusIn (nameDialog.get()));
  11303. if (field != nullptr)
  11304. field->keyPressed (juce::KeyPress ('x', {}, 'x'));
  11305. check ("name dialog: typing replaces the name", nameDialog->getTextEditorContents ("name") == "x");
  11306. nameDialog->exitModalState (0);
  11307. nameDialog = nullptr;
  11308. line (ok ? "result=OK" : "result=FAILED");
  11309. stopTimer();
  11310. done();
  11311. break;
  11312. }
  11313. default:
  11314. break;
  11315. }
  11316. }
  11317. };
  11318. auto* test = new WindowTest();
  11319. test->reportPath = reportPath;
  11320. test->engine = std::make_unique<lynx::AudioEngine> (false);
  11321. test->main = std::make_unique<juce::DocumentWindow> ("LYNX window test", lynx::theme::window, juce::DocumentWindow::allButtons);
  11322. test->main->setUsingNativeTitleBar (true);
  11323. test->ui = new lynx::MainComponent (*test->engine, false);
  11324. test->main->setContentOwned (test->ui, true);
  11325. test->main->setResizable (true, true);
  11326. test->main->centreWithSize (1280, 760);
  11327. test->main->setVisible (true);
  11328. lynx::setMainWindowForOwnership (test->main.get());
  11329. lynx::forceForegroundForTest (*test->main);
  11330. test->main->toFront (true);
  11331. test->done = [this, test] {
  11332. setApplicationReturnValue (test->ok ? 0 : 1);
  11333. juce::MessageManager::callAsync ([this, test] {
  11334. lynx::closeAllToolWindows();
  11335. lynx::setMainWindowForOwnership (nullptr);
  11336. test->main = nullptr;
  11337. delete test;
  11338. quit();
  11339. });
  11340. };
  11341. test->startTimer (1500);
  11342. }
  11343. // --minimizeclicktest (issue #188): see the option. The main window holds a component that counts its mouse-downs.
  11344. void runMinimizeClickTest (const juce::String& reportPath)
  11345. {
  11346. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  11347. struct ClickPad final : juce::Component
  11348. {
  11349. int downs = 0;
  11350. void paint (juce::Graphics& g) override { g.fillAll (juce::Colours::darkslategrey); }
  11351. void mouseDown (const juce::MouseEvent&) override { ++downs; }
  11352. };
  11353. struct MinimizeTest final : juce::Timer
  11354. {
  11355. juce::String reportPath, report;
  11356. bool ok = true;
  11357. int stepIndex = 0, waits = 0;
  11358. std::unique_ptr<juce::DocumentWindow> main;
  11359. ClickPad* pad = nullptr;
  11360. juce::DocumentWindow* tool = nullptr;
  11361. juce::Point<int> inside, outside; // screen points: where the tool window is, and beside it
  11362. std::function<void()> done;
  11363. void line (const juce::String& text)
  11364. {
  11365. report << text << "\n";
  11366. juce::File (reportPath).replaceWithText (report);
  11367. }
  11368. void check (const juce::String& what, bool passed)
  11369. {
  11370. line ((passed ? "ok " : "FAIL ") + what);
  11371. ok = ok && passed;
  11372. }
  11373. // a left click at a screen point through the main window's peer: the path an X ButtonPress takes
  11374. bool clickReachesPad (juce::Point<int> screen)
  11375. {
  11376. auto* peer = main->getPeer();
  11377. if (peer == nullptr)
  11378. return false;
  11379. const auto before = pad->downs;
  11380. const auto local = peer->globalToLocal (screen.toFloat());
  11381. const auto now = juce::Time::currentTimeMillis();
  11382. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier),
  11383. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation, now);
  11384. peer->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, juce::ModifierKeys(),
  11385. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation, now + 1);
  11386. return pad->downs == before + 1;
  11387. }
  11388. bool toolMinimised() const { return tool != nullptr && tool->getPeer() != nullptr && tool->getPeer()->isMinimised(); }
  11389. void timerCallback() override
  11390. {
  11391. switch (stepIndex)
  11392. {
  11393. case 0:
  11394. {
  11395. auto content = std::make_unique<juce::Component>();
  11396. content->setSize (420, 300);
  11397. tool = lynx::openToolWindow (std::move (content), "Tap tempo (test)", "minimizetest");
  11398. ++stepIndex;
  11399. return;
  11400. }
  11401. case 1:
  11402. {
  11403. check ("tool window open", tool != nullptr && tool->isShowing());
  11404. if (tool == nullptr)
  11405. break;
  11406. const auto r = tool->getScreenBounds();
  11407. inside = r.getCentre();
  11408. outside = { main->getScreenBounds().getX() + 40, main->getScreenBounds().getBottom() - 40 };
  11409. line ("main " + main->getScreenBounds().toString() + " tool " + r.toString());
  11410. lynx::matchWindowOrderToScreen();
  11411. check ("a click beside the tool window reaches the main window", clickReachesPad (outside));
  11412. check ("a click on the shown tool window does not reach the main window", ! clickReachesPad (inside));
  11413. tool->setMinimised (true);
  11414. ++stepIndex;
  11415. return;
  11416. }
  11417. case 2:
  11418. if (! toolMinimised() && ++waits < 20)
  11419. return;
  11420. check ("the window manager minimised the tool window", toolMinimised());
  11421. check ("the tool window stays visible for JUCE (as in the report)", tool->isVisible());
  11422. main->toFront (true); // a click on the main window: LYNX puts its secondary windows back above it in JUCE's list
  11423. lynx::matchWindowOrderToScreen();
  11424. ++stepIndex;
  11425. return;
  11426. case 3:
  11427. check ("a click where the minimised tool window was reaches the main window", clickReachesPad (inside));
  11428. check ("a click beside it still reaches the main window", clickReachesPad (outside));
  11429. tool->setMinimised (false);
  11430. waits = 0;
  11431. ++stepIndex;
  11432. return;
  11433. case 4:
  11434. if (toolMinimised() && ++waits < 20)
  11435. return;
  11436. tool->toFront (false);
  11437. lynx::matchWindowOrderToScreen();
  11438. ++stepIndex;
  11439. return;
  11440. case 5:
  11441. check ("the tool window is back", ! toolMinimised());
  11442. check ("a click on the restored tool window does not reach the main window", ! clickReachesPad (inside));
  11443. break;
  11444. default:
  11445. return;
  11446. }
  11447. line (ok ? "result=OK" : "result=FAILED");
  11448. stopTimer();
  11449. done();
  11450. }
  11451. };
  11452. auto* test = new MinimizeTest();
  11453. test->reportPath = reportPath;
  11454. test->main = std::make_unique<juce::DocumentWindow> ("LYNX minimise test", lynx::theme::window, juce::DocumentWindow::allButtons);
  11455. test->main->setUsingNativeTitleBar (true);
  11456. test->pad = new ClickPad();
  11457. test->pad->setSize (1200, 760);
  11458. test->main->setContentOwned (test->pad, true);
  11459. test->main->setTopLeftPosition (60, 60);
  11460. test->main->setVisible (true);
  11461. lynx::setMainWindowForOwnership (test->main.get());
  11462. test->main->toFront (true);
  11463. test->done = [this, test] {
  11464. setApplicationReturnValue (test->ok ? 0 : 1);
  11465. juce::MessageManager::callAsync ([this, test] {
  11466. lynx::closeAllToolWindows();
  11467. lynx::setMainWindowForOwnership (nullptr);
  11468. test->main = nullptr;
  11469. delete test;
  11470. quit();
  11471. });
  11472. };
  11473. test->startTimer (700);
  11474. }
  11475. // LYNX.exe --plugintest plugin.vst3 report.txt ["name"]: loads the plugin (or the one named in a shell), plays notes if it is an
  11476. // instrument (and runs audio through it if it is an effect) and measures the audio.
  11477. // Round 190fw: an instrument plugin file on channel 5 of an offline engine (Image-Line's "FL Studio VSTi", which
  11478. // runs FL Studio inside it). Without a project: four chords at 137 BPM, rendered (notes.wav), the plugin's state
  11479. // saved in <folder>/vstitest.lynx. With a project (one saved by LYNX with the plugin on a channel, e.g. after its
  11480. // window was used): that project. Then: the project loaded back from the file renders the same (reload.wav) and
  11481. // gives the same state back; the project's own notes removed, rendered at 100 and 150 BPM (tempo-100/150.wav), the
  11482. // onsets of what the plugin plays by itself must follow the host tempo; and the outputs the plugin offers.
  11483. void runVstiTest (const juce::String& pluginPath, const juce::String& folderPath, const juce::String& projectPath)
  11484. {
  11485. juce::String report;
  11486. auto ok = true;
  11487. const juce::File folder (folderPath);
  11488. folder.createDirectory();
  11489. const auto check = [&] (const juce::String& name, bool passed) {
  11490. report << name << "=" << (passed ? "OK" : "FAILED") << "\n";
  11491. ok = ok && passed;
  11492. };
  11493. struct Take
  11494. {
  11495. float peak = 0.0f;
  11496. std::vector<float> left;
  11497. };
  11498. // renders `song` with the plugin file known to the engine's host; `wav` (in the folder) gets the audio
  11499. const auto render = [&] (const lynx::Song& song, double seconds, const juce::String& wav, std::function<void (lynx::AudioEngine&)> after = {}) {
  11500. Take take;
  11501. lynx::AudioEngine engine (false);
  11502. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  11503. engine.setSong (song);
  11504. const auto file = folder.getChildFile (wav);
  11505. file.deleteFile();
  11506. std::unique_ptr<juce::AudioFormatWriter> writer;
  11507. if (auto stream = file.createOutputStream())
  11508. {
  11509. juce::WavAudioFormat format;
  11510. writer.reset (format.createWriterFor (stream.get(), 48000.0, 2, 24, {}, 0));
  11511. if (writer != nullptr)
  11512. stream.release();
  11513. }
  11514. lynx::AudioEngine::RenderOptions o;
  11515. o.seconds = seconds;
  11516. o.sampleRate = 48000.0;
  11517. o.output = writer.get();
  11518. o.capture = [&take] (const float* l, const float*, int n) { take.left.insert (take.left.end(), l, l + n); };
  11519. take.peak = engine.renderOffline (o);
  11520. writer.reset();
  11521. if (after)
  11522. after (engine);
  11523. return take;
  11524. };
  11525. // the channel that holds the plugin
  11526. const auto pluginChannel = [&] (const lynx::Song& song) {
  11527. for (std::size_t c = 0; c < song.channels.size(); ++c)
  11528. if (song.channels[c].instrument == lynx::InstrumentKind::plugin
  11529. && juce::String (song.channels[c].plugin.name).containsIgnoreCase (juce::File (pluginPath).getFileNameWithoutExtension().upToFirstOccurrenceOf (" (", false, false)))
  11530. return (int) c;
  11531. return -1;
  11532. };
  11533. lynx::Song song;
  11534. const auto saved = folder.getChildFile ("vstitest.lynx");
  11535. if (projectPath.isEmpty())
  11536. {
  11537. lynx::AudioEngine scanner (false);
  11538. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  11539. std::optional<juce::PluginDescription> type;
  11540. for (const auto& t : scanner.getPluginHost().getKnownPlugins().getTypes())
  11541. if (t.isInstrument && juce::File (t.fileOrIdentifier) == juce::File (pluginPath))
  11542. type = t;
  11543. check ("instrument_found", type.has_value());
  11544. if (! type)
  11545. {
  11546. juce::File (folder.getChildFile ("report.txt")).replaceWithText (report + "result=FAILED\n");
  11547. setApplicationReturnValue (1);
  11548. quit();
  11549. return;
  11550. }
  11551. report << "plugin=" << type->name << " (" << type->manufacturerName << ") outputs=" << type->numOutputChannels << "\n";
  11552. song = lynx::Song::makeDefault();
  11553. song.bpm = 137.0;
  11554. auto& c = song.channels[4];
  11555. c.instrument = lynx::InstrumentKind::plugin;
  11556. c.plugin = {};
  11557. c.plugin.id = type->createIdentifierString().toStdString();
  11558. c.plugin.name = type->name.toStdString();
  11559. c.name = type->name.toStdString();
  11560. c.volume = 1.0f;
  11561. for (std::size_t k = 0; k < song.channels.size(); ++k)
  11562. song.channels[k].muted = k != 4;
  11563. song.patterns[0].notes.clear();
  11564. for (int beat = 0; beat < 8; ++beat) // a chord per beat, two bars
  11565. for (int key : { 60, 64, 67 })
  11566. song.patterns[0].notes.push_back ({ (std::int64_t) beat * lynx::ppq, lynx::ppq / 2, 4, key + (beat / 4) * 5, 0.9f });
  11567. song.patterns[0].sortNotes();
  11568. const auto notes = render (song, 4.0, "notes.wav", [&song] (lynx::AudioEngine& engine) {
  11569. engine.capturePluginStates();
  11570. song = engine.getSong();
  11571. });
  11572. report << "notes_peak=" << notes.peak << "\n";
  11573. check ("notes_play", notes.peak > 0.001f && notes.peak < 10.0f);
  11574. juce::String error;
  11575. check ("project_saved", lynx::ProjectFile::save (song, saved, error));
  11576. }
  11577. else
  11578. {
  11579. juce::String error;
  11580. const auto loaded = lynx::ProjectFile::load (juce::File (projectPath), error);
  11581. check ("project_loaded", loaded.has_value());
  11582. if (loaded)
  11583. song = *loaded;
  11584. juce::File (projectPath).copyFileTo (saved);
  11585. }
  11586. const auto channel = pluginChannel (song);
  11587. check ("plugin_channel", channel >= 0);
  11588. if (channel >= 0)
  11589. {
  11590. const auto& plugin = song.channels[(std::size_t) channel].plugin;
  11591. juce::MemoryBlock state;
  11592. state.fromBase64Encoding (juce::String (plugin.state));
  11593. report << "channel=" << channel + 1 << " state_bytes=" << (int) state.getSize() << "\n";
  11594. check ("state_saved", state.getSize() > 0);
  11595. // the project read back from the file: the same sound, and the same state handed back
  11596. juce::String error;
  11597. const auto again = lynx::ProjectFile::load (saved, error);
  11598. check ("project_reloaded", again.has_value());
  11599. if (again)
  11600. {
  11601. std::string stateBack;
  11602. const auto first = render (*again, 4.0, "reload-a.wav");
  11603. const auto second = render (*again, 4.0, "reload-b.wav", [&] (lynx::AudioEngine& engine) {
  11604. engine.capturePluginStates();
  11605. stateBack = engine.getSong().channels[(std::size_t) channel].plugin.state;
  11606. });
  11607. // two loads of the same project: the same audio (sample for sample, or within -60 dB for a plugin
  11608. // with free-running modulation)
  11609. double energy = 0.0, difference = 0.0;
  11610. const auto n = std::min (first.left.size(), second.left.size());
  11611. for (std::size_t k = 0; k < n; ++k)
  11612. {
  11613. energy += (double) first.left[k] * first.left[k];
  11614. difference += ((double) first.left[k] - second.left[k]) * ((double) first.left[k] - second.left[k]);
  11615. }
  11616. const auto ratioDb = energy > 0.0 ? 10.0 * std::log10 (std::max (difference, 1e-30) / energy) : 0.0;
  11617. report << "reload_peak=" << first.peak << " reload_difference_db=" << juce::String (ratioDb, 1) << "\n";
  11618. check ("reload_plays", first.peak > 0.001f);
  11619. check ("reload_same_sound", energy > 0.0 && ratioDb < -60.0);
  11620. juce::MemoryBlock back;
  11621. back.fromBase64Encoding (juce::String (stateBack));
  11622. report << "state_back_bytes=" << (int) back.getSize() << " identical=" << (int) (back == state) << "\n";
  11623. check ("state_handed_back", back.getSize() > 0);
  11624. }
  11625. // the host tempo: what the plugin plays by itself (FL Studio's own patterns inside FL Studio VSTi) at two
  11626. // tempos, without the project's notes
  11627. auto self = song;
  11628. for (std::size_t k = 0; k < self.channels.size(); ++k)
  11629. self.channels[k].muted = (int) k != channel;
  11630. for (auto& pattern : self.patterns)
  11631. pattern.notes.erase (std::remove_if (pattern.notes.begin(), pattern.notes.end(), [channel] (const lynx::Note& n) { return n.channel == channel; }),
  11632. pattern.notes.end());
  11633. const auto onsets = [] (const std::vector<float>& x) {
  11634. // envelope rises over a threshold (10 ms hold-off of 60 ms): the times in seconds
  11635. std::vector<double> at;
  11636. float peak = 0.0f;
  11637. for (const auto v : x)
  11638. peak = std::max (peak, std::abs (v));
  11639. const auto threshold = peak * 0.3f;
  11640. auto quietFor = 1 << 30;
  11641. for (std::size_t k = 0; k < x.size(); ++k)
  11642. {
  11643. const auto loud = std::abs (x[k]) >= threshold;
  11644. if (loud && quietFor >= 48000 * 60 / 1000)
  11645. at.push_back ((double) k / 48000.0);
  11646. quietFor = loud ? 0 : quietFor + 1;
  11647. }
  11648. return at;
  11649. };
  11650. const auto medianGap = [] (const std::vector<double>& at) {
  11651. std::vector<double> gaps;
  11652. for (std::size_t k = 1; k < at.size(); ++k)
  11653. gaps.push_back (at[k] - at[k - 1]);
  11654. if (gaps.empty())
  11655. return 0.0;
  11656. std::sort (gaps.begin(), gaps.end());
  11657. return gaps[gaps.size() / 2];
  11658. };
  11659. self.bpm = 100.0;
  11660. const auto slow = render (self, 6.0, "tempo-100.wav");
  11661. self.bpm = 150.0;
  11662. const auto fast = render (self, 6.0, "tempo-150.wav");
  11663. const auto gapSlow = medianGap (onsets (slow.left)), gapFast = medianGap (onsets (fast.left));
  11664. report << "self_peak_100=" << slow.peak << " self_peak_150=" << fast.peak << " onsets_100=" << (int) onsets (slow.left).size()
  11665. << " onsets_150=" << (int) onsets (fast.left).size() << " gap_100=" << juce::String (gapSlow, 4) << " gap_150="
  11666. << juce::String (gapFast, 4) << "\n";
  11667. if (slow.peak > 0.001f && gapFast > 0.0)
  11668. {
  11669. report << "tempo_ratio=" << juce::String (gapSlow / gapFast, 3) << " (expected 1.5)\n";
  11670. check ("follows_host_tempo", std::abs (gapSlow / gapFast - 1.5) < 0.05);
  11671. }
  11672. else
  11673. report << "tempo: the plugin plays nothing by itself in this project\n";
  11674. // the outputs it offers (FL Studio VSTi (Multi): FL's mixer tracks as separate outputs)
  11675. lynx::AudioEngine engine (false);
  11676. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  11677. engine.setSong (song);
  11678. engine.renderOffline (0.2, 48000.0);
  11679. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (channel)))
  11680. {
  11681. report << "outputs=" << (int) instrument->outputs().size() << ":";
  11682. for (const auto& o : instrument->outputs())
  11683. report << " [" << o.name << "]";
  11684. report << "\n";
  11685. check ("outputs_listed", ! instrument->outputs().empty());
  11686. }
  11687. else
  11688. check ("instrument_loaded", false);
  11689. }
  11690. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  11691. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  11692. folder.getChildFile ("report.txt").replaceWithText (report);
  11693. setApplicationReturnValue (ok ? 0 : 1);
  11694. quit();
  11695. }
  11696. void runPluginTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& only = {})
  11697. {
  11698. juce::String report;
  11699. bool ok = false;
  11700. {
  11701. lynx::AudioEngine offline (false);
  11702. auto& host = offline.getPluginHost();
  11703. const auto added = host.addPluginFile (juce::File (pluginPath));
  11704. report << "plugins_in_file=" << added << "\n";
  11705. juce::PluginDescription instrument, effect;
  11706. bool hasInstrument = false, hasEffect = false;
  11707. for (const auto& type : host.getKnownPlugins().getTypes())
  11708. {
  11709. if (juce::File (type.fileOrIdentifier).getFileName() != juce::File (pluginPath).getFileName()
  11710. || (only.isNotEmpty() && type.name != only))
  11711. continue;
  11712. report << " " << (type.isInstrument ? "instrument: " : "effect: ") << type.name << " (" << type.manufacturerName
  11713. << ") in " << type.fileOrIdentifier << "\n";
  11714. if (type.isInstrument && ! hasInstrument) { instrument = type; hasInstrument = true; }
  11715. if (! type.isInstrument && ! hasEffect) { effect = type; hasEffect = true; }
  11716. }
  11717. auto song = lynx::Song::makeDefault();
  11718. if (hasInstrument)
  11719. {
  11720. auto& c = song.channels[4]; // the "Synth" channel becomes the plugin
  11721. c.instrument = lynx::InstrumentKind::plugin;
  11722. c.plugin.id = instrument.createIdentifierString().toStdString();
  11723. c.plugin.name = instrument.name.toStdString();
  11724. c.volume = 1.0f;
  11725. for (int i = 0; i < 4; ++i) // one chord per beat
  11726. for (int key : { 60, 64, 67 })
  11727. song.patterns[0].notes.push_back ({ (std::int64_t) i * lynx::ppq, lynx::ppq / 2, 4, key, 0.9f });
  11728. song.patterns[0].sortNotes();
  11729. }
  11730. if (hasEffect)
  11731. {
  11732. lynx::EffectSlot slot;
  11733. slot.kind = lynx::EffectKind::plugin;
  11734. slot.plugin.id = effect.createIdentifierString().toStdString();
  11735. slot.plugin.name = effect.name.toStdString();
  11736. song.mixer[0].effects.push_back (slot);
  11737. }
  11738. const auto effectSlot = (int) song.mixer[0].effects.size() - 1; // (the default master may hold effects already)
  11739. offline.setSong (song);
  11740. // after a render: the rack (and its plugins) is built when the engine is prepared
  11741. const auto peak = offline.renderOffline (3.0, 48000.0);
  11742. const auto* loadedInstrument = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get());
  11743. const auto* loadedEffect = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (0, effectSlot).get());
  11744. report << "instrument_loaded=" << (loadedInstrument != nullptr ? "yes" : "no") << "\n"
  11745. << "effect_loaded=" << (loadedEffect != nullptr ? "yes" : "no") << "\n";
  11746. if (host.getLoadFailures().size() > 0) // why: the host's own message (license, missing file, load failure)
  11747. report << "load_failures=" << host.getLoadFailures().joinIntoString (" | ") << "\n";
  11748. report << "peak=" << peak << "\n";
  11749. // plugins that crashed inside a call, were caught and switched off (round 111)
  11750. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  11751. for (const auto& c : lynx::pluginCrashes())
  11752. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  11753. offline.capturePluginStates();
  11754. const auto stateSize = hasInstrument ? offline.getSong().channels[4].plugin.state.size() : (size_t) 0;
  11755. report << "state_bytes_base64=" << (int) stateSize << "\n";
  11756. ok = (hasInstrument || hasEffect) && (! hasInstrument || loadedInstrument != nullptr)
  11757. && (! hasEffect || loadedEffect != nullptr) && peak > 0.001f && peak < 10.0f;
  11758. }
  11759. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  11760. juce::File (reportPath).replaceWithText (report);
  11761. setApplicationReturnValue (ok ? 0 : 1);
  11762. quit();
  11763. }
  11764. // Round 190gg (B4): --crashguardtest plugin report.txt thread | ui. "thread": the plugin's own thread faults in its 40th
  11765. // block (Linux / macOS): that thread is parked, LYNX switches the plugin off (as the main window's timer does) and goes
  11766. // on; the other inserts play; Reload brings it back. "ui": the calls the UI makes into a plugin, under the guard: a
  11767. // preset load that crashes (the Plugin window's preset menu path) and making the editor (PluginWindows::open, the CLAP
  11768. // test plugin's "editor-create": a display is needed, e.g. Xvfb); each switches the plugin off, LYNX goes on.
  11769. void runCrashGuardThreadOrUiTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
  11770. {
  11771. juce::String report;
  11772. bool ok = true;
  11773. const auto expect = [&] (const char* name, bool value) {
  11774. report << name << "=" << (value ? 1 : 0) << "\n";
  11775. ok = ok && value;
  11776. };
  11777. const auto setEnv = [] (const char* name, const char* value) {
  11778. #if JUCE_WINDOWS
  11779. _putenv_s (name, value);
  11780. #else
  11781. setenv (name, value, 1);
  11782. #endif
  11783. };
  11784. const auto render = [] (lynx::AudioEngine& engine, double seconds, float* peak) {
  11785. lynx::AudioEngine::RenderOptions o;
  11786. o.seconds = seconds;
  11787. o.sampleRate = 48000.0;
  11788. o.pluginWarmUp = false;
  11789. if (peak != nullptr)
  11790. o.capture = [peak] (const float* l, const float* r, int n) {
  11791. for (int k = 0; k < n; ++k)
  11792. *peak = std::max (*peak, std::max (std::abs (l[k]), std::abs (r[k])));
  11793. };
  11794. return engine.renderOffline (o);
  11795. };
  11796. report << "mode=" << mode << "\nthread_guard=" << (lynx::crashguard::pluginThreadFaultsCaught() ? "on" : "off") << "\n";
  11797. setEnv ("LYNX_TEST_CRASH", mode == "thread" ? "thread" : "");
  11798. setEnv ("LYNX_TEST_CRASH_AFTER", "40");
  11799. const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
  11800. .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  11801. tmp.createDirectory();
  11802. {
  11803. lynx::AudioEngine offline (false);
  11804. auto& host = offline.getPluginHost();
  11805. host.addPluginFile (juce::File (pluginPath));
  11806. juce::PluginDescription effect;
  11807. bool found = false;
  11808. for (const auto& type : host.getKnownPlugins().getTypes())
  11809. if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  11810. {
  11811. effect = type;
  11812. found = true;
  11813. }
  11814. expect ("plugin_found", found);
  11815. auto song = lynx::Song::makeDefault();
  11816. lynx::EffectSlot slot;
  11817. slot.kind = lynx::EffectKind::plugin;
  11818. slot.plugin.id = effect.createIdentifierString().toStdString();
  11819. slot.plugin.name = effect.name.toStdString();
  11820. song.mixer[1].effects.push_back (slot);
  11821. offline.setSong (song);
  11822. const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
  11823. render (offline, 0.05, nullptr);
  11824. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  11825. render (offline, 0.05, nullptr);
  11826. auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  11827. expect ("plugin_loaded", first != nullptr);
  11828. const auto crashesBefore = lynx::pluginCrashCount();
  11829. if (mode == "thread")
  11830. {
  11831. const auto faultsBefore = lynx::crashguard::pluginThreadFaultCount();
  11832. float peak = 0.0f;
  11833. render (offline, 3.0, &peak); // (the plugin starts its faulting thread in its 40th block)
  11834. for (int i = 0; i < 200 && lynx::crashguard::pluginThreadFaultCount() == faultsBefore; ++i)
  11835. juce::Thread::sleep (10);
  11836. const auto faults = lynx::crashguard::pluginThreadFaults();
  11837. expect ("thread_fault_parked", lynx::crashguard::pluginThreadFaultCount() == faultsBefore + 1 && ! faults.empty());
  11838. if (! faults.empty())
  11839. report << "thread_fault=" << faults.back().where << " (" << lynx::crashguard::describe (faults.back().code) << ")\n";
  11840. expect ("not_yet_counted_as_a_call_crash", lynx::pluginCrashCount() == crashesBefore);
  11841. // what the main window's timer does
  11842. // (every instance of that module: the engine may hold more than the slot's, e.g. the offline render's)
  11843. if (first != nullptr)
  11844. report << "slot_file=" << first->getInstance().getPluginDescription().fileOrIdentifier << "\n";
  11845. const auto switched = lynx::switchOffPluginsOfThreadFaults();
  11846. report << "switched_off=" << switched << "\n";
  11847. expect ("plugin_switched_off", switched >= 1 && first != nullptr && first->hasCrashed() && lynx::pluginCrashCount() == crashesBefore + switched);
  11848. expect ("only_once", lynx::switchOffPluginsOfThreadFaults() == 0);
  11849. const auto down = offline.downHostedPlugins();
  11850. expect ("slot_down", down.size() == 1 && down[0] == where);
  11851. float after = 0.0f;
  11852. render (offline, 1.0, &after);
  11853. report << "peak_after=" << after << "\n";
  11854. expect ("audio_after_fault", after > 0.01f);
  11855. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
  11856. float others = 0.0f;
  11857. render (offline, 1.0, &others);
  11858. expect ("other_inserts_play", others > 0.01f);
  11859. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  11860. const auto running = offline.reloadHostedPlugins (down);
  11861. auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  11862. float reloaded = 0.0f;
  11863. render (offline, 1.0, &reloaded);
  11864. expect ("reloaded_plays", running == 1 && again != nullptr && again != first && ! again->hasCrashed() && reloaded > 0.01f);
  11865. }
  11866. else
  11867. {
  11868. // a preset that crashes the plugin (the preset menu's load), saved first from the running plugin
  11869. auto& instance = first->getInstance();
  11870. const auto preset = tmp.getChildFile ("crash.lynxpreset");
  11871. juce::String error;
  11872. expect ("preset_saved", lynx::pluginpresetui::save (instance, preset, "crash", error) && preset.existsAsFile());
  11873. setEnv ("LYNX_TEST_CRASH", "state");
  11874. const auto loaded = lynx::pluginpresetui::load (instance, preset, error);
  11875. setEnv ("LYNX_TEST_CRASH", "");
  11876. report << "preset_error=" << error << "\n";
  11877. expect ("preset_crash_caught", ! loaded && lynx::pluginCrashCount() == crashesBefore + 1 && first->hasCrashed());
  11878. expect ("preset_plugin_down", offline.hostedPluginDown (where) && lynx::pluginInstanceDown (instance));
  11879. expect ("not_called_again", ! lynx::callPluginFromUi (instance, "test", [] {}) && lynx::pluginCrashCount() == crashesBefore + 1);
  11880. float after = 0.0f;
  11881. render (offline, 1.0, &after);
  11882. expect ("audio_after_preset_crash", after > 0.01f);
  11883. // Reload; then its editor crashes as it is made (PluginWindows::open): no window, the plugin is down
  11884. setEnv ("LYNX_TEST_CRASH", "editor-create");
  11885. const auto running = offline.reloadHostedPlugins (offline.downHostedPlugins());
  11886. auto held = offline.getEffect (1, 0);
  11887. auto* again = dynamic_cast<lynx::PluginEffect*> (held.get());
  11888. expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
  11889. if (again != nullptr)
  11890. {
  11891. lynx::PluginWindows::open (held, again->getInstance(), "crash test", {});
  11892. expect ("editor_crash_caught", lynx::pluginCrashCount() == crashesBefore + 2 && again->hasCrashed());
  11893. expect ("no_window", ! lynx::PluginWindows::isOpen (again->getInstance()));
  11894. float editorAfter = 0.0f;
  11895. render (offline, 1.0, &editorAfter);
  11896. expect ("audio_after_editor_crash", editorAfter > 0.01f);
  11897. }
  11898. setEnv ("LYNX_TEST_CRASH", "");
  11899. }
  11900. }
  11901. setEnv ("LYNX_TEST_CRASH", "");
  11902. // LYNX's own faults (also on its own threads) stay crashes (child processes; the selftest runs the same)
  11903. const auto own = faultReportSelfTest();
  11904. report << "own_faults=" << own << "\n";
  11905. ok = ok && ! own.startsWith ("ERROR");
  11906. for (const auto& c : lynx::pluginCrashes())
  11907. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << ")\n";
  11908. tmp.deleteRecursively();
  11909. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  11910. juce::File (reportPath).replaceWithText (report);
  11911. setApplicationReturnValue (ok ? 0 : 1);
  11912. quit();
  11913. }
  11914. // LYNX --crashguardtest plugin report.txt [process|memcpy] (round 190dt): see the dispatch in initialise().
  11915. void runCrashGuardTest (const juce::String& pluginPath, const juce::String& reportPath, const juce::String& mode)
  11916. {
  11917. if (mode == "thread" || mode == "ui")
  11918. {
  11919. runCrashGuardThreadOrUiTest (pluginPath, reportPath, mode);
  11920. return;
  11921. }
  11922. juce::String report;
  11923. bool ok = true;
  11924. const auto expect = [&] (const char* name, bool value) {
  11925. report << name << "=" << (value ? 1 : 0) << "\n";
  11926. ok = ok && value;
  11927. };
  11928. const auto setEnv = [] (const char* name, const char* value) {
  11929. #if JUCE_WINDOWS
  11930. _putenv_s (name, value);
  11931. #else
  11932. setenv (name, value, 1);
  11933. #endif
  11934. };
  11935. // renders without the plugin warm-up (its silent blocks would count towards the crash)
  11936. const auto render = [] (lynx::AudioEngine& engine, double seconds, const std::function<void (const float*, const float*, int)>& capture) {
  11937. lynx::AudioEngine::RenderOptions o;
  11938. o.seconds = seconds;
  11939. o.sampleRate = 48000.0;
  11940. o.pluginWarmUp = false;
  11941. o.capture = capture;
  11942. return engine.renderOffline (o);
  11943. };
  11944. const auto peakOf = [] (float& peak) {
  11945. return [&peak] (const float* l, const float* r, int n) {
  11946. for (int k = 0; k < n; ++k)
  11947. peak = std::max (peak, std::max (std::abs (l[k]), std::abs (r[k])));
  11948. };
  11949. };
  11950. report << "guard=" << (lynx::crashguard::pluginFaultsCaught() ? "on" : "off") << "\nmode=" << mode << "\n";
  11951. setEnv ("LYNX_TEST_CRASH", mode == "memcpy" ? "memcpy" : "process");
  11952. setEnv ("LYNX_TEST_CRASH_AFTER", "40");
  11953. const auto tmp = juce::File::getSpecialLocation (juce::File::tempDirectory)
  11954. .getChildFile ("lynx-crashguardtest-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  11955. tmp.createDirectory();
  11956. std::optional<lynx::Song> saved;
  11957. std::string savedState;
  11958. {
  11959. lynx::AudioEngine offline (false);
  11960. auto& host = offline.getPluginHost();
  11961. host.addPluginFile (juce::File (pluginPath));
  11962. juce::PluginDescription effect;
  11963. bool found = false;
  11964. for (const auto& type : host.getKnownPlugins().getTypes())
  11965. if (! found && ! type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  11966. {
  11967. effect = type;
  11968. found = true;
  11969. }
  11970. expect ("plugin_found", found);
  11971. // the plugin on insert 1 (the kick's); the clap and the hat play on inserts 2 and 3
  11972. auto song = lynx::Song::makeDefault();
  11973. lynx::EffectSlot slot;
  11974. slot.kind = lynx::EffectKind::plugin;
  11975. slot.plugin.id = effect.createIdentifierString().toStdString();
  11976. slot.plugin.name = effect.name.toStdString();
  11977. song.mixer[1].effects.push_back (slot);
  11978. offline.setSong (song);
  11979. const lynx::AudioEngine::HostedSlot where { -1, 1, 0 };
  11980. // the rack is published at the engine's rate and an offline render runs at its own (48 kHz) without publishing:
  11981. // one edit after a first render puts the rack (and the plugin) at the render's rate, so later edits keep it
  11982. render (offline, 0.05, {}); // (a few blocks, far from the 40th)
  11983. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  11984. render (offline, 0.05, {});
  11985. auto* first = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  11986. expect ("plugin_loaded", first != nullptr);
  11987. offline.capturePluginStates();
  11988. savedState = offline.getSong().mixer[1].effects[0].plugin.state;
  11989. expect ("state_captured", ! savedState.empty());
  11990. // the crash: 3 s, the plugin faults in its 40th block
  11991. const auto crashesBefore = lynx::pluginCrashCount();
  11992. juce::int64 position = 0, crashAt = -1;
  11993. float peakAfter = 0.0f;
  11994. const auto afterPeak = peakOf (peakAfter);
  11995. const auto peak = render (offline, 3.0, [&] (const float* l, const float* r, int n) {
  11996. if (crashAt < 0 && lynx::pluginCrashCount() != crashesBefore)
  11997. crashAt = position;
  11998. else if (crashAt >= 0)
  11999. afterPeak (l, r, n);
  12000. position += n;
  12001. });
  12002. report << "peak=" << peak << "\ncrash_at_sample=" << crashAt << "\npeak_after_crash=" << peakAfter << "\n";
  12003. const auto crashes = lynx::pluginCrashes();
  12004. expect ("crash_caught", lynx::pluginCrashCount() == crashesBefore + 1 && ! crashes.empty() && ! crashes.back().onLoad);
  12005. if (! crashes.empty())
  12006. report << "crash=" << crashes.back().plugin << " (" << lynx::crashguard::describe (crashes.back().code) << ")\n";
  12007. expect ("slot_marked_crashed", first != nullptr && offline.getEffect (1, 0).get() == first && first->hasCrashed());
  12008. const auto down = offline.downHostedPlugins();
  12009. expect ("slot_down", down.size() == 1 && down[0] == where);
  12010. expect ("audio_after_crash", crashAt >= 0 && peakAfter > 0.01f);
  12011. // the other inserts: with the kick (through the crashed slot) silent, the clap and the hat still play
  12012. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.0f; }, false);
  12013. float othersPeak = 0.0f;
  12014. render (offline, 1.0, peakOf (othersPeak));
  12015. report << "other_inserts_peak=" << othersPeak << "\n";
  12016. expect ("other_inserts_play", othersPeak > 0.01f);
  12017. expect ("nothing_reloads_by_itself", offline.hostedPluginDown (where) && offline.getEffect (1, 0).get() == first);
  12018. offline.editSong ([] (lynx::Song& s) { s.channels[0].volume = 0.85f; }, false);
  12019. // the project saves with the settings the plugin had before it crashed, and opens again
  12020. offline.capturePluginStates();
  12021. expect ("state_kept", offline.getSong().mixer[1].effects[0].plugin.state == savedState);
  12022. const auto file = tmp.getChildFile ("crashed.lynx");
  12023. juce::String error;
  12024. expect ("project_saved", lynx::ProjectFile::save (offline.getSong(), file, error) && file.existsAsFile());
  12025. saved = lynx::ProjectFile::load (file, error);
  12026. expect ("project_reopens", saved.has_value() && saved->mixer.size() > 1 && saved->mixer[1].effects.size() == 1
  12027. && saved->mixer[1].effects[0].plugin.state == savedState);
  12028. // Reload (the prompt's button, round 190ao): a new instance; the module's block count is past 40 now
  12029. const auto running = offline.reloadHostedPlugins (down);
  12030. auto* again = dynamic_cast<lynx::PluginEffect*> (offline.getEffect (1, 0).get());
  12031. expect ("reloaded", running == 1 && again != nullptr && again != first && ! again->hasCrashed());
  12032. float reloadedPeak = 0.0f;
  12033. render (offline, 1.0, peakOf (reloadedPeak));
  12034. report << "reloaded_peak=" << reloadedPeak << "\n";
  12035. expect ("reloaded_plays", reloadedPeak > 0.01f && lynx::pluginCrashCount() == crashesBefore + 1 && again != nullptr && ! again->hasCrashed());
  12036. }
  12037. // the saved project opens again with the plugin crashing on its saved settings: left out, the rest plays, the
  12038. // settings stay in the project
  12039. setEnv ("LYNX_TEST_CRASH", "state");
  12040. if (saved.has_value())
  12041. {
  12042. lynx::AudioEngine reopened (false);
  12043. reopened.getPluginHost().addPluginFile (juce::File (pluginPath));
  12044. const auto before = lynx::pluginCrashCount();
  12045. reopened.setSong (*saved);
  12046. float reopenedPeak = 0.0f;
  12047. render (reopened, 1.0, peakOf (reopenedPeak));
  12048. const auto crashes = lynx::pluginCrashes();
  12049. report << "reopened_peak=" << reopenedPeak << "\n";
  12050. if (reopened.getPluginHost().getLoadFailures().size() > 0)
  12051. report << "load_failures=" << reopened.getPluginHost().getLoadFailures().joinIntoString (" | ") << "\n";
  12052. expect ("state_crash_caught", lynx::pluginCrashCount() == before + 1 && ! crashes.empty() && crashes.back().onLoad);
  12053. expect ("state_crash_left_out", dynamic_cast<lynx::PluginEffect*> (reopened.getEffect (1, 0).get()) == nullptr);
  12054. expect ("state_crash_project_plays", reopenedPeak > 0.01f);
  12055. reopened.capturePluginStates();
  12056. expect ("state_crash_settings_kept", reopened.getSong().mixer[1].effects.size() == 1
  12057. && reopened.getSong().mixer[1].effects[0].plugin.state == savedState);
  12058. }
  12059. setEnv ("LYNX_TEST_CRASH", "");
  12060. // LYNX's own faults inside a guarded call stay crashes (child processes; the selftest runs the same)
  12061. const auto own = faultReportSelfTest();
  12062. report << "own_faults=" << own << "\n";
  12063. ok = ok && ! own.startsWith ("ERROR");
  12064. report << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  12065. for (const auto& c : lynx::pluginCrashes())
  12066. report << " crashed: " << c.plugin << " (" << lynx::crashguard::describe (c.code) << (c.onLoad ? ", loading its state" : "") << ")\n";
  12067. tmp.deleteRecursively();
  12068. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  12069. juce::File (reportPath).replaceWithText (report);
  12070. setApplicationReturnValue (ok ? 0 : 1);
  12071. quit();
  12072. }
  12073. // LYNX.exe --mpetest "LYNX Test MPE.clap" report.txt (tools/testplugin/lynx_test_mpe.c, issue #108): a hosted CLAP
  12074. // instrument with the wrapper's MPE switch on gets each note on its own member channel, its fine pitch / Mod X /
  12075. // Mod Y as tuning / brightness / pressure note expressions before the note on, and a sounding note's expression
  12076. // on that note's channel alone. The plugin writes down what it received; no window, no audio device.
  12077. // Round 190hy: see --mpeplaytest190hy. Note A (C4, 1 s): its pitch curve holds 0 for 0.5 s, rises an octave over
  12078. // 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
  12079. // rendered audio's zero crossings (a silent logging plugin: its log shows the expressions instead).
  12080. void runMpePlayTest190hy (const juce::String& pluginPath, const juce::String& reportPath)
  12081. {
  12082. const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  12083. log.deleteFile();
  12084. #if JUCE_WINDOWS
  12085. _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
  12086. #else
  12087. setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
  12088. #endif
  12089. juce::String report;
  12090. auto ok = false;
  12091. const auto wavFile = juce::File (reportPath).withFileExtension ("wav");
  12092. constexpr double rate = 44100.0;
  12093. {
  12094. lynx::AudioEngine offline (false);
  12095. auto& host = offline.getPluginHost();
  12096. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  12097. const auto wanted = juce::File (pluginPath).hasFileExtension ("clap") ? "CLAP" : "VST3";
  12098. std::optional<juce::PluginDescription> type;
  12099. for (const auto& t : host.getKnownPlugins().getTypes())
  12100. if (t.pluginFormatName == wanted && t.isInstrument && ! type)
  12101. type = t;
  12102. report << "format=" << wanted << " found=" << (type ? type->name : juce::String ("none")) << "\n";
  12103. if (type)
  12104. {
  12105. lynx::Song s;
  12106. s.mixer = lynx::Song::defaultMixer (2);
  12107. s.bpm = 120.0;
  12108. lynx::ChannelDef c;
  12109. c.name = type->name.toStdString();
  12110. c.instrument = lynx::InstrumentKind::plugin;
  12111. c.plugin.id = type->createIdentifierString().toStdString();
  12112. c.plugin.name = type->name.toStdString();
  12113. c.plugin.mpe = true;
  12114. c.mixerTrack = 1;
  12115. s.channels.push_back (c);
  12116. s.patterns.emplace_back();
  12117. auto& p = s.patterns[0];
  12118. lynx::Note a;
  12119. a.channel = 0;
  12120. a.key = 60;
  12121. a.length = 2 * lynx::ppq;
  12122. a.velocity = 0.8f;
  12123. lynx::NoteCurves curves;
  12124. curves.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { (float) lynx::ppq, 0.0f }, { 1.5f * (float) lynx::ppq, 1200.0f },
  12125. { 2.0f * (float) lynx::ppq, 1200.0f } };
  12126. a.curves = curves;
  12127. auto b = a;
  12128. b.key = 67;
  12129. b.start = 2 * lynx::ppq;
  12130. b.length = lynx::ppq;
  12131. b.curves.clear();
  12132. p.notes = { a, b };
  12133. p.lengthTicks = 16 * lynx::ppq; // (one pass: the notes play once in the 1.2 s rendered)
  12134. offline.setSong (std::move (s));
  12135. wavFile.deleteFile();
  12136. juce::WavAudioFormat wav;
  12137. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (wavFile.createOutputStream().release(), rate, 2, 24, {}, 0));
  12138. const auto peak = writer != nullptr ? offline.renderOffline (1.6, rate, writer.get()) : 0.0f;
  12139. writer.reset();
  12140. report << "peak=" << peak << "\n";
  12141. ok = writer == nullptr && wavFile.existsAsFile();
  12142. }
  12143. } // (the plugin writes its log, if any, as it is destroyed)
  12144. // the frequency of [from, to) seconds of the left channel from its rising zero crossings
  12145. juce::AudioBuffer<float> audio;
  12146. {
  12147. juce::AudioFormatManager formats;
  12148. formats.registerBasicFormats();
  12149. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (wavFile)); reader != nullptr)
  12150. {
  12151. audio.setSize (1, (int) reader->lengthInSamples);
  12152. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, false);
  12153. }
  12154. }
  12155. const auto frequency = [&audio] (double from, double to) {
  12156. const auto* x = audio.getReadPointer (0);
  12157. const auto n = audio.getNumSamples();
  12158. long first = -1, last = -1;
  12159. auto crossings = 0;
  12160. for (auto i = juce::jmax (1, (int) (from * rate)); i < juce::jmin (n, (int) (to * rate)); ++i)
  12161. if (x[i - 1] <= 0.0f && x[i] > 0.0f)
  12162. {
  12163. if (first < 0)
  12164. first = i;
  12165. else
  12166. ++crossings, last = i;
  12167. }
  12168. return crossings > 0 ? crossings * rate / (double) (last - first) : 0.0;
  12169. };
  12170. if (audio.getNumSamples() > 0 && audio.getMagnitude (0, 0, audio.getNumSamples()) > 0.001f)
  12171. {
  12172. 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);
  12173. report << "a_before_hz=" << before << " a_rising_hz=" << during << " a_after_hz=" << after << " b_hz=" << next << "\n";
  12174. report << "a_after_over_before=" << (before > 0.0 ? after / before : 0.0) << " (an octave: 2)\n";
  12175. report << "b_over_a_before=" << (before > 0.0 ? next / before : 0.0) << " (a fifth: 1.498)\n";
  12176. }
  12177. else
  12178. report << "audio=silent\n";
  12179. if (log.existsAsFile())
  12180. report << "--- plugin log ---\n" << log.loadFileAsString();
  12181. report << "result=" << (ok ? "RENDERED" : "FAILED") << "\n";
  12182. juce::File (reportPath).replaceWithText (report);
  12183. setApplicationReturnValue (ok ? 0 : 1);
  12184. quit();
  12185. }
  12186. void runMpeTest (const juce::String& pluginPath, const juce::String& reportPath)
  12187. {
  12188. const auto log = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  12189. log.deleteFile();
  12190. #if JUCE_WINDOWS
  12191. _putenv_s ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8());
  12192. #else
  12193. setenv ("LYNX_TEST_MPE_REPORT", log.getFullPathName().toRawUTF8(), 1);
  12194. #endif
  12195. juce::String report;
  12196. auto failures = 0;
  12197. {
  12198. lynx::AudioEngine engine (false);
  12199. auto& host = engine.getPluginHost();
  12200. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  12201. std::optional<juce::PluginDescription> clap;
  12202. for (const auto& type : host.getKnownPlugins().getTypes())
  12203. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  12204. clap = type;
  12205. lynx::PluginRef ref;
  12206. if (clap)
  12207. {
  12208. ref.id = clap->createIdentifierString().toStdString();
  12209. ref.name = clap->name.toStdString();
  12210. }
  12211. ref.mpe = true;
  12212. juce::String error;
  12213. auto instrument = clap ? host.makeInstrument (ref, 48000.0, &error) : nullptr;
  12214. report << "instrument_loaded=" << (instrument != nullptr ? "yes" : "no") << (error.isNotEmpty() ? " (" + error + ")" : juce::String()) << "\n";
  12215. if (instrument != nullptr)
  12216. {
  12217. std::vector<float> l (256), r (256);
  12218. auto block = [&] { instrument->render (l.data(), r.data(), 256, 1.0f, 1.0f); };
  12219. block(); // (the zone's setup)
  12220. instrument->setNextNoteFinePitch (30.0f); // +30 cents
  12221. instrument->setNextNoteModulation (0.75f, 1.0f); // timbre 0.75, full pressure
  12222. instrument->noteOn (60, 0.8f);
  12223. instrument->noteOn (64, 0.5f); // a second note: its own channel, centre values
  12224. block();
  12225. instrument->noteExpression (60, (int) lynx::vfx::Prop::pitch, 200.0f, 0.0f);
  12226. instrument->noteExpression (64, (int) lynx::vfx::Prop::modX, 0.25f, 0.0f);
  12227. instrument->noteExpression (60, (int) lynx::vfx::Prop::modY, 0.75f, 0.0f);
  12228. block();
  12229. instrument->noteOff (60);
  12230. instrument->noteOff (64);
  12231. block();
  12232. }
  12233. else
  12234. ++failures;
  12235. } // (the plugin writes its log as it is destroyed)
  12236. struct Line
  12237. {
  12238. juce::String kind;
  12239. int a = 0, b = 0, c = 0, d = 0;
  12240. };
  12241. std::vector<Line> lines;
  12242. for (const auto& text : juce::StringArray::fromLines (log.loadFileAsString()))
  12243. {
  12244. const auto t = juce::StringArray::fromTokens (text, " ", "");
  12245. if (t.size() >= 3)
  12246. 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 });
  12247. }
  12248. report << "plugin_events=" << (int) lines.size() << "\n";
  12249. // the first line at or after `from` that matches (−1 = none); `value` within `tolerance` (thousandths)
  12250. auto find = [&lines] (const juce::String& kind, int a, int b, int value, int tolerance, int from = 0) {
  12251. for (auto i = (std::size_t) from; i < lines.size(); ++i)
  12252. {
  12253. const auto& x = lines[i];
  12254. const auto v = kind == "expr" ? x.d : x.c;
  12255. if (x.kind == kind && x.a == a && x.b == b && std::abs (v - value) <= tolerance)
  12256. return (int) i;
  12257. }
  12258. return -1;
  12259. };
  12260. auto check = [&] (const char* what, bool ok) {
  12261. report << what << "=" << (ok ? "ok" : "FAILED") << "\n";
  12262. failures += ok ? 0 : 1;
  12263. };
  12264. // (CLAP expression ids: 2 tuning in semitones, 5 brightness, 6 pressure; channels 0-based: the first member = 1)
  12265. const auto on60 = find ("on", 1, 60, 800, 5), on64 = find ("on", 2, 64, 500, 5);
  12266. check ("zone_setup_sent", find ("midi", 176, 6, 15, 0) >= 0 && find ("midi", 177, 6, 48, 0) >= 0);
  12267. check ("notes_on_their_own_channels", on60 >= 0 && on64 > on60);
  12268. const auto tune = find ("expr", 2, 1, 300, 3), bright = find ("expr", 5, 1, 756, 4), press = find ("expr", 6, 1, 1000, 1);
  12269. check ("expression_before_the_note_on", tune >= 0 && bright >= 0 && press >= 0 && tune < on60 && bright < on60 && press < on60);
  12270. 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);
  12271. const auto later = std::max (on60, on64) + 1;
  12272. check ("sounding_note_expression", later > 0 && find ("expr", 2, 1, 2000, 3, later) >= 0 && find ("expr", 5, 2, 252, 4, later) >= 0
  12273. && find ("expr", 6, 1, 504, 4, later) >= 0);
  12274. check ("other_note_untouched", later > 0 && find ("expr", 2, 2, 2000, 3, later) < 0 && find ("expr", 6, 2, 504, 4, later) < 0);
  12275. check ("notes_off_on_their_channels", find ("off", 1, 60, 0, 100000) >= 0 && find ("off", 2, 64, 0, 100000) >= 0);
  12276. auto expressionAsMidi = false; // (a CLAP-dialect plugin gets no raw bend / pressure / CC 74 on a member channel)
  12277. for (const auto& x : lines)
  12278. if (x.kind == "midi" && (x.a & 0x0f) != 0 && ((x.a & 0xf0) == 0xe0 || (x.a & 0xf0) == 0xd0 || ((x.a & 0xf0) == 0xb0 && x.b == 74)))
  12279. expressionAsMidi = true;
  12280. check ("no_duplicate_midi_expression", ! expressionAsMidi);
  12281. report << "--- plugin log ---\n" << log.loadFileAsString() << "result=" << (failures == 0 ? "OK" : "FAILED") << "\n";
  12282. juce::File (reportPath).replaceWithText (report);
  12283. setApplicationReturnValue (failures == 0 ? 0 : 1);
  12284. quit();
  12285. }
  12286. // LYNX.exe --claprestarttest "LYNX Test Restart.clap" report.txt (tools/testplugin/lynx_test_restart.c, PR #29): a
  12287. // CLAP effect on the Master that asks for a restart every 8 blocks while an export renders on a thread of its own
  12288. // (the message thread is free to run the restarts, as with the Export window). The plugin aborts the process when
  12289. // start / stop_processing run off the audio thread or activate / deactivate off the main thread (issue #46, as u-he
  12290. // Presswerk does; an export at 44.1 kHz and prepare calls from the export's thread check the latter) and counts deactivations that
  12291. // landed inside its process() call (must be none), the restarts must happen, and the delay compensation must end on
  12292. // the latency the plugin reports after its last restart.
  12293. void runClapRestartTest (const juce::String& pluginPath, const juce::String& reportPath)
  12294. {
  12295. struct Run
  12296. {
  12297. std::unique_ptr<lynx::AudioEngine> engine;
  12298. juce::String report;
  12299. int slot = -1;
  12300. std::thread render;
  12301. std::atomic<bool> done { false };
  12302. double renderSeconds = 0.0;
  12303. };
  12304. auto run = std::make_shared<Run>();
  12305. const auto counters = juce::File (reportPath).getSiblingFile (juce::File (reportPath).getFileNameWithoutExtension() + "-plugin.txt");
  12306. counters.deleteFile();
  12307. #if JUCE_WINDOWS
  12308. _putenv_s ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8());
  12309. #else
  12310. setenv ("LYNX_TEST_RESTART_REPORT", counters.getFullPathName().toRawUTF8(), 1);
  12311. #endif
  12312. const auto fail = [this, reportPath] (juce::String report) {
  12313. report << "result=FAILED\n";
  12314. juce::File (reportPath).replaceWithText (report);
  12315. setApplicationReturnValue (1);
  12316. quit();
  12317. };
  12318. run->engine = std::make_unique<lynx::AudioEngine> (false);
  12319. auto& host = run->engine->getPluginHost();
  12320. run->report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  12321. std::optional<juce::PluginDescription> clap;
  12322. for (const auto& type : host.getKnownPlugins().getTypes())
  12323. if (type.pluginFormatName == "CLAP" && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  12324. clap = type;
  12325. if (! clap)
  12326. {
  12327. fail (run->report + "no CLAP plugin in the file\n");
  12328. return;
  12329. }
  12330. auto song = lynx::Song::makeDefault();
  12331. lynx::EffectSlot slot;
  12332. slot.kind = lynx::EffectKind::plugin;
  12333. slot.plugin.id = clap->createIdentifierString().toStdString();
  12334. slot.plugin.name = clap->name.toStdString();
  12335. slot.smartDisable = false; // (processed every block, as with music playing: the export itself is silent)
  12336. song.mixer[0].effects = { slot }; // alone on the Master: the delay compensation is the plugin's latency
  12337. run->slot = (int) song.mixer[0].effects.size() - 1;
  12338. run->engine->setSong (song);
  12339. run->engine->renderOffline (0.1, 48000.0); // builds the rack (and the plugin) on the message thread
  12340. if (dynamic_cast<lynx::PluginEffect*> (run->engine->getEffect (0, run->slot).get()) == nullptr)
  12341. {
  12342. fail (run->report + "effect_loaded=no\n");
  12343. return;
  12344. }
  12345. auto effect = std::dynamic_pointer_cast<lynx::PluginEffect> (run->engine->getEffect (0, run->slot));
  12346. run->render = std::thread ([run, effect] () mutable {
  12347. const auto start = juce::Time::getMillisecondCounterHiRes();
  12348. run->engine->renderOffline (30.0, 48000.0);
  12349. run->renderSeconds = (juce::Time::getMillisecondCounterHiRes() - start) * 0.001;
  12350. // issue #46: an export at another rate / block size prepares the plugin from the export's thread; the
  12351. // plugin aborts unless activate / deactivate reach the main thread
  12352. auto& instance = effect->getInstance();
  12353. instance.prepareToPlay (44100.0, 1024);
  12354. instance.releaseResources();
  12355. instance.prepareToPlay (48000.0, 512);
  12356. run->engine->renderOffline (3.0, 44100.0); // (the engine rebuilds its rack at that rate)
  12357. // The engine has replaced this instance (made for 48 kHz) by then, so this is its last reference: it is
  12358. // deleted here, on the export's thread, and its deactivate / destroy go to the message thread, which this
  12359. // waits for. That has to happen before `done`: once the message thread sees it, it blocks in join() until
  12360. // this thread ends, and an instance deleted after that waited 10 s for it and then deactivated the plugin
  12361. // right here, off the main thread (the plugin aborts: about 1 run in 40 under load, round 190au).
  12362. effect.reset();
  12363. run->done = true;
  12364. });
  12365. // after the render: a second for the restarts still queued and the engine's timer (the new PDC plan)
  12366. auto finish = std::make_shared<std::function<void()>>();
  12367. *finish = [this, run, counters, reportPath, fail, finish] {
  12368. if (! run->done)
  12369. {
  12370. juce::Timer::callAfterDelay (50, *finish);
  12371. return;
  12372. }
  12373. run->render.join();
  12374. juce::Timer::callAfterDelay (1000, [this, run, counters, reportPath, fail] {
  12375. auto report = run->report;
  12376. int pluginLatency = -1;
  12377. if (const auto effect = run->engine->getEffect (0, run->slot)) // (not held past the engine's reset)
  12378. pluginLatency = effect->latencySamples();
  12379. const auto pdc = run->engine->getLatencySamples();
  12380. report << "render_seconds=" << juce::String (run->renderSeconds, 2) << "\n"
  12381. << "plugin_latency=" << pluginLatency << "\npdc_total=" << pdc << "\n"
  12382. << "plugin_crashes=" << lynx::pluginCrashCount() << "\n";
  12383. run->engine.reset(); // destroys the plugin: it writes its counters
  12384. // one line per plugin instance (the engine may have made more than one): none may have been
  12385. // deactivated inside process(), and the one that rendered must have restarted
  12386. int overlapped = 0, inactive = 0, requests = 0, activations = 0, lines = 0, wrongThread = 0, misordered = 0, unstopped = 0;
  12387. bool otherRate = false;
  12388. for (const auto& line : juce::StringArray::fromLines (counters.loadFileAsString()))
  12389. {
  12390. juce::StringPairArray values;
  12391. for (const auto& token : juce::StringArray::fromTokens (line, " ", ""))
  12392. if (token.contains ("="))
  12393. values.set (token.upToFirstOccurrenceOf ("=", false, false), token.fromFirstOccurrenceOf ("=", false, false));
  12394. if (values.size() == 0)
  12395. continue;
  12396. ++lines;
  12397. report << "instance: " << line << "\n";
  12398. overlapped += values["overlapped"].getIntValue();
  12399. inactive += values["inactive_blocks"].getIntValue();
  12400. // issue #46: activate / deactivate on the main thread, start / stop_processing on the audio thread
  12401. // (the plugin aborts the process otherwise, as u-he's do), in order, every start stopped
  12402. wrongThread += values["wrong_thread"].getIntValue();
  12403. misordered += values["misordered"].getIntValue();
  12404. unstopped += values["starts"].getIntValue() - values["stops"].getIntValue();
  12405. otherRate = otherRate || values["last_rate"].getIntValue() == 44100;
  12406. if (values["requests"].getIntValue() > requests)
  12407. {
  12408. requests = values["requests"].getIntValue();
  12409. activations = values["activations"].getIntValue();
  12410. }
  12411. }
  12412. report << "wrong_thread=" << wrongThread << "\nmisordered=" << misordered << "\nunstopped=" << unstopped
  12413. << "\nactivated_at_44100=" << (otherRate ? "yes" : "no") << "\n";
  12414. const auto ok = lines > 0 && requests > 0 && activations > requests / 2 && overlapped == 0 && inactive == 0
  12415. && wrongThread == 0 && misordered == 0 && unstopped == 0 && otherRate
  12416. && pluginLatency > 0 && pdc == pluginLatency && lynx::pluginCrashCount() == 0;
  12417. if (! ok)
  12418. {
  12419. fail (report);
  12420. return;
  12421. }
  12422. report << "result=OK\n";
  12423. juce::File (reportPath).replaceWithText (report);
  12424. setApplicationReturnValue (0);
  12425. quit();
  12426. });
  12427. };
  12428. juce::Timer::callAfterDelay (50, *finish);
  12429. }
  12430. // LYNX.exe --vst2test "LYNX Test Synth.dll" report.txt (tools/testplugin/lynx_test_vst2.c): LYNX's own VST2 host.
  12431. // Scans the DLL, imports it the way an .flp holds it (Fruity Wrapper VST2 state with a chunk, REA_rodada89 §2),
  12432. // renders with two saved gains (the level must follow the restored state) and checks the plugin saw the song tempo.
  12433. void runVst2Test (const juce::String& pluginPath, const juce::String& reportPath)
  12434. {
  12435. juce::String report;
  12436. bool ok = false;
  12437. {
  12438. lynx::AudioEngine offline (false);
  12439. auto& host = offline.getPluginHost();
  12440. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  12441. std::optional<juce::PluginDescription> vst2;
  12442. for (const auto& type : host.getKnownPlugins().getTypes())
  12443. if (type.pluginFormatName == "VST")
  12444. vst2 = type;
  12445. auto render = [&] (float gain, float& tempoSeen, int& adopted) {
  12446. lynx::FlVst2State state;
  12447. state.flags = 8;
  12448. state.chunk = { 'L', 'X', 'V', '2', 0, 0, 0, 0 };
  12449. std::memcpy (state.chunk.data() + 4, &gain, 4);
  12450. auto song = lynx::Song::makeDefault();
  12451. song.bpm = 137.0;
  12452. auto& f = song.channels[4].plugin.foreign;
  12453. f.format = lynx::ForeignPlugin::Format::vst2;
  12454. f.vst2Id = (std::uint32_t) vst2->uniqueId;
  12455. f.name = "Some other name"; // found by the VST2 ID
  12456. f.state = lynx::writeFlVst2State (state);
  12457. song.channels[4].volume = 1.0f;
  12458. song.patterns[0].notes.clear();
  12459. song.patterns[0].notes.push_back ({ 0, 4 * lynx::ppq, 4, 69, 1.0f });
  12460. for (std::size_t c = 0; c < song.channels.size(); ++c)
  12461. if (c != 4)
  12462. song.channels[c].muted = true;
  12463. adopted = host.adoptFlPlugins (song);
  12464. offline.setSong (song);
  12465. const auto peak = offline.renderOffline (1.0, 48000.0);
  12466. offline.capturePluginStates();
  12467. juce::MemoryBlock saved;
  12468. saved.fromBase64Encoding (juce::String (offline.getSong().channels[4].plugin.state));
  12469. lynx::FlVst2State back;
  12470. tempoSeen = 0.0f;
  12471. if (lynx::parseFlVst2State (std::vector<std::uint8_t> ((const std::uint8_t*) saved.getData(), (const std::uint8_t*) saved.getData() + saved.getSize()), back)
  12472. && back.chunk.size() >= 12)
  12473. std::memcpy (&tempoSeen, back.chunk.data() + 8, 4);
  12474. return peak;
  12475. };
  12476. if (vst2)
  12477. {
  12478. report << "plugin=" << vst2->name << " id=" << vst2->uniqueId << " instrument=" << (int) vst2->isInstrument << "\n";
  12479. float tempoA = 0, tempoB = 0;
  12480. int adoptedA = 0, adoptedB = 0;
  12481. const auto quiet = render (0.1f, tempoA, adoptedA);
  12482. const auto loud = render (0.4f, tempoB, adoptedB);
  12483. report << "adopted=" << adoptedA << "," << adoptedB << " peak_gain_0.1=" << quiet << " peak_gain_0.4=" << loud
  12484. << " tempo_seen=" << tempoB * 1000.0f << "\n";
  12485. ok = adoptedA == 1 && adoptedB == 1 && quiet > 0.01f && std::abs (loud / quiet - 4.0f) < 0.2f
  12486. && std::abs (tempoB * 1000.0f - 137.0f) < 0.01f;
  12487. }
  12488. }
  12489. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  12490. juce::File (reportPath).replaceWithText (report);
  12491. setApplicationReturnValue (ok ? 0 : 1);
  12492. quit();
  12493. }
  12494. // LYNX --vst3noteidtest "LYNX Test Synth.vst3" report.txt (round 190fg, cmake/LynxPatchJuce.cmake fix 26): the VST3
  12495. // test synth (tools/testplugin/lynx_test_synth_vst3.cpp: voices kept by noteId, its log the ids it got) plays two
  12496. // 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).
  12497. // 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
  12498. // 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).
  12499. void runVst3NoteIdTest (const juce::String& pluginPath, const juce::String& reportPath)
  12500. {
  12501. juce::String report;
  12502. bool ok = false;
  12503. const auto logBase = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-noteid-" + juce::String (juce::Time::currentTimeMillis()));
  12504. // (read by each new instance)
  12505. #if JUCE_WINDOWS
  12506. _putenv_s ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8());
  12507. #else
  12508. setenv ("LYNX_TEST_SYNTH_LOG", logBase.getFullPathName().toRawUTF8(), 1);
  12509. #endif
  12510. struct E
  12511. {
  12512. bool on = false;
  12513. int key = 0, id = -1;
  12514. };
  12515. // (the lines each render added: a running instance keeps its log file open, so the files stay until the end)
  12516. std::map<juce::String, int> linesRead;
  12517. const auto readLog = [&logBase, &linesRead] {
  12518. std::vector<E> events;
  12519. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  12520. {
  12521. juce::StringArray lines;
  12522. f.readLines (lines);
  12523. auto& done = linesRead[f.getFullPathName()];
  12524. for (int i = done; i < lines.size(); ++i)
  12525. {
  12526. const auto p = juce::StringArray::fromTokens (lines[i], " ", {});
  12527. if (p.size() >= 5 && p[0].startsWith ("E"))
  12528. events.push_back ({ p[1] == "on", p[2].getIntValue(), p[4].getIntValue() });
  12529. }
  12530. done = lines.size() - (lines.isEmpty() || lines[lines.size() - 1].isNotEmpty() ? 0 : 1);
  12531. }
  12532. return events;
  12533. };
  12534. {
  12535. lynx::AudioEngine offline (false);
  12536. auto& host = offline.getPluginHost();
  12537. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  12538. std::optional<juce::PluginDescription> vst3;
  12539. for (const auto& type : host.getKnownPlugins().getTypes())
  12540. if (type.pluginFormatName == "VST3" && type.isInstrument)
  12541. vst3 = type;
  12542. const auto render = [&] (bool tags) {
  12543. auto song = lynx::Song::makeDefault();
  12544. song.bpm = 120.0;
  12545. auto& c = song.channels[0];
  12546. c.instrument = lynx::InstrumentKind::plugin;
  12547. c.plugin.id = vst3->createIdentifierString().toStdString();
  12548. c.plugin.name = vst3->name.toStdString();
  12549. for (std::size_t k = 1; k < song.channels.size(); ++k)
  12550. song.channels[k].muted = true;
  12551. auto& notes = song.patterns[0].notes;
  12552. notes.clear();
  12553. const auto beat = (std::int64_t) lynx::ppq;
  12554. notes.push_back ({ 0, 4 * beat, 0, 60, 0.8f }); // A
  12555. notes.push_back ({ 2 * beat, 4 * beat, 0, 60, 0.8f }); // B
  12556. notes.push_back ({ 8 * beat, 6 * beat, 0, 64, 0.8f }); // C
  12557. notes.push_back ({ 10 * beat, 2 * beat, 0, 64, 0.8f }); // D (inside C)
  12558. song.patterns[0].sortNotes();
  12559. song.patterns[0].lengthTicks = 16 * beat;
  12560. offline.setSong (song);
  12561. offline.dispatchPendingMessages();
  12562. if (! tags)
  12563. juce::lynxNoteTagHook = nullptr; // (fix 14 alone: the oldest sounding id; the next instance sets it again)
  12564. offline.renderOffline (7.9, 48000.0); // (C ends at 7 s; the 8 s pattern does not loop yet)
  12565. return readLog();
  12566. };
  12567. const auto check = [&report] (const char* name, const std::vector<E>& events, bool expectOwn) {
  12568. // ons and offs of each key in the order the plugin got them
  12569. std::map<int, std::vector<int>> ons, offs;
  12570. for (const auto& e : events)
  12571. (e.on ? ons : offs)[e.key].push_back (e.id);
  12572. const auto& a = ons[60]; const auto& o60 = offs[60];
  12573. const auto& c = ons[64]; const auto& o64 = offs[64];
  12574. report << name << ": key 60 ons";
  12575. for (auto id : a) report << " " << id;
  12576. report << " offs";
  12577. for (auto id : o60) report << " " << id;
  12578. report << "; key 64 ons";
  12579. for (auto id : c) report << " " << id;
  12580. report << " offs";
  12581. for (auto id : o64) report << " " << id;
  12582. report << "\n";
  12583. if (a.size() != 2 || o60.size() != 2 || c.size() != 2 || o64.size() != 2 || a[0] < 0 || c[0] < 0)
  12584. return false;
  12585. const auto fifo = o60[0] == a[0] && o60[1] == a[1]; // A ends first: A's id either way
  12586. // LIFO: D (c[1]) ends first; its own id with the tags, C's (the oldest) without
  12587. const auto lifo = expectOwn ? (o64[0] == c[1] && o64[1] == c[0]) : (o64[0] == c[0] && o64[1] == c[1]);
  12588. return fifo && lifo;
  12589. };
  12590. if (vst3)
  12591. {
  12592. report << "plugin=" << vst3->name << "\n";
  12593. const auto withTags = render (true);
  12594. const auto okTags = check ("with_tags", withTags, true);
  12595. const auto withoutTags = render (false);
  12596. const auto okBefore = check ("fix14_only", withoutTags, false);
  12597. report << "own_ids=" << (okTags ? "yes" : "NO") << " fix14_only_oldest=" << (okBefore ? "yes" : "NO") << "\n";
  12598. ok = okTags && okBefore;
  12599. }
  12600. }
  12601. if (ok) // (a failure leaves the logs for a look: their path is in the report)
  12602. for (const auto& f : logBase.getParentDirectory().findChildFiles (juce::File::findFiles, false, logBase.getFileName() + ".*"))
  12603. f.deleteFile();
  12604. else
  12605. report << "synth_logs=" << logBase.getFullPathName() << ".*\n";
  12606. #if JUCE_WINDOWS
  12607. _putenv_s ("LYNX_TEST_SYNTH_LOG", "");
  12608. #else
  12609. unsetenv ("LYNX_TEST_SYNTH_LOG");
  12610. #endif
  12611. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  12612. juce::File (reportPath).replaceWithText (report);
  12613. setApplicationReturnValue (ok ? 0 : 1);
  12614. quit();
  12615. }
  12616. // Round 181c: a wrapper MIDI option changed on a running plugin must act like the same option on a new one. For each
  12617. // option: a control engine whose plugin is created with the option set (proves the test can see it), then an engine
  12618. // whose plugin is already running when the option changes through editSong, as the wrapper page does it. What the
  12619. // plugin received comes from the test plugin's own log. The running instance must also stay the same one.
  12620. void runWrapperMidiTest (const juce::String& pluginPath, const juce::String& reportPath)
  12621. {
  12622. juce::String report;
  12623. auto ok = true;
  12624. const juce::File logFile (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_VST2_MIDILOG", {}));
  12625. struct Event { juce::String instance; int status, data1, data2; };
  12626. auto take = [&] {
  12627. std::vector<Event> out;
  12628. juce::StringArray lines;
  12629. logFile.readLines (lines);
  12630. for (const auto& line : lines)
  12631. {
  12632. const auto p = juce::StringArray::fromTokens (line, " ", {});
  12633. if (p.size() == 4)
  12634. out.push_back ({ p[0], p[1].getIntValue(), p[2].getIntValue(), p[3].getIntValue() });
  12635. }
  12636. logFile.deleteFile();
  12637. return out;
  12638. };
  12639. auto count = [] (const std::vector<Event>& events, int status, int data1, int data2) {
  12640. int n = 0;
  12641. for (const auto& e : events)
  12642. n += (e.status & 0xF0) == status && (data1 < 0 || e.data1 == data1) && (data2 < 0 || e.data2 == data2) ? 1 : 0;
  12643. return n;
  12644. };
  12645. struct Option
  12646. {
  12647. const char* name;
  12648. std::function<void (lynx::PluginRef&)> before, change;
  12649. std::function<juce::String (const std::vector<Event>&)> seen;
  12650. };
  12651. const Option options[] = {
  12652. { "Send note release velocity off", {}, [] (lynx::PluginRef& r) { r.releaseVelocity = false; },
  12653. [&] (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)); } },
  12654. { "Send pitch bend range on", {}, [] (lynx::PluginRef& r) { r.sendBendRange = true; },
  12655. [&] (const std::vector<Event>& e) { return "rpn_range_12=" + juce::String (count (e, 0xB0, 6, 12)); } },
  12656. { "Pitch bend range 24", [] (lynx::PluginRef& r) { r.sendBendRange = true; }, [] (lynx::PluginRef& r) { r.bendRange = 24; },
  12657. [&] (const std::vector<Event>& e) { return "rpn_range_24=" + juce::String (count (e, 0xB0, 6, 24)); } },
  12658. { "Send MOD X as polyphonic aftertouch on", {}, [] (lynx::PluginRef& r) { r.modXAftertouch = true; },
  12659. [&] (const std::vector<Event>& e) { return "aftertouch=" + juce::String (count (e, 0xA0, 69, -1)); } },
  12660. { "Send All Notes Off when playback stops off", {}, [] (lynx::PluginRef& r) { r.allNotesOffOnStop = false; },
  12661. [&] (const std::vector<Event>& e) { return "cc123=" + juce::String (count (e, 0xB0, 123, -1)); } },
  12662. };
  12663. // each phase has its own engine: an engine keeps the running instance across setSong, so one engine would
  12664. // carry the control's plugin into the "before" phase
  12665. lynx::AudioEngine scanner (false);
  12666. auto& host = scanner.getPluginHost();
  12667. report << "plugins_in_file=" << host.addPluginFile (juce::File (pluginPath)) << "\n";
  12668. std::optional<juce::PluginDescription> vst2;
  12669. for (const auto& type : host.getKnownPlugins().getTypes())
  12670. if (type.pluginFormatName == "VST")
  12671. vst2 = type;
  12672. if (! vst2 || logFile.getFullPathName().isEmpty())
  12673. ok = false;
  12674. else
  12675. for (const auto& option : options)
  12676. {
  12677. auto makeSong = [&] (bool changed) {
  12678. auto song = lynx::Song::makeDefault();
  12679. auto& channel = song.channels[0];
  12680. channel.instrument = lynx::InstrumentKind::plugin;
  12681. channel.plugin = {};
  12682. channel.plugin.id = vst2->createIdentifierString().toStdString();
  12683. channel.plugin.name = vst2->name.toStdString();
  12684. if (option.before)
  12685. option.before (channel.plugin);
  12686. if (changed)
  12687. option.change (channel.plugin);
  12688. song.patterns[0].notes.clear();
  12689. lynx::Note note;
  12690. note.start = 0;
  12691. note.length = lynx::ppq;
  12692. note.channel = 0;
  12693. note.key = 69;
  12694. note.velocity = 1.0f;
  12695. note.release = 0.25f; // 32 of 127
  12696. note.modX = 0.75f;
  12697. song.patterns[0].notes.push_back (note);
  12698. for (std::size_t c = 1; c < song.channels.size(); ++c)
  12699. song.channels[c].muted = true;
  12700. return song;
  12701. };
  12702. // a block of the song, then a note held across "playback stopped", as the options act on either
  12703. auto play = [&] (lynx::AudioEngine& engine) {
  12704. logFile.deleteFile();
  12705. engine.renderOffline (1.0, 48000.0);
  12706. if (auto instrument = engine.getChannelInstrument (0))
  12707. {
  12708. instrument->noteOn (60, 1.0f);
  12709. instrument->transportStopped();
  12710. }
  12711. engine.renderOffline (0.1, 48000.0);
  12712. return take();
  12713. };
  12714. auto newEngine = [&] {
  12715. auto engine = std::make_unique<lynx::AudioEngine> (false);
  12716. engine->getPluginHost().addPluginFile (juce::File (pluginPath));
  12717. return engine;
  12718. };
  12719. std::vector<Event> control;
  12720. {
  12721. auto engine = newEngine();
  12722. engine->setSong (makeSong (true));
  12723. control = play (*engine);
  12724. }
  12725. auto engine = newEngine();
  12726. engine->setSong (makeSong (false));
  12727. const auto before = play (*engine);
  12728. const auto instrumentBefore = engine->getChannelInstrument (0).get();
  12729. engine->capturePluginStates(); // as the wrapper page does
  12730. engine->editSong ([&] (lynx::Song& song) { option.change (song.channels[0].plugin); });
  12731. const auto after = play (*engine);
  12732. const auto sameInstance = engine->getChannelInstrument (0).get() == instrumentBefore;
  12733. // the counts differ between phases (how many blocks the note spans, how many instances the phase made):
  12734. // what matters is whether each kind of event is there at all
  12735. auto shape = [] (const juce::String& seen) {
  12736. juce::String out;
  12737. for (const auto& token : juce::StringArray::fromTokens (seen, " ", {}))
  12738. out << token.upToFirstOccurrenceOf ("=", false, false) << (token.fromFirstOccurrenceOf ("=", false, false).getIntValue() > 0 ? "=yes " : "=no ");
  12739. return out;
  12740. };
  12741. auto instances = [] (const std::vector<Event>& events) {
  12742. std::set<juce::String> made;
  12743. for (const auto& e : events)
  12744. made.insert (e.instance);
  12745. return (int) made.size();
  12746. };
  12747. const auto a = option.seen (control) + " instances=" + juce::String (instances (control)),
  12748. b = option.seen (before) + " instances=" + juce::String (instances (before)),
  12749. c = option.seen (after) + " instances=" + juce::String (instances (after));
  12750. const auto visible = shape (option.seen (control)) != shape (option.seen (before));
  12751. const auto works = shape (option.seen (after)) == shape (option.seen (control));
  12752. report << option.name << ": control " << a << " | before " << b << " | after the change " << c << " | same_instance=" << (int) sameInstance
  12753. << " | test_sees_the_option=" << (int) visible << " | " << (! visible ? "NOT PROVEN" : works ? "acts on the plugin" : "DEAD until re-created") << "\n";
  12754. ok = ok && visible && works;
  12755. }
  12756. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  12757. juce::File (reportPath).replaceWithText (report);
  12758. setApplicationReturnValue (ok ? 0 : 1);
  12759. quit();
  12760. }
  12761. // LYNX.exe --wrappershot "LYNX Test Drums.dll" <folder> (round 188d): the wrapper's Processing tab drawn offscreen
  12762. // (no window, no focus) for the FL | LYNX review: wrap-default.png (a fresh plugin), wrap-automap.png (Auto map
  12763. // outputs, output 3 off: FL's shot b23), wrap-settings.png. Scale 1.5 (FL's shots are at 150 %).
  12764. // (round 190oh, --wrappershot190oh: the steps run from a timer, so the editors' windows get their messages)
  12765. struct WrapperShot190oh final : juce::Timer
  12766. {
  12767. std::function<bool()> step; // false: done
  12768. void timerCallback() override
  12769. {
  12770. if (! step())
  12771. stopTimer();
  12772. }
  12773. };
  12774. std::unique_ptr<WrapperShot190oh> wrapperShot190oh;
  12775. void runWrapperShot190oh (const juce::String& pluginPath, const juce::String& folderPath, bool openEditors)
  12776. {
  12777. struct State
  12778. {
  12779. juce::File folder;
  12780. juce::String report;
  12781. bool ok = true;
  12782. std::shared_ptr<lynx::AudioEngine> engine;
  12783. std::optional<juce::PluginDescription> type;
  12784. int phase = 0, wait = 0;
  12785. void expect (const char* name, bool value)
  12786. {
  12787. report << name << "=" << (value ? 1 : 0) << "\n";
  12788. ok = ok && value;
  12789. }
  12790. static lynx::PluginRef* find (lynx::Song& s)
  12791. {
  12792. return s.mixer.size() < 2 || s.mixer[1].effects.empty() ? nullptr : &s.mixer[1].effects[0].plugin;
  12793. }
  12794. std::shared_ptr<lynx::PluginEffect> effect() { return std::dynamic_pointer_cast<lynx::PluginEffect> (engine->getEffect (1, 0)); }
  12795. bool save (const juce::String& name, float scale)
  12796. {
  12797. auto fx = effect();
  12798. if (fx == nullptr)
  12799. return false;
  12800. const auto image = lynx::wrapperSettingsSnapshot (*engine, &State::find, fx->getInstance(), false, 0, scale, 1, 0);
  12801. auto file = folder.getChildFile (name);
  12802. file.deleteFile();
  12803. juce::FileOutputStream out (file);
  12804. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  12805. }
  12806. void open()
  12807. {
  12808. if (auto fx = effect())
  12809. {
  12810. lynx::PluginWindows::WrapperContext context;
  12811. context.engine = engine.get();
  12812. context.find = &State::find;
  12813. context.track = 1;
  12814. context.slot = 0;
  12815. lynx::PluginWindows::open (fx, fx->getInstance(), type->name, context);
  12816. }
  12817. }
  12818. // what the open editor was marked with and (Windows) the DPI awareness of its window and of the windows
  12819. // inside it (the plugin's own)
  12820. void describe (const char* tag)
  12821. {
  12822. auto fx = effect();
  12823. if (fx == nullptr)
  12824. return;
  12825. auto& instance = fx->getInstance();
  12826. auto* editor = instance.getActiveEditor();
  12827. report << tag << ".editor=" << (editor != nullptr ? 1 : 0);
  12828. if (editor != nullptr)
  12829. report << " size=" << editor->getWidth() << "x" << editor->getHeight()
  12830. << " unaware_mark=" << (int) (bool) editor->getProperties()["lynxDpiUnaware"]
  12831. << " dims_mark=" << (int) (bool) editor->getProperties()["lynxScaleEditorDimensions"];
  12832. report << " docked=" << (int) lynx::PluginWindows::isDocked (instance);
  12833. int windows = 0;
  12834. if (const auto unaware = lynx::platform::dpiUnawareWindowCount (lynx::PluginWindows::hostWindowHandle (instance), windows); unaware >= 0)
  12835. {
  12836. report << " windows=" << windows << " unaware_windows=" << unaware;
  12837. expect ((juce::String (tag) + "_unaware_as_set").toRawUTF8(),
  12838. juce::String (tag) == "default" ? unaware == 0 : (windows > 0 && unaware == windows));
  12839. }
  12840. report << "\n";
  12841. lynx::PluginWindows::close (instance);
  12842. }
  12843. void change()
  12844. {
  12845. engine->editSong ([] (lynx::Song& s) {
  12846. s.mixer[1].effects[0].plugin.dpiAware = false;
  12847. s.mixer[1].effects[0].plugin.scaleEditorDimensions = true;
  12848. });
  12849. engine->renderOffline (0.05, 48000.0); // ("DPI aware" reloads the plugin)
  12850. }
  12851. };
  12852. auto st = std::make_shared<State>();
  12853. st->folder = juce::File (folderPath);
  12854. st->folder.createDirectory();
  12855. st->engine = std::make_shared<lynx::AudioEngine> (false);
  12856. st->engine->getPluginHost().addPluginFile (juce::File (pluginPath));
  12857. for (const auto& t : st->engine->getPluginHost().getKnownPlugins().getTypes())
  12858. if (! st->type && (juce::File (t.fileOrIdentifier) == juce::File (pluginPath) || juce::File (pluginPath).isAChildOf (juce::File (t.fileOrIdentifier))
  12859. || juce::File (t.fileOrIdentifier).isAChildOf (juce::File (pluginPath))))
  12860. st->type = t;
  12861. st->expect ("plugin_found", st->type.has_value());
  12862. if (st->type)
  12863. {
  12864. st->report << "plugin=" << st->type->name << " (" << st->type->pluginFormatName << ")\n";
  12865. auto song = lynx::Song::makeDefault();
  12866. auto slot = lynx::makeEffectSlot (lynx::EffectKind::plugin);
  12867. slot.plugin.id = st->type->createIdentifierString().toStdString();
  12868. slot.plugin.name = st->type->name.toStdString();
  12869. song.mixer[1].effects = { slot };
  12870. st->engine->setSong (song);
  12871. st->engine->renderOffline (0.05, 48000.0);
  12872. const auto* ref = State::find (const_cast<lynx::Song&> (st->engine->getSong()));
  12873. st->expect ("fl_defaults", ref != nullptr && ref->dpiAware && ! ref->scaleEditorDimensions);
  12874. st->expect ("shot_default_100", st->save ("gui-default.png", 1.0f));
  12875. st->expect ("shot_default_150", st->save ("gui-default@150.png", 1.5f));
  12876. }
  12877. auto finish = [this, st] {
  12878. st->folder.getChildFile ("report.txt").replaceWithText (st->report + "result=" + (st->ok ? "OK" : "FAIL") + "\n");
  12879. st->engine.reset();
  12880. setApplicationReturnValue (st->ok ? 0 : 1);
  12881. quit();
  12882. };
  12883. if (! st->type || ! openEditors)
  12884. {
  12885. if (st->type)
  12886. {
  12887. st->change();
  12888. st->expect ("shot_changed_100", st->save ("gui-changed.png", 1.0f));
  12889. st->expect ("shot_changed_150", st->save ("gui-changed@150.png", 1.5f));
  12890. }
  12891. finish();
  12892. return;
  12893. }
  12894. // with --open: open the editor (default settings), look after 1 s, close; change; open again, look, close
  12895. wrapperShot190oh = std::make_unique<WrapperShot190oh>();
  12896. wrapperShot190oh->step = [st, finish] {
  12897. if (st->wait-- > 0)
  12898. return true;
  12899. switch (st->phase++)
  12900. {
  12901. case 0: st->open(); st->wait = 10; return true;
  12902. case 1: st->describe ("default"); st->wait = 3; return true;
  12903. case 2:
  12904. st->change();
  12905. st->expect ("shot_changed_100", st->save ("gui-changed.png", 1.0f));
  12906. st->expect ("shot_changed_150", st->save ("gui-changed@150.png", 1.5f));
  12907. st->open();
  12908. st->wait = 10;
  12909. return true;
  12910. case 3: st->describe ("changed"); st->wait = 3; return true;
  12911. default: finish(); return false;
  12912. }
  12913. };
  12914. wrapperShot190oh->startTimer (100);
  12915. }
  12916. void runWrapperShot (const juce::String& pluginPath, const juce::String& folderPath)
  12917. {
  12918. const juce::File folder (folderPath);
  12919. folder.createDirectory();
  12920. auto ok = false;
  12921. lynx::AudioEngine engine (false);
  12922. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  12923. std::optional<juce::PluginDescription> vst2;
  12924. for (const auto& type : engine.getPluginHost().getKnownPlugins().getTypes())
  12925. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  12926. vst2 = type; // (the profile may know other test plugins)
  12927. if (vst2 && ! vst2->isInstrument)
  12928. {
  12929. // an effect (round 188d): on insert 1, with insert 2 routed there as a sidechain (FL's k65 / k78 shots):
  12930. // wrap-fx-default.png, wrap-fx-automap.png (Auto map inputs and outputs)
  12931. auto song = lynx::Song::makeDefault();
  12932. if (song.mixer.size() < 4)
  12933. song.mixer.resize (4);
  12934. auto slot = lynx::makeEffectSlot (lynx::EffectKind::plugin);
  12935. slot.plugin.id = vst2->createIdentifierString().toStdString();
  12936. slot.plugin.name = vst2->name.toStdString();
  12937. song.mixer[1].effects = { slot };
  12938. lynx::mixerops::sidechainTo (song, 2, 1);
  12939. engine.setSong (song);
  12940. engine.renderOffline (0.05, 48000.0);
  12941. if (auto fx = std::dynamic_pointer_cast<lynx::PluginEffect> (engine.getEffect (1, 0)))
  12942. {
  12943. auto find = [] (lynx::Song& s) -> lynx::PluginRef* {
  12944. return s.mixer.size() < 2 || s.mixer[1].effects.empty() ? nullptr : &s.mixer[1].effects[0].plugin;
  12945. };
  12946. auto save = [&] (const char* name) {
  12947. const auto image = lynx::wrapperSettingsSnapshot (engine, find, fx->getInstance(), false, 1, 1.5f, 1, 0);
  12948. juce::FileOutputStream out (folder.getChildFile (name));
  12949. out.setPosition (0);
  12950. out.truncate();
  12951. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  12952. };
  12953. ok = save ("wrap-fx-default.png");
  12954. engine.editSong ([] (lynx::Song& s) {
  12955. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.inputs, 2);
  12956. lynx::autoMapOutputs (s.mixer[1].effects[0].plugin.outputs, 2);
  12957. s.mixer[1].effects[0].sidechain = lynx::mixerops::sidechainIndexSource (s, 1, 1);
  12958. });
  12959. ok = ok && save ("wrap-fx-automap.png") && engine.getSong().mixer[1].effects[0].sidechain == 2;
  12960. }
  12961. }
  12962. else if (vst2)
  12963. {
  12964. auto song = lynx::Song::makeDefault();
  12965. auto& channel = song.channels[0];
  12966. channel.instrument = lynx::InstrumentKind::plugin;
  12967. channel.plugin = {};
  12968. channel.plugin.id = vst2->createIdentifierString().toStdString();
  12969. channel.plugin.name = vst2->name.toStdString();
  12970. channel.mixerTrack = 5;
  12971. engine.setSong (song);
  12972. engine.renderOffline (0.05, 48000.0); // (the plugin is hosted by then)
  12973. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  12974. {
  12975. auto find = [] (lynx::Song& s) -> lynx::PluginRef* { return s.channels.empty() ? nullptr : &s.channels[0].plugin; };
  12976. auto save = [&] (const char* name, int tab) {
  12977. const auto image = lynx::wrapperSettingsSnapshot (engine, find, instrument->getInstance(), true, tab, 1.5f);
  12978. juce::FileOutputStream out (folder.getChildFile (name));
  12979. out.setPosition (0);
  12980. out.truncate();
  12981. return out.openedOk() && juce::PNGImageFormat().writeImageToStream (image, out);
  12982. };
  12983. ok = save ("wrap-default.png", 1) && save ("wrap-settings.png", 0);
  12984. engine.editSong ([] (lynx::Song& s) {
  12985. lynx::autoMapOutputs (s.channels[0].plugin.outputs, 8);
  12986. s.channels[0].plugin.outputs.resize (8);
  12987. s.channels[0].plugin.outputs[2].active = 0;
  12988. s.channels[0].plugin.processInactive = false; // (as an LED click does, FL's b23)
  12989. });
  12990. ok = ok && save ("wrap-automap.png", 1);
  12991. }
  12992. }
  12993. setApplicationReturnValue (ok ? 0 : 1);
  12994. quit();
  12995. }
  12996. // LYNX.exe --multiouttest "LYNX Test Drums.dll" report.txt (round 188d, issue #114): a multi-output VST2
  12997. // (tools/testplugin/lynx_test_drums_vst2.c: key 36 = output 1 at 110 Hz, key 37 = output 2 at 220 Hz) on a
  12998. // channel routed to insert 1; the wrapper's Processing › Connections as FL plays them [EXEC fl188d]: every output
  12999. // on the channel's insert by default, an offset to another insert, an inactive output silent, the channel's
  13000. // volume on all of them. Measured on the master with insert 1 muted or not.
  13001. void runMultiOutTest (const juce::String& pluginPath, const juce::String& reportPath)
  13002. {
  13003. juce::String report;
  13004. auto ok = true;
  13005. lynx::AudioEngine scanner (false);
  13006. report << "plugins_in_file=" << scanner.getPluginHost().addPluginFile (juce::File (pluginPath)) << "\n";
  13007. std::optional<juce::PluginDescription> vst2;
  13008. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  13009. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == juce::File (pluginPath))
  13010. vst2 = type; // (the profile may know other test plugins)
  13011. struct Case
  13012. {
  13013. const char* name;
  13014. std::vector<lynx::PluginOutputRoute> routes;
  13015. bool muteInsert1;
  13016. float volume;
  13017. bool kick, snare; // expected on the master
  13018. };
  13019. const Case cases[] = {
  13020. { "defaults", {}, false, -1.0f, true, true },
  13021. { "defaults, insert 1 muted", {}, true, -1.0f, false, false },
  13022. { "auto map, insert 1 muted", { { 0, 1 }, { 1, 1 } }, true, -1.0f, false, true },
  13023. { "auto map", { { 0, 1 }, { 1, 1 } }, false, -1.0f, true, true },
  13024. { "output 2 inactive", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, false },
  13025. { "output 1 inactive", { { 0, 0 } }, false, -1.0f, false, true },
  13026. { "auto map, channel volume 0", { { 0, 1 }, { 1, 1 } }, false, 0.0f, false, false },
  13027. { "output 2 inactive, Process inactive inputs and outputs on", { { 0, 1 }, { 1, 0 } }, false, -1.0f, true, true },
  13028. };
  13029. auto tone = [] (const std::vector<float>& x, double hz) {
  13030. // Goertzel magnitude over the buffer (normalised to a sine's amplitude)
  13031. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 48000.0;
  13032. double s1 = 0.0, s2 = 0.0;
  13033. for (const auto v : x)
  13034. {
  13035. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  13036. s2 = s1;
  13037. s1 = s0;
  13038. }
  13039. 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());
  13040. };
  13041. if (! vst2)
  13042. ok = false;
  13043. else
  13044. for (const auto& c : cases)
  13045. {
  13046. lynx::AudioEngine engine (false);
  13047. engine.getPluginHost().addPluginFile (juce::File (pluginPath));
  13048. auto song = lynx::Song::makeDefault();
  13049. auto& channel = song.channels[0];
  13050. channel.instrument = lynx::InstrumentKind::plugin;
  13051. channel.plugin = {};
  13052. channel.plugin.id = vst2->createIdentifierString().toStdString();
  13053. channel.plugin.name = vst2->name.toStdString();
  13054. channel.plugin.outputs = c.routes;
  13055. // (FL's "Process inactive inputs and outputs" plays an inactive output: off but for the case named so)
  13056. channel.plugin.processInactive = juce::String (c.name).contains ("Process inactive");
  13057. channel.mixerTrack = 1;
  13058. if (c.volume >= 0.0f)
  13059. channel.volume = c.volume;
  13060. for (std::size_t k = 1; k < song.channels.size(); ++k)
  13061. song.channels[k].muted = true;
  13062. if (song.mixer.size() < 4)
  13063. song.mixer.resize (4);
  13064. song.mixer[1].muted = c.muteInsert1;
  13065. song.patterns[0].notes.clear();
  13066. for (const auto key : { 36, 37 })
  13067. {
  13068. lynx::Note note;
  13069. note.start = 0;
  13070. note.length = lynx::ppq;
  13071. note.channel = 0;
  13072. note.key = key;
  13073. note.velocity = 1.0f;
  13074. song.patterns[0].notes.push_back (note);
  13075. }
  13076. engine.setSong (song);
  13077. std::vector<float> master;
  13078. lynx::AudioEngine::RenderOptions options;
  13079. options.seconds = 0.25;
  13080. options.sampleRate = 48000.0;
  13081. options.capture = [&master] (const float* l, const float*, int n) { master.insert (master.end(), l, l + n); };
  13082. engine.renderOffline (options);
  13083. const auto kick = tone (master, 110.0), snare = tone (master, 220.0);
  13084. const auto pass = (kick > 0.01) == c.kick && (snare > 0.01) == c.snare;
  13085. report << c.name << ": kick_110Hz=" << juce::String (kick, 4) << " snare_220Hz=" << juce::String (snare, 4) << " expected kick="
  13086. << (int) c.kick << " snare=" << (int) c.snare << (pass ? " OK" : " FAILED") << "\n";
  13087. ok = ok && pass;
  13088. if (auto instrument = std::dynamic_pointer_cast<lynx::PluginInstrument> (engine.getChannelInstrument (0)))
  13089. if (&c == &cases[0])
  13090. {
  13091. report << "outputs=" << (int) instrument->outputs().size();
  13092. for (const auto& o : instrument->outputs())
  13093. report << " [" << o.name << " ch" << o.channel << "x" << o.channels << "]";
  13094. report << "\n";
  13095. ok = ok && instrument->outputs().size() == 8 && instrument->outputs()[1].name == "Snare";
  13096. }
  13097. }
  13098. // round 189j: "LYNX Test SC.dll" next to it (tools/testplugin/lynx_test_sc_vst2.c) as an effect on insert 1
  13099. const auto sc = juce::File (pluginPath).getSiblingFile ("LYNX Test SC.dll");
  13100. if (sc.existsAsFile())
  13101. ok = runEffectConnectionsTest (sc, report) && ok;
  13102. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  13103. juce::File (reportPath).replaceWithText (report);
  13104. setApplicationReturnValue (ok ? 0 : 1);
  13105. quit();
  13106. }
  13107. // Round 189j: a hosted effect's Processing › Connections against FL 2026's own renders of the same projects
  13108. // [EXEC fxconn189j: FL /R renders of LYNX's .flp exports, docs/analise/REA_rodada189j.md]. Insert 1: a 440 Hz
  13109. // sampler and "LYNX Test SC" (output 1 = input 1, output 2 = input 2); inserts 2 (1000 Hz) and 3 (1500 Hz) routed
  13110. // to insert 1 at level 0 only; insert 4 a 2500 Hz reference on the Master; insert 1 routed to the Master and at
  13111. // level 0 to inserts 5 (panned left) and 6 (right). Each tone's level per side, in dB from the reference's, must be
  13112. // FL's within 0.5 dB (absent: 50 dB under it).
  13113. bool runEffectConnectionsTest (const juce::File& scFile, juce::String& report)
  13114. {
  13115. lynx::AudioEngine scanner (false);
  13116. scanner.getPluginHost().addPluginFile (scFile);
  13117. std::optional<juce::PluginDescription> sc;
  13118. for (const auto& type : scanner.getPluginHost().getKnownPlugins().getTypes())
  13119. if (type.pluginFormatName == "VST" && juce::File (type.fileOrIdentifier) == scFile)
  13120. sc = type;
  13121. report << "effect_plugin=" << (sc ? sc->name : juce::String ("not found")) << "\n";
  13122. if (! sc)
  13123. return false;
  13124. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-fxconn189j");
  13125. dir.createDirectory();
  13126. const double tones[] = { 440.0, 1000.0, 1500.0, 2500.0 };
  13127. for (const auto hz : tones)
  13128. {
  13129. const auto wav = dir.getChildFile ("sine" + juce::String ((int) hz) + ".wav");
  13130. if (wav.existsAsFile())
  13131. continue;
  13132. juce::AudioBuffer<float> sine (1, 44100 * 3);
  13133. for (int i = 0; i < sine.getNumSamples(); ++i)
  13134. sine.setSample (0, i, 0.25f * (float) std::sin (2.0 * juce::MathConstants<double>::pi * hz * i / 44100.0));
  13135. juce::WavAudioFormat format;
  13136. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  13137. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  13138. {
  13139. out.release();
  13140. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  13141. writer->writeFromAudioSampleBuffer (sine, 0, sine.getNumSamples());
  13142. }
  13143. }
  13144. using Route = lynx::PluginOutputRoute;
  13145. constexpr float none = -999.0f;
  13146. struct Case
  13147. {
  13148. const char* name;
  13149. std::vector<Route> inputs, outputs;
  13150. int tweak; // 1 no Master route, 2 insert 1 fader at 0.4, 3 Process inactive off, 4 Master route level 0, 5 route
  13151. // to 7 too, 6 insert 2 fader at 0.4, 7 insert 2 muted, 8 insert 2 panned left
  13152. float level[3][2]; // 440 / 1000 / 1500 Hz, left / right: dB from the reference, FL's
  13153. };
  13154. const Route d { 0, 1 };
  13155. const Case cases[] = {
  13156. { "e00 FL defaults", { d, d }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  13157. { "e01 input 1 at 1", { { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  13158. { "e02 input 1 at 2", { { 2, 1 } }, {}, 0, { { 0, 0 }, { none, none }, { 0, 0 } } },
  13159. { "e03 input 2 at 1", { d, { 1, 1 } }, {}, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  13160. { "e04 output 2 at 1 (Master)", { d, { 1, 1 } }, { d, { 1, 1 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  13161. { "e05 output 2 at 2 (insert 5)", { d, { 1, 1 } }, { d, { 2, 1 } }, 0, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  13162. { "e06 output 1 at 1", {}, { { 1, 1 } }, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  13163. { "e07 output 2 at 5 (past the list)", { d, { 1, 1 } }, { d, { 5, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  13164. { "e08 inputs 1 and 2 at 1", { { 1, 1 }, { 1, 1 } }, {}, 0, { { none, none }, { 6.1f, 6.1f }, { none, none } } },
  13165. { "e09 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 0, { { 0, 0 }, { 0, 0 }, { none, none } } },
  13166. { "e10 input 1 at 5 (past the list)", { { 5, 1 } }, {}, 0, { { 6.1f, 6.1f }, { none, none }, { none, none } } },
  13167. { "e11 output 2 at 3 (insert 6)", { d, { 1, 1 } }, { d, { 3, 1 } }, 0, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  13168. { "e13 no Master route, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 1, { { none, none }, { 3.0f, none }, { none, none } } },
  13169. { "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 } } },
  13170. { "e15 input 2 inactive", { d, { 1, 0 } }, { d, d }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  13171. { "e16 output 2 inactive", { d, { 1, 1 } }, { d, { 0, 0 } }, 3, { { 0, 0 }, { none, none }, { none, none } } },
  13172. { "e18 route to 7 too, output 2 at 3", { d, { 1, 1 } }, { d, { 3, 1 } }, 5, { { 0, 0 }, { none, 3.0f }, { none, none } } },
  13173. { "e19 Master route at 0, output 2 at 1", { d, { 1, 1 } }, { d, { 1, 1 } }, 4, { { none, none }, { 0, 0 }, { none, none } } },
  13174. { "e22 input 1 at 1 inactive", { { 1, 0 } }, {}, 3, { { 0, 0 }, { none, none }, { none, none } } },
  13175. { "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 } } },
  13176. { "e24 input 1 at 1, insert 2 fader 0.4", { { 1, 1 } }, {}, 6, { { 0, 0 }, { -12.7f, -12.7f }, { none, none } } },
  13177. { "e25 input 1 at 1, insert 2 muted", { { 1, 1 } }, {}, 7, { { 0, 0 }, { none, none }, { none, none } } },
  13178. { "e26 input 1 at 1, insert 2 panned left", { { 1, 1 } }, {}, 8, { { 0, 0 }, { 3.0f, none }, { none, none } } },
  13179. };
  13180. auto goertzel = [] (const std::vector<float>& x, double hz) {
  13181. const auto w = 2.0 * juce::MathConstants<double>::pi * hz / 44100.0;
  13182. double s1 = 0.0, s2 = 0.0;
  13183. for (const auto v : x)
  13184. {
  13185. const auto s0 = v + 2.0 * std::cos (w) * s1 - s2;
  13186. s2 = s1;
  13187. s1 = s0;
  13188. }
  13189. 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());
  13190. return a > 1e-7 ? 20.0 * std::log10 (a) : -140.0;
  13191. };
  13192. auto ok = true;
  13193. for (const auto& c : cases)
  13194. {
  13195. lynx::AudioEngine engine (false);
  13196. engine.getPluginHost().addPluginFile (scFile);
  13197. auto song = lynx::Song::makeDefault();
  13198. song.bpm = 120.0;
  13199. song.channels.clear();
  13200. song.automations.clear();
  13201. for (auto& p : song.patterns)
  13202. p.notes.clear();
  13203. for (int k = 0; k < 4; ++k)
  13204. {
  13205. lynx::ChannelDef ch;
  13206. ch.name = "S" + std::to_string ((int) tones[k]);
  13207. ch.instrument = lynx::InstrumentKind::sampler;
  13208. ch.samplePath = dir.getChildFile ("sine" + juce::String ((int) tones[k]) + ".wav").getFullPathName().toStdString();
  13209. ch.mixerTrack = k + 1;
  13210. song.channels.push_back (ch);
  13211. lynx::Note note;
  13212. note.start = 0;
  13213. note.length = 8 * lynx::ppq;
  13214. note.channel = k;
  13215. note.key = 60;
  13216. note.velocity = 0.78f;
  13217. song.patterns[0].notes.push_back (note);
  13218. }
  13219. if (song.mixer.size() < 10)
  13220. song.mixer.resize (10);
  13221. for (auto& t : song.mixer)
  13222. {
  13223. t.effects.clear();
  13224. t.sends.clear();
  13225. t.toMaster = true;
  13226. }
  13227. lynx::EffectSlot fx;
  13228. fx.kind = lynx::EffectKind::plugin;
  13229. fx.plugin.id = sc->createIdentifierString().toStdString();
  13230. fx.plugin.name = sc->name.toStdString();
  13231. fx.plugin.inputs = c.inputs;
  13232. fx.plugin.outputs = c.outputs;
  13233. fx.plugin.processInactive = c.tweak != 3;
  13234. auto& one = song.mixer[1];
  13235. one.effects.push_back (fx);
  13236. one.sends = { { 5, 0.0f }, { 6, 0.0f } };
  13237. for (const int t : { 2, 3 })
  13238. {
  13239. song.mixer[(std::size_t) t].toMaster = false;
  13240. song.mixer[(std::size_t) t].sends = { { 1, 0.0f } };
  13241. }
  13242. song.mixer[5].pan = -1.0f;
  13243. song.mixer[6].pan = 1.0f;
  13244. one.toMaster = c.tweak != 1;
  13245. if (c.tweak == 2)
  13246. one.volume = 0.4f;
  13247. if (c.tweak == 4)
  13248. one.masterLevel = 0.0f;
  13249. if (c.tweak == 6)
  13250. song.mixer[2].volume = 0.4f;
  13251. song.mixer[2].muted = c.tweak == 7;
  13252. song.mixer[2].pan = c.tweak == 8 ? -1.0f : 0.0f;
  13253. if (c.tweak == 5)
  13254. {
  13255. one.sends = { { 7, 0.0f }, { 5, 0.0f }, { 6, 0.0f } };
  13256. song.mixer[7].pan = 0.5f;
  13257. }
  13258. // (input 2's index sets the slot's side input source, as the Connections page and the import do)
  13259. if (c.inputs.size() > 1 && c.inputs[1].offset > 0)
  13260. one.effects[0].sidechain = lynx::mixerops::sidechainIndexSource (song, 1, c.inputs[1].offset);
  13261. engine.setSong (song);
  13262. std::vector<float> left, right;
  13263. lynx::AudioEngine::RenderOptions options;
  13264. options.seconds = 1.2;
  13265. options.sampleRate = 44100.0;
  13266. options.capture = [&] (const float* l, const float* r, int n) {
  13267. left.insert (left.end(), l, l + n);
  13268. right.insert (right.end(), r, r + n);
  13269. };
  13270. engine.renderOffline (options);
  13271. const auto from = (std::size_t) 22050, to = (std::size_t) 44100;
  13272. if (right.size() < to)
  13273. {
  13274. report << c.name << ": rendered " << (int) right.size() << " samples FAILED\n";
  13275. ok = false;
  13276. continue;
  13277. }
  13278. const std::vector<float> l (left.begin() + (std::ptrdiff_t) from, left.begin() + (std::ptrdiff_t) to);
  13279. const std::vector<float> r (right.begin() + (std::ptrdiff_t) from, right.begin() + (std::ptrdiff_t) to);
  13280. const auto ref = 0.5 * (goertzel (l, 2500.0) + goertzel (r, 2500.0));
  13281. auto pass = ref > -60.0;
  13282. report << c.name << ": ref=" << juce::String (ref, 1);
  13283. for (int k = 0; k < 3; ++k)
  13284. for (int side = 0; side < 2; ++side)
  13285. {
  13286. const auto got = goertzel (side == 0 ? l : r, tones[k]) - ref;
  13287. const auto want = c.level[k][side];
  13288. const auto good = want == none ? got < -50.0 : std::abs (got - want) < 0.5;
  13289. pass = pass && good;
  13290. report << " " << (int) tones[k] << (side == 0 ? "L" : "R") << "=" << (got < -50.0 ? juce::String ("-") : juce::String (got, 1))
  13291. << (good ? "" : "(FL " + (want == none ? juce::String ("-") : juce::String (want, 1)) + ")");
  13292. }
  13293. report << (pass ? " OK" : " FAILED") << "\n";
  13294. ok = ok && pass;
  13295. }
  13296. return ok;
  13297. }
  13298. // LYNX.exe --wrappertest plugin.vst3 report.txt: builds a VST3 state the way FL's Fruity
  13299. // Wrapper stores it (REA_rodada5 §3.2), runs it through the import (adoptFlPlugins) and checks
  13300. // that the plugin comes back with the changed parameter.
  13301. void runWrapperTest (const juce::String& pluginPath, const juce::String& reportPath)
  13302. {
  13303. juce::String report;
  13304. bool ok = false;
  13305. {
  13306. lynx::AudioEngine offline (false);
  13307. auto& host = offline.getPluginHost();
  13308. host.addPluginFile (juce::File (pluginPath));
  13309. const juce::PluginDescription* vst3 = nullptr;
  13310. const auto types = host.getKnownPlugins().getTypes(); // copy: the pointer below points into it
  13311. for (const auto& type : types)
  13312. if (type.pluginFormatName == "VST3" && type.isInstrument)
  13313. vst3 = &type;
  13314. if (vst3 != nullptr)
  13315. {
  13316. juce::String error;
  13317. auto plugin = host.getFormats().createPluginInstance (*vst3, 48000.0, 512, error);
  13318. auto* parameter = plugin != nullptr && ! plugin->getParameters().isEmpty() ? plugin->getParameters()[0] : nullptr;
  13319. if (parameter != nullptr)
  13320. {
  13321. const auto target = parameter->getValue() > 0.5f ? 0.13f : 0.87f;
  13322. parameter->setValueNotifyingHost (target);
  13323. juce::MemoryBlock juceState;
  13324. plugin->getStateInformation (juceState);
  13325. report << "parameter=" << parameter->getName (64) << " target=" << target << "\n";
  13326. // JUCE state -> FL container: u32 1 + records 1 (flags), 3 (component), 2 (controller)
  13327. std::vector<std::uint8_t> flState;
  13328. auto put32 = [&] (std::uint32_t v) { for (int b = 0; b < 4; ++b) flState.push_back ((std::uint8_t) (v >> (8 * b))); };
  13329. auto record = [&] (std::uint32_t id, const juce::MemoryBlock& data) {
  13330. put32 (id);
  13331. put32 ((std::uint32_t) data.getSize());
  13332. put32 (0);
  13333. flState.insert (flState.end(), (const std::uint8_t*) data.getData(), (const std::uint8_t*) data.getData() + data.getSize());
  13334. };
  13335. put32 (1);
  13336. record (1, juce::MemoryBlock (64, true));
  13337. // record 4 (REA_rodada22 §2.3): slots 0/1 hold the ParamIDs of parameters 2 and 0, so FL's
  13338. // automations k = 0, 1, 2 mean positions 2, 0 and 1 (the first parameter without a slot)
  13339. juce::MemoryBlock slots;
  13340. const auto paramId = [&] (int i) {
  13341. const auto* hosted = dynamic_cast<const juce::HostedAudioProcessorParameter*> (plugin->getParameters()[i]);
  13342. return hosted != nullptr ? (std::uint32_t) hosted->getParameterID().getLargeIntValue() : 0u;
  13343. };
  13344. const bool reorder = plugin->getParameters().size() >= 3;
  13345. if (reorder)
  13346. {
  13347. for (auto v : { 2u, paramId (2), paramId (0) })
  13348. slots.append (&v, 4);
  13349. report << "slot_param_ids=" << (juce::int64) paramId (2) << "," << (juce::int64) paramId (0) << "\n";
  13350. }
  13351. if (auto xml = juce::AudioProcessor::getXmlFromBinary (juceState.getData(), (int) juceState.getSize()))
  13352. for (auto [tag, id] : { std::pair { "IComponent", 3u }, { "IEditController", 2u } })
  13353. if (auto* child = xml->getChildByName (tag))
  13354. {
  13355. juce::MemoryBlock data;
  13356. data.fromBase64Encoding (child->getAllSubText());
  13357. record (id, data);
  13358. report << tag << "_bytes=" << (int) data.getSize() << "\n";
  13359. }
  13360. if (reorder)
  13361. record (4, slots);
  13362. plugin.reset();
  13363. auto song = lynx::Song::makeDefault();
  13364. auto& f = song.channels[4].plugin.foreign;
  13365. f.format = lynx::ForeignPlugin::Format::vst3;
  13366. f.name = vst3->name.toStdString(); // no class ID: find it by name (fallback)
  13367. f.state = flState;
  13368. {
  13369. std::vector<std::uint8_t> comp, ctrl;
  13370. report << "split=" << (int) lynx::splitFlVst3State (flState, comp, ctrl) << " component=" << (int) comp.size()
  13371. << " saved_slots=" << (int) lynx::flVst3ParamSlots (flState).size() << "\n";
  13372. }
  13373. for (int k = 0; k < 3; ++k)
  13374. {
  13375. lynx::Automation a;
  13376. a.target = { lynx::AutomationTargetKind::channelParam, 4, 0, k };
  13377. song.automations.push_back (a);
  13378. }
  13379. const auto adopted = host.adoptFlPlugins (song);
  13380. report << "adopted=" << adopted << "\n";
  13381. juce::String mapped;
  13382. for (const auto& a : song.automations)
  13383. if (a.target.kind == lynx::AutomationTargetKind::channelParam && a.target.index == 4)
  13384. mapped << (mapped.isEmpty() ? "" : ",") << a.target.param;
  13385. report << "slot_positions=" << mapped << "\n";
  13386. const auto slotsOk = ! reorder || mapped == "2,0,1";
  13387. offline.setSong (song);
  13388. if (auto* loaded = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (4).get()))
  13389. {
  13390. const auto value = loaded->getInstance().getParameters()[0]->getValue();
  13391. report << "restored_value=" << value << "\n";
  13392. ok = adopted == 1 && std::abs (value - target) < 0.02f && slotsOk;
  13393. }
  13394. }
  13395. }
  13396. }
  13397. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  13398. juce::File (reportPath).replaceWithText (report);
  13399. setApplicationReturnValue (ok ? 0 : 1);
  13400. quit();
  13401. }
  13402. void runDemoSongs (const juce::String& folderPath)
  13403. {
  13404. const juce::File folder (folderPath);
  13405. folder.createDirectory();
  13406. bool ok = true;
  13407. for (int d = 1; d < lynx::demos::count; ++d)
  13408. {
  13409. juce::String error;
  13410. ok = lynx::ProjectFile::save (lynx::demos::make (d), folder.getChildFile (lynx::demos::fileName (d)), error) && ok;
  13411. }
  13412. setApplicationReturnValue (ok ? 0 : 1);
  13413. quit();
  13414. }
  13415. // --perfgen (round perfgate190id): each synthetic project of the performance gate written as <folder>/<name>.lynx, its
  13416. // audio as 16-bit WAVs in <folder>/<name>/ (written once: the same code makes the same audio). The report gives, per
  13417. // project, the .lynx size, the time to write it (ProjectFile::save, which reads it back) and to read it
  13418. // (ProjectFile::load), the medians of 5, and a hash of its text.
  13419. void runPerfGen (const juce::String& folderPath, const juce::String& reportPath, const juce::String& only)
  13420. {
  13421. const juce::File folder (folderPath);
  13422. folder.createDirectory();
  13423. const auto wanted = juce::StringArray::fromTokens (only, ",", "");
  13424. juce::String report;
  13425. bool ok = true;
  13426. auto median = [] (std::vector<double> v) {
  13427. std::sort (v.begin(), v.end());
  13428. return v[v.size() / 2];
  13429. };
  13430. for (const auto& name : lynx::perfprojects::names())
  13431. {
  13432. if (! wanted.isEmpty() && ! wanted.contains (juce::String (name)))
  13433. continue;
  13434. lynx::Song song;
  13435. lynx::perfprojects::Samples samples;
  13436. const auto audioFolder = folder.getChildFile (juce::String (name));
  13437. lynx::perfprojects::make (name, song, samples, audioFolder.getFullPathName().toStdString());
  13438. for (const auto& [path, data] : samples)
  13439. {
  13440. const juce::File wav { juce::String (path) };
  13441. if (wav.existsAsFile())
  13442. continue;
  13443. wav.getParentDirectory().createDirectory();
  13444. const auto frames = (int) data->frames();
  13445. juce::AudioBuffer<float> audio (2, frames);
  13446. audio.copyFrom (0, 0, data->leftData(), frames);
  13447. audio.copyFrom (1, 0, data->rightData(), frames);
  13448. juce::WavAudioFormat format;
  13449. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  13450. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), data->sampleRate, 2, 16, {}, 0) : nullptr)
  13451. {
  13452. out.release();
  13453. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  13454. ok = writer->writeFromAudioSampleBuffer (audio, 0, frames) && ok;
  13455. }
  13456. else
  13457. ok = false;
  13458. }
  13459. const auto file = folder.getChildFile (juce::String (name) + ".lynx");
  13460. std::vector<double> saveMs, loadMs;
  13461. juce::String error;
  13462. bool loadedOk = true;
  13463. for (int rep = 0; rep < 5; ++rep)
  13464. {
  13465. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  13466. ok = lynx::ProjectFile::save (song, file, error) && ok;
  13467. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  13468. const auto loaded = lynx::ProjectFile::load (file, error);
  13469. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  13470. loadedOk = loadedOk && loaded.has_value() && loaded->channels.size() == song.channels.size()
  13471. && loaded->playlist.size() == song.playlist.size() && loaded->automations.size() == song.automations.size();
  13472. saveMs.push_back (t1 - t0);
  13473. loadMs.push_back (t2 - t1);
  13474. }
  13475. ok = ok && loadedOk;
  13476. const auto text = file.loadFileAsString();
  13477. std::uint64_t h = 1469598103934665603ull;
  13478. for (auto* c = text.toRawUTF8(); *c != 0; ++c)
  13479. h = (h ^ (std::uint8_t) *c) * 1099511628211ull;
  13480. report << name << ": channels=" << (int) song.channels.size() << " inserts=" << (int) song.mixer.size() - 1
  13481. << " clips=" << (int) song.playlist.size() << " automations=" << (int) song.automations.size()
  13482. << " wavs=" << (int) samples.size() << " lynx_kb=" << juce::String ((double) file.getSize() / 1024.0, 1)
  13483. << " save_ms=" << juce::String (median (saveMs), 2) << " load_ms=" << juce::String (median (loadMs), 2)
  13484. << " roundtrip=" << (loadedOk ? "OK" : "FAILED") << " text_hash=" << juce::String::toHexString ((juce::int64) h)
  13485. << (error.isNotEmpty() ? " error=" + error : juce::String()) << "\n";
  13486. }
  13487. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  13488. if (reportPath.isNotEmpty())
  13489. juce::File (reportPath).replaceWithText (report);
  13490. else
  13491. std::fputs (report.toRawUTF8(), stdout);
  13492. setApplicationReturnValue (ok ? 0 : 1);
  13493. quit();
  13494. }
  13495. void runShowcase (const juce::String& outputPath, int currentPattern)
  13496. {
  13497. const auto song = lynx::makeShowcaseSong (currentPattern);
  13498. juce::String error;
  13499. const auto ok = lynx::ProjectFile::save (song, juce::File (outputPath), error);
  13500. setApplicationReturnValue (ok ? 0 : 1);
  13501. quit();
  13502. }
  13503. // LYNX.exe --sandboxtest plugin.vst3 report.txt: opens the instrument in a separate process, plays a
  13504. // note, changes a parameter, checks the state (back in an in-process plugin) and makes the child hang
  13505. // to check that LYNX keeps going (silence, without waiting longer than the timeout).
  13506. // --sandboxtest: plays an instrument (a note) or an effect (a 440 Hz tone through it); render() adds into l / r
  13507. struct TestVoice
  13508. {
  13509. explicit TestVoice (std::unique_ptr<juce::AudioPluginInstance> p)
  13510. {
  13511. if (p->acceptsMidi() && p->getTotalNumInputChannels() == 0)
  13512. instrument = std::make_unique<lynx::PluginInstrument> (std::move (p), 512);
  13513. else
  13514. effect = std::move (p);
  13515. }
  13516. void noteOn()
  13517. {
  13518. if (instrument != nullptr)
  13519. instrument->noteOn (60, 0.9f);
  13520. }
  13521. void render (float* l, float* r, int n, float gainLeft, float gainRight)
  13522. {
  13523. if (instrument != nullptr)
  13524. {
  13525. instrument->render (l, r, n, gainLeft, gainRight);
  13526. return;
  13527. }
  13528. const auto channels = juce::jmax (2, effect->getTotalNumInputChannels(), effect->getTotalNumOutputChannels());
  13529. juce::AudioBuffer<float> block (channels, 512);
  13530. juce::MidiBuffer midi;
  13531. for (int done = 0; done < n; done += 512)
  13532. {
  13533. const auto k = juce::jmin (512, n - done);
  13534. block.setSize (channels, k, false, false, true);
  13535. for (int i = 0; i < k; ++i)
  13536. {
  13537. const auto v = 0.25f * (float) std::sin (phase);
  13538. phase += 2.0 * juce::MathConstants<double>::pi * 440.0 / 48000.0;
  13539. for (int c = 0; c < channels; ++c)
  13540. block.setSample (c, i, v);
  13541. }
  13542. effect->processBlock (block, midi);
  13543. for (int i = 0; i < k; ++i)
  13544. {
  13545. l[done + i] += gainLeft * block.getSample (0, i);
  13546. r[done + i] += gainRight * block.getSample (1, i);
  13547. }
  13548. }
  13549. }
  13550. void release()
  13551. {
  13552. instrument.reset();
  13553. effect.reset();
  13554. }
  13555. std::unique_ptr<lynx::PluginInstrument> instrument;
  13556. std::unique_ptr<juce::AudioPluginInstance> effect;
  13557. double phase = 0.0;
  13558. };
  13559. void runSandboxTest (const juce::String& pluginPath, const juce::String& reportPath)
  13560. {
  13561. juce::String report;
  13562. bool ok = false;
  13563. lynx::setPluginSandboxAlerts (false);
  13564. const juce::File log (reportPath + ".log");
  13565. auto step = [&] (const char* what) { log.appendText (juce::String (what) + "\n"); };
  13566. log.deleteFile();
  13567. {
  13568. lynx::PluginHost host (false);
  13569. host.addPluginFile (juce::File (pluginPath));
  13570. const auto types = host.getKnownPlugins().getTypes(); // getTypes() returns a copy
  13571. // the file's instrument, else its first effect (round 161: effects too, e.g. a Windows effect through yabridge)
  13572. const juce::PluginDescription* instrument = nullptr;
  13573. for (const auto& type : types)
  13574. if (type.isInstrument)
  13575. instrument = &type;
  13576. for (const auto& type : types)
  13577. if (instrument == nullptr && ! type.isInstrument)
  13578. instrument = &type;
  13579. step ("host");
  13580. juce::String error;
  13581. auto remote = instrument != nullptr ? lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error) : nullptr;
  13582. report << "opened=" << (remote != nullptr ? 1 : 0) << " error=" << error << "\n";
  13583. step ("created");
  13584. if (remote != nullptr)
  13585. {
  13586. auto& proxy = *remote;
  13587. TestVoice voice (std::move (remote));
  13588. std::vector<float> l (48000), r (48000);
  13589. auto peakOf = [&] {
  13590. float peak = 0.0f;
  13591. for (std::size_t k = 0; k < l.size(); ++k)
  13592. peak = std::max ({ peak, std::abs (l[k]), std::abs (r[k]) });
  13593. return peak;
  13594. };
  13595. const auto start = juce::Time::getMillisecondCounterHiRes();
  13596. voice.noteOn();
  13597. voice.render (l.data(), r.data(), 48000, 1.0f, 1.0f);
  13598. const auto renderMs = juce::Time::getMillisecondCounterHiRes() - start;
  13599. const auto peak = peakOf();
  13600. step ("played");
  13601. if (juce::JUCEApplication::getCommandLineParameters().contains ("--expect-crash"))
  13602. {
  13603. // a plugin that crashes while playing (round 161 test plugin): LYNX notices, mutes it and keeps running
  13604. const auto dead = lynx::isSandboxedPluginDead (proxy);
  13605. std::fill (l.begin(), l.end(), 0.0f);
  13606. std::fill (r.begin(), r.end(), 0.0f);
  13607. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  13608. report << "peak=" << peak << " render_1s_ms=" << renderMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << peakOf() << "\n";
  13609. ok = dead && peak > 1e-4f && renderMs < 2000.0 && peakOf() == 0.0f;
  13610. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  13611. juce::File (reportPath).replaceWithText (report);
  13612. setApplicationReturnValue (ok ? 0 : 1);
  13613. quit();
  13614. return;
  13615. }
  13616. report << "plugin=" << proxy.getName() << (instrument->isInstrument ? " (instrument)" : " (effect)") << " parameters="
  13617. << proxy.getParameters().size() << " peak=" << peak << " render_1s_ms=" << renderMs << "\n";
  13618. if (juce::JUCEApplication::getCommandLineParameters().contains ("--editor") && proxy.hasEditor())
  13619. {
  13620. // the plugin's own window, opened by the child process (4 s on screen); the child must stay responsive
  13621. std::unique_ptr<juce::AudioProcessorEditor> editor (proxy.createEditorIfNeeded());
  13622. juce::Thread::sleep (4000);
  13623. juce::MemoryBlock state;
  13624. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  13625. proxy.getStateInformation (state);
  13626. report << "editor_shown=1 state_with_editor_ms=" << (juce::Time::getMillisecondCounterHiRes() - t0) << " dead=" << (lynx::isSandboxedPluginDead (proxy) ? 1 : 0) << "\n";
  13627. editor.reset();
  13628. }
  13629. // parameter -> state -> in-process plugin
  13630. bool stateOk = false;
  13631. if (! proxy.getParameters().isEmpty())
  13632. {
  13633. auto* p = proxy.getParameters()[0];
  13634. const auto target = p->getValue() > 0.5f ? 0.13f : 0.87f;
  13635. p->setValue (target);
  13636. std::fill (l.begin(), l.end(), 0.0f);
  13637. voice.render (l.data(), r.data(), 512, 1.0f, 1.0f); // carries the change to the child
  13638. juce::MemoryBlock state;
  13639. proxy.getStateInformation (state);
  13640. if (auto local = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  13641. {
  13642. local->setStateInformation (state.getData(), (int) state.getSize());
  13643. const auto back = local->getParameters()[0]->getValue();
  13644. // the same steps without the sandbox: some plugins quantise the value or keep it out of their state
  13645. auto control = target;
  13646. if (auto a = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  13647. {
  13648. a->enableAllBuses();
  13649. a->prepareToPlay (48000.0, 512);
  13650. a->getParameters()[0]->setValue (target);
  13651. juce::AudioBuffer<float> block (juce::jmax (2, a->getTotalNumInputChannels(), a->getTotalNumOutputChannels()), 512);
  13652. block.clear();
  13653. juce::MidiBuffer none;
  13654. a->processBlock (block, none);
  13655. juce::MemoryBlock direct;
  13656. a->getStateInformation (direct);
  13657. if (auto b = host.getFormats().createPluginInstance (*instrument, 48000.0, 512, error))
  13658. {
  13659. b->setStateInformation (direct.getData(), (int) direct.getSize());
  13660. control = b->getParameters()[0]->getValue();
  13661. }
  13662. a->releaseResources();
  13663. }
  13664. report << "state_bytes=" << (int) state.getSize() << " target=" << target << " in_process=" << back << " in_process_control=" << control << "\n";
  13665. stateOk = std::abs (back - control) < 0.02f;
  13666. }
  13667. }
  13668. step ("state");
  13669. // hung child: the block returns in ~0.5 s, muted, and the plugin is marked dead
  13670. lynx::hangSandboxedPluginForTest (proxy);
  13671. juce::Thread::sleep (200);
  13672. std::fill (l.begin(), l.end(), 1.0f);
  13673. std::fill (r.begin(), r.end(), 1.0f);
  13674. const auto hangStart = juce::Time::getMillisecondCounterHiRes();
  13675. voice.render (l.data(), r.data(), 4096, 0.0f, 0.0f);
  13676. std::fill (l.begin(), l.end(), 0.0f);
  13677. std::fill (r.begin(), r.end(), 0.0f);
  13678. voice.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  13679. const auto hangMs = juce::Time::getMillisecondCounterHiRes() - hangStart;
  13680. const auto dead = lynx::isSandboxedPluginDead (proxy);
  13681. const auto hangPeak = peakOf();
  13682. report << "hung_ms=" << hangMs << " dead=" << (dead ? 1 : 0) << " peak_after=" << hangPeak << "\n";
  13683. // crashed child (round 161): a second instance aborts; LYNX notices, mutes it and keeps running
  13684. bool crashOk = false;
  13685. if (auto second = lynx::createSandboxedPlugin (*instrument, 48000.0, 512, {}, error))
  13686. {
  13687. auto& proxy2 = *second;
  13688. TestVoice voice2 (std::move (second));
  13689. voice2.noteOn();
  13690. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  13691. lynx::crashSandboxedPluginForTest (proxy2);
  13692. const auto crashStart = juce::Time::getMillisecondCounterHiRes();
  13693. while (! lynx::isSandboxedPluginDead (proxy2) && juce::Time::getMillisecondCounterHiRes() - crashStart < 5000.0)
  13694. {
  13695. voice2.render (l.data(), r.data(), 512, 1.0f, 1.0f);
  13696. juce::Thread::sleep (5);
  13697. }
  13698. const auto crashMs = juce::Time::getMillisecondCounterHiRes() - crashStart;
  13699. std::fill (l.begin(), l.end(), 0.0f);
  13700. std::fill (r.begin(), r.end(), 0.0f);
  13701. voice2.render (l.data(), r.data(), 4096, 1.0f, 1.0f);
  13702. const auto crashDead = lynx::isSandboxedPluginDead (proxy2);
  13703. report << "crash_ms=" << crashMs << " crash_dead=" << (crashDead ? 1 : 0) << " crash_peak_after=" << peakOf() << "\n";
  13704. crashOk = crashDead && crashMs < 3000.0;
  13705. // issue #159: freeing the crashed plugin doesn't wait on its pipe (JUCE waited up to 10 s there for
  13706. // the gone child, on the message thread when the rack freed it); its teardown ends on its own
  13707. const auto freeStart = juce::Time::getMillisecondCounterHiRes();
  13708. voice2.release();
  13709. const auto freeMs = juce::Time::getMillisecondCounterHiRes() - freeStart;
  13710. const auto endedAll = lynx::finishSandboxTeardowns (15000);
  13711. report << "crashed_free_ms=" << freeMs << " teardown_done=" << (endedAll ? 1 : 0) << "\n";
  13712. crashOk = crashOk && freeMs < 250.0 && endedAll;
  13713. }
  13714. step ("crash");
  13715. ok = peak > 1e-4f && stateOk && dead && hangMs < 1500.0 && hangPeak == 0.0f && crashOk;
  13716. }
  13717. }
  13718. report << "result=" << (ok ? "OK" : "FAILED") << "\n";
  13719. juce::File (reportPath).replaceWithText (report);
  13720. setApplicationReturnValue (ok ? 0 : 1);
  13721. quit();
  13722. }
  13723. // --timertest (round 174f): a view's polling timer follows the view and its parents, and survives a minimised window
  13724. void runTimerTest (const juce::File& report)
  13725. {
  13726. struct Ticks final : juce::Timer
  13727. {
  13728. void timerCallback() override {}
  13729. } timer;
  13730. juce::Component top, parent, view;
  13731. parent.addChildComponent (view);
  13732. top.addChildComponent (parent);
  13733. top.setSize (320, 200);
  13734. lynx::ui::TimerWhileShowing watch (view, timer, 30);
  13735. juce::String text;
  13736. auto failures = 0;
  13737. auto expect = [&] (const char* step, bool running) {
  13738. const auto ok = timer.isTimerRunning() == running;
  13739. failures += ok ? 0 : 1;
  13740. text << step << ": timer " << (timer.isTimerRunning() ? "running" : "stopped") << (ok ? "" : " FAIL") << "\n";
  13741. };
  13742. expect ("never shown", false);
  13743. view.setVisible (true);
  13744. parent.setVisible (true);
  13745. expect ("view and parent visible, not on the desktop", false);
  13746. top.addToDesktop (juce::ComponentPeer::windowHasTitleBar);
  13747. top.setVisible (true);
  13748. expect ("window shown", true);
  13749. parent.setVisible (false);
  13750. expect ("parent hidden", false);
  13751. parent.setVisible (true);
  13752. expect ("parent shown", true);
  13753. view.setVisible (false);
  13754. expect ("view hidden", false);
  13755. top.getPeer()->setMinimised (true);
  13756. view.setVisible (true);
  13757. expect ("view shown while minimised", true);
  13758. top.getPeer()->setMinimised (false);
  13759. expect ("window restored", true);
  13760. top.setVisible (false);
  13761. expect ("window hidden", false);
  13762. top.setVisible (true);
  13763. expect ("window shown again", true);
  13764. top.removeFromDesktop();
  13765. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  13766. report.replaceWithText (text);
  13767. setApplicationReturnValue (failures == 0 ? 0 : 1);
  13768. quit();
  13769. }
  13770. // --cachetest (round 174f): PlaylistComponent::cacheSelfTest on the project, the Playlist off screen at 1466 x 930
  13771. void runCacheTest (const juce::File& project, const juce::File& report)
  13772. {
  13773. engine = std::make_unique<lynx::AudioEngine>();
  13774. juce::String error;
  13775. auto ok = false;
  13776. // (round 190nq: a Live set, FL Studio Mobile project or DAWproject takes the same import, issue #193's set)
  13777. if (project.hasFileExtension ("flp;als;flm;dawproject"))
  13778. ok = engine->importFlpFile (project, error);
  13779. else if (auto song = lynx::ProjectFile::load (project, error))
  13780. {
  13781. engine->setSong (std::move (*song));
  13782. ok = true;
  13783. }
  13784. juce::String text = "project: " + project.getFullPathName() + "\n";
  13785. if (ok)
  13786. {
  13787. text << "video tracks: " << (int) engine->getSong().videoTracks.size() << "\n";
  13788. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  13789. playlist->setBounds (0, 0, 1466, 930);
  13790. playlist->setVisible (true);
  13791. text << playlist->cacheSelfTest ([] { lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000); }, report.getParentDirectory());
  13792. }
  13793. else
  13794. text << "result=ERROR " << error << "\n";
  13795. report.replaceWithText (text);
  13796. setApplicationReturnValue (ok && text.contains ("result=OK") ? 0 : 1);
  13797. quit();
  13798. }
  13799. // --picturetest (round 190bm): ui/PictureCheck.h on the Playlist and the Mixer, at a window's usual size, at a 4K
  13800. // screen's, and wider than a GPU bitmap can be (16384 px)
  13801. void runPictureTest (const juce::File& report, const juce::File& project)
  13802. {
  13803. engine = std::make_unique<lynx::AudioEngine>();
  13804. juce::String error, text;
  13805. if (project != juce::File())
  13806. {
  13807. auto ok = false;
  13808. if (project.hasFileExtension ("flp"))
  13809. ok = engine->importFlpFile (project, error);
  13810. else if (auto song = lynx::ProjectFile::load (project, error))
  13811. {
  13812. engine->setSong (std::move (*song));
  13813. ok = true;
  13814. }
  13815. text << "project: " << project.getFullPathName() << (ok ? "" : " (not loaded: " + error + ")") << "\n";
  13816. }
  13817. #if JUCE_WINDOWS
  13818. text << "native image: " << juce::NativeImageType().create (juce::Image::RGB, 8, 8, true)->createType()->getTypeID()
  13819. << " (software = " << juce::SoftwareImageType().getTypeID() << ")\n";
  13820. #endif
  13821. auto failures = 0;
  13822. struct Size
  13823. {
  13824. int width, height;
  13825. std::vector<float> scales;
  13826. };
  13827. const auto folder = report.getParentDirectory();
  13828. 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 } } })
  13829. {
  13830. const auto label = [&size] (const char* name) { return juce::String (name) + " " + juce::String (size.width) + " x " + juce::String (size.height); };
  13831. {
  13832. auto playlist = std::make_unique<lynx::PlaylistComponent> (*engine);
  13833. playlist->setBounds (0, 0, size.width, size.height);
  13834. playlist->setVisible (true);
  13835. {
  13836. juce::Image warm (juce::Image::RGB, 64, 64, true); // (one paint asks for the waveforms, then they are waited for)
  13837. juce::Graphics g (warm);
  13838. playlist->paintEntireComponent (g, true);
  13839. }
  13840. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  13841. text << lynx::ui::picturecheck::run (*playlist, label ("Playlist"), size.scales, failures, folder);
  13842. }
  13843. {
  13844. auto mixer = std::make_unique<lynx::MixerComponent> (*engine);
  13845. mixer->setBounds (0, 0, size.width, juce::jmin (size.height, 700));
  13846. mixer->setVisible (true);
  13847. text << lynx::ui::picturecheck::run (*mixer, label ("Mixer"), size.scales, failures, folder);
  13848. }
  13849. }
  13850. text << "failures: " << failures << "\nresult=" << (failures == 0 ? "OK" : "FAIL") << "\n";
  13851. report.replaceWithText (text);
  13852. setApplicationReturnValue (failures == 0 ? 0 : 1);
  13853. quit();
  13854. }
  13855. // --uiperf (round 161): opens the project in the normal window, plays it, and drives the heavy UI cases of round 151
  13856. // through the window's own event path — the default layout, the Mixer maximised (meters while playing, then
  13857. // scrolled), the Playlist maximised (scroll down, scroll sideways, zoom in and out) and the Channel rack scrolled.
  13858. // Every frame is painted right after its event (ComponentPeer::performAnyPendingRepaintsNow) and timed; the report
  13859. // has, per case, the time to show it and the frames' mean / p95 / max, how many took longer than 16 ms, and the
  13860. // process CPU. The same on every OS, so Linux (X11, XWayland) and Windows numbers can be put side by side.
  13861. void runUiPerf (const juce::File& project, const juce::File& report)
  13862. {
  13863. if (const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {}); profile.isNotEmpty())
  13864. lynx::crashguard::startMainProfiler (profile.toStdString()); // (stopped in shutdown)
  13865. startupOptions = lynx::StartupOptions::load();
  13866. engine = std::make_unique<lynx::AudioEngine>();
  13867. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  13868. crashEngine = engine.get();
  13869. createMainWindow();
  13870. mainWindow->reveal();
  13871. // LYNX_UIPERF_SIZE=WxH, LYNX_UIPERF_SCALE=<percent> (round 179a): a large window, a HiDPI desktop's scale
  13872. if (const auto scale = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SCALE", {}).getIntValue(); scale > 0)
  13873. juce::Desktop::getInstance().setGlobalScaleFactor ((float) scale / 100.0f);
  13874. if (const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SIZE", {}), "x", ""); size.size() == 2)
  13875. mainWindow->setBounds (0, 0, size[0].getIntValue(), size[1].getIntValue());
  13876. juce::String error;
  13877. auto ok = false;
  13878. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  13879. if (project.hasFileExtension ("flp;als;flm;band;blx")) // (round 190gr: a Live set, its Session clips in the grid)
  13880. ok = engine->importFlpFile (project, error);
  13881. else if (auto song = lynx::ProjectFile::load (project, error))
  13882. {
  13883. engine->setSong (std::move (*song));
  13884. ok = true;
  13885. }
  13886. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  13887. if (! ok)
  13888. {
  13889. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  13890. setApplicationReturnValue (1);
  13891. quit();
  13892. return;
  13893. }
  13894. // LYNX_UIPERF_MUTE=1: the Master fader down (the meters of the inserts still move): a run on a desktop someone uses
  13895. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_MUTE", {}) == "1")
  13896. engine->editSong ([] (lynx::Song& s) { if (! s.mixer.empty()) s.mixer[0].volume = 0.0f; }, false);
  13897. struct Step
  13898. {
  13899. juce::String name;
  13900. std::function<void()> setup;
  13901. std::function<void (int)> action; // per frame; none: the step watches the window for `frames` ms
  13902. int frames;
  13903. std::function<juce::String()> finish = {}; // round 173f: after the step, its own lines for the report
  13904. };
  13905. struct UiPerf final : juce::Timer
  13906. {
  13907. LynxApplication& app;
  13908. juce::File report;
  13909. juce::String text;
  13910. std::vector<Step> steps;
  13911. std::size_t step = 0;
  13912. int frame = -1;
  13913. std::vector<double> times, rendered; // whole frames (event + paint + blit, when this timer paints) / the window's paints
  13914. std::vector<double> frames; // round 173f: the time of every frame the window painted (ui/FrameProbe.h)
  13915. double paintedPixels = 0.0; // round 190ge: the dirty area of those frames, summed (overdraw / repaint storms)
  13916. double setupMs = 0.0, wallStart = 0.0;
  13917. double cpuStart = 0.0; // process CPU seconds (std::clock is wall time on Windows)
  13918. bool threadsWanted = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_THREADS", {}) == "1";
  13919. std::vector<lynx::ThreadCpu> threadsStart;
  13920. double messageCpuStart = 0.0; // the message thread's CPU seconds
  13921. // round 190jx: LYNX_UIPERF_PEER_PID=<pid> (Linux): another process's CPU over each step too (the X server, which
  13922. // draws the overlay's marks there)
  13923. int peerPid = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_PEER_PID", "0").getIntValue();
  13924. double peerCpuStart = 0.0;
  13925. static double peerCpuSeconds (int pid)
  13926. {
  13927. if (pid <= 0)
  13928. return 0.0;
  13929. const auto stat = juce::File ("/proc/" + juce::String (pid) + "/stat").loadFileAsString();
  13930. const auto fields = juce::StringArray::fromTokens (stat.fromLastOccurrenceOf (")", false, false), " ", "");
  13931. // (after the name: state is field 0, utime 11, stime 12, in clock ticks)
  13932. return fields.size() > 12 ? (fields[11].getDoubleValue() + fields[12].getDoubleValue()) / 100.0 : 0.0;
  13933. }
  13934. int presentsStart = 0; // round 190jy: Direct2D presents of every LYNX window (Windows)
  13935. double audioLoadSum = 0.0; // the device's CPU use (AudioDeviceManager::getCpuUsage), summed per tick
  13936. int audioLoadTicks = 0;
  13937. // round 190kb: exact CPU cycles, the worker pool's waiting, the callbacks' deadlines, the Direct2D presents
  13938. std::uint64_t cyclesStart = 0;
  13939. lynx::WorkerPool::Stats poolStart;
  13940. lynx::RtStats::Snapshot rtStart; // (presentsStart: 190jy's, above)
  13941. std::map<std::string, std::pair<long long, long long>> tickersStart; // round 190kr
  13942. int coveredStart = 0;
  13943. UiPerf (LynxApplication& a, juce::File r) : app (a), report (std::move (r))
  13944. {
  13945. lynx::WorkerPool::nameCurrentThread ("LYNX message thread"); // (round 190kb: the threads' lines)
  13946. }
  13947. juce::ComponentPeer* peer() const { return app.mainWindow != nullptr ? app.mainWindow->getPeer() : nullptr; }
  13948. double paintNow() const
  13949. {
  13950. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  13951. if (auto* p = peer())
  13952. p->performAnyPendingRepaintsNow();
  13953. return juce::Time::getMillisecondCounterHiRes() - t0;
  13954. }
  13955. void timerCallback() override
  13956. {
  13957. if (step >= steps.size())
  13958. {
  13959. stopTimer();
  13960. finish();
  13961. return;
  13962. }
  13963. auto& s = steps[step];
  13964. if (frame < 0)
  13965. {
  13966. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  13967. if (s.setup)
  13968. s.setup();
  13969. paintNow();
  13970. setupMs = juce::Time::getMillisecondCounterHiRes() - t0;
  13971. times.clear();
  13972. rendered.clear();
  13973. frames.clear();
  13974. paintedPixels = 0.0;
  13975. wallStart = juce::Time::getMillisecondCounterHiRes();
  13976. cpuStart = lynx::processCpuSeconds();
  13977. messageCpuStart = lynx::threadCpuSeconds();
  13978. peerCpuStart = peerCpuSeconds (peerPid);
  13979. presentsStart = uiPerfPresents();
  13980. if (threadsWanted) // round 190ih: LYNX_UIPERF_THREADS=1, the CPU of every thread over the step
  13981. threadsStart = lynx::threadCpuList();
  13982. lynx::grossBeatPaintStats (true);
  13983. cyclesStart = lynx::processCpuCycles();
  13984. tickersStart = lynx::ui::FrameTicker::perOwner();
  13985. coveredStart = lynx::nativechild::coveredSkips().load();
  13986. if (const auto* pool = app.engine->getWorkerPool())
  13987. poolStart = pool->stats();
  13988. rtStart = app.engine->getRtStats().snapshot();
  13989. audioLoadSum = 0.0;
  13990. audioLoadTicks = 0;
  13991. frame = 0;
  13992. return;
  13993. }
  13994. audioLoadSum += app.engine->getDeviceManager().getCpuUsage();
  13995. ++audioLoadTicks;
  13996. if (s.action)
  13997. s.action (frame);
  13998. if (const auto ms = paintNow(); ms > 0.25) // (nothing to paint: not a frame)
  13999. times.push_back (ms);
  14000. ++frame;
  14001. if (s.action ? frame < s.frames : juce::Time::getMillisecondCounterHiRes() - wallStart < (double) s.frames)
  14002. return;
  14003. const auto wall = juce::Time::getMillisecondCounterHiRes() - wallStart;
  14004. const auto cpu = 1000.0 * (lynx::processCpuSeconds() - cpuStart);
  14005. const auto messageCpu = 1000.0 * (lynx::threadCpuSeconds() - messageCpuStart);
  14006. text << s.name << ": show " << juce::String (setupMs, 1) << " ms\n"
  14007. << " painted frames: " << stats (rendered) << "\n"
  14008. << " timed here (event + paint + blit): " << stats (times)
  14009. << "\n window frames (probe): " << lynx::ui::FrameStats::of (frames, wall).describe()
  14010. << ", painted " << juce::String (wall > 0.0 ? paintedPixels / wall / 1000.0 : 0.0, 2) << " Mpx/s"
  14011. << "\n CPU " << juce::String (wall > 0.0 ? 100.0 * cpu / wall : 0.0, 0) << "% (process, " << juce::String (wall / 1000.0, 1) << " s), message thread "
  14012. << juce::String (wall > 0.0 ? 100.0 * messageCpu / wall : 0.0, 1) << "%, audio device "
  14013. << juce::String (audioLoadTicks > 0 ? 100.0 * audioLoadSum / audioLoadTicks : 0.0, 1) << "%\n";
  14014. if (peerPid > 0 && wall > 0.0)
  14015. text << " peer process " << peerPid << " CPU " << juce::String (100.0 * 1000.0 * (peerCpuSeconds (peerPid) - peerCpuStart) / wall, 1) << "%\n";
  14016. // round 190jy: every LYNX window's Direct2D presents (the main window's and each native child's) and how
  14017. // the docked LYNX editors were drawn
  14018. {
  14019. int native = 0, inMain = 0, hidden = 0;
  14020. for (auto* w : lynx::dockedEditorWindows())
  14021. if (w != nullptr)
  14022. (! w->isVisible() ? hidden : lynx::isEditorInMainWindow (*w) ? inMain : native) += 1;
  14023. text << " presents " << juce::String (wall > 0.0 ? 1000.0 * (uiPerfPresents() - presentsStart) / wall : 0.0, 1)
  14024. << "/s; docked editors: " << native << " own windows, " << inMain << " in the main window, " << hidden << " hidden\n";
  14025. }
  14026. const auto cycleRate = lynx::cpuCyclesPerSecond();
  14027. if (cycleRate > 0.0 && wall > 0.0)
  14028. text << " CPU cycles " << juce::String (100.0 * (double) (lynx::processCpuCycles() - cyclesStart) / cycleRate / (wall / 1000.0), 1)
  14029. << "% (process, exact); presents " << juce::String (1000.0 * (uiPerfPresents() - presentsStart) / wall, 1) << "/s\n";
  14030. if (const auto* pool = app.engine->getWorkerPool(); pool != nullptr && wall > 0.0)
  14031. {
  14032. // round 190kb: per second of the step (time in ms/s = tenths of a percent of one core)
  14033. const auto p = pool->stats();
  14034. const auto& a = poolStart;
  14035. const auto perS = [wall] (std::uint64_t v) { return juce::String (1000.0 * (double) v / wall, 0); };
  14036. const auto msS = [wall] (std::uint64_t ns) { return juce::String ((double) ns / 1.0e6 * 1000.0 / wall, 2); };
  14037. text << " pool: rounds " << perS (p.rounds - a.rounds) << "/s; workers work " << msS (p.workNs - a.workNs)
  14038. << " ms/s, spin " << msS (p.spinNs - a.spinNs) << " ms/s (" << perS (p.spins - a.spins) << "/s: found "
  14039. << perS (p.spinFound - a.spinFound) << ", parked " << perS (p.spinParked - a.spinParked) << ", timed out "
  14040. << perS (p.spinTimedOut - a.spinTimedOut) << "), sleeps " << perS (p.sleeps - a.sleeps) << "/s (early "
  14041. << perS (p.earlyWakes - a.earlyWakes) << "); waits " << msS (p.waitNs - a.waitNs) << " ms/s (" << perS (p.waits - a.waits)
  14042. << "/s, yields " << perS (p.waitYields - a.waitYields) << ", sleeps " << perS (p.waitSleeps - a.waitSleeps) << " = " << msS (p.waitSleepNs - a.waitSleepNs) << " ms/s"
  14043. << "); caller wait " << msS (p.callerWaitNs - a.callerWaitNs) << " ms/s (sleeps " << perS (p.callerSleeps - a.callerSleeps) << "/s)\n";
  14044. }
  14045. {
  14046. const auto r = app.engine->getRtStats().snapshot();
  14047. text << " callbacks " << juce::String ((juce::int64) (r.callbacks - rtStart.callbacks)) << ", over the deadline "
  14048. << juce::String ((juce::int64) (r.overBudget - rtStart.overBudget)) << ", 80-100 % " << juce::String ((juce::int64) (r.nearBudget - rtStart.nearBudget))
  14049. << ", late " << juce::String ((juce::int64) (r.lateCalls - rtStart.lateCalls)) << "\n";
  14050. // round 190ok (P24): Settings › Audio › "Safe overloads" (core/OverloadGuard.h), since the start
  14051. const auto& guard = app.engine->getOverloadGuard();
  14052. text << " safe overloads " << (guard.isEnabled() ? "on" : "off") << ": engaged " << (juce::int64) guard.timesEngaged()
  14053. << " times" << (guard.engaged() ? " (now)" : "") << ", yielded " << juce::String (guard.yieldedMs(), 0) << " ms\n";
  14054. }
  14055. if (threadsWanted && wall > 0.0)
  14056. {
  14057. // (round 190kb: and each thread's exact cycles in brackets, as % of one core; sorted by them where known)
  14058. std::vector<std::pair<double, juce::String>> rows;
  14059. for (const auto& t : lynx::threadCpuList())
  14060. {
  14061. auto before = 0.0;
  14062. std::uint64_t cyclesBefore = 0;
  14063. for (const auto& b : threadsStart)
  14064. if (b.id == t.id)
  14065. before = b.seconds, cyclesBefore = b.cycles;
  14066. const auto used = t.seconds - before;
  14067. const auto exact = cycleRate > 0.0 ? 100.0 * (double) (t.cycles - cyclesBefore) / cycleRate / (wall / 1000.0) : -1.0;
  14068. if (used > 0.0005 || exact > 0.05)
  14069. rows.push_back ({ exact >= 0.0 ? exact : 100.0 * 1000.0 * used / wall,
  14070. juce::String (t.id) + " " + (t.name.empty() ? juce::String ("(unnamed)") : juce::String (t.name)) + " "
  14071. + juce::String (100.0 * 1000.0 * used / wall, 1) + "%" + (exact >= 0.0 ? " [" + juce::String (exact, 1) + "%]" : juce::String()) });
  14072. }
  14073. std::sort (rows.begin(), rows.end(), [] (const auto& a, const auto& b) { return a.first > b.first; });
  14074. text << " threads:";
  14075. for (std::size_t k = 0; k < rows.size() && k < 16; ++k)
  14076. text << " " << rows[k].second << ";";
  14077. text << "\n";
  14078. }
  14079. if (const auto gb = lynx::grossBeatPaintStats (false); gb.isNotEmpty())
  14080. text << " " << gb << "\n";
  14081. // round 190kr: LYNX_UIPERF_TICKERS=1, the live views' frame steps per second (run / moved) and the steps
  14082. // left out because the view's docked panel was covered
  14083. if (lynx::ui::FrameTicker::perOwnerWanted() && wall > 0.0)
  14084. {
  14085. text << " tickers:";
  14086. for (const auto& [name, counts] : lynx::ui::FrameTicker::perOwner())
  14087. {
  14088. const auto before = tickersStart.count (name) != 0 ? tickersStart.at (name) : std::pair<long long, long long> {};
  14089. if (counts.first != before.first)
  14090. text << " " << juce::String (name).fromLastOccurrenceOf ("::", false, false).retainCharacters ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_")
  14091. << " " << juce::String (1000.0 * (double) (counts.first - before.first) / wall, 0) << "/" << juce::String (1000.0 * (double) (counts.second - before.second) / wall, 0);
  14092. }
  14093. text << "; covered skips " << juce::String (1000.0 * (double) (lynx::nativechild::coveredSkips().load() - coveredStart) / wall, 0) << "/s\n";
  14094. }
  14095. if (s.finish)
  14096. text << s.finish();
  14097. juce::File (report).replaceWithText (text);
  14098. ++step;
  14099. frame = -1;
  14100. }
  14101. static juce::String stats (std::vector<double> sorted)
  14102. {
  14103. std::sort (sorted.begin(), sorted.end());
  14104. 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()))]; };
  14105. double sum = 0.0;
  14106. int over = 0;
  14107. for (auto t : sorted)
  14108. {
  14109. sum += t;
  14110. over += t > 16.0 ? 1 : 0;
  14111. }
  14112. return juce::String ((int) sorted.size()) + ", mean " + juce::String (sorted.empty() ? 0.0 : sum / (double) sorted.size(), 1)
  14113. + " ms, p95 " + juce::String (at (0.95), 1) + " ms, max " + juce::String (sorted.empty() ? 0.0 : sorted.back(), 1)
  14114. + " ms, >16 ms " + juce::String (over);
  14115. }
  14116. void finish()
  14117. {
  14118. // the cost of asking where the mouse is (X11: a round trip to the display server)
  14119. const auto q0 = juce::Time::getMillisecondCounterHiRes();
  14120. for (int i = 0; i < 100; ++i)
  14121. juce::ignoreUnused (juce::Desktop::getInstance().getMainMouseSource().getScreenPosition());
  14122. text << "mouse position query: " << juce::String ((juce::Time::getMillisecondCounterHiRes() - q0) / 100.0, 3) << " ms\n";
  14123. app.mainWindow->onFrame = nullptr;
  14124. app.mainWindow->watchFrames ({});
  14125. app.engine->stop();
  14126. text << "result=OK\n";
  14127. report.replaceWithText (text);
  14128. app.setApplicationReturnValue (0);
  14129. app.quit();
  14130. }
  14131. };
  14132. auto* ui = &mainWindow->getContent();
  14133. auto wheelAt = [this] (juce::Component& target, float dx, float dy, juce::ModifierKeys mods) {
  14134. auto* peer = mainWindow->getPeer();
  14135. if (peer == nullptr || ! target.isShowing())
  14136. return;
  14137. juce::ModifierKeys::currentModifiers = mods;
  14138. const auto local = peer->globalToLocal (target.localPointToGlobal (target.getLocalBounds().getCentre()).toFloat());
  14139. juce::MouseWheelDetails wheel { dx, dy, false, false, false };
  14140. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  14141. juce::ModifierKeys::currentModifiers = {};
  14142. };
  14143. auto run = std::make_unique<UiPerf> (*this, report);
  14144. mainWindow->onFrame = [r = run.get()] (double ms) { if (r->frame >= 0) r->rendered.push_back (ms); };
  14145. // round 173f: every frame the window paints; a fader drag's moves count as shown when a frame covers the fader
  14146. auto drag = std::make_shared<UiPerfDrag>();
  14147. mainWindow->watchFrames ([r = run.get(), drag] (double now, juce::Rectangle<int> area) {
  14148. if (r->frame >= 0)
  14149. {
  14150. r->frames.push_back (now);
  14151. r->paintedPixels += (double) area.getWidth() * (double) area.getHeight();
  14152. }
  14153. drag->framePainted (now, area);
  14154. });
  14155. run->text << "project: " << project.getFullPathName() << "\n"
  14156. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  14157. << juce::SystemStats::getCpuModel() << ", window " << mainWindow->getWidth() << "x" << mainWindow->getHeight()
  14158. << ", scale " << juce::String (juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
  14159. ? juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale : 1.0, 2)
  14160. << ", audio device " << (engine->getDeviceManager().getCurrentAudioDevice() != nullptr ? engine->getDeviceManager().getCurrentAudioDevice()->getName() : juce::String ("none")) << "\n"
  14161. << "load " << juce::String (loadMs / 1000.0, 2) << " s\n";
  14162. const auto none = juce::ModifierKeys();
  14163. // discussion #10 (round 173f): the reporter's screen — the Channel Rack and the Mixer open, the pattern playing —
  14164. // watched as it is, then insert 3's fader dragged up and down with the mouse (125 moves a second through the
  14165. // window's own mouse path, the frames painted as the window paints them)
  14166. const auto dragTrack = engine->getSong().mixer.size() > 3 ? 3 : 1;
  14167. run->steps.push_back ({ "rack + mixer, pattern playing", [this, ui] {
  14168. ui->showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  14169. engine->getTransport().songMode = false;
  14170. engine->rewind();
  14171. engine->play();
  14172. }, {}, 4000 });
  14173. run->steps.push_back ({ "fader drag by mouse, rack + mixer, pattern playing", [this, ui, drag, dragTrack] {
  14174. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  14175. const auto rail = strips.faderRailForSnapshot (dragTrack);
  14176. drag->start (*mainWindow, strips, rail, engine.get(), dragTrack);
  14177. }, {}, 3000, [drag] { return drag->stop(); } });
  14178. run->steps.push_back ({ "song stopped during the drag", {}, {}, 500, [drag] { return drag->release(); } });
  14179. run->steps.push_back ({ "after the drag (released)", {}, {}, 600, [drag] { return drag->released(); } });
  14180. run->steps.push_back ({ "desktop, playing", [this, ui] { ui->showDesktopForSnapshot (false); engine->rewind(); engine->play(); }, {}, 3000 });
  14181. run->steps.push_back ({ "mixer maximised, playing", [ui] { ui->selectTabForSnapshot (3); }, {}, 3000 });
  14182. // round 177a: only the meters move, so the strips' picture must stay valid, also with a folded group's tab and VCA
  14183. // strips on screen (their levels are drawn over the picture, like the inserts' meters)
  14184. run->steps.push_back ({ "mixer meters over the picture, playing", [this, ui] {
  14185. ui->selectTabForSnapshot (3);
  14186. engine->getTransport().songMode = false;
  14187. engine->rewind();
  14188. engine->play();
  14189. ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  14190. }, {}, 6000, [this, ui, report] {
  14191. const auto [spoiled, refills] = ui->getMixerForSnapshot().getStripsForSnapshot().cacheCountersForPerf();
  14192. if (juce::FileOutputStream out (report.withFileExtension ("png")); out.openedOk())
  14193. {
  14194. out.setPosition (0);
  14195. out.truncate();
  14196. juce::PNGImageFormat().writeImageToStream (mainWindow->createComponentSnapshot (mainWindow->getLocalBounds()), out);
  14197. }
  14198. return juce::String (" mixer picture: spoiled ") + juce::String (spoiled) + " times, drawn again " + juce::String (refills) + " times\n";
  14199. } });
  14200. // (round 190my: the wheel goes to a strip's blank body near the Mixer's centre — since 293333ae6's Current strip the
  14201. // centre itself can be a control, which the wheel would turn instead of scrolling; trace 190my: the strips then
  14202. // move from x -56 to -325 in a 1113 px view. Strips that fit their view can't scroll: the step uses Extra large
  14203. // then, e.g. at a wide window.)
  14204. auto scrollLayout = std::make_shared<std::optional<lynx::mixerlayout::Layout>>();
  14205. auto scrollTrace = std::make_shared<juce::String>();
  14206. run->steps.push_back ({ "mixer scroll",
  14207. [ui, scrollLayout, scrollTrace] {
  14208. scrollTrace->clear();
  14209. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  14210. const auto* holder = strips.getParentComponent();
  14211. if (holder != nullptr && strips.getWidth() <= holder->getWidth() + 200)
  14212. {
  14213. *scrollLayout = lynx::MixerStrips::layout;
  14214. strips.setLayout (lynx::mixerlayout::Layout::extraLarge);
  14215. }
  14216. },
  14217. [this, ui, scrollTrace] (int f) {
  14218. auto& mixer = ui->getMixerForSnapshot();
  14219. auto& strips = mixer.getStripsForSnapshot();
  14220. auto* peer = mainWindow->getPeer();
  14221. if (peer == nullptr || ! strips.isShowing())
  14222. return;
  14223. const auto centre = strips.getLocalPoint (&mixer, mixer.getLocalBounds().getCentre());
  14224. const auto at = strips.wheelScrollPointForPerf (centre, strips.getParentComponent() != nullptr
  14225. ? strips.getLocalArea (strips.getParentComponent(), strips.getParentComponent()->getLocalBounds())
  14226. : strips.getLocalBounds());
  14227. const auto local = peer->globalToLocal (strips.localPointToGlobal (at).toFloat());
  14228. juce::ModifierKeys::currentModifiers = {};
  14229. juce::MouseWheelDetails wheel { 0.0f, f < 30 ? -0.25f : 0.25f, false, false, false };
  14230. peer->handleMouseWheel (juce::MouseInputSource::InputSourceType::mouse, local, juce::Time::currentTimeMillis(), wheel);
  14231. if (f == 0 || f == 29)
  14232. {
  14233. auto* under = peer->getComponent().getComponentAt (local.roundToInt());
  14234. const auto* holder = strips.getParentComponent();
  14235. *scrollTrace << " mixer scroll frame " << f << ": wheel at " << at.toString() << " (strips), under it "
  14236. << (under == &strips ? juce::String ("the strips") : under != nullptr ? juce::String (typeid (*under).name()) : juce::String ("nothing"))
  14237. << ", view " << (holder != nullptr ? holder->getBounds().toString() : juce::String()) << ", strips at x " << strips.getX() << "\n";
  14238. }
  14239. }, 60,
  14240. [ui, scrollLayout, scrollTrace] {
  14241. auto& strips = ui->getMixerForSnapshot().getStripsForSnapshot();
  14242. const auto width = strips.getWidth();
  14243. juce::String used = scrollLayout->has_value() ? "Extra large (the strips fit the view in their layout)" : "the project's layout";
  14244. if (scrollLayout->has_value())
  14245. strips.setLayout (**scrollLayout);
  14246. scrollLayout->reset();
  14247. return juce::String (" mixer scroll: strips ") + juce::String (width) + " px, " + used + "\n" + *scrollTrace;
  14248. } });
  14249. // a fader dragged while the song plays (round 171c, discussion #10): 4 mouse moves per frame on insert 1's fader,
  14250. // through the old path (a whole snapshot per move) and through editLevels
  14251. auto faderMove = [this] (bool levels, int f) {
  14252. for (int k = 0; k < 4; ++k)
  14253. {
  14254. const auto v = 0.5f + 0.3f * std::sin ((float) (f * 4 + k) * 0.05f);
  14255. const auto edit = [v] (lynx::Song& s) { if (s.mixer.size() > 1) s.mixer[1].volume = v; };
  14256. if (levels)
  14257. engine->editLevels (edit, false); // (no undo step: in a real drag only the press saves one)
  14258. else
  14259. engine->editSong (edit, false);
  14260. }
  14261. };
  14262. run->steps.push_back ({ "mixer fader drag, playing, rebuild per move (before 171c)", {}, [faderMove] (int f) { faderMove (false, f); }, 60 });
  14263. run->steps.push_back ({ "mixer fader drag, playing, live levels (171c)", {}, [faderMove, this] (int f) { faderMove (true, f); if (f == 59) engine->flushLevels(); }, 60 });
  14264. // F8's Plugin picker (round 171c): opening it (the "show" time = building it + its first paint), its pictures
  14265. // loading while it stays open, pointing at the tiles, then closing it
  14266. run->steps.push_back ({ "plugin picker open (F8)", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 2500 });
  14267. run->steps.push_back ({ "plugin picker, pointing at tiles", {}, [ui] (int f) {
  14268. // (round 175b: the picker is its own window)
  14269. if (auto* picker = ui->pluginPickerForSnapshot(); picker != nullptr && picker->getPeer() != nullptr)
  14270. {
  14271. const auto p = picker->localPointToGlobal (juce::Point<int> (60 + (f * 37) % juce::jmax (1, picker->getWidth() - 120),
  14272. 90 + (f * 53) % juce::jmax (1, picker->getHeight() - 200)));
  14273. const auto local = picker->getPeer()->globalToLocal (p.toFloat());
  14274. picker->getPeer()->handleMouseEvent (juce::MouseInputSource::InputSourceType::mouse, local, {}, 0.0f, 0.0f,
  14275. juce::Time::currentTimeMillis());
  14276. }
  14277. }, 60 });
  14278. run->steps.push_back ({ "plugin picker close", [ui] { ui->togglePluginPickerForSnapshot(); }, {}, 300 });
  14279. run->steps.push_back ({ "playlist maximised, playing", [ui] { ui->selectTabForSnapshot (2); }, {}, 3000 });
  14280. run->steps.push_back ({ "playlist scroll down/up", [this] { engine->stop(); },
  14281. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), 0.0f, f < 40 ? -0.15f : 0.15f, none); }, 80 });
  14282. run->steps.push_back ({ "playlist scroll sideways", {},
  14283. [wheelAt, ui, none] (int f) { wheelAt (ui->getPlaylistForSnapshot(), f < 40 ? -0.15f : 0.15f, 0.0f, none); }, 80 });
  14284. // round 174f: Ctrl+wheel zoom, a notch every third frame (~20 a second), three in then three out, as dupmon drives it
  14285. run->steps.push_back ({ "playlist zoom (Ctrl+wheel)", {},
  14286. [wheelAt, ui] (int f) {
  14287. if (f % 3 == 0)
  14288. wheelAt (ui->getPlaylistForSnapshot(), 0.0f, (f / 9) % 2 == 0 ? 0.15f : -0.15f, juce::ModifierKeys (juce::ModifierKeys::ctrlModifier));
  14289. }, 120 });
  14290. run->steps.push_back ({ "playlist after the zoom (settles)", {}, {}, 500 });
  14291. run->steps.push_back ({ "whole window repainted", {}, [this] (int) { mainWindow->repaint(); }, 40 });
  14292. run->steps.push_back ({ "channel rack scroll", [ui] { ui->selectTabForSnapshot (0); },
  14293. [wheelAt, ui, none] (int f) { wheelAt (ui->getRackViewportForSnapshot(), 0.0f, f < 30 ? -0.25f : 0.25f, none); }, 60 });
  14294. // round 190ge: the other main views while the pattern plays, then every view with the transport stopped and
  14295. // nothing moving (an idle view should paint nothing: its frames and painted area are the repaint storms), then
  14296. // the Clip-launch grid playing
  14297. auto playPattern = [this] {
  14298. engine->getTransport().songMode = false;
  14299. engine->rewind();
  14300. engine->play();
  14301. };
  14302. run->steps.push_back ({ "piano roll maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (1); playPattern(); }, {}, 3000 });
  14303. // round 190jx: the moving playheads alone, for the overlay's A/B (LYNX_UIPERF_ONLY="overlay A/B", LYNX_OVERLAY=0|1):
  14304. // the Playlist with the song playing and the Piano roll with the pattern playing, LYNX_UIPERF_PLAY_MS each (10 s)
  14305. {
  14306. const auto playMs = juce::jmax (1000, juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_PLAY_MS", "10000").getIntValue());
  14307. run->steps.push_back ({ "overlay A/B: playlist maximised, song playing", [this, ui] {
  14308. ui->selectTabForSnapshot (2);
  14309. engine->getTransport().songMode = true;
  14310. engine->rewind();
  14311. engine->play();
  14312. }, {}, playMs });
  14313. // round 190ok (P24): LYNX_UIPERF_RECOVERY=1 — the song stopped after it, 3 s: the safe-overload guard lets go
  14314. // and the callbacks keep their deadline again (the report's "safe overloads" line: no "(now)")
  14315. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_RECOVERY", "0") == "1")
  14316. run->steps.push_back ({ "overlay A/B: playlist maximised, stopped after the song (recovery)", [this] { engine->stop(); }, {}, 3000 });
  14317. run->steps.push_back ({ "overlay A/B: piano roll maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (1); playPattern(); }, {}, playMs,
  14318. [this] { engine->stop(); return juce::String(); } });
  14319. }
  14320. run->steps.push_back ({ "channel rack maximised, pattern playing", [ui, playPattern] { ui->selectTabForSnapshot (0); playPattern(); }, {}, 3000 });
  14321. const char* idleViews[] { "channel rack", "piano roll", "playlist", "mixer" };
  14322. for (int view = 0; view < 4; ++view)
  14323. run->steps.push_back ({ juce::String ("idle: ") + idleViews[view] + ", stopped", [this, ui, view] { engine->stop(); ui->selectTabForSnapshot (view); }, {}, 3000 });
  14324. run->steps.push_back ({ "idle: desktop, stopped", [this, ui] { engine->stop(); ui->showDesktopForSnapshot (false); }, {}, 3000 });
  14325. // round 190im (R1, DE-124): the automation editor window open over the Playlist, stopped and then playing (its
  14326. // timer only while it plays, its playhead columns only); closed after
  14327. {
  14328. int automation = -1;
  14329. for (const auto& c : engine->getSong().playlist)
  14330. if (c.kind == lynx::ClipKind::automation && c.automation >= 0 && automation < 0)
  14331. automation = c.automation;
  14332. if (automation >= 0)
  14333. {
  14334. run->steps.push_back ({ "automation editor open, stopped", [this, ui, automation] {
  14335. engine->stop();
  14336. ui->selectTabForSnapshot (2);
  14337. lynx::openAutomationEditor (*engine, automation);
  14338. }, {}, 3000 });
  14339. run->steps.push_back ({ "automation editor open, song playing", [this] {
  14340. engine->getTransport().songMode = true;
  14341. engine->rewind();
  14342. engine->play();
  14343. }, {}, 3000, [this] {
  14344. engine->stop();
  14345. auto& desktop = juce::Desktop::getInstance();
  14346. for (int i = desktop.getNumComponents(); --i >= 0;)
  14347. if (auto* w = dynamic_cast<juce::DocumentWindow*> (desktop.getComponent (i)); w != nullptr && w->getName().startsWith ("Automation - "))
  14348. w->closeButtonPressed();
  14349. return juce::String();
  14350. } });
  14351. }
  14352. }
  14353. run->steps.push_back ({ "clip grid, song playing", [this, ui] {
  14354. ui->selectTabForSnapshot (2);
  14355. ui->setClipLaunchWorkflow (true);
  14356. ui->setClipGridView (lynx::PlaylistArea::GridView::grid);
  14357. engine->getTransport().songMode = true;
  14358. engine->rewind();
  14359. engine->play();
  14360. }, {}, 3000 });
  14361. // round 190gr: the grid's clips launched (every scene that has clips, one after the other: the playing cells'
  14362. // progress bars move, the launches blink until their grid point)
  14363. run->steps.push_back ({ "clip grid, clips launched", [this] {
  14364. engine->getTransport().songMode = true;
  14365. if (const auto& grid = engine->getSong().clipGrid)
  14366. for (int scene = 0; scene < juce::jmin (8, (int) grid->scenes.size()); ++scene)
  14367. engine->launcherCommand ({ lynx::launcher::Command::Type::launchScene, 0, scene });
  14368. }, {}, 3000, [this] {
  14369. int playing = 0;
  14370. if (const auto* state = engine->launcherState())
  14371. for (const auto& t : state->tracks)
  14372. playing += t.playing.load() >= 0 ? 1 : 0;
  14373. engine->launcherCommand ({ lynx::launcher::Command::Type::stopAll });
  14374. return " tracks playing a clip: " + juce::String (playing) + "\n";
  14375. } });
  14376. run->steps.push_back ({ "idle: clip grid, stopped", [this] { engine->stop(); }, {}, 3000, [ui] { ui->setClipLaunchWorkflow (false); return juce::String(); } });
  14377. // round 190jn: the Clip-launch layout's Arrangement (Live's look: 19 px lanes, colour blocks, dark waveforms) playing,
  14378. // then idle
  14379. run->steps.push_back ({ "clip arrangement, song playing", [this, ui] {
  14380. ui->selectTabForSnapshot (2);
  14381. ui->setClipLaunchWorkflow (true);
  14382. ui->setClipGridView (lynx::PlaylistArea::GridView::song);
  14383. engine->getTransport().songMode = true;
  14384. engine->rewind();
  14385. engine->play();
  14386. }, {}, 3000 });
  14387. run->steps.push_back ({ "idle: clip arrangement, stopped", [this] { engine->stop(); }, {}, 3000, [ui] {
  14388. ui->setClipGridView (lynx::PlaylistArea::GridView::grid);
  14389. ui->setClipLaunchWorkflow (false);
  14390. return juce::String();
  14391. } });
  14392. // round 190ih: the plugin windows with live parts — Gross Beat (its locator), the Formula Controller (its monitor),
  14393. // the Envelope Controller (its meters and key line) — idle with the song stopped, then Gross Beat while it plays
  14394. // (CPU and frames; the windows are their own, so the main window's painted area stays the main window's)
  14395. run->steps.push_back ({ "idle: Gross Beat + Formula + Envelope controller windows, stopped", [this] {
  14396. engine->stop();
  14397. auto& song = engine->getSong();
  14398. int gbTrack = -1, gbSlot = -1;
  14399. for (int t = 0; t < (int) song.mixer.size() && gbTrack < 0; ++t)
  14400. for (int k = 0; k < (int) song.mixer[(std::size_t) t].effects.size(); ++k)
  14401. if (song.mixer[(std::size_t) t].effects[(std::size_t) k].kind == lynx::EffectKind::grossBeat)
  14402. {
  14403. gbTrack = t;
  14404. gbSlot = k;
  14405. break;
  14406. }
  14407. const auto last = (int) song.mixer.size() - 1;
  14408. const auto formulaSlot = last >= 1 ? (int) song.mixer[(std::size_t) last].effects.size() : -1;
  14409. engine->editSong ([last] (lynx::Song& s) {
  14410. if (last >= 1 && s.mixer[(std::size_t) last].effects.size() < (std::size_t) lynx::maxEffectSlots)
  14411. s.mixer[(std::size_t) last].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::formulaController));
  14412. lynx::ChannelDef env;
  14413. env.name = "Envelope Controller";
  14414. env.instrument = lynx::InstrumentKind::controller;
  14415. env.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  14416. s.channels.push_back (env);
  14417. }, false);
  14418. engine->dispatchPendingMessages();
  14419. // LYNX_UIPERF_WINDOWS: which of them (G Gross Beat, F Formula, E Envelope Controller; default all)
  14420. const auto which = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_WINDOWS", "GFE");
  14421. if (gbTrack >= 0 && which.containsChar ('G'))
  14422. lynx::NativeEffectWindows::open (*engine, gbTrack, gbSlot);
  14423. if (formulaSlot >= 0 && which.containsChar ('F'))
  14424. lynx::FormulaControllerWindows::open (*engine, last, formulaSlot);
  14425. if (which.containsChar ('E'))
  14426. lynx::openChannelSettings (*engine, (int) engine->getSong().channels.size() - 1);
  14427. }, {}, 3000 });
  14428. // round 190ih: LYNX_UIPERF_GBAB=n — n cycles over Gross Beat's live-display variants, playing, 2.5 s each, in one
  14429. // process (other load hits every variant alike): the names carry the LYNX_GB_DIAG mask
  14430. if (const auto cycles = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_GBAB", "0").getIntValue(); cycles > 0)
  14431. {
  14432. run->steps.push_back ({ "Gross Beat A/B start", [this] {
  14433. engine->getTransport().songMode = true;
  14434. engine->rewind();
  14435. engine->play();
  14436. }, {}, 1500 });
  14437. // (off, the default, 30 / s, off, 10 / s; LYNX_UIPERF_GBAB_MASKS="1,2,0" picks others, e.g. round 190iy's
  14438. // locator on the GPU overlay (0) against the repaint path (2))
  14439. std::vector<int> masks { 1, 0, 30 << 8, 1, 10 << 8 };
  14440. if (const auto list = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_GBAB_MASKS", {}); list.isNotEmpty())
  14441. {
  14442. masks.clear();
  14443. for (const auto& m : juce::StringArray::fromTokens (list, ",", {}))
  14444. masks.push_back (m.trim().getIntValue());
  14445. }
  14446. for (int c = 0; c < cycles; ++c)
  14447. for (const int mask : masks)
  14448. run->steps.push_back ({ "Gross Beat A/B mask " + juce::String (mask) + " cycle " + juce::String (c + 1),
  14449. [this, mask] {
  14450. lynx::setGrossBeatDiagnostics (mask);
  14451. if (! engine->getTransport().playing.load()) // (the song ended: again)
  14452. {
  14453. engine->rewind();
  14454. engine->play();
  14455. }
  14456. }, {}, 2500 });
  14457. }
  14458. // round 190jy (queue item 44): LYNX_UIPERF_DOCKAB=n — the docked LYNX editors with live displays, playing, each set
  14459. // hidden / a native child window / drawn by the main window, n cycles of 2.5 s steps in one process.
  14460. // LYNX_UIPERF_DOCKAB_SETS (default "G,L,M,GLM"): G Gross Beat, L Fruity Limiter, M Maximus (both on the master).
  14461. if (const auto cycles = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKAB", "0").getIntValue(); cycles > 0)
  14462. {
  14463. auto sets = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKAB_SETS", "G,L,M,GLM"), ",", {});
  14464. auto shown = std::make_shared<std::vector<juce::Component::SafePointer<juce::DocumentWindow>>>();
  14465. auto keepPlaying = [this] {
  14466. engine->getTransport().songMode = true;
  14467. if (! engine->getTransport().playing.load()) // (the song ended: again)
  14468. {
  14469. engine->rewind();
  14470. engine->play();
  14471. }
  14472. };
  14473. for (const auto& set : sets)
  14474. {
  14475. const auto name = set.trim();
  14476. run->steps.push_back ({ "dock A/B " + name + " open", [this, name, shown, keepPlaying] {
  14477. lynx::NativeEffectWindows::closeAll();
  14478. for (auto* w : lynx::dockedEditorWindows()) // (a channel's settings window of the set before)
  14479. if (w != nullptr)
  14480. w->closeButtonPressed();
  14481. shown->clear();
  14482. auto& song = engine->getSong();
  14483. auto openKind = [this] (lynx::EffectKind kind) {
  14484. auto& so = engine->getSong();
  14485. for (int t = 0; t < (int) so.mixer.size(); ++t)
  14486. for (int k = 0; k < (int) so.mixer[(std::size_t) t].effects.size(); ++k)
  14487. if (so.mixer[(std::size_t) t].effects[(std::size_t) k].kind == kind)
  14488. {
  14489. lynx::NativeEffectWindows::open (*engine, t, k);
  14490. return;
  14491. }
  14492. // (not in the project: on the master, after its effects)
  14493. if (so.mixer.empty() || so.mixer[0].effects.size() >= (std::size_t) lynx::maxEffectSlots)
  14494. return;
  14495. const auto slot = (int) so.mixer[0].effects.size();
  14496. engine->editSong ([kind] (lynx::Song& s2) { s2.mixer[0].effects.push_back (lynx::makeEffectSlot (kind)); }, false);
  14497. engine->dispatchPendingMessages();
  14498. lynx::NativeEffectWindows::open (*engine, 0, slot);
  14499. };
  14500. juce::ignoreUnused (song);
  14501. if (name.containsChar ('G'))
  14502. openKind (lynx::EffectKind::grossBeat);
  14503. if (name.containsChar ('L'))
  14504. openKind (lynx::EffectKind::fruityLimiter);
  14505. if (name.containsChar ('M'))
  14506. openKind (lynx::EffectKind::maximus);
  14507. // S: a Slicex channel (a 2 s tone in 4 regions) that plays the notes of the project's busiest
  14508. // channel, its settings window open (its deck's play line moves while it sounds)
  14509. if (name.containsChar ('S'))
  14510. {
  14511. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-uiperf-slicex.wav");
  14512. {
  14513. juce::AudioBuffer<float> tone (2, 96000);
  14514. for (int i = 0; i < tone.getNumSamples(); ++i)
  14515. tone.setSample (0, i, 0.3f * (float) std::sin (juce::MathConstants<double>::twoPi * (200.0 + 200.0 * (i / 24000)) * i / 48000.0));
  14516. tone.copyFrom (1, 0, tone, 0, 0, tone.getNumSamples());
  14517. wav.deleteFile();
  14518. if (auto out = std::unique_ptr<juce::OutputStream> (wav.createOutputStream()))
  14519. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), 48000.0, 2, 16, {}, 0)))
  14520. {
  14521. out.release();
  14522. writer->writeFromAudioSampleBuffer (tone, 0, tone.getNumSamples());
  14523. }
  14524. }
  14525. int busiest = -1;
  14526. {
  14527. std::map<int, int> count;
  14528. for (const auto& pat : engine->getSong().patterns)
  14529. for (const auto& n : pat.notes)
  14530. ++count[n.channel];
  14531. int best = 0;
  14532. for (const auto& [ch, n] : count)
  14533. if (n > best)
  14534. best = n, busiest = ch;
  14535. }
  14536. const auto index = (int) engine->getSong().channels.size();
  14537. engine->editSong ([&wav, busiest, index] (lynx::Song& s2) {
  14538. lynx::ChannelDef ch;
  14539. ch.name = "Slicex (uiperf)";
  14540. ch.instrument = lynx::InstrumentKind::slicex;
  14541. ch.samplePath = wav.getFullPathName().toStdString();
  14542. auto state = lynx::slicex::fresh();
  14543. lynx::slicex::setDeckFile (state, 0, ch.samplePath, 4);
  14544. lynx::slicex::setDeckBeats (state, 0, 0.0, 4.0);
  14545. ch.pluginState = lynx::slicex::write (state);
  14546. s2.channels.push_back (ch);
  14547. for (auto& pat : s2.patterns)
  14548. {
  14549. std::vector<lynx::Note> copies;
  14550. for (const auto& n : pat.notes)
  14551. if (n.channel == busiest)
  14552. {
  14553. auto c = n;
  14554. c.channel = index;
  14555. c.key = 60 + (int) (copies.size() % 4); // (the four slices in turn)
  14556. copies.push_back (c);
  14557. }
  14558. pat.notes.insert (pat.notes.end(), copies.begin(), copies.end());
  14559. pat.sortNotes();
  14560. }
  14561. }, false);
  14562. engine->dispatchPendingMessages();
  14563. lynx::openChannelSettings (*engine, index);
  14564. }
  14565. for (auto* w : lynx::dockedEditorWindows())
  14566. shown->emplace_back (w);
  14567. keepPlaying();
  14568. }, {}, 1500 });
  14569. static const char* variantNames[] = { "hidden", "own window", "main window" };
  14570. for (int c = 0; c < cycles; ++c)
  14571. for (int v = 0; v < 3; ++v)
  14572. run->steps.push_back ({ "dock A/B " + name + " " + variantNames[v] + " cycle " + juce::String (c + 1), [v, shown, keepPlaying] {
  14573. if (v > 0)
  14574. lynx::moveDockedEditors (v == 2);
  14575. for (auto& w : *shown)
  14576. if (w != nullptr && w->isVisible() != (v > 0))
  14577. w->setVisible (v > 0);
  14578. keepPlaying();
  14579. }, {}, 2500 });
  14580. }
  14581. run->steps.push_back ({ "dock A/B close", [this, shown] {
  14582. engine->stop();
  14583. shown->clear();
  14584. lynx::NativeEffectWindows::closeAll();
  14585. for (auto* w : lynx::dockedEditorWindows())
  14586. if (w != nullptr)
  14587. w->closeButtonPressed();
  14588. }, {}, 500 });
  14589. }
  14590. // round 190jy: LYNX_UIPERF_DOCKCHECK=1 — the checks of a docked editor drawn by the main window (ui/DockPaintCheck.h),
  14591. // on screen in this main window; LYNX_UIPERF_DOCKCHECK_SHOTS=<folder> keeps the two on-screen pictures compared
  14592. if (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKCHECK", {}) == "1")
  14593. {
  14594. auto check = std::make_shared<std::unique_ptr<lynx::dockpaint::Check>>();
  14595. auto lines = std::make_shared<juce::String>();
  14596. for (int i = 0; i < lynx::dockpaint::Check::count(); ++i)
  14597. run->steps.push_back ({ "dock check " + juce::String (i), [this, ui, check, lines, i] {
  14598. if (*check == nullptr)
  14599. *check = std::make_unique<lynx::dockpaint::Check> (*engine, *ui, *mainWindow,
  14600. juce::File (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_DOCKCHECK_SHOTS", {})));
  14601. *lines = (*check)->step (i);
  14602. }, {}, 700, [lines] { return *lines; } });
  14603. }
  14604. run->steps.push_back ({ "Gross Beat window, song playing", [this] {
  14605. engine->getTransport().songMode = true;
  14606. engine->rewind();
  14607. engine->play();
  14608. }, {}, 3000, [this] {
  14609. engine->stop();
  14610. lynx::NativeEffectWindows::closeAll();
  14611. lynx::FormulaControllerWindows::closeAll();
  14612. return juce::String();
  14613. } });
  14614. // round 190kb: LYNX_UIPERF_SPINAB=n — the worker pool's waiting policies (WorkerPool::Tuning) A/B inside one
  14615. // process while the song plays with live editor windows: per set (LYNX_UIPERF_SPINAB_SETS, default "G,GLM": G
  14616. // Gross Beat, L Fruity Limiter, M Maximus; on the master when the project has none), n cycles over every
  14617. // variant (LYNX_UIPERF_SPINAB_VARIANTS="name:spec;…", spec as LYNX_POOL) with the windows hidden and shown,
  14618. // 2.5 s steps, the order turning every cycle. Run with LYNX_UIPERF_THREADS=1 for the threads' lines.
  14619. if (const auto cycles = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SPINAB", "0").getIntValue(); cycles > 0)
  14620. {
  14621. auto sets = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SPINAB_SETS", "G,GLM"), ",", {});
  14622. struct Variant
  14623. {
  14624. juce::String name, spec;
  14625. };
  14626. std::vector<Variant> variants;
  14627. for (const auto& v : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable (
  14628. "LYNX_UIPERF_SPINAB_VARIANTS", "old:spin=60,adaptive=0,wait=0;new:spin=60,adaptive=1,dry=4,wait=1,waitspin=30"),
  14629. ";", {}))
  14630. if (v.containsChar (':'))
  14631. variants.push_back ({ v.upToFirstOccurrenceOf (":", false, false).trim(), v.fromFirstOccurrenceOf (":", false, false).trim() });
  14632. auto shown = std::make_shared<std::vector<juce::Component::SafePointer<juce::Component>>>();
  14633. // every step plays the same part of the song (LYNX_UIPERF_SPINAB_AT: a fraction of the song, default 0.4): the
  14634. // audio work differs from part to part far more than between the variants (a first run without this put the
  14635. // variants of one cycle in different parts and read the parts)
  14636. auto at = std::make_shared<double> (0.0);
  14637. const auto atFraction = juce::jlimit (0.0, 0.95, juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_SPINAB_AT", "0.4").getDoubleValue());
  14638. auto keepPlaying = [this, at] {
  14639. engine->getTransport().songMode = true;
  14640. engine->seek (*at);
  14641. if (! engine->getTransport().playing.load())
  14642. engine->play();
  14643. };
  14644. for (const auto& set : sets)
  14645. {
  14646. const auto name = set.trim();
  14647. run->steps.push_back ({ "spin A/B " + name + " open", [this, name, shown, keepPlaying, at, atFraction] {
  14648. *at = atFraction * engine->getTransport().songEnd.load();
  14649. lynx::NativeEffectWindows::closeAll();
  14650. shown->clear();
  14651. std::vector<juce::Component*> before;
  14652. auto& desktop = juce::Desktop::getInstance();
  14653. for (int i = 0; i < desktop.getNumComponents(); ++i)
  14654. before.push_back (desktop.getComponent (i));
  14655. auto openKind = [this] (lynx::EffectKind kind) {
  14656. auto& so = engine->getSong();
  14657. for (int t = 0; t < (int) so.mixer.size(); ++t)
  14658. for (int k = 0; k < (int) so.mixer[(std::size_t) t].effects.size(); ++k)
  14659. if (so.mixer[(std::size_t) t].effects[(std::size_t) k].kind == kind)
  14660. {
  14661. lynx::NativeEffectWindows::open (*engine, t, k);
  14662. return;
  14663. }
  14664. // (not in the project: on the master, after its effects)
  14665. if (so.mixer.empty() || so.mixer[0].effects.size() >= (std::size_t) lynx::maxEffectSlots)
  14666. return;
  14667. const auto slot = (int) so.mixer[0].effects.size();
  14668. engine->editSong ([kind] (lynx::Song& s2) { s2.mixer[0].effects.push_back (lynx::makeEffectSlot (kind)); }, false);
  14669. engine->dispatchPendingMessages();
  14670. lynx::NativeEffectWindows::open (*engine, 0, slot);
  14671. };
  14672. if (name.containsChar ('G'))
  14673. openKind (lynx::EffectKind::grossBeat);
  14674. if (name.containsChar ('L'))
  14675. openKind (lynx::EffectKind::fruityLimiter);
  14676. if (name.containsChar ('M'))
  14677. openKind (lynx::EffectKind::maximus);
  14678. for (int i = 0; i < desktop.getNumComponents(); ++i)
  14679. if (auto* c = desktop.getComponent (i); std::find (before.begin(), before.end(), c) == before.end())
  14680. shown->emplace_back (c);
  14681. keepPlaying();
  14682. }, {}, 1500, [shown, at] { return " windows of the set: " + juce::String ((int) shown->size()) + ", every step from tick " + juce::String (*at, 0) + "\n"; } });
  14683. for (int c = 0; c < cycles; ++c)
  14684. for (int k = 0; k < (int) variants.size() * 2; ++k)
  14685. {
  14686. // (the variants in turn, starting one further each cycle; hidden / shown swapped every cycle)
  14687. const auto& v = variants[(std::size_t) ((k / 2 + c) % (int) variants.size())];
  14688. const auto visible = ((k % 2) == 1) != ((c % 2) == 1);
  14689. run->steps.push_back ({ "spin A/B " + name + " " + v.name + (visible ? " shown" : " hidden") + " cycle " + juce::String (c + 1),
  14690. [spec = v.spec, visible, shown, keepPlaying] {
  14691. lynx::WorkerPool::tuning().apply (spec.toRawUTF8());
  14692. for (auto& w : *shown)
  14693. if (w != nullptr && w->isVisible() != visible)
  14694. w->setVisible (visible);
  14695. keepPlaying();
  14696. }, {}, 2500 });
  14697. }
  14698. }
  14699. run->steps.push_back ({ "spin A/B close", [this, shown] {
  14700. engine->stop();
  14701. shown->clear();
  14702. lynx::NativeEffectWindows::closeAll();
  14703. lynx::WorkerPool::tuning().apply (juce::SystemStats::getEnvironmentVariable ("LYNX_POOL", "").toRawUTF8());
  14704. }, {}, 500 });
  14705. }
  14706. // round 190iv: the Simple layout (its toolbar) idle and while the song plays
  14707. run->steps.push_back ({ "idle: simple layout, stopped", [this, ui] {
  14708. engine->stop();
  14709. ui->setLayoutStyle (lynx::layoutstyle::Style::simple, false);
  14710. }, {}, 3000 });
  14711. run->steps.push_back ({ "simple layout, song playing", [this] {
  14712. engine->getTransport().songMode = true;
  14713. engine->rewind();
  14714. engine->play();
  14715. }, {}, 3000, [this, ui] {
  14716. engine->stop();
  14717. ui->setLayoutStyle (lynx::layoutstyle::Style::pattern, false);
  14718. return juce::String();
  14719. } });
  14720. // LYNX_UIPERF_ONLY=text: only the steps whose name has that text
  14721. if (const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_UIPERF_ONLY", {}); only.isNotEmpty())
  14722. run->steps.erase (std::remove_if (run->steps.begin(), run->steps.end(), [&only] (const auto& s) { return ! juce::String (s.name).contains (only); }), run->steps.end());
  14723. // let the window draw the project first
  14724. perf = std::move (run);
  14725. juce::Timer::callAfterDelay (1500, [this] { if (perf != nullptr) perf->startTimer (16); });
  14726. }
  14727. // --rtstress: opens the project in the normal window with the saved audio device, plays it from the start for
  14728. // `seconds` and writes the real-time statistics (deadline misses, late device calls, load histogram, heaviest units)
  14729. // --rtstress --backuptest N (round 177d): while the project plays, a device's MIDI clock (10/s) and active sensing
  14730. // (3/s) arrive, and the project counts as changed. N > 0 also forces a backup every N seconds on top of the timed ones.
  14731. // The report tells how many backups were written, when, and what the MIDI counters did.
  14732. struct BackupTest final : juce::Timer
  14733. {
  14734. lynx::AudioEngine* engine = nullptr;
  14735. lynx::MainComponent* ui = nullptr;
  14736. double everyMs = 0.0, startMs = 0.0, lastForcedMs = 0.0, longestCallMs = 0.0;
  14737. int ticks = 0, forced = 0;
  14738. std::uint64_t seenOver = 0, seenNear = 0;
  14739. juce::String misses; // each callback over (or near) its deadline: how long after the last forced backup
  14740. void timerCallback() override
  14741. {
  14742. engine->injectMidiInput (juce::MidiMessage (0xf8));
  14743. if (++ticks % 3 == 0)
  14744. engine->injectMidiInput (juce::MidiMessage (0xfe));
  14745. const auto now = juce::Time::getMillisecondCounterHiRes();
  14746. const auto s = engine->getRtStats().snapshot();
  14747. if (s.overBudget != seenOver || s.nearBudget != seenNear)
  14748. {
  14749. misses << " +" << juce::String ((now - lastForcedMs) / 1000.0, 1) << " s after the last forced backup (or the start): over +"
  14750. << (juce::int64) (s.overBudget - seenOver) << ", near +" << (juce::int64) (s.nearBudget - seenNear) << "\n";
  14751. seenOver = s.overBudget;
  14752. seenNear = s.nearBudget;
  14753. }
  14754. if (everyMs > 0.0 && now - lastForcedMs >= everyMs)
  14755. {
  14756. lastForcedMs = now;
  14757. ++forced;
  14758. ui->backupNowForTest();
  14759. longestCallMs = juce::jmax (longestCallMs, juce::Time::getMillisecondCounterHiRes() - now);
  14760. }
  14761. }
  14762. };
  14763. std::unique_ptr<BackupTest> backupTest;
  14764. void startBackupTest()
  14765. {
  14766. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  14767. const auto at = cli.indexOf ("--backuptest");
  14768. auto* ui = mainWindow != nullptr ? dynamic_cast<lynx::MainComponent*> (mainWindow->getContentComponent()) : nullptr;
  14769. if (at < 0 || ui == nullptr)
  14770. return;
  14771. backupTest = std::make_unique<BackupTest>();
  14772. backupTest->engine = engine.get();
  14773. backupTest->ui = ui;
  14774. backupTest->everyMs = cli[at + 1].getDoubleValue() * 1000.0;
  14775. backupTest->startMs = backupTest->lastForcedMs = juce::Time::getMillisecondCounterHiRes();
  14776. // (the project counts as changed, so a backup has something to write; the Master's fader is down, so a long run
  14777. // makes no sound: everything else is processed as usual)
  14778. engine->editSong ([] (lynx::Song& s) {
  14779. if (! s.mixer.empty())
  14780. s.mixer[0].volume = 0.0f;
  14781. });
  14782. backupTest->startTimer (100);
  14783. }
  14784. juce::String finishBackupTest()
  14785. {
  14786. if (backupTest == nullptr)
  14787. return {};
  14788. backupTest->stopTimer();
  14789. juce::String text;
  14790. const auto played = engine->getMidiPlayed();
  14791. text << " backup test: MIDI light count " << (int) engine->getMidiActivity() << ", played count " << (int) played << " (clock and active sensing only)\n";
  14792. text << " backup test: " << backupTest->forced << " forced, longest forced call on the message thread "
  14793. << juce::String (backupTest->longestCallMs, 1) << " ms\n";
  14794. if (backupTest->misses.isNotEmpty())
  14795. text << " backup test: callbacks over or near the deadline (seen within 100 ms):\n" << backupTest->misses;
  14796. auto files = lynx::autosaveFolder().findChildFiles (juce::File::findFiles, false, "*.lynx");
  14797. text << " backup test: " << files.size() << " file(s) in the backup folder:\n";
  14798. for (const auto& f : files)
  14799. text << " " << juce::String ((f.getLastModificationTime().toMilliseconds() - juce::Time::getCurrentTime().toMilliseconds()) / 1000) << " s before the end: "
  14800. << f.getFileName() << " (" << f.getSize() << " bytes)\n";
  14801. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 1));
  14802. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  14803. text << " backup test: after a played note, played count " << (int) engine->getMidiPlayed() << "\n";
  14804. backupTest.reset();
  14805. return text;
  14806. }
  14807. void runRealtimeStress (const juce::File& project, const juce::File& report, double seconds, int bufferSize,
  14808. const juce::String& deviceType, const juce::String& deviceName, const juce::String& recordTo = {})
  14809. {
  14810. startupOptions = lynx::StartupOptions::load();
  14811. engine = std::make_unique<lynx::AudioEngine>();
  14812. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  14813. crashEngine = engine.get();
  14814. // the user's saved device stays as it was: this run's choices are undone before quitting
  14815. savedDeviceState = engine->getDeviceManager().createStateXml();
  14816. auto& devices = engine->getDeviceManager();
  14817. const auto driverFile = addDriverFileDeviceType();
  14818. const auto type = deviceType.isEmpty() && driverFile ? juce::String (lynx::dllAsioTypeName) : deviceType;
  14819. if (type.isNotEmpty() && devices.getCurrentAudioDeviceType() != type)
  14820. devices.setCurrentAudioDeviceType (type, true);
  14821. if (bufferSize > 0 || deviceName.isNotEmpty())
  14822. {
  14823. auto setup = devices.getAudioDeviceSetup();
  14824. if (bufferSize > 0)
  14825. setup.bufferSize = bufferSize;
  14826. if (deviceName.isNotEmpty())
  14827. setup.outputDeviceName = deviceName;
  14828. const auto error = devices.setAudioDeviceSetup (setup, true);
  14829. if (error.isNotEmpty())
  14830. report.replaceWithText ("device error: " + error + "\n");
  14831. }
  14832. createMainWindow();
  14833. if (! juce::JUCEApplication::getCommandLineParameters().contains ("--no-window")) // --no-window: is it the UI?
  14834. mainWindow->reveal();
  14835. juce::String error;
  14836. auto ok = false;
  14837. const auto loadStart = juce::Time::getMillisecondCounterHiRes();
  14838. if (project.hasFileExtension ("flp"))
  14839. ok = engine->importFlpFile (project, error);
  14840. else if (auto song = lynx::ProjectFile::load (project, error))
  14841. {
  14842. engine->setSong (std::move (*song));
  14843. ok = true;
  14844. }
  14845. const auto loadMs = juce::Time::getMillisecondCounterHiRes() - loadStart;
  14846. if (! ok)
  14847. {
  14848. report.replaceWithText ("project: " + project.getFullPathName() + "\nresult=ERROR " + error + "\n");
  14849. restoreSavedDeviceState();
  14850. setApplicationReturnValue (1);
  14851. quit();
  14852. return;
  14853. }
  14854. if (recordTo.isNotEmpty())
  14855. engine->setAudioRecordingArmed (true); // opens the input of the driver
  14856. // let the window draw the project, then play from the start with fresh statistics
  14857. juce::Timer::callAfterDelay (1500, [this, project, report, seconds, loadMs, recordTo] {
  14858. if (engine == nullptr)
  14859. return;
  14860. engine->stop();
  14861. engine->rewind();
  14862. engine->getRtStats().reset();
  14863. engine->takeUiPulse();
  14864. if (recordTo.isNotEmpty())
  14865. engine->setRecording (true);
  14866. // --log folder: the audio logger records what the Master plays during the run (realtime vs export checks)
  14867. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  14868. if (const auto at = cli.indexOf ("--log"); at >= 0 && at + 1 < cli.size())
  14869. engine->getAudioLogger().start (juce::File (cli[at + 1].unquoted()), engine->getDeviceManager().getCurrentAudioDevice() != nullptr
  14870. ? engine->getDeviceManager().getCurrentAudioDevice()->getCurrentSampleRate() : 44100.0);
  14871. engine->play();
  14872. startBackupTest();
  14873. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, project, report, seconds, loadMs, recordTo] {
  14874. if (engine == nullptr)
  14875. return;
  14876. const auto backupReport = finishBackupTest();
  14877. engine->stop();
  14878. juce::String recording;
  14879. if (engine->getAudioLogger().isLogging())
  14880. {
  14881. recording << " logged: " << engine->getAudioLogger().currentFile().getFullPathName() << "\n";
  14882. engine->getAudioLogger().stop();
  14883. }
  14884. if (recordTo.isNotEmpty())
  14885. recording = finishStressTake (juce::File (recordTo), seconds);
  14886. const auto& cli = juce::JUCEApplication::getCommandLineParameterArray();
  14887. const auto s = engine->getRtStats().snapshot();
  14888. juce::String text;
  14889. text << "project: " << project.getFullPathName() << "\n"
  14890. << "LYNX " << getApplicationVersion() << ", " << juce::SystemStats::getOperatingSystemName() << ", "
  14891. << juce::SystemStats::getNumCpus() << " logical CPUs (" << juce::SystemStats::getNumPhysicalCpus() << " cores), "
  14892. << juce::SystemStats::getCpuModel() << "\n"
  14893. << "load " << juce::String (loadMs / 1000.0, 1) << " s, played " << juce::String (seconds, 0) << " s\n"
  14894. << engine->describeRealtime();
  14895. const auto pulse = engine->takeUiPulse();
  14896. text << " UI: the 30 Hz engine timer ran " << pulse.calls << " times (" << juce::String (pulse.calls / seconds, 1)
  14897. << "/s), longest gap " << juce::String (pulse.maxGapMs, 0) << " ms" << (mainWindow == nullptr || ! mainWindow->isVisible() ? " (window hidden)" : "") << "\n";
  14898. text << " load histogram (share of the deadline: callbacks):";
  14899. for (std::size_t b = 0; b < s.histogram.size(); ++b)
  14900. if (s.histogram[b] > 0)
  14901. text << " " << (int) (b * 10) << (b + 1 == s.histogram.size() ? juce::String ("+") : "-" + juce::String ((int) (b * 10 + 10))) << "%:" << (juce::int64) s.histogram[b];
  14902. text << "\n";
  14903. text << recording << backupReport;
  14904. // --settingsshot file.png (round 161): Options > Audio settings of this run's device, as a picture
  14905. if (const auto at = cli.indexOf ("--settingsshot"); at >= 0 && at + 1 < cli.size())
  14906. {
  14907. auto page = lynx::makeSettingsPanel (*engine, lynx::SettingsPage::audio);
  14908. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  14909. {
  14910. juce::Graphics g (image);
  14911. g.fillAll (lynx::theme::panel);
  14912. page->paintEntireComponent (g, false);
  14913. }
  14914. const juce::File shot (cli[at + 1].unquoted());
  14915. shot.deleteFile();
  14916. if (auto out = shot.createOutputStream())
  14917. juce::PNGImageFormat().writeImageToStream (image, *out);
  14918. }
  14919. text << "result=" << (s.callbacks == 0 ? "ERROR no audio callbacks" : s.overBudget == 0 && s.lateCalls == 0 ? "OK" : "GLITCHES") << "\n";
  14920. report.replaceWithText (text);
  14921. restoreSavedDeviceState();
  14922. setApplicationReturnValue (s.callbacks == 0 ? 1 : 0);
  14923. quit();
  14924. });
  14925. });
  14926. }
  14927. // --bendrectest (round 167a): see the command line above
  14928. void runBendRecordTest (const juce::File& report, bool songMode)
  14929. {
  14930. engine = std::make_unique<lynx::AudioEngine>();
  14931. auto text = std::make_shared<juce::String>();
  14932. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  14933. auto finish = [this] (int code) {
  14934. setApplicationReturnValue (code);
  14935. quit();
  14936. };
  14937. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  14938. if (device == nullptr)
  14939. {
  14940. step ("result=ERROR no audio device");
  14941. finish (1);
  14942. return;
  14943. }
  14944. step ("device=" + device->getTypeName() + " | " + device->getName() + " | mode " + (songMode ? "song" : "pattern"));
  14945. auto song = lynx::Song::makeDefault();
  14946. song.bpm = 120.0;
  14947. song.mode = songMode ? lynx::PlayMode::song : lynx::PlayMode::pattern;
  14948. engine->setSong (std::move (song));
  14949. auto o = engine->getRecordOptions();
  14950. o.mode = lynx::RecordMode::overdub;
  14951. o.recordNotes = true;
  14952. o.recordAutomation = true;
  14953. o.countInBars = 0;
  14954. o.waitForInput = false;
  14955. o.quantiseAutomation = false;
  14956. o.punchLoopRegion = false;
  14957. o.preRollBars = o.postRollBars = 0;
  14958. engine->setRecordOptions (o);
  14959. engine->stop();
  14960. engine->rewind();
  14961. engine->setRecording (true);
  14962. engine->startPlayback();
  14963. // 2 s of wheel at ~100 messages a second: 0 → +1 (0.5 s), +1 → −1 (1 s), −1 → 0 (0.5 s)
  14964. auto sent = std::make_shared<std::vector<std::pair<double, float>>>();
  14965. auto t0 = std::make_shared<double> (juce::Time::getMillisecondCounterHiRes());
  14966. engine->injectMidiInput (juce::MidiMessage::noteOn (1, 60, (juce::uint8) 100));
  14967. auto tick = std::make_shared<std::function<void()>>();
  14968. *tick = [this, sent, t0, tick, step, finish, songMode] {
  14969. if (engine == nullptr)
  14970. return;
  14971. const auto ms = juce::Time::getMillisecondCounterHiRes() - *t0;
  14972. if (ms < 2000.0)
  14973. {
  14974. const auto x = ms / 1000.0;
  14975. 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);
  14976. const auto wheel = juce::jlimit (0, 16383, 8192 + juce::roundToInt (v * 8191.0f));
  14977. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, wheel));
  14978. sent->push_back ({ ms, (float) (wheel - 8192) / 8192.0f });
  14979. juce::Timer::callAfterDelay (10, *tick);
  14980. return;
  14981. }
  14982. engine->injectMidiInput (juce::MidiMessage::pitchWheel (1, 8192));
  14983. engine->injectMidiInput (juce::MidiMessage::noteOff (1, 60));
  14984. juce::Timer::callAfterDelay (400, [this, sent, step, finish, songMode] {
  14985. if (engine == nullptr)
  14986. return;
  14987. engine->stop();
  14988. juce::Timer::callAfterDelay (600, [this, sent, step, finish, songMode] {
  14989. if (engine == nullptr)
  14990. return;
  14991. engine->setRecording (false);
  14992. const auto& s = engine->getSong();
  14993. // the channel's pitch bend (MIDI channel 1), recorded as a lane or a clip
  14994. std::vector<std::pair<std::int64_t, float>> got;
  14995. juce::String where = "nothing";
  14996. for (const auto& a : s.automations)
  14997. if (a.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (a.target.param))
  14998. {
  14999. where = "automation clip \"" + juce::String (a.name) + "\"";
  15000. for (const auto& pt : a.points)
  15001. got.push_back ({ pt.tick, pt.value });
  15002. }
  15003. for (const auto& p : s.patterns)
  15004. for (const auto& lane : p.events)
  15005. if (lane.target.kind == lynx::AutomationTargetKind::channelParam && lynx::midictl::isPitchBend (lane.target.param))
  15006. {
  15007. where = "pattern \"" + juce::String (p.name) + "\" event lane";
  15008. for (const auto& e : lane.events)
  15009. got.push_back ({ e.tick, e.value });
  15010. }
  15011. int notes = 0;
  15012. for (const auto& p : s.patterns)
  15013. notes += (int) p.notes.size();
  15014. float lo = 1.0f, hi = 0.0f;
  15015. for (const auto& [t, v] : got)
  15016. lo = std::min (lo, v), hi = std::max (hi, v);
  15017. // ticks: in order, spread over the ~2 s sweep (8 beats of 96 ticks at 120 bpm ≈ 4 beats)
  15018. const auto span = got.empty() ? 0 : got.back().first - got.front().first;
  15019. const auto sorted = std::is_sorted (got.begin(), got.end(), [] (const auto& a, const auto& b) { return a.first < b.first; });
  15020. step ("sent=" + juce::String ((int) sent->size()) + " wheel messages over 2 s");
  15021. step ("recorded=" + juce::String ((int) got.size()) + " points in " + where + ", value " + juce::String (lo, 3) + " .. "
  15022. + juce::String (hi, 3) + " (0.5 = centre), ticks " + juce::String (span) + " apart, " + (sorted ? "in order" : "OUT OF ORDER")
  15023. + ", notes " + juce::String (notes));
  15024. if (! got.empty())
  15025. step ("last=" + juce::String (got.back().second, 3));
  15026. // song mode: a clip over the take, ending back at the centre. Pattern mode: the take loops the 1-bar pattern
  15027. // (4.6 beats of take), so the lane spans the bar and the last wheel message (the centre) lands inside it
  15028. const auto centred = std::any_of (got.begin(), got.end(), [] (const auto& p) { return std::abs (p.second - 0.5f) < 0.02f; });
  15029. const auto ok = got.size() >= 20 && hi > 0.97f && lo < 0.03f && sorted && notes >= 1
  15030. && (songMode ? span > lynx::ppq * 3 && span < lynx::ppq * 6 && std::abs (got.back().second - 0.5f) < 0.02f
  15031. : span > lynx::ppq * 2 && span <= lynx::ppq * 4 && centred);
  15032. step (ok ? "result=OK" : "result=FAILED");
  15033. finish (ok ? 0 : 1);
  15034. });
  15035. });
  15036. };
  15037. juce::Timer::callAfterDelay (300, *tick);
  15038. }
  15039. // --countinrectest (round 170d): see the command line above.
  15040. void runCountInRecordTest (const juce::File& report)
  15041. {
  15042. engine = std::make_unique<lynx::AudioEngine>();
  15043. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  15044. struct StandIn final : juce::AudioIODevice
  15045. {
  15046. StandIn() : juce::AudioIODevice ("countin", "test") {}
  15047. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  15048. juce::StringArray getInputChannelNames() override { return {}; }
  15049. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  15050. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  15051. int getDefaultBufferSize() override { return 512; }
  15052. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  15053. void close() override {}
  15054. bool isOpen() override { return true; }
  15055. void start (juce::AudioIODeviceCallback*) override {}
  15056. void stop() override {}
  15057. bool isPlaying() override { return true; }
  15058. juce::String getLastError() override { return {}; }
  15059. int getCurrentBufferSizeSamples() override { return 512; }
  15060. double getCurrentSampleRate() override { return 48000.0; }
  15061. int getCurrentBitDepth() override { return 32; }
  15062. juce::BigInteger getActiveOutputChannels() const override
  15063. {
  15064. juce::BigInteger b;
  15065. b.setRange (0, 2, true);
  15066. return b;
  15067. }
  15068. juce::BigInteger getActiveInputChannels() const override { return {}; }
  15069. int getOutputLatencyInSamples() override { return 256; }
  15070. int getInputLatencyInSamples() override { return 0; }
  15071. };
  15072. auto device = std::make_shared<StandIn>();
  15073. auto text = std::make_shared<juce::String>();
  15074. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  15075. auto finish = [this] (int code) {
  15076. setApplicationReturnValue (code);
  15077. quit();
  15078. };
  15079. constexpr std::int64_t bar = 4 * lynx::ppq; // 120 BPM, 4/4
  15080. lynx::Song song; // (as --cliplooptest: one synth channel on insert 1, an empty pattern)
  15081. song.bpm = 120.0;
  15082. song.mixer = lynx::Song::defaultMixer (2);
  15083. song.channels.resize (1);
  15084. song.channels[0].mixerTrack = 1;
  15085. song.patterns.emplace_back();
  15086. song.mode = lynx::PlayMode::song;
  15087. song.currentPattern = 0;
  15088. engine->setSong (song);
  15089. engine->getTransport().metronome.store (true);
  15090. auto o = engine->getRecordOptions();
  15091. o.mode = lynx::RecordMode::overdub;
  15092. o.countInBars = 1;
  15093. o.catchWindow = lynx::ppq / 4;
  15094. o.compensateOutput = true;
  15095. o.recordNotes = true;
  15096. o.recordAudio = false;
  15097. o.recordAutomation = false;
  15098. o.waitForInput = false;
  15099. o.quantise = 0;
  15100. o.placeSongClip = true;
  15101. o.recordingMarkers = false;
  15102. o.punchLoopRegion = false;
  15103. o.preRollBars = o.postRollBars = 0;
  15104. engine->setRecordOptions (o);
  15105. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  15106. 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");
  15107. // an event heard at output sample `heard` (counted from the first block after Play), sent as MIDI input
  15108. struct Event
  15109. {
  15110. std::int64_t heard;
  15111. juce::MidiMessage message;
  15112. };
  15113. struct Pass
  15114. {
  15115. std::vector<float> out;
  15116. std::vector<Event> events;
  15117. std::int64_t playingAt = -1; // the first sample of the block the song started in
  15118. int block = 0, blocks = 0;
  15119. std::function<void()> done;
  15120. };
  15121. constexpr int n = 512;
  15122. constexpr double rate = 48000.0;
  15123. // one pass: the take recorded from bar 3, `blocks` blocks driven by hand, 8 at a time between the engine's timer
  15124. // ticks (the take is committed there); then stopped and its results left to the timer
  15125. auto runPass = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  15126. *runPass = [this] (std::shared_ptr<Pass> pass) {
  15127. auto& cb = engine->deviceCallback();
  15128. std::vector<float> l (n), r (n);
  15129. float* outs[] = { l.data(), r.data() };
  15130. juce::AudioIODeviceCallbackContext context;
  15131. if (pass->block == 0)
  15132. {
  15133. engine->stop();
  15134. engine->seek ((double) (2 * bar));
  15135. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context); // (the seek, stopped)
  15136. engine->setRecording (true);
  15137. engine->startPlayback(); // the count-in starts
  15138. }
  15139. for (int k = 0; k < 8 && pass->block < pass->blocks; ++k, ++pass->block)
  15140. {
  15141. // the events heard in this block: stamped the way the engine's clock maps time to heard samples
  15142. const auto blockStart = (std::int64_t) pass->block * n;
  15143. const auto clock = engine->liveClock();
  15144. const auto compMs = 1000.0 * (n + 256) / rate;
  15145. for (auto& e : pass->events)
  15146. if (e.heard >= blockStart && e.heard < blockStart + n)
  15147. {
  15148. auto m = e.message;
  15149. m.setTimeStamp ((clock.timeMs + compMs + (double) (e.heard - blockStart) * 1000.0 / rate) * 0.001);
  15150. engine->injectMidiInput (m);
  15151. }
  15152. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, n, context);
  15153. pass->out.insert (pass->out.end(), l.begin(), l.end());
  15154. if (pass->playingAt < 0 && engine->getTransport().playing.load())
  15155. pass->playingAt = blockStart;
  15156. }
  15157. };
  15158. // (the recursion through the message loop; written out so each step lets the engine's timer run)
  15159. auto drive = std::make_shared<std::function<void (std::shared_ptr<Pass>)>>();
  15160. *drive = [this, runPass, drive, device] (std::shared_ptr<Pass> pass) { // (the stand-in lives while the passes run)
  15161. if (engine == nullptr)
  15162. return;
  15163. (*runPass) (pass);
  15164. if (pass->block < pass->blocks)
  15165. {
  15166. juce::Timer::callAfterDelay (40, [pass, drive] { (*drive) (pass); });
  15167. return;
  15168. }
  15169. engine->stop();
  15170. juce::Timer::callAfterDelay (300, [this, pass] {
  15171. if (engine == nullptr)
  15172. return;
  15173. engine->setRecording (false);
  15174. juce::Timer::callAfterDelay (200, [pass] { pass->done(); });
  15175. });
  15176. };
  15177. auto onsets = [] (const std::vector<float>& out) {
  15178. std::vector<std::int64_t> at;
  15179. std::int64_t last = -100000;
  15180. for (std::size_t i = 0; i < out.size(); ++i)
  15181. if (std::abs (out[i]) > 0.02f && (std::int64_t) i - last > 4000)
  15182. {
  15183. at.push_back ((std::int64_t) i);
  15184. last = (std::int64_t) i;
  15185. }
  15186. else if (std::abs (out[i]) > 0.02f)
  15187. last = (std::int64_t) i;
  15188. return at;
  15189. };
  15190. // the graph is (re)built on the message thread: start once it has settled
  15191. juce::Timer::callAfterDelay (1500, [this, step, finish, drive, onsets] {
  15192. if (engine == nullptr)
  15193. return;
  15194. auto first = std::make_shared<Pass>();
  15195. first->blocks = (int) (rate * 18.0 / n); // count-in + 8 bars
  15196. first->done = [this, first, step, finish, drive, onsets] {
  15197. const auto clicks = onsets (first->out);
  15198. juce::String list;
  15199. for (std::size_t i = 0; i < std::min<std::size_t> (clicks.size(), 8); ++i)
  15200. list << clicks[i] << " ";
  15201. step ("pass 1: clicks heard at samples " + list + "…, the song started in the block at " + juce::String (first->playingAt));
  15202. // the bar-3 downbeat: the click at the block the song started in
  15203. std::int64_t down = -1;
  15204. for (auto c : clicks)
  15205. if (std::abs (c - first->playingAt) < n)
  15206. down = c;
  15207. if (down < 0 || engine->getSong().patterns[0].notes.size() != 0)
  15208. {
  15209. step ("result=FAILED no downbeat click found (or notes recorded without input)");
  15210. finish (1);
  15211. return;
  15212. }
  15213. const auto ms = [down] (double t) { return down + (std::int64_t) std::llround (t * rate / 1000.0); };
  15214. auto second = std::make_shared<Pass>();
  15215. second->blocks = first->blocks;
  15216. auto add = [&second] (std::int64_t at, int key, bool on) {
  15217. second->events.push_back ({ at, on ? juce::MidiMessage::noteOn (1, key, (juce::uint8) 100) : juce::MidiMessage::noteOff (1, key) });
  15218. };
  15219. for (int key : { 60, 64, 67 }) // the chord, 15 ms early, held half a second
  15220. {
  15221. add (ms (-15.0), key, true);
  15222. add (ms (500.0), key, false);
  15223. }
  15224. add (ms (-1500.0), 62, true); // beat 2 of the count-in bar (bar 2)
  15225. add (ms (-1250.0), 62, false);
  15226. add (ms (503.0), 77, true); // 3 ms after beat 2
  15227. add (ms (603.0), 77, false);
  15228. for (int b = 1; b <= 6; ++b) // a note a bar ("it stopped after two bars")
  15229. {
  15230. add (ms (b * 2000.0), 70 + b, true);
  15231. add (ms (b * 2000.0 + 250.0), 70 + b, false);
  15232. }
  15233. second->done = [this, step, finish] {
  15234. const auto& s = engine->getSong();
  15235. const auto& p = s.patterns[0];
  15236. const lynx::Clip* clip = nullptr;
  15237. for (const auto& c : s.playlist)
  15238. if (c.kind == lynx::ClipKind::pattern && c.pattern == 0)
  15239. clip = &c;
  15240. const auto origin = clip != nullptr ? clip->start - clip->offset : -1;
  15241. step ("pass 2: " + juce::String ((int) p.notes.size()) + " notes recorded, clip at " + juce::String (clip != nullptr ? clip->start : -1));
  15242. auto ok = clip != nullptr && origin == bar && p.notes.size() == 11;
  15243. // where each one was heard (song ticks): 0.5 ms = ~1 tick
  15244. const std::vector<std::pair<int, double>> want = { { 60, 2.0 * bar }, { 64, 2.0 * bar }, { 67, 2.0 * bar },
  15245. { 62, 2.0 * bar - 3 * lynx::ppq }, { 77, 2.0 * bar + lynx::ppq + 3.0 * 1.92 },
  15246. { 71, 3.0 * bar }, { 72, 4.0 * bar }, { 73, 5.0 * bar },
  15247. { 74, 6.0 * bar }, { 75, 7.0 * bar }, { 76, 8.0 * bar } };
  15248. for (const auto& [key, tick] : want)
  15249. {
  15250. const lynx::Note* found = nullptr;
  15251. for (const auto& note : p.notes)
  15252. if (note.key == key)
  15253. found = &note;
  15254. const auto at = found != nullptr ? (double) (origin + found->start) : -1.0;
  15255. const auto good = found != nullptr && std::abs (at - tick) <= 2.0;
  15256. ok = ok && good;
  15257. step ("key " + juce::String (key) + ": heard at tick " + juce::String (tick, 2) + ", recorded at " + juce::String (at, 0)
  15258. + (good ? " ok" : " WRONG"));
  15259. }
  15260. const auto* chord = [&p] () -> const lynx::Note* {
  15261. for (const auto& note : p.notes)
  15262. if (note.key == 60)
  15263. return &note;
  15264. return nullptr;
  15265. }();
  15266. if (chord != nullptr)
  15267. step ("chord length " + juce::String (chord->length) + " ticks (caught 15 ms early, released 500 ms after bar 3: 960)");
  15268. step (ok ? "result=OK" : "result=FAILED");
  15269. finish (ok ? 0 : 1);
  15270. };
  15271. (*drive) (second);
  15272. };
  15273. (*drive) (first);
  15274. });
  15275. }
  15276. // --cliplooptest (round 167q): see the command line above.
  15277. // --slicexedittest (round 190aj): see the command line above
  15278. void runDirectWaveEditTest (const juce::String& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
  15279. {
  15280. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15281. juce::StringArray lines;
  15282. {
  15283. lynx::AudioEngine offline (false);
  15284. lynx::MainComponent ui (offline, false);
  15285. ui.setSize (1280, 720);
  15286. if (project == "new")
  15287. {
  15288. if (auto c = lynx::natives::makeChannel (lynx::InstrumentKind::directwave, {}))
  15289. offline.editSong ([c] (lynx::Song& s) { s.channels.push_back (*c); });
  15290. }
  15291. else
  15292. ui.openFile (juce::File (project));
  15293. offline.dispatchPendingMessages();
  15294. int channel = -1;
  15295. for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
  15296. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::directwave)
  15297. channel = c;
  15298. if (channel < 0)
  15299. lines.add ("no DirectWave channel in " + project);
  15300. else
  15301. {
  15302. auto panel = lynx::makeChannelSettingsPanel (offline, channel);
  15303. juce::Component frame;
  15304. frame.setSize (panel->getWidth(), panel->getHeight());
  15305. frame.setOpaque (true);
  15306. frame.addAndMakeVisible (*panel);
  15307. panel->setTopLeftPosition (0, 0);
  15308. offline.dispatchPendingMessages();
  15309. juce::StringArray commands;
  15310. script.readLines (commands);
  15311. for (const auto& raw : commands)
  15312. {
  15313. const auto command = raw.trim();
  15314. if (command.isEmpty() || command.startsWith ("#"))
  15315. {
  15316. lines.add (command);
  15317. continue;
  15318. }
  15319. if (command.startsWith ("shot "))
  15320. {
  15321. frame.setSize (panel->getWidth(), panel->getHeight());
  15322. // (round 190jd: at the shot scale, --shot-scale / LYNX_SHOT_SCALE, with its suffix; scale 1 = the same pixels)
  15323. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  15324. const auto file = lynx::shot::file (juce::File (prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png"));
  15325. file.deleteFile();
  15326. juce::PNGImageFormat png;
  15327. if (auto out = file.createOutputStream())
  15328. png.writeImageToStream (image, *out);
  15329. lines.add (command + " -> " + file.getFileName());
  15330. continue;
  15331. }
  15332. if (command.startsWith ("savestate "))
  15333. {
  15334. const auto& st = offline.getSong().channels[(std::size_t) channel].pluginState;
  15335. juce::File (command.fromFirstOccurrenceOf (" ", false, false).trim()).replaceWithData (st.data(), st.size());
  15336. lines.add (command + " -> " + juce::String ((int) st.size()) + " bytes");
  15337. continue;
  15338. }
  15339. const auto result = lynx::directWaveEditorTest (*panel, command);
  15340. offline.dispatchPendingMessages();
  15341. lines.add (command + " -> " + result);
  15342. }
  15343. }
  15344. }
  15345. report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
  15346. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  15347. quit();
  15348. }
  15349. void runSlicexEditTest (const juce::File& project, const juce::File& script, const juce::File& report, const juce::String& prefix)
  15350. {
  15351. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  15352. juce::StringArray lines;
  15353. {
  15354. lynx::AudioEngine offline (false);
  15355. lynx::MainComponent ui (offline, false);
  15356. ui.setSize (1280, 720);
  15357. ui.openFile (project);
  15358. offline.dispatchPendingMessages();
  15359. int channel = -1;
  15360. for (int c = 0; c < (int) offline.getSong().channels.size() && channel < 0; ++c)
  15361. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  15362. channel = c;
  15363. if (channel < 0)
  15364. lines.add ("no Slicex channel in " + project.getFullPathName());
  15365. else
  15366. {
  15367. auto panel = lynx::makeChannelSettingsPanel (offline, channel);
  15368. juce::Component frame;
  15369. frame.setSize (panel->getWidth(), panel->getHeight());
  15370. frame.setOpaque (true);
  15371. frame.addAndMakeVisible (*panel);
  15372. panel->setTopLeftPosition (0, 0);
  15373. offline.dispatchPendingMessages();
  15374. juce::StringArray commands;
  15375. script.readLines (commands);
  15376. for (const auto& raw : commands)
  15377. {
  15378. const auto command = raw.trim();
  15379. if (command.isEmpty() || command.startsWith ("#"))
  15380. {
  15381. lines.add (command);
  15382. continue;
  15383. }
  15384. if (command.startsWith ("shot "))
  15385. {
  15386. frame.setSize (panel->getWidth(), panel->getHeight()); // (round 190hg: the display modes resize the editor)
  15387. // (round 190jd: at the shot scale, --shot-scale / LYNX_SHOT_SCALE, with its suffix; scale 1 = the same pixels)
  15388. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  15389. const auto file = lynx::shot::file (juce::File (prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png"));
  15390. file.deleteFile();
  15391. juce::PNGImageFormat png;
  15392. if (auto out = file.createOutputStream())
  15393. png.writeImageToStream (image, *out);
  15394. lines.add (command + " -> " + file.getFileName());
  15395. continue;
  15396. }
  15397. if (command.startsWith ("menushot ")) // round 190jd: the deck's Snap menu as a picture
  15398. {
  15399. const auto file = prefix + command.fromFirstOccurrenceOf (" ", false, false).trim() + ".png";
  15400. saveMenus (juce::StringArray { "Slicex deck: Snap" }, std::vector<juce::PopupMenu> { lynx::slicexSnapMenuForSnapshot (*panel) }, file);
  15401. lines.add (command + " -> " + juce::File (file).getFileName());
  15402. continue;
  15403. }
  15404. const auto result = lynx::slicexEditorTest (*panel, command);
  15405. offline.dispatchPendingMessages();
  15406. lines.add (command + " -> " + result);
  15407. }
  15408. }
  15409. }
  15410. report.replaceWithText (lines.joinIntoString ("\n") + "\nresult=DONE\n");
  15411. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  15412. quit();
  15413. }
  15414. // --slicexkeytest (round 190ac): see the command line above
  15415. void runSlicexKeyTest (const juce::File& report)
  15416. {
  15417. engine = std::make_unique<lynx::AudioEngine>();
  15418. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  15419. struct StandIn final : juce::AudioIODevice
  15420. {
  15421. StandIn() : juce::AudioIODevice ("slicexkey", "test") {}
  15422. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  15423. juce::StringArray getInputChannelNames() override { return {}; }
  15424. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  15425. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  15426. int getDefaultBufferSize() override { return 512; }
  15427. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  15428. void close() override {}
  15429. bool isOpen() override { return true; }
  15430. void start (juce::AudioIODeviceCallback*) override {}
  15431. void stop() override {}
  15432. bool isPlaying() override { return true; }
  15433. juce::String getLastError() override { return {}; }
  15434. int getCurrentBufferSizeSamples() override { return 512; }
  15435. double getCurrentSampleRate() override { return 48000.0; }
  15436. int getCurrentBitDepth() override { return 32; }
  15437. juce::BigInteger getActiveOutputChannels() const override
  15438. {
  15439. juce::BigInteger b;
  15440. b.setRange (0, 2, true);
  15441. return b;
  15442. }
  15443. juce::BigInteger getActiveInputChannels() const override { return {}; }
  15444. int getOutputLatencyInSamples() override { return 0; }
  15445. int getInputLatencyInSamples() override { return 0; }
  15446. };
  15447. auto device = std::make_shared<StandIn>();
  15448. auto text = std::make_shared<juce::String>();
  15449. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  15450. // 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
  15451. // × region number), so the region a key played can be read from the output
  15452. constexpr int rate = 48000, regionFrames = rate / 4;
  15453. const auto wavFile = report.getSiblingFile ("slicexkey-deck.wav");
  15454. {
  15455. juce::MemoryOutputStream w;
  15456. auto chunk = [&w] (const char* id, const juce::MemoryBlock& body) {
  15457. w.write (id, 4);
  15458. w.writeInt ((int) body.getSize());
  15459. w.write (body.getData(), body.getSize());
  15460. };
  15461. juce::MemoryOutputStream fmt, data, cue;
  15462. fmt.writeShort (1);
  15463. fmt.writeShort (1);
  15464. fmt.writeInt (rate);
  15465. fmt.writeInt (rate * 2);
  15466. fmt.writeShort (2);
  15467. fmt.writeShort (16);
  15468. for (int i = 0; i < 4 * regionFrames; ++i)
  15469. data.writeShort ((short) std::lround (12000.0 * std::sin (juce::MathConstants<double>::twoPi * 200.0 * (double) (i / regionFrames + 1) * (double) i / rate)));
  15470. cue.writeInt (4);
  15471. for (int k = 0; k < 4; ++k)
  15472. {
  15473. cue.writeInt (k + 1);
  15474. cue.writeInt (k * regionFrames);
  15475. cue.write ("data", 4);
  15476. cue.writeInt (0);
  15477. cue.writeInt (0);
  15478. cue.writeInt (k * regionFrames);
  15479. }
  15480. juce::MemoryOutputStream riff;
  15481. riff.write ("WAVE", 4);
  15482. w.reset();
  15483. chunk ("fmt ", fmt.getMemoryBlock());
  15484. chunk ("data", data.getMemoryBlock());
  15485. chunk ("cue ", cue.getMemoryBlock());
  15486. riff.write (w.getData(), w.getDataSize());
  15487. juce::MemoryOutputStream file;
  15488. file.write ("RIFF", 4);
  15489. file.writeInt ((int) riff.getDataSize());
  15490. file.write (riff.getData(), riff.getDataSize());
  15491. wavFile.replaceWithData (file.getData(), file.getDataSize());
  15492. }
  15493. lynx::Song song;
  15494. song.bpm = 120.0;
  15495. song.mixer = lynx::Song::defaultMixer (2);
  15496. song.channels.resize (1);
  15497. auto& channel = song.channels[0];
  15498. channel.instrument = lynx::InstrumentKind::slicex;
  15499. channel.mixerTrack = 1;
  15500. channel.samplePath = wavFile.getFullPathName().toStdString();
  15501. {
  15502. auto state = lynx::slicex::fresh();
  15503. lynx::slicex::setDeckFile (state, 0, channel.samplePath, 4);
  15504. lynx::slicex::setDeckBeats (state, 0, 0.0, 2.0);
  15505. channel.pluginState = lynx::slicex::write (state);
  15506. }
  15507. song.patterns.emplace_back();
  15508. engine->setSong (song);
  15509. auto& callback = engine->deviceCallback();
  15510. callback.audioDeviceAboutToStart (device.get());
  15511. 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");
  15512. juce::Timer::callAfterDelay (2000, [this, device, step] {
  15513. if (engine == nullptr)
  15514. return;
  15515. auto& cb = engine->deviceCallback();
  15516. auto pump = [&cb] (int blocks) {
  15517. std::vector<float> l (512), r (512), out;
  15518. float* outs[] = { l.data(), r.data() };
  15519. juce::AudioIODeviceCallbackContext context;
  15520. for (int k = 0; k < blocks; ++k)
  15521. {
  15522. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  15523. out.insert (out.end(), l.begin(), l.end());
  15524. }
  15525. return out;
  15526. };
  15527. auto rms = [] (const std::vector<float>& x, int from, int count) {
  15528. double sum = 0.0;
  15529. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  15530. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  15531. return std::sqrt (sum / juce::jmax (1, count));
  15532. };
  15533. // the tone's frequency from its rising zero crossings over a stretch
  15534. auto hertz = [] (const std::vector<float>& x, int from, int count) {
  15535. int crossings = 0, first = -1, last = -1;
  15536. for (int i = from + 1; i < from + count && i < (int) x.size(); ++i)
  15537. if (x[(std::size_t) i - 1] < 0.0f && x[(std::size_t) i] >= 0.0f)
  15538. {
  15539. first = first < 0 ? i : first;
  15540. last = i;
  15541. ++crossings;
  15542. }
  15543. return crossings > 1 ? 48000.0 * (double) (crossings - 1) / (double) (last - first) : 0.0;
  15544. };
  15545. bool ok = true;
  15546. auto check = [&ok, step] (bool good, const juce::String& what) {
  15547. ok = ok && good;
  15548. step ((good ? "ok " : "FAIL ") + what);
  15549. };
  15550. const auto idle = pump (20);
  15551. engine->getMeters().takePeak (1, 0);
  15552. check (rms (idle, 0, (int) idle.size()) < 1.0e-6, "idle: rms " + juce::String (rms (idle, 0, (int) idle.size()), 9));
  15553. // 4 regions map to keys 60…63 (FL's automatic map); the editor's click: velocity 100 / 128
  15554. engine->sendLiveNote (0, 60, 0.78125f, true);
  15555. const auto first = pump (16); // 8192 frames = 171 ms, inside region 1 (250 ms)
  15556. const auto meter = engine->getMeters().takePeak (1, 0);
  15557. 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");
  15558. check (std::abs (hertz (first, 1024, 6000) - 200.0) < 4.0, "key 60 plays region 1 (200 Hz)");
  15559. check (meter > 0.01f, "mixer track 1 meter peak " + juce::String (meter, 6));
  15560. engine->sendLiveNote (0, 60, 0.0f, false);
  15561. const auto tail = pump (60);
  15562. 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));
  15563. engine->sendLiveNote (0, 62, 0.78125f, true);
  15564. const auto third = pump (16);
  15565. check (rms (third, 1024, 6000) > 0.01 && std::abs (hertz (third, 1024, 6000) - 600.0) < 8.0,
  15566. "key 62 plays region 3 (600 Hz): rms " + juce::String (rms (third, 1024, 6000), 6) + ", " + juce::String (hertz (third, 1024, 6000), 1) + " Hz");
  15567. engine->sendLiveNote (0, 62, 0.0f, false);
  15568. engine->sendLiveNote (0, 72, 0.78125f, true); // a key without a region
  15569. const auto none = pump (60);
  15570. 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));
  15571. engine->sendLiveNote (0, 72, 0.0f, false);
  15572. step (ok ? "result=OK" : "result=FAILED");
  15573. setApplicationReturnValue (ok ? 0 : 1);
  15574. quit();
  15575. });
  15576. }
  15577. // --renderaheadtest (round 190gq): see the command line above
  15578. void runRenderAheadTest (const juce::File& report, const juce::StringArray& projects, int block, double seconds)
  15579. {
  15580. struct StandIn final : juce::AudioIODevice
  15581. {
  15582. explicit StandIn (int b) : juce::AudioIODevice ("renderahead", "test"), block (b) {}
  15583. const int block;
  15584. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  15585. juce::StringArray getInputChannelNames() override { return {}; }
  15586. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  15587. juce::Array<int> getAvailableBufferSizes() override { return { block }; }
  15588. int getDefaultBufferSize() override { return block; }
  15589. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  15590. void close() override {}
  15591. bool isOpen() override { return true; }
  15592. void start (juce::AudioIODeviceCallback*) override {}
  15593. void stop() override {}
  15594. bool isPlaying() override { return true; }
  15595. juce::String getLastError() override { return {}; }
  15596. int getCurrentBufferSizeSamples() override { return block; }
  15597. double getCurrentSampleRate() override { return 48000.0; }
  15598. int getCurrentBitDepth() override { return 32; }
  15599. juce::BigInteger getActiveOutputChannels() const override
  15600. {
  15601. juce::BigInteger b;
  15602. b.setRange (0, 2, true);
  15603. return b;
  15604. }
  15605. juce::BigInteger getActiveInputChannels() const override { return {}; }
  15606. int getOutputLatencyInSamples() override { return 0; }
  15607. int getInputLatencyInSamples() override { return 0; }
  15608. };
  15609. struct Scenario
  15610. {
  15611. juce::String name;
  15612. juce::File file; // a project, or none: the showcase song
  15613. int mode = 0; // 0 Song mode from the start, 1 a loop region, 2 Pattern mode
  15614. };
  15615. auto scenarios = std::make_shared<std::vector<Scenario>>();
  15616. scenarios->push_back ({ "showcase, Song mode", {}, 0 });
  15617. scenarios->push_back ({ "showcase, a loop region wrapping mid-block", {}, 1 });
  15618. scenarios->push_back ({ "showcase, Pattern mode", {}, 2 });
  15619. for (const auto& p : projects)
  15620. scenarios->push_back ({ juce::File (p).getFileName(), juce::File (p), 0 });
  15621. auto text = std::make_shared<juce::String>();
  15622. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  15623. step ("render-ahead test: blocks of " + juce::String (block) + " at 48 kHz, " + juce::String (seconds, 1) + " s per run");
  15624. auto outputs = std::make_shared<std::vector<std::vector<float>>>();
  15625. auto ok = std::make_shared<bool> (true);
  15626. auto run = std::make_shared<std::function<void (std::size_t, int)>>();
  15627. *run = [this, scenarios, step, outputs, ok, run, block, seconds, report] (std::size_t index, int pass) {
  15628. if (index >= scenarios->size())
  15629. {
  15630. lynx::renderAheadOption().store (true);
  15631. step (juce::String ("result=") + (*ok ? "OK" : "FAIL"));
  15632. setApplicationReturnValue (*ok ? 0 : 1);
  15633. engine.reset();
  15634. quit();
  15635. return;
  15636. }
  15637. const auto& sc = (*scenarios)[index];
  15638. lynx::renderAheadOption().store (pass == 1);
  15639. engine = std::make_unique<lynx::AudioEngine>();
  15640. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  15641. engine->setRenderAheadAlways (true); // (the showcase song is light: the app would leave it real-time)
  15642. juce::String error;
  15643. auto loaded = true;
  15644. if (sc.file == juce::File())
  15645. {
  15646. auto song = lynx::makeShowcaseSong (0);
  15647. if (sc.mode == 1)
  15648. {
  15649. song.loopStart = 4 * lynx::ppq * song.beatsPerBar + 37; // (not on a block boundary)
  15650. song.loopEnd = 6 * lynx::ppq * song.beatsPerBar + 211;
  15651. song.loopOff = false;
  15652. }
  15653. if (sc.mode == 2)
  15654. song.mode = lynx::PlayMode::pattern;
  15655. engine->setSong (std::move (song));
  15656. }
  15657. else if (sc.file.hasFileExtension ("flp"))
  15658. loaded = engine->importFlpFile (sc.file, error);
  15659. else if (auto song = lynx::ProjectFile::load (sc.file, error))
  15660. engine->setSong (std::move (*song));
  15661. else
  15662. loaded = false;
  15663. if (! loaded)
  15664. {
  15665. step ("FAIL " + sc.name + ": " + error);
  15666. *ok = false;
  15667. (*run) (index + 1, 0);
  15668. return;
  15669. }
  15670. auto device = std::make_shared<StandIn> (block);
  15671. engine->deviceCallback().audioDeviceAboutToStart (device.get());
  15672. // the graph is (re)built on the message thread: the run starts once it has settled
  15673. juce::Timer::callAfterDelay (1500, [this, scenarios, step, outputs, ok, run, block, seconds, index, pass, device] {
  15674. if (engine == nullptr)
  15675. return;
  15676. const auto& sc = (*scenarios)[index];
  15677. auto& cb = engine->deviceCallback();
  15678. std::vector<float> l ((std::size_t) block), r ((std::size_t) block), out;
  15679. float* outs[] = { l.data(), r.data() };
  15680. juce::AudioIODeviceCallbackContext context;
  15681. engine->stop();
  15682. engine->seek (0.0);
  15683. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context); // (the seek, stopped)
  15684. engine->play();
  15685. const auto blocks = (int) (seconds * 48000.0 / block);
  15686. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  15687. for (int k = 0; k < blocks; ++k)
  15688. {
  15689. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
  15690. out.insert (out.end(), l.begin(), l.end());
  15691. out.insert (out.end(), r.begin(), r.end());
  15692. // (about the device's pace at the start of each second, so the render-ahead thread gets ahead)
  15693. if (k % (48000 / block) < 48000 / block / 2)
  15694. std::this_thread::sleep_for (std::chrono::microseconds ((int) (block * 1.0e6 / 48000.0 * 0.6)));
  15695. }
  15696. const auto ms = juce::Time::getMillisecondCounterHiRes() - t0;
  15697. engine->stop();
  15698. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, block, context);
  15699. const auto* st = engine->renderAheadStats();
  15700. auto n = [] (const std::atomic<std::uint64_t>& v) { return (juce::int64) v.load(); };
  15701. juce::String line = sc.name + (pass == 1 ? ", render ahead on: " : ", render ahead off: ") + juce::String (ms / 1000.0, 1) + " s";
  15702. if (st != nullptr && pass == 1)
  15703. line << "; blocks " << n (st->blocks) << ", from the ring " << n (st->fromRing) << ", waited " << n (st->waited) << ", in the callback "
  15704. << n (st->inline_) << ", dropped " << n (st->flushes) << ", drained " << n (st->drains) << ", started " << n (st->engagements)
  15705. << ", boundary mismatches " << n (st->splitMismatches) << "; ahead " << st->aheadChannels.load() << " channels / "
  15706. << st->aheadTracks.load() << " inserts, boundary " << st->boundary.load() << ", window " << st->window.load();
  15707. step (" " + line);
  15708. if (pass == 0)
  15709. {
  15710. outputs->assign (1, std::move (out));
  15711. (*run) (index, 1);
  15712. return;
  15713. }
  15714. const auto& off = outputs->front();
  15715. std::size_t first = off.size() == out.size() ? off.size() : 0;
  15716. for (std::size_t s = 0; s < std::min (off.size(), out.size()); ++s)
  15717. if (std::memcmp (&off[s], &out[s], sizeof (float)) != 0)
  15718. {
  15719. first = s;
  15720. break;
  15721. }
  15722. const auto same = off.size() == out.size() && first == off.size();
  15723. const auto clean = st != nullptr && st->flushes.load() == 0 && st->splitMismatches.load() == 0 && st->engagements.load() >= 1
  15724. && st->fromRing.load() > st->blocks.load() / 4;
  15725. *ok = *ok && same && clean;
  15726. 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))
  15727. + (clean ? "" : ", render-ahead counters off (see above)"));
  15728. (*run) (index + 1, 0);
  15729. });
  15730. };
  15731. (*run) (0, 0);
  15732. }
  15733. void runClipLoopTest (const juce::File& report, const juce::File& wavFile)
  15734. {
  15735. engine = std::make_unique<lynx::AudioEngine>();
  15736. engine->getDeviceManager().closeAudioDevice(); // the engine's callback is driven by hand below
  15737. struct StandIn final : juce::AudioIODevice
  15738. {
  15739. StandIn() : juce::AudioIODevice ("cliploop", "test") {}
  15740. juce::StringArray getOutputChannelNames() override { return { "L", "R" }; }
  15741. juce::StringArray getInputChannelNames() override { return {}; }
  15742. juce::Array<double> getAvailableSampleRates() override { return { 48000.0 }; }
  15743. juce::Array<int> getAvailableBufferSizes() override { return { 512 }; }
  15744. int getDefaultBufferSize() override { return 512; }
  15745. juce::String open (const juce::BigInteger&, const juce::BigInteger&, double, int) override { return {}; }
  15746. void close() override {}
  15747. bool isOpen() override { return true; }
  15748. void start (juce::AudioIODeviceCallback*) override {}
  15749. void stop() override {}
  15750. bool isPlaying() override { return true; }
  15751. juce::String getLastError() override { return {}; }
  15752. int getCurrentBufferSizeSamples() override { return 512; }
  15753. double getCurrentSampleRate() override { return 48000.0; }
  15754. int getCurrentBitDepth() override { return 32; }
  15755. juce::BigInteger getActiveOutputChannels() const override
  15756. {
  15757. juce::BigInteger b;
  15758. b.setRange (0, 2, true);
  15759. return b;
  15760. }
  15761. juce::BigInteger getActiveInputChannels() const override { return {}; }
  15762. int getOutputLatencyInSamples() override { return 0; }
  15763. int getInputLatencyInSamples() override { return 0; }
  15764. };
  15765. auto device = std::make_shared<StandIn>();
  15766. auto text = std::make_shared<juce::String>();
  15767. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  15768. constexpr int bar = 96000, beat = bar / 4; // 120 BPM, 48 kHz
  15769. const auto ppq = (double) lynx::ppq;
  15770. lynx::Song song;
  15771. song.bpm = 120.0;
  15772. song.mixer = lynx::Song::defaultMixer (2);
  15773. song.channels.resize (1); // the synth of a new channel: deterministic
  15774. song.channels[0].mixerTrack = 1;
  15775. auto& pattern = song.patterns.emplace_back(); // 1 bar: C5 on beat 0, C6 on beat 2
  15776. for (auto [b, key] : { std::pair { 0, 60 }, std::pair { 2, 72 } })
  15777. {
  15778. lynx::Note n;
  15779. n.start = b * lynx::ppq;
  15780. n.length = lynx::ppq / 4;
  15781. n.key = key;
  15782. pattern.notes.push_back (n);
  15783. }
  15784. lynx::Clip clip;
  15785. clip.pattern = 0;
  15786. clip.length = 16 * lynx::ppq; // stretched to 4 bars
  15787. song.playlist.push_back (clip);
  15788. song.mode = lynx::PlayMode::song;
  15789. {
  15790. // the Windows GUI check's project: the same song with a 1-bar clip, to stretch with the mouse
  15791. auto gui = song;
  15792. gui.playlist[0].length = 4 * lynx::ppq;
  15793. juce::String error;
  15794. lynx::ProjectFile::save (gui, report.getSiblingFile ("cliploop-gui.lynx"), error);
  15795. }
  15796. engine->setSong (song);
  15797. auto& callback = engine->deviceCallback();
  15798. callback.audioDeviceAboutToStart (device.get());
  15799. step ("song=1-bar synth pattern, clip stretched to 4 bars, 120 BPM, 48 kHz, blocks of 512");
  15800. // the graph is (re)built on the message thread: the scenarios run once it has settled
  15801. juce::Timer::callAfterDelay (1500, [this, device, step, wavFile, ppq] {
  15802. if (engine == nullptr)
  15803. return;
  15804. auto& cb = engine->deviceCallback();
  15805. // plays `samples` from tick `from` through the device callback; `between` runs after each block (block index)
  15806. auto play = [this, &cb] (double from, int samples, const std::function<void (int)>& between = {}) {
  15807. engine->stop();
  15808. engine->seek (from);
  15809. std::vector<float> l (512), r (512), out;
  15810. float* outs[] = { l.data(), r.data() };
  15811. juce::AudioIODeviceCallbackContext context;
  15812. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context); // (the seek, stopped)
  15813. engine->play();
  15814. for (int k = 0; (int) out.size() < samples; ++k)
  15815. {
  15816. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  15817. out.insert (out.end(), l.begin(), l.end());
  15818. if (between)
  15819. between (k);
  15820. }
  15821. engine->stop();
  15822. for (int k = 0; k < 400; ++k) // the tails of the scenario die out
  15823. cb.audioDeviceIOCallbackWithContext (nullptr, 0, outs, 2, 512, context);
  15824. out.resize ((std::size_t) samples);
  15825. return out;
  15826. };
  15827. auto rms = [] (const std::vector<float>& x, int from, int count) {
  15828. double sum = 0.0;
  15829. for (int i = from; i < from + count && i < (int) x.size(); ++i)
  15830. sum += (double) x[(std::size_t) i] * x[(std::size_t) i];
  15831. return std::sqrt (sum / juce::jmax (1, count));
  15832. };
  15833. auto diff = [] (const std::vector<float>& a, int aFrom, const std::vector<float>& b, int bFrom, int count) {
  15834. double m = 0.0;
  15835. for (int i = 0; i < count && aFrom + i < (int) a.size() && bFrom + i < (int) b.size(); ++i)
  15836. m = juce::jmax (m, (double) std::abs (a[(std::size_t) (aFrom + i)] - b[(std::size_t) (bFrom + i)]));
  15837. return m;
  15838. };
  15839. auto num = [] (double v) { return juce::String (v, 6); };
  15840. bool ok = true;
  15841. auto check = [&ok, step] (bool good, const juce::String& what) {
  15842. ok = ok && good;
  15843. step ((good ? "ok " : "FAIL ") + what);
  15844. };
  15845. lynx::setStretchedClipsLoop (true);
  15846. const auto a = play (0.0, 4 * bar);
  15847. const auto bar1 = rms (a, 0, bar);
  15848. check (bar1 > 0.01, "play from the start: bar 1 RMS " + num (bar1));
  15849. for (int k = 1; k < 4; ++k)
  15850. {
  15851. const auto rk = rms (a, k * bar, bar), d = diff (a, k * bar, a, 0, bar);
  15852. check (std::abs (rk / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  15853. "bar " + juce::String (k + 1) + " RMS " + num (rk) + " (x" + num (rk / bar1) + " of bar 1), max |bar - bar 1| " + juce::String (d, 9));
  15854. }
  15855. {
  15856. const auto x = play (10 * ppq, bar + bar / 2);
  15857. const auto d = juce::jmax (diff (x, 0, a, 2 * beat, bar / 2), diff (x, bar / 2, a, 0, bar));
  15858. check (rms (x, 0, bar / 2) > 0.01 && d < 1.0e-4,
  15859. "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));
  15860. }
  15861. {
  15862. // a seek while playing, after 6.99 beats, to bar 4 beat 3 (a ruler click)
  15863. const auto jumpBlock = 7 * beat / 512 - 1;
  15864. const auto x = play (0.0, 2 * bar, [this, jumpBlock, ppq] (int k) {
  15865. if (k == jumpBlock)
  15866. engine->seek (14 * ppq);
  15867. });
  15868. // (the best of 0-2 samples late: anything but 0 fails)
  15869. const auto at = (jumpBlock + 1) * 512;
  15870. int lag = 0;
  15871. auto d = 1.0e9;
  15872. for (int l = 0; l <= 2; ++l)
  15873. if (const auto dl = diff (x, at + l, a, 2 * beat, beat - 2); dl < d)
  15874. d = dl, lag = l;
  15875. d = lag == 0 ? d : 1.0;
  15876. const auto ratio = rms (x, at, beat) / rms (a, 2 * beat, beat);
  15877. check (std::abs (ratio - 1.0) < 1.0e-3 && d < 1.0e-4,
  15878. "jump mid-clip to bar 4 beat 3: RMS " + num (rms (x, at, beat)) + " (x" + num (ratio) + " of bar 1 beat 3), max diff "
  15879. + juce::String (d, 9) + " (" + juce::String (lag) + " sample(s) late)");
  15880. }
  15881. {
  15882. engine->editSong ([ppq] (lynx::Song& s) {
  15883. s.loopStart = (std::int64_t) (4 * ppq);
  15884. s.loopEnd = (std::int64_t) (12 * ppq);
  15885. }, false);
  15886. const auto x = play (0.0, 7 * bar);
  15887. double d = 0.0;
  15888. juce::String lags;
  15889. for (int k = 1; k < 7; ++k) // (the best of 0-2 samples late after a wrap, as after a jump)
  15890. {
  15891. auto best = 1.0e9;
  15892. int lag = 0;
  15893. for (int l = 0; l <= 2; ++l)
  15894. if (const auto dl = diff (x, k * bar + l, a, 0, bar - 2); dl < best)
  15895. best = dl, lag = l;
  15896. d = juce::jmax (d, lag == 0 ? best : 1.0); // a sample gained at a wrap fails (round 167q loopwrap)
  15897. lags << (k > 1 ? "," : "") << lag;
  15898. }
  15899. const auto r = rms (x, bar, 6 * bar);
  15900. check (std::abs (r / bar1 - 1.0) < 1.0e-3 && d < 1.0e-4,
  15901. "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)
  15902. + " (samples late, bars 2-7: " + lags + ")");
  15903. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  15904. }
  15905. {
  15906. // 100 wraps of a 1-bar loop region (bar 2): every pass on its sample, none gained (round 167q loopwrap: each
  15907. // wrap used to play one sample more)
  15908. engine->editSong ([ppq] (lynx::Song& s) {
  15909. s.loopStart = (std::int64_t) (4 * ppq);
  15910. s.loopEnd = (std::int64_t) (8 * ppq);
  15911. }, false);
  15912. const auto x = play (0.0, 101 * bar);
  15913. double d = 0.0;
  15914. int worst = 0;
  15915. for (int k = 1; k <= 100; ++k)
  15916. if (const auto dk = diff (x, k * bar, a, 0, bar); dk > d)
  15917. d = dk, worst = k + 1;
  15918. check (d < 1.0e-4, "loop region bar 2, 100 wraps: max diff of every pass vs bar 1 " + juce::String (d, 9)
  15919. + (d < 1.0e-4 ? juce::String() : " (worst: bar " + juce::String (worst) + ")"));
  15920. engine->editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  15921. }
  15922. lynx::setStretchedClipsLoop (false);
  15923. {
  15924. const auto x = play (0.0, 4 * bar);
  15925. const auto r = juce::jmax (rms (x, bar, bar), juce::jmax (rms (x, 2 * bar, bar), rms (x, 3 * bar, bar)));
  15926. 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));
  15927. }
  15928. lynx::setStretchedClipsLoop (true);
  15929. cb.audioDeviceStopped();
  15930. // the export: a WAV of the 4 bars, read back from the file
  15931. if (wavFile != juce::File())
  15932. {
  15933. for (const auto loops : { true, false })
  15934. {
  15935. lynx::setStretchedClipsLoop (loops);
  15936. const auto file = loops ? wavFile : wavFile.getSiblingFile (wavFile.getFileNameWithoutExtension() + "-off.wav");
  15937. file.deleteFile();
  15938. {
  15939. juce::WavAudioFormat wav;
  15940. std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (file.createOutputStream().release(), 48000.0, 2, 32, {}, 0));
  15941. engine->stop();
  15942. engine->seek (0.0);
  15943. lynx::AudioEngine::RenderOptions o;
  15944. o.seconds = 8.0;
  15945. o.sampleRate = 48000.0;
  15946. o.output = writer.get();
  15947. engine->renderOffline (o);
  15948. }
  15949. juce::WavAudioFormat wav;
  15950. std::unique_ptr<juce::AudioFormatReader> reader (wav.createReaderFor (file.createInputStream().release(), true));
  15951. std::vector<float> x;
  15952. if (reader != nullptr)
  15953. {
  15954. juce::AudioBuffer<float> buffer (2, (int) reader->lengthInSamples);
  15955. reader->read (&buffer, 0, (int) reader->lengthInSamples, 0, true, true);
  15956. x.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + buffer.getNumSamples());
  15957. }
  15958. const auto b1 = rms (x, 0, bar);
  15959. juce::String line = juce::String (loops ? "export" : "export, option off") + " (" + file.getFileName() + ", " + juce::String ((int) x.size()) + " samples): bar 1 RMS " + num (b1);
  15960. bool good = x.size() >= (std::size_t) 4 * bar && b1 > 0.01;
  15961. for (int k = 1; k < 4; ++k)
  15962. {
  15963. const auto rk = rms (x, k * bar, bar);
  15964. line << ", bar " << (k + 1) << " " << num (rk);
  15965. 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);
  15966. }
  15967. if (loops)
  15968. 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);
  15969. check (good, line);
  15970. }
  15971. lynx::setStretchedClipsLoop (true);
  15972. }
  15973. step (ok ? "result=OK" : "result=FAILED");
  15974. setApplicationReturnValue (ok ? 0 : 1);
  15975. quit();
  15976. });
  15977. }
  15978. // --rectest (round 163): see the command line above. Writes report lines step by step (a driver that ends the
  15979. // process leaves what was done).
  15980. void runRecordTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  15981. const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
  15982. {
  15983. engine = std::make_unique<lynx::AudioEngine>();
  15984. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  15985. savedDeviceState = engine->getDeviceManager().createStateXml();
  15986. auto text = std::make_shared<juce::String>();
  15987. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  15988. auto finish = [this, step] (int code) {
  15989. restoreSavedDeviceState();
  15990. setApplicationReturnValue (code);
  15991. quit();
  15992. };
  15993. auto& devices = engine->getDeviceManager();
  15994. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  15995. devices.setCurrentAudioDeviceType (deviceType, true);
  15996. {
  15997. auto setup = devices.getAudioDeviceSetup();
  15998. if (deviceName.isNotEmpty())
  15999. setup.outputDeviceName = deviceName;
  16000. if (bufferSize > 0)
  16001. setup.bufferSize = bufferSize;
  16002. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  16003. step ("device_error=" + error);
  16004. }
  16005. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  16006. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  16007. // takes go next to the report, not into the user's recordings folder
  16008. engine->setRecordingTarget (report.getSiblingFile (report.getFileNameWithoutExtension() + "-takes"), {});
  16009. auto* device = devices.getCurrentAudioDevice();
  16010. if (device == nullptr || engine->getInputChannelNames().empty())
  16011. {
  16012. step ("result=ERROR no device / no input");
  16013. finish (1);
  16014. return;
  16015. }
  16016. const auto rate = device->getCurrentSampleRate();
  16017. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples())
  16018. + " | driver latency in " + juce::String (device->getInputLatencyInSamples()) + " out " + juce::String (device->getOutputLatencyInSamples()));
  16019. // a click (the ping's pulse) on every beat at 120 bpm: beat k at sample k * rate / 2
  16020. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  16021. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  16022. {
  16023. lynx::takes::WavTakeWriter w;
  16024. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  16025. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  16026. std::vector<float> block (4096);
  16027. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  16028. {
  16029. std::fill (block.begin(), block.end(), 0.0f);
  16030. for (int k = 0; k < (int) block.size(); ++k)
  16031. {
  16032. const auto f = at + k;
  16033. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  16034. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  16035. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  16036. if (rel >= 0 && rel < 5)
  16037. block[(std::size_t) k] = 0.5f * shape[rel];
  16038. }
  16039. const float* d[] { block.data() };
  16040. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  16041. }
  16042. w.close();
  16043. }
  16044. lynx::Song song = lynx::Song::makeDefault();
  16045. song.bpm = 120.0;
  16046. song.mode = lynx::PlayMode::song;
  16047. song.playlist.clear();
  16048. lynx::ChannelDef c;
  16049. c.name = "Clicks";
  16050. c.instrument = lynx::InstrumentKind::audioClip;
  16051. c.samplePath = clickFile.getFullPathName().toStdString();
  16052. c.mixerTrack = 0;
  16053. c.volume = 1.0f;
  16054. song.channels.push_back (c);
  16055. lynx::Clip clip;
  16056. clip.kind = lynx::ClipKind::audio;
  16057. clip.channel = (int) song.channels.size() - 1;
  16058. clip.track = 0;
  16059. clip.start = 0;
  16060. clip.length = (std::int64_t) beats * lynx::ppq;
  16061. song.playlist.push_back (clip);
  16062. if (mode == 1) // loop recording, bars 2-4
  16063. {
  16064. song.loopStart = 4 * lynx::ppq;
  16065. song.loopEnd = 16 * lynx::ppq;
  16066. }
  16067. else if (mode == 2) // punch in/out, bars 3-4
  16068. {
  16069. song.loopStart = 8 * lynx::ppq;
  16070. song.loopEnd = 16 * lynx::ppq;
  16071. }
  16072. if (song.mixer.size() > 1)
  16073. {
  16074. song.mixer[1].name = "Loop In";
  16075. song.mixer[1].monitor = lynx::InputMonitor::off; // (the loopback must not hear itself)
  16076. }
  16077. engine->setSong (std::move (song));
  16078. engine->setInsertInput (1, 0, false);
  16079. juce::ignoreUnused (pdcSamples);
  16080. // 1) the ping
  16081. if (const auto error = engine->startLatencyPing(); error.isNotEmpty())
  16082. step ("ping_error=" + error);
  16083. juce::Timer::callAfterDelay (3500, [this, step, finish, seconds, rate, report, mode] {
  16084. if (engine == nullptr)
  16085. return;
  16086. if (engine->isPinging())
  16087. engine->cancelLatencyPing();
  16088. const auto r = engine->finishLatencyPing();
  16089. step ("ping=" + juce::String (r.ok ? "ok" : "FAILED " + juce::String (r.problem)) + " samples " + juce::String (r.samples) + " spread " + juce::String (r.spread)
  16090. + " found " + juce::String (r.found) + "/" + juce::String (r.sent) + " peak " + juce::String (juce::Decibels::gainToDecibels (r.peak, -150.0f), 1) + " dB");
  16091. const auto l = engine->currentLatency();
  16092. step ("compensation=" + juce::String (l.total()) + " (round trip " + juce::String (l.roundTrip()) + ", manual " + juce::String (l.manual) + ", pdc " + juce::String (l.pdc) + ")");
  16093. // 2) record
  16094. engine->setInsertArmed (1, true);
  16095. auto o = engine->getRecordOptions();
  16096. o.recordAudio = true;
  16097. o.countInBars = 0;
  16098. o.waitForInput = false;
  16099. o.punchLoopRegion = mode == 2;
  16100. o.preRollBars = mode == 2 ? 1 : 0;
  16101. o.postRollBars = mode == 2 ? 1 : 0;
  16102. // (round 177c: LYNX_RECTEST_BLEND_OFF=1: Blend off; LYNX_RECTEST_LAST_PASS=1: "only the last pass plays")
  16103. o.mode = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_BLEND_OFF", {}) == "1" ? lynx::RecordMode::replace
  16104. : lynx::RecordMode::overdub;
  16105. o.lastLoopPassPlays = juce::SystemStats::getEnvironmentVariable ("LYNX_RECTEST_LAST_PASS", {}) == "1";
  16106. engine->setRecordOptions (o);
  16107. engine->stop();
  16108. engine->rewind();
  16109. engine->setRecording (true);
  16110. juce::Timer::callAfterDelay (300, [this, step, finish, seconds, rate, report, mode] {
  16111. if (engine == nullptr)
  16112. return;
  16113. engine->startPlayback(); // (as the Play button: pre-roll / punch)
  16114. juce::Timer::callAfterDelay ((int) (seconds * 1000.0), [this, step, finish, seconds, rate, report, mode] {
  16115. if (engine == nullptr)
  16116. return;
  16117. if (mode == 2)
  16118. step (juce::String ("stopped_by_post_roll=") + (engine->getTransport().playing.load() ? "no" : "yes"));
  16119. engine->stop();
  16120. juce::Timer::callAfterDelay (500, [this, step, finish, seconds, rate, report, mode] {
  16121. if (engine == nullptr)
  16122. return;
  16123. engine->setRecording (false);
  16124. const auto& s = engine->getSong();
  16125. const auto tps = 120.0 * lynx::ppq / (60.0 * rate);
  16126. int take = -1;
  16127. for (int ch = 0; ch < (int) s.channels.size(); ++ch)
  16128. if (s.channels[(std::size_t) ch].instrument == lynx::InstrumentKind::audioClip && s.channels[(std::size_t) ch].name != "Clicks")
  16129. take = ch;
  16130. if (take < 0)
  16131. {
  16132. step ("result=ERROR no take (" + engine->getLastRecordingError() + ")");
  16133. finish (1);
  16134. return;
  16135. }
  16136. std::vector<std::vector<float>> audio;
  16137. double takeRate = 0.0;
  16138. const auto& path = s.channels[(std::size_t) take].samplePath;
  16139. lynx::takes::readWav (path, audio, &takeRate);
  16140. const auto frames = audio.empty() ? (juce::int64) 0 : (juce::int64) audio[0].size();
  16141. step ("take=" + juce::String::fromUTF8 (path.c_str()) + " frames " + juce::String (frames) + " (" + juce::String ((double) frames / rate, 3)
  16142. + " s of " + juce::String (seconds, 1) + " s played) lost " + juce::String (engine->getLostRecordingFrames()));
  16143. // the clicks in the file (peaks above -12 dBFS, one per 1/8 s at most)
  16144. std::vector<juce::int64> peaks;
  16145. if (! audio.empty())
  16146. for (juce::int64 f = 1; f + 1 < frames; ++f)
  16147. {
  16148. const auto x = std::abs (audio[0][(std::size_t) f]);
  16149. if (x > 0.25f && x >= std::abs (audio[0][(std::size_t) f - 1]) && x > std::abs (audio[0][(std::size_t) f + 1])
  16150. && (peaks.empty() || f - peaks.back() > (juce::int64) (rate / 8)))
  16151. peaks.push_back (f);
  16152. }
  16153. // every clip of the take: each click inside it against the nearest beat
  16154. int clips = 0, checked = 0, muted = 0;
  16155. double worst = 0.0, sum = 0.0;
  16156. for (const auto& c : s.playlist)
  16157. {
  16158. if (c.kind != lynx::ClipKind::audio || c.channel != take)
  16159. continue;
  16160. ++clips;
  16161. muted += c.muted ? 1 : 0;
  16162. const auto skip = ((double) c.offset + (double) c.offsetFraction) / tps; // file samples before the clip start
  16163. for (const auto f : peaks)
  16164. {
  16165. const auto intoClip = (double) f - skip;
  16166. if (intoClip < 0.0 || intoClip * tps >= (double) c.length)
  16167. continue;
  16168. const auto songTick = (double) c.start + intoClip * tps - 2.0 * tps; // (the pulse's peak is its 3rd sample)
  16169. const auto beat = std::round (songTick / lynx::ppq) * lynx::ppq;
  16170. const auto error = (songTick - beat) / tps;
  16171. worst = std::max (worst, std::abs (error));
  16172. sum += error;
  16173. ++checked;
  16174. }
  16175. step ("clip track " + juce::String (c.track) + " start " + juce::String ((juce::int64) c.start) + " length " + juce::String ((juce::int64) c.length)
  16176. + " offset " + juce::String ((juce::int64) c.offset) + juce::String (c.offsetFraction >= 0.0f ? "+" : "") + juce::String (c.offsetFraction, 4)
  16177. + (c.muted ? " (muted lane)" : ""));
  16178. }
  16179. step ("clicks_in_file=" + juce::String ((int) peaks.size()) + " checked=" + juce::String (checked) + " clips=" + juce::String (clips)
  16180. + " muted_lanes=" + juce::String (muted));
  16181. step ("placement_error_samples=max " + juce::String (worst, 3) + " mean " + juce::String (checked > 0 ? sum / checked : 0.0, 3));
  16182. auto ok = checked > 0 && worst <= 1.0 && engine->getLostRecordingFrames() == 0;
  16183. if (mode == 2) // one clip, exactly the punch range, its 8 beats
  16184. {
  16185. const auto& sp = engine->getSong();
  16186. bool exact = false;
  16187. for (const auto& c : sp.playlist)
  16188. if (c.kind == lynx::ClipKind::audio && c.channel == take)
  16189. exact = c.start == sp.loopStart && c.start + c.length == sp.loopEnd;
  16190. step (juce::String ("punch_clip_matches_range=") + (exact ? "yes" : "no"));
  16191. ok = ok && clips == 1 && exact && checked == 8;
  16192. }
  16193. report.getSiblingFile (report.getFileNameWithoutExtension() + "-project.lynx").replaceWithText (lynx::ProjectFile::toJson (engine->getSong()));
  16194. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  16195. finish (ok ? 0 : 1);
  16196. });
  16197. });
  16198. });
  16199. });
  16200. }
  16201. // --hwinserttest (round 164d): see the command line above.
  16202. void runHwInsertTest (const juce::File& report, double seconds, const juce::String& deviceType, const juce::String& deviceName,
  16203. const juce::String& inputName, int bufferSize, bool inPatcher = false, juce::File bounceFile = {})
  16204. {
  16205. engine = std::make_unique<lynx::AudioEngine>();
  16206. lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
  16207. savedDeviceState = engine->getDeviceManager().createStateXml();
  16208. auto text = std::make_shared<juce::String>();
  16209. auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
  16210. auto finish = [this] (int code) {
  16211. if (engine != nullptr)
  16212. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  16213. restoreSavedDeviceState();
  16214. setApplicationReturnValue (code);
  16215. quit();
  16216. };
  16217. auto& devices = engine->getDeviceManager();
  16218. if (deviceType.isNotEmpty() && devices.getCurrentAudioDeviceType() != deviceType)
  16219. devices.setCurrentAudioDeviceType (deviceType, true);
  16220. {
  16221. auto setup = devices.getAudioDeviceSetup();
  16222. if (deviceName.isNotEmpty())
  16223. setup.outputDeviceName = deviceName;
  16224. if (bufferSize > 0)
  16225. setup.bufferSize = bufferSize;
  16226. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  16227. step ("device_error=" + error);
  16228. }
  16229. if (const auto r = engine->openAudioInput (inputName.isNotEmpty() ? inputName : deviceName); r.issue != lynx::AudioEngine::InputIssue::none)
  16230. step ("input_error=" + juce::String ((int) r.issue) + " " + r.detail);
  16231. auto* device = devices.getCurrentAudioDevice();
  16232. if (device == nullptr || engine->getInputChannelNames().empty())
  16233. {
  16234. step ("result=ERROR no device / no input");
  16235. finish (1);
  16236. return;
  16237. }
  16238. const auto rate = device->getCurrentSampleRate();
  16239. step ("device=" + device->getTypeName() + " | " + device->getName() + " | " + juce::String (rate) + " Hz | block " + juce::String (device->getCurrentBufferSizeSamples()));
  16240. // the click track: the ping's pulse on every beat at 120 bpm
  16241. const auto beats = (int) std::ceil (seconds * 2.0) + 8;
  16242. const auto clickFile = report.getSiblingFile (report.getFileNameWithoutExtension() + "-clicks.wav");
  16243. {
  16244. lynx::takes::WavTakeWriter w;
  16245. w.open (clickFile.getFullPathName().toStdString(), rate, 1, lynx::takes::SampleFormat::float32);
  16246. const auto total = (juce::int64) std::llround ((double) beats * rate / 2.0);
  16247. std::vector<float> block (4096);
  16248. for (juce::int64 at = 0; at < total; at += (juce::int64) block.size())
  16249. {
  16250. std::fill (block.begin(), block.end(), 0.0f);
  16251. for (int k = 0; k < (int) block.size(); ++k)
  16252. {
  16253. const auto f = at + k;
  16254. const auto beat = (juce::int64) std::floor ((double) f / (rate / 2.0));
  16255. const auto rel = f - (juce::int64) std::llround ((double) beat * rate / 2.0);
  16256. static constexpr float shape[] { 0.25f, 0.75f, 1.0f, 0.75f, 0.25f };
  16257. if (rel >= 0 && rel < 5)
  16258. block[(std::size_t) k] = 0.5f * shape[rel];
  16259. }
  16260. const float* d[] { block.data() };
  16261. w.write (d, (int) std::min<juce::int64> ((juce::int64) block.size(), total - at));
  16262. }
  16263. w.close();
  16264. }
  16265. lynx::Song song = lynx::Song::makeDefault();
  16266. song.bpm = 120.0;
  16267. song.mode = lynx::PlayMode::song;
  16268. song.playlist.clear();
  16269. song.channels.clear();
  16270. for (int k = 0; k < 2; ++k)
  16271. {
  16272. lynx::ChannelDef c;
  16273. c.name = k == 0 ? "Wet" : "Dry";
  16274. c.instrument = lynx::InstrumentKind::audioClip;
  16275. c.samplePath = clickFile.getFullPathName().toStdString();
  16276. c.mixerTrack = k + 1;
  16277. c.volume = 1.0f;
  16278. song.channels.push_back (c);
  16279. lynx::Clip clip;
  16280. clip.kind = lynx::ClipKind::audio;
  16281. clip.channel = k;
  16282. clip.track = k;
  16283. clip.start = 0;
  16284. clip.length = (std::int64_t) beats * lynx::ppq;
  16285. song.playlist.push_back (clip);
  16286. }
  16287. song.mixer[0].outputChannel = lynx::outputNone; // (the cable carries the send only)
  16288. for (auto& fx : song.mixer[0].effects) // (no Master effects: the default limiter's PDC would hide nothing, but keep it plain)
  16289. fx.enabled = false;
  16290. song.mixer[1].pan = -1.0f;
  16291. song.mixer[2].pan = 1.0f;
  16292. auto hw = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  16293. hw.params[lynx::hwinsert::output] = lynx::hwinsert::channelValue (0);
  16294. hw.params[lynx::hwinsert::input] = lynx::hwinsert::channelValue (0);
  16295. hw.params[lynx::hwinsert::inputStereo] = 1.0f;
  16296. song.mixer[1].effects.clear();
  16297. lynx::AudioEngine::HardwareInsertRef ref { false, 1, 0, {} };
  16298. if (inPatcher) // (round 165c) From LYNX -> Hardware Insert -> To LYNX
  16299. {
  16300. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  16301. lynx::PatchNode node;
  16302. node.effect = hw;
  16303. slot.patcher.nodes = { node };
  16304. lynx::PatchWire in, out;
  16305. in.from = lynx::patchFromHost;
  16306. in.to = 0;
  16307. out.from = 0;
  16308. out.to = lynx::patchToHost;
  16309. slot.patcher.wires = { in, out };
  16310. song.mixer[1].effects.push_back (slot);
  16311. ref.nodes = { 0 };
  16312. }
  16313. else
  16314. song.mixer[1].effects.push_back (hw);
  16315. engine->setSong (std::move (song));
  16316. step (juce::String ("insert=") + (inPatcher ? "inside a Patcher on Insert 1" : "Insert 1 slot 1"));
  16317. const auto meter = [this, ref] (int output) {
  16318. const auto fx = engine->runningHardwareInsert (ref);
  16319. return fx != nullptr ? fx->controlOutput (output) : 0.0f;
  16320. };
  16321. // 1) the insert's ping (as its Ping button: a momentary value flipped)
  16322. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  16323. if (engine == nullptr)
  16324. return;
  16325. engine->pingHardwareInserts ({ ref });
  16326. juce::Timer::callAfterDelay (3500, [this, report, step, finish, seconds, rate, meter, ref, inPatcher, bounceFile] {
  16327. if (engine == nullptr)
  16328. return;
  16329. // (round 165c) the engine makes a ping's result the slot's round trip with the device setup it belongs to; the
  16330. // new round trip rebuilds the insert (its latency), so the result is read from the slot
  16331. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  16332. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  16333. const auto setup = slot != nullptr ? lynx::hwinsert::measuredSetup (*slot) : std::string();
  16334. const auto state = meter (lynx::hwinsert::pingState);
  16335. const auto ok = samples > 0 && setup == engine->currentSetupKey();
  16336. step ("ping_round_trip=" + juce::String (samples) + " measured_setup=" + juce::String (setup) + (ok ? " (ok)" : " (FAILED)")
  16337. + " live_ping_state=" + juce::String (state, 3) + " status_flags=" + juce::String (juce::roundToInt (meter (lynx::hwinsert::status) * 16.0f)));
  16338. if (! ok)
  16339. {
  16340. step ("result=FAILED ping");
  16341. finish (1);
  16342. return;
  16343. }
  16344. // a stale setup is noticed: another setup key on the slot gives the notice, the real one none
  16345. step ("stale_now=" + juce::String ((int) engine->staleHardwareInserts().size()));
  16346. // 2) play, capturing the Master
  16347. juce::Timer::callAfterDelay (500, [this, report, step, finish, seconds, rate, samples, ref, inPatcher, bounceFile] {
  16348. if (engine == nullptr)
  16349. return;
  16350. step ("pdc_total=" + juce::String (engine->getLatencySamples()) + " (expected " + juce::String (samples) + ")");
  16351. // saved in the project: the slot comes back the same (routing, round trip), and its latency with it — also an
  16352. // odd round trip (12345 samples: the project keeps it to the sample)
  16353. if (! inPatcher)
  16354. {
  16355. auto odd = engine->getSong();
  16356. odd.mixer[1].effects[0].params[lynx::hwinsert::roundTrip] = lynx::hwinsert::roundTripValue (12345);
  16357. juce::String error;
  16358. auto same = true;
  16359. for (const auto* song : { &engine->getSong(), (const lynx::Song*) &odd })
  16360. {
  16361. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (song == &odd ? "-odd.lynx" : ".lynx"));
  16362. const auto saved = lynx::ProjectFile::save (*song, file, error);
  16363. const auto loaded = saved ? lynx::ProjectFile::load (file, error) : std::nullopt;
  16364. same = same && loaded && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  16365. && loaded->mixer[1].effects[0].kind == lynx::EffectKind::hardwareInsert
  16366. && loaded->mixer[1].effects[0].params == song->mixer[1].effects[0].params
  16367. && lynx::makeEffect (loaded->mixer[1].effects[0])->latencySamples() == (song == &odd ? 12345 : samples);
  16368. }
  16369. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + ".lynx");
  16370. step (juce::String ("project_round_trip=") + (same ? "same" : "DIFFERENT " + error) + " (" + file.getFileName() + ")");
  16371. if (! same)
  16372. {
  16373. step ("result=FAILED project");
  16374. finish (1);
  16375. return;
  16376. }
  16377. }
  16378. auto left = std::make_shared<std::vector<float>>(), right = std::make_shared<std::vector<float>>();
  16379. engine->stop();
  16380. engine->rewind();
  16381. engine->getMeters().capture.setSource (0);
  16382. engine->play();
  16383. auto pulls = std::make_shared<int> ((int) (seconds * 5.0));
  16384. auto pull = std::make_shared<std::function<void()>>();
  16385. *pull = [this, report, step, finish, seconds, rate, samples, left, right, pulls, pull, ref, inPatcher, bounceFile] {
  16386. if (engine == nullptr)
  16387. return;
  16388. engine->getMeters().capture.pull (*left, *right);
  16389. if (*pulls == 10) // the insert's editor while it plays (next to the report)
  16390. for (const auto scale : { 1.0f, 1.5f })
  16391. {
  16392. auto editor = inPatcher ? lynx::makeNodeEffectEditor (
  16393. *engine, [ref] (lynx::Song& s) { return lynx::AudioEngine::locateHardwareInsert (s, ref); },
  16394. [this, ref] { return engine->runningHardwareInsert (ref); }, "Insert 1 (Patcher)", scale)
  16395. : lynx::makeNativeEffectEditor (*engine, 1, 0, scale, 0);
  16396. juce::Image image (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  16397. {
  16398. juce::Graphics g (image);
  16399. g.fillAll (lynx::theme::panel);
  16400. editor->paintEntireComponent (g, false);
  16401. }
  16402. const auto file = report.getSiblingFile (report.getFileNameWithoutExtension() + (scale > 1.0f ? "-editor150.png" : "-editor.png"));
  16403. file.deleteFile();
  16404. juce::PNGImageFormat png;
  16405. if (auto stream = file.createOutputStream())
  16406. png.writeImageToStream (image, *stream);
  16407. }
  16408. if (--*pulls > 0)
  16409. {
  16410. juce::Timer::callAfterDelay (200, *pull);
  16411. return;
  16412. }
  16413. engine->stop();
  16414. const auto dropped = engine->getMeters().capture.droppedFrames();
  16415. engine->getMeters().capture.setSource (lynx::AudioCapture::off);
  16416. // the clicks of each side (peaks above -12 dBFS, one per 1/8 s at most)
  16417. auto peaksOf = [rate] (const std::vector<float>& x) {
  16418. std::vector<juce::int64> peaks;
  16419. for (std::size_t f = 1; f + 1 < x.size(); ++f)
  16420. 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])
  16421. && (peaks.empty() || (juce::int64) f - peaks.back() > (juce::int64) (rate / 8)))
  16422. peaks.push_back ((juce::int64) f);
  16423. return peaks;
  16424. };
  16425. const auto wet = peaksOf (*left), dry = peaksOf (*right);
  16426. int pairs = 0;
  16427. juce::int64 worst = 0;
  16428. double gainSum = 0.0, residual = 0.0, energy = 0.0;
  16429. for (const auto w : wet)
  16430. {
  16431. 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); });
  16432. if (best == dry.end() || std::abs (*best - w) > (juce::int64) (rate / 8))
  16433. continue;
  16434. ++pairs;
  16435. worst = std::max (worst, std::abs (*best - w));
  16436. gainSum += (*left)[(std::size_t) w] / (*right)[(std::size_t) *best];
  16437. }
  16438. const auto gain = pairs > 0 ? gainSum / pairs : 1.0;
  16439. // dry clicks with no wet click beside them (a dropout of the cable / device), listed
  16440. juce::String unmatched;
  16441. for (const auto d : dry)
  16442. if (std::none_of (wet.begin(), wet.end(), [d, rate] (juce::int64 w) { return std::abs (w - d) <= (juce::int64) (rate / 8); }))
  16443. unmatched << " " << (juce::int64) d << " (" << juce::String ((*left)[(std::size_t) d], 3) << ")";
  16444. if (unmatched.isNotEmpty())
  16445. step ("dry_clicks_without_wet=" + unmatched);
  16446. // the null test: left − gain · right around each click (both sides aligned → only the cable's colour remains)
  16447. for (const auto w : wet)
  16448. for (juce::int64 f = std::max<juce::int64> (0, w - 16); f < std::min<juce::int64> ((juce::int64) left->size(), w + 16); ++f)
  16449. {
  16450. const auto d = (double) (*left)[(std::size_t) f] - gain * (double) (*right)[(std::size_t) f];
  16451. residual += d * d;
  16452. energy += (double) (*left)[(std::size_t) f] * (*left)[(std::size_t) f];
  16453. }
  16454. const auto nullDb = energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, residual / energy)) : 0.0;
  16455. step ("captured=" + juce::String ((int) left->size()) + " frames dropped=" + juce::String (dropped) + " wet_clicks=" + juce::String ((int) wet.size())
  16456. + " dry_clicks=" + juce::String ((int) dry.size()) + " pairs=" + juce::String (pairs));
  16457. step ("alignment_error_samples=max " + juce::String ((int) worst) + " cable_gain=" + juce::String (gain, 4) + " null_residual_db=" + juce::String (nullDb, 1));
  16458. auto* dev = engine->getDeviceManager().getCurrentAudioDevice();
  16459. const auto xruns = dev != nullptr ? dev->getXRunCount() : -1;
  16460. step ("device_xruns=" + juce::String (xruns) + " (a dropout loses what was on the cable then: its clicks are excused)");
  16461. const auto excused = xruns > 0 ? 2 * xruns : 0;
  16462. const auto ok = pairs >= (int) (seconds * 2.0) - 2 - excused && worst == 0 && dropped == 0 && engine->getLatencySamples() == samples;
  16463. step (juce::String ("result=") + (ok ? "OK" : "FAILED"));
  16464. // (round 165c) then the re-ping notice after a buffer size change
  16465. auto then = [this, ref, step, finish] (int code) {
  16466. if (code != 0)
  16467. finish (code);
  16468. else
  16469. runRepingCheck (ref, step, finish);
  16470. };
  16471. if (! ok)
  16472. {
  16473. finish (1);
  16474. return;
  16475. }
  16476. if (bounceFile == juce::File())
  16477. then (0);
  16478. else
  16479. runBounceCheck (bounceFile, step, then);
  16480. };
  16481. juce::Timer::callAfterDelay (200, *pull);
  16482. });
  16483. });
  16484. });
  16485. }
  16486. // --hwinserttest --bounce (round 165c): Export › "Render through the hardware in real time" of the test song next to
  16487. // the offline export of the same song. Through the loopback cable (gain 1) the return is the send delayed by the
  16488. // pinged round trip, so the real-time file must equal the offline one (which passes the dry signal at that delay)
  16489. // to float rounding, with the wet clicks (left) on the dry clicks' samples (right).
  16490. // --hwinserttest (round 165c): the buffer size changes (another round trip on the device): the engine notices the
  16491. // insert measured for the old setup (the app's "Ping now?" prompt), "Ping now" measures it again for the new one
  16492. void runRepingCheck (lynx::AudioEngine::HardwareInsertRef ref, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  16493. {
  16494. auto& devices = engine->getDeviceManager();
  16495. auto setup = devices.getAudioDeviceSetup();
  16496. const auto before = setup.bufferSize;
  16497. setup.bufferSize = before == 512 ? 256 : 512;
  16498. if (const auto error = devices.setAudioDeviceSetup (setup, true); error.isNotEmpty())
  16499. step ("reping_device_error=" + error);
  16500. engine->takeHardwareInsertNotice(); // (whatever was pending before the change)
  16501. juce::Timer::callAfterDelay (1500, [this, ref, step, finish, before] {
  16502. if (engine == nullptr)
  16503. return;
  16504. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  16505. const auto block = device != nullptr ? device->getCurrentBufferSizeSamples() : 0;
  16506. const auto notice = engine->takeHardwareInsertNotice();
  16507. step ("reping_buffer=" + juce::String (before) + "->" + juce::String (block) + " notice=" + juce::String ((int) notice.size())
  16508. + " stale=" + juce::String ((int) engine->staleHardwareInserts().size()));
  16509. if (notice.size() != 1 || ! (notice[0] == ref))
  16510. {
  16511. step ("result_reping=FAILED (no notice)");
  16512. finish (1);
  16513. return;
  16514. }
  16515. engine->pingHardwareInserts (notice); // ("Ping now")
  16516. juce::Timer::callAfterDelay (3500, [this, ref, step, finish, block] {
  16517. if (engine == nullptr)
  16518. return;
  16519. const auto* slot = lynx::AudioEngine::locateHardwareInsert (const_cast<lynx::Song&> (engine->getSong()), ref);
  16520. const auto samples = slot != nullptr ? lynx::hwinsert::roundTripOf (slot->params[lynx::hwinsert::roundTrip]) : 0;
  16521. const auto stale = (int) engine->staleHardwareInserts().size();
  16522. step ("reping_round_trip=" + juce::String (samples) + " pdc_total=" + juce::String (engine->getLatencySamples()) + " stale=" + juce::String (stale));
  16523. const auto ok = stale == 0 && samples > 0 && engine->getLatencySamples() == samples;
  16524. step (juce::String ("result_reping=") + (ok ? "OK" : "FAILED") + " (device block " + juce::String (block) + ")");
  16525. finish (ok ? 0 : 1);
  16526. });
  16527. });
  16528. }
  16529. void runBounceCheck (const juce::File& bounceFile, std::function<void (const juce::String&)> step, std::function<void (int)> finish)
  16530. {
  16531. // the Export window as the user sees it with the real-time option ticked (next to the report)
  16532. lynx::showExportDialog (*engine, bounceFile.getParentDirectory(), "bounce", 0);
  16533. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  16534. if (auto* w = juce::TopLevelWindow::getTopLevelWindow (k))
  16535. {
  16536. std::function<juce::ToggleButton* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ToggleButton* {
  16537. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Render through the hardware in real time"))
  16538. return t;
  16539. for (auto* child : c.getChildren())
  16540. if (auto* t = find (*child))
  16541. return t;
  16542. return nullptr;
  16543. };
  16544. if (auto* toggle = find (*w))
  16545. {
  16546. step (juce::String ("export_option_visible=") + (toggle->isVisible() ? "yes" : "NO"));
  16547. toggle->setToggleState (true, juce::sendNotificationSync); // (calls its onClick, as a click)
  16548. auto* c = dynamic_cast<juce::DocumentWindow*> (w) != nullptr ? static_cast<juce::DocumentWindow*> (w)->getContentComponent() : w;
  16549. if (c != nullptr)
  16550. {
  16551. const auto file = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-export.png");
  16552. file.deleteFile();
  16553. juce::FileOutputStream out (file);
  16554. juce::PNGImageFormat png;
  16555. if (out.openedOk())
  16556. png.writeImageToStream (c->createComponentSnapshot (c->getLocalBounds()), out);
  16557. }
  16558. delete w;
  16559. break;
  16560. }
  16561. }
  16562. lynx::exportopts::Options o;
  16563. o.format = lynx::exportopts::Format::wav;
  16564. o.wavBits = 32;
  16565. o.dither = lynx::exportopts::DitherMode::none;
  16566. o.tail = lynx::exportopts::TailMode::cut;
  16567. o.range = lynx::exportopts::Range::song;
  16568. o.trimPdc = true;
  16569. o.hqAllPlugins = false;
  16570. o.pluginWarmUp = false;
  16571. const auto offlineFile = bounceFile.getSiblingFile (bounceFile.getFileNameWithoutExtension() + "-offline.wav");
  16572. auto realtimeJob = std::make_shared<lynx::ExportJob> (*engine, o, bounceFile);
  16573. o.sampleRate = engine->getTransport().sampleRate.load();
  16574. auto offlineJob = std::make_shared<lynx::ExportJob> (engine->getSong(), o, offlineFile);
  16575. struct Shared
  16576. {
  16577. std::atomic<int> done { 0 };
  16578. bool okRealtime = false, okOffline = false;
  16579. juce::String errorRealtime, errorOffline;
  16580. double lastProgress = 0.0;
  16581. double started = juce::Time::getMillisecondCounterHiRes();
  16582. };
  16583. auto shared = std::make_shared<Shared>();
  16584. // (the jobs stay owned by the message thread's poll below: they are destroyed there)
  16585. juce::Thread::launch ([rt = realtimeJob.get(), off = offlineJob.get(), shared] {
  16586. shared->okRealtime = rt->run ([shared] (double p) { shared->lastProgress = p; return true; }, shared->errorRealtime);
  16587. shared->okOffline = off->run ({}, shared->errorOffline);
  16588. shared->done.store (1);
  16589. });
  16590. auto poll = std::make_shared<std::function<void()>>();
  16591. *poll = [this, poll, shared, realtimeJob, offlineJob, bounceFile, offlineFile, step, finish] {
  16592. if (shared->done.load() == 0)
  16593. {
  16594. juce::Timer::callAfterDelay (100, *poll);
  16595. return;
  16596. }
  16597. const auto seconds = (juce::Time::getMillisecondCounterHiRes() - shared->started) / 1000.0;
  16598. step ("bounce_realtime=" + juce::String (shared->okRealtime ? "ok" : "FAILED " + shared->errorRealtime) + " offline="
  16599. + juce::String (shared->okOffline ? "ok" : "FAILED " + shared->errorOffline) + " took=" + juce::String (seconds, 1) + " s (music "
  16600. + juce::String (realtimeJob->getMusicSeconds(), 1) + " s)" + (realtimeJob->getNotice().isNotEmpty() ? " notice=" + realtimeJob->getNotice() : juce::String()));
  16601. juce::AudioFormatManager formats;
  16602. formats.registerBasicFormats();
  16603. std::unique_ptr<juce::AudioFormatReader> a (formats.createReaderFor (bounceFile)), b (formats.createReaderFor (offlineFile));
  16604. if (! shared->okRealtime || ! shared->okOffline || a == nullptr || b == nullptr)
  16605. {
  16606. step ("result=FAILED bounce");
  16607. finish (1);
  16608. return;
  16609. }
  16610. const auto frames = (int) std::min (a->lengthInSamples, b->lengthInSamples);
  16611. juce::AudioBuffer<float> x (2, frames), y (2, frames);
  16612. a->read (&x, 0, frames, 0, true, true);
  16613. b->read (&y, 0, frames, 0, true, true);
  16614. double residual = 0.0, energy = 0.0, wetDry = 0.0;
  16615. for (int ch = 0; ch < 2; ++ch)
  16616. for (int i = 0; i < frames; ++i)
  16617. {
  16618. const double d = x.getSample (ch, i) - y.getSample (ch, i);
  16619. residual += d * d;
  16620. energy += (double) y.getSample (ch, i) * y.getSample (ch, i);
  16621. }
  16622. for (int i = 0; i < frames; ++i) // the wet side against the dry side of the real-time file
  16623. wetDry += std::pow ((double) x.getSample (0, i) - x.getSample (1, i), 2.0);
  16624. const auto db = [energy] (double r) { return energy > 0.0 ? 10.0 * std::log10 (std::max (1e-30, r / energy)) : 0.0; };
  16625. step ("bounce_frames=" + juce::String ((juce::int64) a->lengthInSamples) + " offline_frames=" + juce::String ((juce::int64) b->lengthInSamples)
  16626. + " rate=" + juce::String (a->sampleRate) + " bounce_vs_offline_db=" + juce::String (db (residual), 1)
  16627. + " wet_vs_dry_db=" + juce::String (db (2.0 * wetDry), 1) + " peak=" + juce::String (realtimeJob->getPeak(), 3));
  16628. const auto ok = std::abs (a->lengthInSamples - b->lengthInSamples) <= 1 && db (residual) < -100.0 && realtimeJob->getPeak() > 0.1f;
  16629. step (juce::String ("result_bounce=") + (ok ? "OK" : "FAILED"));
  16630. finish (ok ? 0 : 1);
  16631. };
  16632. juce::Timer::callAfterDelay (100, *poll);
  16633. }
  16634. // --rtstress --record: stops recording (the take becomes a clip of the song, as in the app), moves the take's WAV to
  16635. // `target` and describes it: length against the time played, channels, peak, the latencies the driver reported.
  16636. juce::String finishStressTake (const juce::File& target, double seconds)
  16637. {
  16638. juce::String text;
  16639. auto* device = engine->getDeviceManager().getCurrentAudioDevice();
  16640. text << " recording: input " << (device != nullptr ? device->getActiveInputChannels().countNumberOfSetBits() : 0) << " channel(s)";
  16641. if (device != nullptr)
  16642. text << ", input latency " << device->getInputLatencyInSamples() << " + output latency " << device->getOutputLatencyInSamples() << " samples";
  16643. engine->setRecording (false); // closes the take: a clip of the song
  16644. juce::File take;
  16645. for (const auto& c : engine->getSong().channels)
  16646. if (c.instrument == lynx::InstrumentKind::audioClip)
  16647. take = juce::File (juce::String::fromUTF8 (c.samplePath.c_str()));
  16648. if (! take.existsAsFile())
  16649. return text + "\n recording: no take (" + engine->getLastRecordingError() + ")\n";
  16650. target.deleteFile();
  16651. if (! take.moveFileTo (target))
  16652. take.copyFileTo (target);
  16653. juce::AudioFormatManager formats;
  16654. formats.registerBasicFormats();
  16655. if (std::unique_ptr<juce::AudioFormatReader> reader (formats.createReaderFor (target)); reader != nullptr)
  16656. {
  16657. juce::AudioBuffer<float> audio ((int) reader->numChannels, (int) reader->lengthInSamples);
  16658. reader->read (&audio, 0, (int) reader->lengthInSamples, 0, true, true);
  16659. const auto peak = audio.getMagnitude (0, audio.getNumSamples());
  16660. const auto length = (double) reader->lengthInSamples / reader->sampleRate;
  16661. text << "\n recording: take " << juce::String (length, 3) << " s of " << juce::String (seconds, 0) << " s played, "
  16662. << (int) reader->numChannels << " ch @ " << (int) reader->sampleRate << " Hz, peak "
  16663. << juce::String (juce::Decibels::gainToDecibels (peak, -150.0f), 1) << " dBFS -> " << target.getFullPathName() << "\n";
  16664. }
  16665. else
  16666. text << "\n recording: take unreadable (" << target.getFullPathName() << ")\n";
  16667. return text;
  16668. }
  16669. // LYNX.exe --render project.(flp|lynx) output.wav [seconds]
  16670. // Exports the current pattern to 24-bit WAV (for an imported .flp, the one with the most notes).
  16671. void runRender (const juce::String& inputPath, const juce::String& outputPath, double seconds)
  16672. {
  16673. lynx::AudioEngine offline (false);
  16674. const juce::File input (inputPath);
  16675. juce::String error, report;
  16676. bool ok = false;
  16677. if (input.hasFileExtension ("flp;als;flm;songtmpl;band;blx;mod;xm;s3m;it")) // (round 190ic: a GarageBand .band folder too; 190nw: a module)
  16678. ok = offline.importFlpFile (input, error);
  16679. else if (auto song = lynx::ProjectFile::load (input, error))
  16680. {
  16681. offline.setSong (std::move (*song));
  16682. ok = true;
  16683. }
  16684. int samplers = 0, samplersLoaded = 0;
  16685. if (ok)
  16686. {
  16687. for (const auto& c : offline.getSong().channels)
  16688. if (c.instrument == lynx::InstrumentKind::sampler || c.instrument == lynx::InstrumentKind::audioClip)
  16689. {
  16690. ++samplers;
  16691. samplersLoaded += offline.getSampleLibrary().load (juce::String::fromUTF8 (c.samplePath.c_str())) != nullptr;
  16692. }
  16693. const juce::File output (outputPath);
  16694. output.deleteFile();
  16695. juce::WavAudioFormat wav;
  16696. std::unique_ptr<juce::AudioFormatWriter> writer (
  16697. wav.createWriterFor (output.createOutputStream().release(), 44100.0, 2, 24, {}, 0));
  16698. if (writer == nullptr)
  16699. {
  16700. ok = false;
  16701. error = lynx::utf8 ("could not create ") + outputPath;
  16702. }
  16703. else
  16704. {
  16705. const auto peak = offline.renderOffline (seconds > 0.0 ? seconds : 10.0, 44100.0, writer.get());
  16706. report << "peak=" << peak << "\n";
  16707. ok = peak > 0.001f;
  16708. }
  16709. }
  16710. report << "samples=" << samplersLoaded << "/" << samplers << "\n"
  16711. << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  16712. juce::File (outputPath + ".txt").replaceWithText (report);
  16713. setApplicationReturnValue (ok ? 0 : 1);
  16714. quit();
  16715. }
  16716. // LYNX.exe --export-flp project.(lynx|flp|als) output.(flp|zip) [--substitute] (round 171e): File › Export › FL Studio
  16717. // project without the window (option A unless --substitute; the renders next to a .flp in "<name> audio"); the
  16718. // report goes to output.txt
  16719. void runAlsExport (const juce::String& inputPath, const juce::String& folderPath, bool live11, bool reference)
  16720. {
  16721. juce::String error;
  16722. juce::StringArray notes;
  16723. juce::File als;
  16724. {
  16725. lynx::AudioEngine loader (false);
  16726. const juce::File input (inputPath);
  16727. bool ok = false;
  16728. // --scan: the targeted plugin scan an open runs first (child processes), so the set's plugins load
  16729. if (juce::JUCEApplication::getCommandLineParameterArray().contains ("--scan") && input.hasFileExtension ("flp;als;flm;songtmpl"))
  16730. {
  16731. juce::MemoryBlock data;
  16732. if (input.loadFileAsData (data))
  16733. {
  16734. const std::vector<std::uint8_t> bytes (static_cast<const std::uint8_t*> (data.getData()),
  16735. static_cast<const std::uint8_t*> (data.getData()) + data.getSize());
  16736. try
  16737. {
  16738. const auto uses = input.hasFileExtension ("als") ? lynx::alsForeignPlugins (bytes)
  16739. : lynx::flpForeignPlugins (flp::parseProject ({ bytes.data(), bytes.size() }));
  16740. loader.getPluginHost().scanFiles (loader.getPluginHost().filesToScanFor (uses), {});
  16741. }
  16742. catch (const std::exception&)
  16743. {
  16744. }
  16745. }
  16746. }
  16747. if (input.hasFileExtension ("flp;als;flm;songtmpl;band;blx;mod;xm;s3m;it"))
  16748. ok = loader.importFlpFile (input, error);
  16749. else if (auto song = lynx::ProjectFile::load (input, error))
  16750. {
  16751. loader.setSong (std::move (*song));
  16752. ok = true;
  16753. }
  16754. if (ok)
  16755. {
  16756. loader.capturePluginStates();
  16757. const juce::File folder (folderPath);
  16758. folder.createDirectory();
  16759. als = lynx::writeAlsProject (loader.getSong(), &loader.getPluginHost(), live11 ? lynx::AlsVersion::live11 : lynx::AlsVersion::live12, ! reference, folder,
  16760. input.getFileNameWithoutExtension(), notes, error);
  16761. }
  16762. }
  16763. juce::String report;
  16764. report << (als != juce::File() ? "ok " + als.getFullPathName() : "error=" + error) << "\n" << notes.joinIntoString ("\n") << "\n";
  16765. juce::File (folderPath).getChildFile ("export-als.txt").replaceWithText (report);
  16766. setApplicationReturnValue (als != juce::File() ? 0 : 1);
  16767. quit();
  16768. }
  16769. // --versionsshot <prefix> (round 190ap): everything the round adds, offscreen (no window on the desktop):
  16770. // -versions.png / -versions-unsaved.png the Versions panel (a project with versions, backups and labels; a new one)
  16771. // -menu-file.png / -menu-file-pluginsoff.png the File menu, and as it is while the plugins are off
  16772. // -pluginsoff-window.png / -pluginsoff-mixer.png a project opened without its third-party plugins (the tags)
  16773. // -pluginsoff-panel.png / -pluginsoff-panel-one.png the list, all off, then after "Switch on" for one
  16774. // -export-default.png / -export.png the Export window as it opens, and with the additions in use
  16775. bool runLinkShot (const juce::String& prefix)
  16776. {
  16777. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  16778. juce::StringArray report;
  16779. bool allOk = true;
  16780. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  16781. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  16782. allOk = allOk && ok;
  16783. };
  16784. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  16785. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  16786. };
  16787. using lynx::AutomationTarget;
  16788. using lynx::AutomationTargetKind;
  16789. using lynx::MidiLink;
  16790. lynx::AudioEngine engine (false);
  16791. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 },
  16792. insert { AutomationTargetKind::mixerVolume, 1 };
  16793. // ---- the window as it opens on a control with no link (FL's defaults)
  16794. {
  16795. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  16796. shoot (*panel, "remote-default");
  16797. check ("default_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  16798. // Auto detect: the controller that sends next fills the fields
  16799. engine.injectControllerForTest (74, 2, 100, 5);
  16800. lynx::remoteControlPanelPoll (*panel);
  16801. check ("auto_detect", lynx::remoteControlPanelState (*panel).startsWith ("5|3|74|"), lynx::remoteControlPanelState (*panel));
  16802. // a formula preset, smoothing; Accept writes the link
  16803. lynx::remoteControlPanelSetController (*panel, -1, 1, 7);
  16804. lynx::remoteControlPanelSetFormula (*panel, "Tension(Input,10)");
  16805. lynx::remoteControlPanelSetSmoothing (*panel, true, 469);
  16806. shoot (*panel, "remote-formula-smoothing");
  16807. lynx::remoteControlPanelPress (*panel, 2);
  16808. const auto& links = engine.getSong().midiLinks;
  16809. check ("accept_writes_link", links.size() == 1 && links[0].cc == 7 && links[0].channel == 0 && links[0].port == -1
  16810. && links[0].formula == "Tension(Input,10)" && links[0].smooth && links[0].target == volume);
  16811. }
  16812. // ---- a broken formula: the message, the red text
  16813. {
  16814. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  16815. lynx::remoteControlPanelSetFormula (*panel, "Min(Input*2,");
  16816. shoot (*panel, "remote-formula-error");
  16817. check ("formula_error_shown", ! lynx::remoteControlPanelState (*panel).contains ("Compiled ok."), lynx::remoteControlPanelState (*panel));
  16818. }
  16819. // ---- the engine: formula, port, conflicts, omni
  16820. {
  16821. engine.editSong ([&] (lynx::Song& s) {
  16822. s.midiLinks.clear();
  16823. MidiLink inverted { 20, 0, volume };
  16824. inverted.formula = "1-Input";
  16825. MidiLink ported { 21, 0, pan };
  16826. ported.port = 3;
  16827. s.midiLinks = { inverted, ported };
  16828. });
  16829. engine.injectControllerForTest (20, 0, 127);
  16830. check ("formula_inverts", std::abs (engine.currentTargetValue (volume)) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  16831. engine.injectControllerForTest (20, 0, 0);
  16832. check ("formula_inverts_back", std::abs (engine.currentTargetValue (volume) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (volume)));
  16833. const auto panBefore = engine.currentTargetValue (pan);
  16834. engine.injectControllerForTest (21, 0, 127); // no port: not this link's device
  16835. check ("port_must_match", std::abs (engine.currentTargetValue (pan) - panBefore) < 0.001f);
  16836. engine.injectControllerForTest (21, 0, 127, 3);
  16837. check ("port_matches", std::abs (engine.currentTargetValue (pan) - 1.0f) < 0.01f, juce::String (engine.currentTargetValue (pan)));
  16838. // the window on a control whose controller another control uses: Remove conflicts in red; Accept removes it
  16839. auto panel = lynx::makeRemoteControlPanel (engine, { insert }, false);
  16840. lynx::remoteControlPanelSetController (*panel, -1, 1, 20);
  16841. shoot (*panel, "remote-conflict");
  16842. check ("conflict_counted", lynx::remoteControlPanelState (*panel).contains ("|1|"), lynx::remoteControlPanelState (*panel));
  16843. lynx::remoteControlPanelPress (*panel, 2);
  16844. const auto& links = engine.getSong().midiLinks;
  16845. check ("conflict_removed", links.size() == 2
  16846. && std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; })
  16847. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == insert && l.cc == 20; }));
  16848. engine.undo();
  16849. check ("accept_is_one_undo_step", engine.getSong().midiLinks.size() == 2 && engine.getSong().midiLinks[0].target == volume);
  16850. }
  16851. // ---- an existing link opened again: "Link 1" / "New link"
  16852. {
  16853. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  16854. shoot (*panel, "remote-existing-link");
  16855. check ("existing_link_loaded", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|20|1-Input|"), lynx::remoteControlPanelState (*panel));
  16856. // Reset, then Accept: a link without a controller is removed
  16857. lynx::remoteControlPanelPress (*panel, 0);
  16858. check ("reset_state", lynx::remoteControlPanelState (*panel).startsWith ("-1|1|-1|Input|"), lynx::remoteControlPanelState (*panel));
  16859. lynx::remoteControlPanelPress (*panel, 2);
  16860. const auto& links = engine.getSong().midiLinks;
  16861. check ("reset_accept_unlinks", std::none_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume; }));
  16862. }
  16863. // ---- several controls ("Link to controllers..."): Accept and Skip step through them
  16864. {
  16865. auto panel = lynx::makeRemoteControlPanel (engine, { volume, pan, insert }, false, [] {});
  16866. shoot (*panel, "remote-multilink");
  16867. const auto parameter = [&panel] { return juce::StringArray::fromTokens (lynx::remoteControlPanelState (*panel), "|", "")[6]; };
  16868. const auto first = parameter();
  16869. check ("multilink_caption_and_skip", first.startsWith ("1/3") && first.contains (lynx::tr ("Channel volume"))
  16870. && lynx::remoteControlPanelState (*panel).contains ("S|omni"),
  16871. lynx::remoteControlPanelState (*panel));
  16872. lynx::remoteControlPanelSetController (*panel, -1, 1, 30);
  16873. lynx::remoteControlPanelPress (*panel, 2); // Accept: volume linked, on to pan
  16874. const auto second = parameter();
  16875. lynx::remoteControlPanelPress (*panel, 1); // Skip: pan untouched, on to the insert
  16876. const auto third = parameter();
  16877. const auto beforeLast = lynx::remoteControlPanelFinished (*panel);
  16878. lynx::remoteControlPanelPress (*panel, 1); // Skip on the last one: done
  16879. const auto closed = ! beforeLast && lynx::remoteControlPanelFinished (*panel);
  16880. const auto& links = engine.getSong().midiLinks;
  16881. check ("multilink_steps", first != second && second != third && closed
  16882. && std::any_of (links.begin(), links.end(), [&] (const MidiLink& l) { return l.target == volume && l.cc == 30; }),
  16883. first + " > " + second + " > " + third);
  16884. }
  16885. // ---- Global link settings
  16886. {
  16887. auto panel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  16888. shoot (*panel, "global-default");
  16889. lynx::remoteControlPanelSetController (*panel, 2, 1, 11);
  16890. lynx::remoteControlPanelSetFormula (*panel, "Input*0.5");
  16891. lynx::remoteControlPanelPress (*panel, 2);
  16892. const auto global = engine.globalLinkOf (volume);
  16893. check ("global_link_written", global && global->cc == 11 && global->port == 2 && global->formula == "Input*0.5");
  16894. const auto text = engine.getMidiPrefs().toText();
  16895. const auto back = lynx::prefs::MidiPrefs::fromText (text);
  16896. check ("global_link_settings_round_trip", back.globalLinks == engine.getMidiPrefs().globalLinks && text.find ("linkset=2|0|469|Input*0.5") != std::string::npos);
  16897. auto again = lynx::makeRemoteControlPanel (engine, { volume }, true);
  16898. shoot (*again, "global-existing-link");
  16899. engine.setGlobalLink (volume, std::nullopt);
  16900. check ("global_link_removed", ! engine.globalLinkOf (volume));
  16901. }
  16902. // ---- the project file: links with settings come back; a project of an older version loads the same
  16903. {
  16904. lynx::Song song = engine.getSong();
  16905. MidiLink plain { 7, -1, volume };
  16906. MidiLink rich { 74, 2, pan };
  16907. rich.port = 4;
  16908. rich.formula = "Min(Input*1.1,0.5)+Max(Input*1.1,0.6)-0.6";
  16909. rich.smooth = true;
  16910. rich.smoothing = -300;
  16911. rich.omni = true;
  16912. song.midiLinks = { plain, rich };
  16913. juce::String error;
  16914. const auto json = lynx::ProjectFile::toJson (song);
  16915. const auto back = lynx::ProjectFile::fromJson (json, error);
  16916. check ("project_round_trip", back && back->midiLinks == song.midiLinks, error);
  16917. // without settings the file holds only the list older versions wrote
  16918. song.midiLinks = { plain };
  16919. const auto plainJson = lynx::ProjectFile::toJson (song);
  16920. check ("plain_links_write_the_old_form", ! plainJson.contains ("midiLinkSettings") && plainJson.contains ("midiLinks"));
  16921. const auto plainBack = lynx::ProjectFile::fromJson (plainJson, error);
  16922. check ("old_project_loads_the_same", plainBack && plainBack->midiLinks.size() == 1 && plainBack->midiLinks[0] == plain
  16923. && ! plainBack->midiLinks[0].hasSettings());
  16924. // what an older version does with a new file: it reads "midiLinks" alone, so the links stay (plain)
  16925. auto parsed = juce::JSON::parse (json);
  16926. if (auto* o = parsed.getDynamicObject())
  16927. o->removeProperty ("midiLinkSettings");
  16928. const auto stripped = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  16929. check ("older_version_keeps_the_links", stripped && stripped->midiLinks.size() == 2 && stripped->midiLinks[1].cc == 74
  16930. && ! stripped->midiLinks[1].hasSettings());
  16931. }
  16932. // ---- round 190cs: FL's live answers (live check 190cq) and the note / button link modes
  16933. {
  16934. const auto state = [] (juce::Component& p) { return lynx::remoteControlPanelState (p); };
  16935. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  16936. // the layout FL shows: no assignment list without a link, no Skip outside Multilink, no internal
  16937. // controller group without a controller in the project; the parameter caption in FL's words
  16938. auto fresh = lynx::makeRemoteControlPanel (engine, { volume }, false);
  16939. shoot (*fresh, "cs-remote-default");
  16940. check ("cs_layout_without_link", state (*fresh).contains ("|" + lynx::tr ("Channel volume") + "|") && state (*fresh).contains ("|shown=POC|"), state (*fresh));
  16941. // Omni: enabled on a mixer track's volume (FL: "Insert 1 - Volume"), greyed on the tempo
  16942. auto onInsert = lynx::makeRemoteControlPanel (engine, { insert }, false);
  16943. auto onTempo = lynx::makeRemoteControlPanel (engine, { AutomationTarget { AutomationTargetKind::tempo, 0 } }, false);
  16944. shoot (*onInsert, "cs-remote-omni-insert");
  16945. check ("cs_omni_mixer_track", state (*onInsert).contains ("|omni=on|") && state (*onTempo).contains ("|omni=off|"),
  16946. state (*onInsert) + " / " + state (*onTempo));
  16947. // the formula compiles on Enter only; FL's messages and colours
  16948. lynx::remoteControlPanelSetFormula (*fresh, "1-Input^2", false);
  16949. check ("cs_no_compile_while_typing", state (*fresh).contains ("|" + lynx::tr ("(default 1:1 mapping)") + "|"), state (*fresh));
  16950. lynx::remoteControlPanelSetFormula (*fresh, "-Input^2");
  16951. shoot (*fresh, "cs-remote-compiled");
  16952. check ("cs_compiled_on_enter", state (*fresh).contains ("|" + lynx::tr ("Compiled ok.") + "|"), state (*fresh));
  16953. const std::pair<const char*, const char*> errors[] { { "Input*", "Syntax error: function or operand" },
  16954. { "foo(Input)", "Invalid identifier: foo" },
  16955. { "Sin(Input", "Unequal brackets" },
  16956. { "Input 2", "input two space limited" } };
  16957. for (const auto& [text, expected] : errors)
  16958. {
  16959. lynx::remoteControlPanelSetFormula (*fresh, text);
  16960. check ("cs_fl_error_text", state (*fresh).contains (expected), state (*fresh));
  16961. }
  16962. lynx::remoteControlPanelSetFormula (*fresh, "foo(Input)");
  16963. shoot (*fresh, "cs-remote-error");
  16964. // Accept with that formula: the link is made, the formula is not kept (FL reopens it as "Input")
  16965. lynx::remoteControlPanelSetController (*fresh, -1, 1, 7);
  16966. lynx::remoteControlPanelPress (*fresh, 2);
  16967. check ("cs_bad_formula_accept_is_input", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == 7
  16968. && engine.getSong().midiLinks[0].formula.empty());
  16969. auto reopened = lynx::makeRemoteControlPanel (engine, { volume }, false);
  16970. shoot (*reopened, "cs-remote-reopened");
  16971. check ("cs_reopened_shows_input_and_link_list", state (*reopened).startsWith ("-1|1|7|Input|" + lynx::tr ("(default 1:1 mapping)") + "|")
  16972. && state (*reopened).contains ("|shown=PAOC|"),
  16973. state (*reopened));
  16974. // the internal controller group appears with a controller in the project, with "Record automation"
  16975. engine.editSong ([] (lynx::Song& s) {
  16976. lynx::EffectSlot peak;
  16977. peak.kind = lynx::EffectKind::peakController;
  16978. s.mixer[0].effects.push_back (peak);
  16979. });
  16980. auto withController = lynx::makeRemoteControlPanel (engine, { volume }, false);
  16981. lynx::remoteControlPanelSetInternal (*withController, 1, true);
  16982. shoot (*withController, "cs-remote-internal");
  16983. check ("cs_internal_group_shown", state (*withController).contains ("|shown=PAIOC|") && state (*withController).startsWith ("-1|1|-1|"),
  16984. state (*withController));
  16985. lynx::remoteControlPanelPress (*withController, 2);
  16986. const auto& autos = engine.getSong().automations;
  16987. check ("cs_record_automation_kept", std::any_of (autos.begin(), autos.end(), [&] (const lynx::Automation& a) {
  16988. return a.isLive() && a.target == volume && a.recordLive;
  16989. }));
  16990. engine.editSong ([] (lynx::Song& s) {
  16991. s.mixer[0].effects.pop_back();
  16992. s.automations.clear();
  16993. s.midiLinks.clear();
  16994. });
  16995. // the global window: no parameter list, Omni, Remove conflicts or Skip; Mode is there
  16996. auto globalPanel = lynx::makeRemoteControlPanel (engine, { volume }, true);
  16997. shoot (*globalPanel, "cs-global-default");
  16998. check ("cs_global_layout", state (*globalPanel).contains ("|shown=|"), state (*globalPanel));
  16999. // a key link in each Mode: note 60 = FL's controller number 256 + 60
  17000. const auto key = lynx::linkNoteBase + 60;
  17001. auto modePanel = lynx::makeRemoteControlPanel (engine, { volume }, false);
  17002. lynx::remoteControlPanelSetController (*modePanel, -1, 1, key);
  17003. lynx::remoteControlPanelSetMode (*modePanel, 2);
  17004. shoot (*modePanel, "cs-remote-note-latch");
  17005. lynx::remoteControlPanelPress (*modePanel, 2);
  17006. check ("cs_note_link_written", engine.getSong().midiLinks.size() == 1 && engine.getSong().midiLinks[0].cc == key
  17007. && engine.getSong().midiLinks[0].mode == 2);
  17008. const auto play = [&engine, key, volume] (int velocity) {
  17009. engine.injectControllerForTest (key, 0, velocity);
  17010. return engine.currentTargetValue (volume);
  17011. };
  17012. const auto setMode = [&engine] (int mode) {
  17013. engine.editSong ([mode] (lynx::Song& s) { s.midiLinks[0].mode = mode; });
  17014. engine.editSong ([] (lynx::Song& s) { s.setTargetValue ({ AutomationTargetKind::channelVolume, 0 }, 0.25f); });
  17015. };
  17016. setMode (2); // Latch: press switches, release does nothing
  17017. const auto l1 = play (100), l1off = play (0), l2 = play (90), l2off = play (0);
  17018. check ("cs_mode_latch", std::abs (l1 - 1.0f) < 1e-4f && std::abs (l1off - 1.0f) < 1e-4f && l2 < 1e-4f && l2off < 1e-4f,
  17019. juce::String (l1) + " " + juce::String (l1off) + " " + juce::String (l2) + " " + juce::String (l2off));
  17020. setMode (1); // Hold: the velocity while held, back to 0 on release
  17021. const auto h1 = play (100), h1off = play (0);
  17022. check ("cs_mode_hold", std::abs (h1 - 100.0f / 127.0f) < 1e-4f && h1off < 1e-4f, juce::String (h1) + " " + juce::String (h1off));
  17023. setMode (0); // Default: as Hold for a key
  17024. const auto d1 = play (64), d1off = play (0);
  17025. check ("cs_mode_default", std::abs (d1 - 64.0f / 127.0f) < 1e-4f && d1off < 1e-4f, juce::String (d1) + " " + juce::String (d1off));
  17026. setMode (3); // Inc: each press adds 1/128
  17027. const auto i1 = play (100), i1off = play (0), i2 = play (20);
  17028. check ("cs_mode_inc", std::abs (i1 - (0.25f + 1.0f / 128.0f)) < 1e-4f && std::abs (i1off - i1) < 1e-6f
  17029. && std::abs (i2 - (0.25f + 2.0f / 128.0f)) < 1e-4f,
  17030. juce::String (i1) + " " + juce::String (i2));
  17031. setMode (4); // Stay: the velocity, kept after the release
  17032. const auto s1 = play (100), s1off = play (0);
  17033. 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));
  17034. // the project file keeps the key link and its mode; an older reader skips it
  17035. lynx::Song song = engine.getSong();
  17036. song.midiLinks[0].mode = 2;
  17037. MidiLink cc7 { 7, 0, pan };
  17038. cc7.mode = 4;
  17039. song.midiLinks.insert (song.midiLinks.begin(), cc7);
  17040. juce::String error;
  17041. const auto json = lynx::ProjectFile::toJson (song);
  17042. const auto back = lynx::ProjectFile::fromJson (json, error);
  17043. check ("cs_note_link_round_trip", back && back->midiLinks == song.midiLinks && json.contains ("midiNoteLinks"), error);
  17044. auto parsed = juce::JSON::parse (json);
  17045. if (auto* o = parsed.getDynamicObject())
  17046. {
  17047. o->removeProperty ("midiNoteLinks");
  17048. o->removeProperty ("midiLinkSettings");
  17049. }
  17050. const auto older = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  17051. check ("cs_older_reader_keeps_cc_links_only", older && older->midiLinks.size() == 1 && older->midiLinks[0].cc == 7);
  17052. // "Record automation" of an internal-controller link, saved only when on
  17053. lynx::Automation live;
  17054. live.target = volume;
  17055. live.source.track = 0;
  17056. live.recordLive = true;
  17057. song.automations = { live };
  17058. const auto withLive = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  17059. live.recordLive = false;
  17060. song.automations = { live };
  17061. check ("cs_record_automation_round_trip", withLive && withLive->automations.size() == 1 && withLive->automations[0].recordLive
  17062. && ! lynx::ProjectFile::toJson (song).contains ("recordLive"));
  17063. engine.editSong ([] (lynx::Song& s) { s.midiLinks.clear(); });
  17064. }
  17065. // ---- menus: the control menu, the formula presets, the controller list, the Multilink items
  17066. {
  17067. juce::PopupMenu control;
  17068. lynx::addAutomationItem (control, engine, volume, true);
  17069. engine.setMultilink (true);
  17070. engine.noteTweaked (volume);
  17071. engine.noteTweaked (pan);
  17072. juce::PopupMenu multilink;
  17073. lynx::addMultilinkControlsItems (multilink, engine);
  17074. check ("multilink_queue", engine.multilinkTargets().size() == 2);
  17075. engine.setMultilink (false);
  17076. saveMenus (juce::StringArray { "Control menu", "Formula presets", "Multilink" },
  17077. std::vector<juce::PopupMenu> { control, lynx::remoteControlFormulaMenu ([] (const juce::String&) {}), multilink },
  17078. prefix + "-menus.png");
  17079. saveMenus (juce::StringArray { "Ctrl menu" }, std::vector<juce::PopupMenu> { lynx::remoteControlControllerMenu ([] (int) {}) },
  17080. prefix + "-ctrl-menu.png");
  17081. // the Mode list as its box pops it up (round 190cs)
  17082. juce::PopupMenu modes;
  17083. for (const char* m : { "Default", "Hold", "Latch", "Inc", "Stay" })
  17084. modes.addItem (lynx::tr (m), true, juce::String (m) == "Default", [] {});
  17085. saveMenus (juce::StringArray { "Mode" }, std::vector<juce::PopupMenu> { modes }, prefix + "-mode-menu.png");
  17086. }
  17087. // ---- Settings > MIDI: the input's Port box, the link list with a link's settings
  17088. {
  17089. engine.editSong ([&] (lynx::Song& s) {
  17090. MidiLink l { 74, 2, pan };
  17091. l.port = 4;
  17092. l.formula = "1-Input";
  17093. l.smooth = true;
  17094. s.midiLinks = { MidiLink { 7, 0, volume }, l };
  17095. });
  17096. auto page = lynx::makeMidiPage (engine, {}, false);
  17097. page->setSize (760, 900);
  17098. shoot (*page, "settings-midi");
  17099. }
  17100. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  17101. return allOk;
  17102. }
  17103. // A stand-in hosted plugin for the shot route: three parameters, its state = their values
  17104. struct FlCtlShotPlugin final : juce::AudioPluginInstance
  17105. {
  17106. FlCtlShotPlugin()
  17107. {
  17108. for (const char* n : { "Cutoff", "Resonance", "Drive" })
  17109. addHostedParameter (std::make_unique<juce::AudioParameterFloat> (juce::ParameterID (n, 1), n, 0.0f, 1.0f, 0.5f));
  17110. }
  17111. const juce::String getName() const override { return "Shot plugin"; }
  17112. void prepareToPlay (double, int) override {}
  17113. void releaseResources() override {}
  17114. void processBlock (juce::AudioBuffer<float>&, juce::MidiBuffer&) override {}
  17115. double getTailLengthSeconds() const override { return 0.0; }
  17116. bool acceptsMidi() const override { return false; }
  17117. bool producesMidi() const override { return false; }
  17118. juce::AudioProcessorEditor* createEditor() override { return nullptr; }
  17119. bool hasEditor() const override { return false; }
  17120. int getNumPrograms() override { return 1; }
  17121. int getCurrentProgram() override { return 0; }
  17122. void setCurrentProgram (int) override {}
  17123. const juce::String getProgramName (int) override { return {}; }
  17124. void changeProgramName (int, const juce::String&) override {}
  17125. void getStateInformation (juce::MemoryBlock& b) override
  17126. {
  17127. for (auto* p : getParameters())
  17128. {
  17129. const float v = static_cast<juce::AudioParameterFloat*> (p)->get();
  17130. b.append (&v, sizeof (float));
  17131. }
  17132. }
  17133. void setStateInformation (const void* data, int size) override
  17134. {
  17135. const auto& list = getParameters();
  17136. for (int i = 0; i < list.size() && (i + 1) * (int) sizeof (float) <= size; ++i)
  17137. *static_cast<juce::AudioParameterFloat*> (list[i]) = static_cast<const float*> (data)[i];
  17138. }
  17139. void fillInPluginDescription (juce::PluginDescription& d) const override
  17140. {
  17141. d.name = getName();
  17142. d.pluginFormatName = "Shot";
  17143. d.fileOrIdentifier = "shot";
  17144. }
  17145. };
  17146. static juce::File writeShotSample (const juce::File& file, double hz)
  17147. {
  17148. juce::AudioBuffer<float> buffer (1, 22050);
  17149. for (int i = 0; i < buffer.getNumSamples(); ++i)
  17150. buffer.setSample (0, i, (float) (std::sin (juce::MathConstants<double>::twoPi * hz * i / 44100.0) * std::exp (-i / 6000.0)));
  17151. file.deleteFile();
  17152. juce::WavAudioFormat wav;
  17153. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  17154. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  17155. return file;
  17156. }
  17157. static bool clickMenuItem (const juce::PopupMenu& menu, const juce::String& text)
  17158. {
  17159. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  17160. if (it.getItem().text == text && it.getItem().isEnabled && it.getItem().action != nullptr)
  17161. {
  17162. it.getItem().action();
  17163. return true;
  17164. }
  17165. return false;
  17166. }
  17167. // --samplerpageshot <prefix> (round 190dh): FL's Sampler page offscreen — the page as FL's shot (dock188a) shows it,
  17168. // the legacy effects, a small window, a zoomed waveform — and its laws turned as a user would; prefix-checks.txt
  17169. bool runSamplerPageShot (const juce::String& prefix)
  17170. {
  17171. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17172. juce::StringArray report;
  17173. bool allOk = true;
  17174. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  17175. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  17176. allOk = allOk && ok;
  17177. };
  17178. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  17179. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  17180. };
  17181. lynx::AudioEngine engine (false);
  17182. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("sampler-samples");
  17183. folder.createDirectory();
  17184. // an 808-like kick, 1 s (FL's shot: "Basic 808 Kick.wav")
  17185. const auto kick = folder.getChildFile ("Basic 808 Kick.wav");
  17186. {
  17187. juce::AudioBuffer<float> buffer (1, 44100);
  17188. double phase = 0.0;
  17189. for (int i = 0; i < buffer.getNumSamples(); ++i)
  17190. {
  17191. const auto t = i / 44100.0;
  17192. phase += juce::MathConstants<double>::twoPi * (48.0 + 90.0 * std::exp (-t * 30.0)) / 44100.0;
  17193. buffer.setSample (0, i, (float) (0.9 * std::sin (phase) * std::exp (-t * 3.2)));
  17194. }
  17195. kick.deleteFile();
  17196. juce::WavAudioFormat wav;
  17197. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (kick.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  17198. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  17199. }
  17200. engine.editSong ([&] (lynx::Song& s) {
  17201. if (s.channels.empty())
  17202. s.channels.resize (1);
  17203. lynx::audioclips::loadSampleInto (s.channels[0], kick.getFullPathName().toStdString(), "808 Kick");
  17204. // FL's shot: Resample and Load regions on, Use loop points on, declicking "Out only (no bleeding)"
  17205. s.channels[0].sampler.resampleOnLoad = true;
  17206. });
  17207. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  17208. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  17209. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  17210. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  17211. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  17212. shoot (*frame, "sampler-page");
  17213. report.add ("page size " + juce::String (frame->getWidth()) + "x" + juce::String (frame->getHeight()));
  17214. // ---- the laws, turned on the page
  17215. auto& f = *frame;
  17216. lynx::samplerPageTurn (f, "pingPong", 1.0);
  17217. check ("ping_pong", sampler().precompute.pingPong);
  17218. lynx::samplerPageTurn (f, "pingPong", 0.0);
  17219. lynx::samplerPageTurn (f, "loopStart", 5000.0);
  17220. check ("loop_start", sampler().loopStart == 5000 && sampler().loopEnd == 5001, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  17221. lynx::samplerPageTurn (f, "loopEnd", 15000.0);
  17222. check ("loop_end", sampler().loopStart == 5000 && sampler().loopEnd == 15000);
  17223. lynx::samplerPageTurn (f, "loopStart", 20000.0, true); // Shift: the loop moves
  17224. check ("loop_shift_moves", sampler().loopStart == 20000 && sampler().loopEnd == 30000, juce::String (sampler().loopStart) + "/" + juce::String (sampler().loopEnd));
  17225. check ("keep_on_disk_greyed_with_loop", lynx::samplerPageQuery (f, "keepOnDisk") == "0");
  17226. lynx::samplerPageTurn (f, "useLoops", 0.0);
  17227. check ("keep_on_disk_back", lynx::samplerPageQuery (f, "keepOnDisk") == "1" && ! sampler().useLoopPoints);
  17228. check ("not_cut_yet", ! lynx::channelCutsItself (engine.getSong().channels[0]));
  17229. lynx::samplerPageTurn (f, "useLoops", 1.0);
  17230. check ("use_loops_cuts_itself", sampler().useLoopPoints && lynx::channelCutsItself (engine.getSong().channels[0]));
  17231. engine.editSong ([] (lynx::Song& s) {
  17232. lynx::setChannelCutsItself (s.channels[0], 0, false);
  17233. s.channels[0].sampler.useLoopPoints = false;
  17234. });
  17235. lynx::samplerPageTurn (f, "crossfade", 300.0); // (Use loop points off: the crossfade switches it on)
  17236. check ("crossfade_switches_loops_on", sampler().precompute.crossfade == 300 && sampler().useLoopPoints);
  17237. lynx::samplerPageTurn (f, "crossfade", 0.0);
  17238. lynx::samplerPageTurn (f, "pitch", 300.0); // (Resample: FL switches to Auto)
  17239. check ("pitch_resample_to_auto", sampler().keepPitch && sampler().flStretchMode == 5 && sampler().flStretchPitch == 300
  17240. && lynx::samplerPageQuery (f, "mode") == lynx::tr ("General"),
  17241. lynx::samplerPageQuery (f, "mode") + " " + juce::String (sampler().pitch));
  17242. lynx::samplerPageTurn (f, "pitch", 0.0);
  17243. lynx::samplerPageTurn (f, "mode", 1.0); // Resample
  17244. check ("mode_resample", ! sampler().keepPitch && std::abs (sampler().pitch) < 1.0e-4f);
  17245. lynx::samplerPageTurn (f, "time", 4.0);
  17246. lynx::samplerPageTurn (f, "mul", 10000.0);
  17247. check ("time_mul", std::abs (sampler().stretchBeats - 8.0f) < 1.0e-3f && sampler().stretchMul == 10000, juce::String (sampler().stretchBeats));
  17248. lynx::samplerPageTurn (f, "mul", 0.0);
  17249. lynx::samplerPageTurn (f, "time", 0.0);
  17250. lynx::samplerPageTurn (f, "length", 0.5);
  17251. lynx::samplerPageTurn (f, "smpStart", 0.5);
  17252. check ("smp_start_keeps_length", std::abs (sampler().regionStart - 0.5f) < 1.0e-3f && std::abs (sampler().regionEnd - 0.75f) < 1.0e-3f,
  17253. juce::String (sampler().regionStart) + "-" + juce::String (sampler().regionEnd));
  17254. lynx::samplerPageTurn (f, "smpStart", 0.0);
  17255. lynx::samplerPageTurn (f, "length", 1.0);
  17256. lynx::samplerPageTurn (f, "declick", 4.0);
  17257. check ("declick_mode", sampler().declickMode == 4);
  17258. lynx::samplerPageTurn (f, "declick", 0.0);
  17259. // ---- the .lynx keeps what the page set
  17260. {
  17261. lynx::samplerPageTurn (f, "mul", -5000.0);
  17262. lynx::samplerPageTurn (f, "keepOnDisk", 1.0);
  17263. juce::String error;
  17264. const auto json = lynx::ProjectFile::toJson (engine.getSong(), false);
  17265. const auto back = lynx::ProjectFile::fromJson (json, error);
  17266. check ("lynx_round_trip", back.has_value() && back->channels[0].sampler == engine.getSong().channels[0].sampler, error);
  17267. lynx::samplerPageTurn (f, "mul", 0.0);
  17268. lynx::samplerPageTurn (f, "keepOnDisk", 0.0);
  17269. }
  17270. // ---- shots: FL's state again (loop points from the file: none), the legacy panel, a zoom, a small window
  17271. engine.editSong ([] (lynx::Song& s) {
  17272. auto& ch = s.channels[0];
  17273. ch.sampler.loopStart = ch.sampler.loopEnd = -1;
  17274. ch.sampler.useLoopPoints = true;
  17275. ch.sampler.precompute = {};
  17276. });
  17277. lynx::samplerPageTurn (f, "show", 0.0); // (no control: the page shows the channel again)
  17278. frame->createComponentSnapshot (frame->getLocalBounds());
  17279. shoot (*frame, "sampler-page-fl-state");
  17280. lynx::samplerPageTurn (f, "legacy", 1.0);
  17281. check ("legacy_panel", lynx::samplerPageQuery (f, "legacy") == "1");
  17282. shoot (*frame, "sampler-page-legacy");
  17283. lynx::samplerPageTurn (f, "legacy", 0.0);
  17284. lynx::samplerPageTurn (f, "zoom", 0.25);
  17285. check ("zoom_scroll", lynx::samplerPageQuery (f, "scroll") == "0.250", lynx::samplerPageQuery (f, "scroll"));
  17286. shoot (*frame, "sampler-page-zoom");
  17287. lynx::samplerPageTurn (f, "zoom", 1.0);
  17288. frame->setSize (520, 470);
  17289. frame->createComponentSnapshot (frame->getLocalBounds());
  17290. shoot (*frame, "sampler-page-small");
  17291. report.add (juce::String ("result=") + (allOk ? "OK" : "FAIL"));
  17292. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  17293. return allOk;
  17294. }
  17295. bool runFlCtlShot (const juce::String& prefix)
  17296. {
  17297. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17298. juce::StringArray report;
  17299. bool allOk = true;
  17300. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  17301. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  17302. allOk = allOk && ok;
  17303. };
  17304. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  17305. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  17306. };
  17307. using lynx::AutomationTarget;
  17308. using lynx::AutomationTargetKind;
  17309. lynx::AudioEngine engine (false);
  17310. engine.editSong ([] (lynx::Song& s) {
  17311. if (s.channels.size() < 3)
  17312. s.channels.resize (3);
  17313. if (s.patterns.empty())
  17314. s.patterns.resize (1);
  17315. s.currentPattern = 0;
  17316. });
  17317. const AutomationTarget volume { AutomationTargetKind::channelVolume, 0 }, pan { AutomationTargetKind::channelPan, 0 };
  17318. // ---- FL's multilink menu: on with two queued controls, off with the last tweaked parameters
  17319. {
  17320. engine.setMultilink (true);
  17321. engine.noteTweaked (volume);
  17322. engine.noteTweaked (pan);
  17323. auto on = lynx::multilinkButtonMenu (engine);
  17324. juce::PopupMenu::MenuItemIterator first (on);
  17325. first.next();
  17326. check ("ml_caption_on", first.getItem().isSectionHeader && first.getItem().text == lynx::tr ("{0} parameters selected", { "2" }), first.getItem().text);
  17327. // Init pattern: the values at the pattern's start; ends multilink
  17328. const auto v0 = engine.currentTargetValue (volume);
  17329. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initPattern, engine.multilinkTargets(), 0);
  17330. const auto& lanes = engine.getSong().patterns[0].events;
  17331. check ("ml_init_pattern", lanes.size() == 2 && ! lanes[0].events.empty() && lanes[0].events[0].tick == 0
  17332. && std::abs (lanes[0].events[0].value - v0) < 1.0e-6f && ! engine.isMultilinkOn());
  17333. // Randomize keeps multilink on; Humanize moves at most an eighth
  17334. engine.setMultilink (true);
  17335. engine.noteTweaked (volume);
  17336. engine.noteTweaked (pan);
  17337. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::randomize, engine.multilinkTargets(), 1234);
  17338. check ("ml_randomize_keeps_queue", engine.isMultilinkOn() && engine.multilinkTargets().size() == 2);
  17339. const auto before = engine.currentTargetValue (volume);
  17340. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::humanize, engine.multilinkTargets(), 99);
  17341. check ("ml_humanize_small", std::abs (engine.currentTargetValue (volume) - before) <= 0.1251f && engine.isMultilinkOn(),
  17342. juce::String (before) + " -> " + juce::String (engine.currentTargetValue (volume)));
  17343. lynx::runMultilinkAction (engine, lynx::mlmenu::Action::initSong, engine.multilinkTargets(), 0);
  17344. check ("ml_init_song", engine.getSong().findInitialValue (volume) >= 0 && ! engine.isMultilinkOn());
  17345. // off: the last two tweaked parameters, no Cancel
  17346. auto off = lynx::multilinkButtonMenu (engine);
  17347. bool hasCancel = false;
  17348. for (juce::PopupMenu::MenuItemIterator it (off); it.next();)
  17349. hasCancel = hasCancel || it.getItem().text == lynx::tr ("Cancel");
  17350. juce::PopupMenu::MenuItemIterator offFirst (off);
  17351. offFirst.next();
  17352. check ("ml_off_caption", offFirst.getItem().text == lynx::tr ("Last 2 tweaked parameters") && ! hasCancel, offFirst.getItem().text);
  17353. // LYNX's own one-step items stay, after FL's items below a line (greyed while multilink is off)
  17354. juce::String last;
  17355. bool lineBefore = false, prevLine = false;
  17356. for (juce::PopupMenu::MenuItemIterator it (on); it.next();)
  17357. {
  17358. if (it.getItem().text == lynx::tr ("Link to controller"))
  17359. lineBefore = prevLine;
  17360. prevLine = it.getItem().isSeparator;
  17361. last = it.getItem().text;
  17362. }
  17363. check ("ml_lynx_items_after_fl", lineBefore && last == lynx::tr ("Override global links"), last);
  17364. saveMenus (juce::StringArray { "Multilink on (2 queued)", "Multilink off" }, std::vector<juce::PopupMenu> { on, off },
  17365. prefix + "-multilink-menu.png");
  17366. }
  17367. // ---- the plugin menu's spare state and Parameters > Link all parameters...
  17368. {
  17369. FlCtlShotPlugin plugin;
  17370. juce::PopupMenu menu;
  17371. lynx::addPluginWrapperItems (menu, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  17372. saveMenus (juce::StringArray { "Plugin menu: spare state and parameters" }, std::vector<juce::PopupMenu> { menu }, prefix + "-plugin-menu.png");
  17373. const auto targets = lynx::allPluginParameterTargets (plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  17374. check ("link_all_parameters", targets.size() == 3 && targets[2].param == 2 && targets[2].index == 1);
  17375. auto* cutoff = static_cast<juce::AudioParameterFloat*> (plugin.getParameters()[0]);
  17376. *cutoff = 0.2f;
  17377. check ("spare_store", clickMenuItem (menu, lynx::tr ("Store in spare state")));
  17378. *cutoff = 0.9f;
  17379. juce::PopupMenu again;
  17380. lynx::addPluginWrapperItems (again, engine, plugin, { AutomationTargetKind::channelParam, 1, 0, 0 });
  17381. check ("spare_flip", clickMenuItem (again, lynx::tr ("Flip with spare state")) && std::abs (cutoff->get() - 0.2f) < 1.0e-6f, juce::String (cutoff->get()));
  17382. 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()));
  17383. lynx::sparestate::shared().forget (&plugin);
  17384. }
  17385. // ---- the sampler's File row: Load (history menu, wheel), Locate, Remove
  17386. {
  17387. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flctl-samples");
  17388. folder.createDirectory();
  17389. const auto a = writeShotSample (folder.getChildFile ("Kick 1.wav"), 60.0), b = writeShotSample (folder.getChildFile ("Snare 2.wav"), 200.0),
  17390. c = writeShotSample (folder.getChildFile ("Hat 3.wav"), 900.0);
  17391. lynx::samplehistory::list().clear();
  17392. engine.editSong ([&] (lynx::Song& s) {
  17393. for (const auto& f : { c, b, a }) // (each load goes into the history, newest first)
  17394. lynx::audioclips::loadSampleInto (s.channels[1], f.getFullPathName().toStdString(), f.getFileNameWithoutExtension().toStdString());
  17395. });
  17396. check ("history_order", lynx::samplehistory::list().size() == 3 && lynx::samplehistory::list().front() == a.getFullPathName().toStdString());
  17397. juce::File located;
  17398. lynx::locateInBrowserHandler() = [&located] (const juce::File& f) { located = f; };
  17399. auto frame = lynx::makeChannelFrame (engine, 1, 0);
  17400. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 820);
  17401. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the waveform's analysis)
  17402. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  17403. shoot (*frame, "sampler-file-row");
  17404. const auto history = lynx::samplerHistoryMenu (*frame);
  17405. check ("history_menu", history.has_value() && history->getNumItems() == 4); // (caption + three samples)
  17406. if (history)
  17407. saveMenus (juce::StringArray { "Load: Sample history" }, std::vector<juce::PopupMenu> { *history }, prefix + "-sample-history.png");
  17408. lynx::samplerFileRowPress (*frame, 0); // wheel down: the next (older) sample
  17409. check ("wheel_down", engine.getSong().channels[1].samplePath == b.getFullPathName().toStdString(), juce::String (engine.getSong().channels[1].samplePath));
  17410. lynx::samplerFileRowPress (*frame, 1); // wheel up: back
  17411. check ("wheel_up", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  17412. lynx::samplerFileRowPress (*frame, 2);
  17413. check ("locate", located == a, located.getFullPathName());
  17414. lynx::samplerFileRowPress (*frame, 3);
  17415. check ("remove", engine.getSong().channels[1].samplePath.empty());
  17416. engine.undo();
  17417. check ("remove_undo", engine.getSong().channels[1].samplePath == a.getFullPathName().toStdString());
  17418. lynx::locateInBrowserHandler() = nullptr;
  17419. }
  17420. // ---- a sampler running FL's voice: FL's Envelope / instrument page with the tensions, the predelay and presets
  17421. {
  17422. engine.editSong ([] (lynx::Song& s) {
  17423. auto& ch = s.channels[2];
  17424. ch.instrument = lynx::InstrumentKind::sampler;
  17425. ch.name = "FL sampler";
  17426. const auto snap = lynx::flvp::defaultSnapshot();
  17427. ch.sampler.flChannel.assign (90, 0);
  17428. std::memcpy (ch.sampler.flChannel.data(), snap.data(), 85 * 4);
  17429. std::memcpy (&ch.sampler.flChannel[85], snap.data() + 0x15c, 4);
  17430. std::memcpy (&ch.sampler.flChannel[86], snap.data() + 0x160, 4);
  17431. std::memcpy (&ch.sampler.flChannel[87], snap.data() + 0x168, 4);
  17432. ch.sampler.flChannel[88] = 96;
  17433. ch.sampler.flChannel[89] = 0;
  17434. auto& vol = ch.sampler.flChannel; // the volume envelope on, bent
  17435. vol[17 + 1] = -1;
  17436. vol[17 + 2] = 4000; // predelay
  17437. vol[17 + 14] = -70; // attack tension
  17438. vol[17 + 15] = 60; // decay tension
  17439. vol[17 + 16] = -40; // release tension
  17440. });
  17441. auto frame = lynx::makeChannelFrame (engine, 2, 1);
  17442. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 600, frame->getHeight() > 0 ? frame->getHeight() : 560);
  17443. shoot (*frame, "sampler-fl-envelope");
  17444. check ("fl_page_shown", lynx::flVoicePresetsMenu (*frame).has_value());
  17445. lynx::flVoicePresetFolder().deleteRecursively();
  17446. check ("preset_save", lynx::flVoiceSavePreset (*frame, "Bent volume")
  17447. && lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV").getSize() == 68);
  17448. if (const auto menu = lynx::flVoicePresetsMenu (*frame))
  17449. saveMenus (juce::StringArray { "Channel envelope presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-envelope-presets.png");
  17450. // the preset into the pitch target: its record becomes the saved one
  17451. lynx::showFlVoiceTarget (*frame, lynx::flvoice::pitch);
  17452. const auto loaded = lynx::flVoiceLoadPreset (*frame, lynx::flVoicePresetFolder().getChildFile ("Bent volume.CHENV"));
  17453. const auto& fl = engine.getSong().channels[2].sampler.flChannel;
  17454. check ("preset_load", loaded && fl.size() == 90 && fl[68 + 2] == 4000 && fl[68 + 14] == -70 && fl[68 + 16] == -40 && fl[88] == 96);
  17455. engine.undo();
  17456. check ("preset_load_undo", engine.getSong().channels[2].sampler.flChannel[68 + 14] != -70);
  17457. }
  17458. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  17459. return allOk;
  17460. }
  17461. // --flplshot (round 190dx): see the dispatch above
  17462. bool runHdrShot190ft (const juce::String& prefix)
  17463. {
  17464. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17465. juce::StringArray report;
  17466. bool allOk = true;
  17467. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  17468. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  17469. allOk = allOk && ok;
  17470. };
  17471. const auto list = [] (const std::vector<int>& v) {
  17472. juce::StringArray out;
  17473. for (auto i : v)
  17474. out.add (juce::String (i));
  17475. return out.joinIntoString (",");
  17476. };
  17477. lynx::AudioEngine engine (false);
  17478. lynx::MainComponent ui (engine, false);
  17479. ui.setSize (1600, 900);
  17480. {
  17481. auto song = lynx::Song::makeDefault();
  17482. song.playlist.clear();
  17483. for (int t = 0; t < 6; ++t)
  17484. {
  17485. if ((int) song.playlistTracks.size() <= t)
  17486. song.playlistTracks.resize ((std::size_t) t + 1);
  17487. song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
  17488. for (int k = 0; k < 2; ++k)
  17489. {
  17490. lynx::Clip c;
  17491. c.kind = lynx::ClipKind::pattern;
  17492. c.pattern = 0;
  17493. c.track = t;
  17494. c.start = (std::int64_t) (k * 4 + t % 3) * lynx::ppq;
  17495. c.length = 2 * lynx::ppq;
  17496. song.playlist.push_back (c);
  17497. }
  17498. }
  17499. if (song.mixer.size() < 4)
  17500. song.mixer.resize (4);
  17501. song.playlistTracks[2].mode = lynx::PlaylistTrackMode::audio; // an audio track linked to mixer track 3
  17502. song.playlistTracks[2].mixerTrack = 3;
  17503. song.playlistTracks[2].name = "Vox";
  17504. engine.setSong (std::move (song));
  17505. }
  17506. engine.dispatchPendingMessages();
  17507. ui.selectTabForSnapshot (2);
  17508. engine.dispatchPendingMessages();
  17509. auto& pl = ui.getPlaylistForSnapshot();
  17510. pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
  17511. auto source = juce::Desktop::getInstance().getMainMouseSource();
  17512. const auto now = juce::Time::getCurrentTime();
  17513. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  17514. const int ctrl = juce::ModifierKeys::commandModifier; // (FL's Ctrl: Cmd on a Mac)
  17515. const int shift = juce::ModifierKeys::shiftModifier;
  17516. const int alt = juce::ModifierKeys::altModifier;
  17517. const auto event = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  17518. 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);
  17519. };
  17520. // a press (and release) at p with the modifiers; `to`: a drag there before the release
  17521. const auto press = [&] (juce::Component& c, juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}, int clicks = 1) {
  17522. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  17523. c.mouseMove (event (c, p, mods, p, 1, false));
  17524. c.mouseDown (event (c, p, down, p, clicks, false));
  17525. if (to)
  17526. c.mouseDrag (event (c, *to, down, p, clicks, true));
  17527. c.mouseUp (event (c, to ? *to : p, mods, p, clicks, to.has_value()));
  17528. };
  17529. const auto headerPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getY() + juce::jmin (10, r.getHeight() / 3)); };
  17530. const auto bandPoint = [&] (int track) { const auto r = pl.trackRowForSnapshot (track); return juce::Point<int> (40, r.getBottom() - 2); };
  17531. const auto clipsOn = [&] (const std::vector<int>& tracks) {
  17532. std::vector<int> out;
  17533. const auto& song = engine.getSong();
  17534. for (int i = 0; i < (int) song.playlist.size(); ++i)
  17535. if (std::find (tracks.begin(), tracks.end(), song.playlist[(std::size_t) i].track) != tracks.end())
  17536. out.push_back (i);
  17537. return out;
  17538. };
  17539. const auto sortedClips = [&] { auto v = pl.getSelectedClips(); std::sort (v.begin(), v.end()); return v; };
  17540. const auto headerShot = [&] (const juce::String& name, int rows) {
  17541. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  17542. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 760), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  17543. };
  17544. // ---- 1. selection (AUTracksPanelMouseDown / FUN_012e83e0)
  17545. press (pl, headerPoint (1), {});
  17546. check ("click_selects_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
  17547. pl.selectClipsForSnapshot ({});
  17548. // LYNX extra (issue #163): Ctrl+click adds / removes one track, its clips follow
  17549. press (pl, headerPoint (3), ctrl);
  17550. check ("ctrl_click_adds_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3 } && sortedClips() == clipsOn ({ 3 }),
  17551. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  17552. press (pl, headerPoint (5), ctrl);
  17553. press (pl, headerPoint (1), ctrl);
  17554. check ("ctrl_click_removes_lynx", pl.selectedTracksForSnapshot() == std::vector<int> { 3, 5 } && sortedClips() == clipsOn ({ 3, 5 }),
  17555. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  17556. // FL's own toggle: Ctrl+Shift+click (its clips are added)
  17557. press (pl, headerPoint (1), ctrl | shift);
  17558. check ("ctrl_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
  17559. check ("ctrl_shift_click_adds_clips", sortedClips() == clipsOn ({ 1, 3, 5 }), list (sortedClips()));
  17560. press (pl, headerPoint (3), ctrl | shift);
  17561. check ("ctrl_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 5 }, list (pl.selectedTracksForSnapshot()));
  17562. press (pl, headerPoint (3), ctrl | shift);
  17563. check ("ctrl_shift_click_adds_again", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 3, 5 }, list (pl.selectedTracksForSnapshot()));
  17564. pl.selectClipsForSnapshot ({});
  17565. headerShot ("-ctrl-multiselect.png", 6);
  17566. press (pl, headerPoint (0), ctrl, headerPoint (2));
  17567. check ("ctrl_drag_range_with_clips", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2 } && sortedClips() == clipsOn ({ 0, 1, 2 }),
  17568. list (pl.selectedTracksForSnapshot()) + " clips " + list (sortedClips()));
  17569. press (pl, headerPoint (1), shift); // LYNX's own Shift+click range (from the last clicked track, 0)
  17570. check ("lynx_shift_range_kept", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
  17571. {
  17572. int linked = -1;
  17573. auto old = pl.onLinkedMixerTrack;
  17574. pl.onLinkedMixerTrack = [&linked] (int insert) { linked = insert; };
  17575. press (pl, headerPoint (2), {});
  17576. check ("audio_track_click_links_mixer_track", linked == 3, juce::String (linked));
  17577. pl.onLinkedMixerTrack = old;
  17578. }
  17579. // ---- 2. the resize band (FUN_00ea93a0, AUTracksPanelMouseMove)
  17580. const auto heightOf = [&] (int t) { return pl.trackRowForSnapshot (t).getHeight(); };
  17581. const auto& tracks = [&]() -> const std::vector<lynx::PlaylistTrack>& { return engine.getSong().playlistTracks; };
  17582. press (pl, headerPoint (4), {}); // (track 4 alone selected)
  17583. {
  17584. const auto start = bandPoint (4);
  17585. press (pl, start, {}, start + juce::Point<int> (0, 41));
  17586. 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)
  17587. headerShot ("-resized.png", 6);
  17588. const auto again = bandPoint (4);
  17589. press (pl, again, {}, again + juce::Point<int> (0, -100)); // (above the row's top, but less than 32 px)
  17590. check ("drag_stops_at_16", heightOf (4) == 16, juce::String (heightOf (4)));
  17591. press (pl, bandPoint (4), alt);
  17592. check ("alt_click_resets", tracks()[4].height == 0 && tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (heightOf (4)));
  17593. press (pl, bandPoint (4), {}, {}, 2); // the second press of a double click
  17594. check ("double_click_locks_small", tracks()[4].lockedHeight == 1 && heightOf (4) == 16, juce::String (tracks()[4].lockedHeight));
  17595. press (pl, bandPoint (4), {});
  17596. check ("click_on_locked_band_unlocks", tracks()[4].lockedHeight == -1 && heightOf (4) == 48, juce::String (tracks()[4].lockedHeight));
  17597. const auto top = pl.trackRowForSnapshot (4).getY();
  17598. const auto b = bandPoint (4);
  17599. press (pl, b, {}, juce::Point<int> (b.x, top - 40));
  17600. check ("drag_past_the_top_groups", tracks()[4].grouped && tracks()[4].height == 0, juce::String ((int) tracks()[4].grouped));
  17601. const auto b2 = bandPoint (4);
  17602. press (pl, b2, {}, juce::Point<int> (b2.x, pl.trackRowForSnapshot (4).getY() - 40));
  17603. check ("again_ungroups", ! tracks()[4].grouped, juce::String ((int) tracks()[4].grouped));
  17604. }
  17605. {
  17606. // every selected track: the same height, from the first one's top to the mouse
  17607. press (pl, headerPoint (1), {});
  17608. press (pl, headerPoint (2), ctrl | shift);
  17609. press (pl, headerPoint (3), ctrl | shift);
  17610. const auto top = pl.trackRowForSnapshot (1).getY();
  17611. const auto b = bandPoint (2);
  17612. press (pl, b, {}, juce::Point<int> (b.x, top + 2 * 50));
  17613. check ("selected_tracks_share_the_height", tracks()[1].height == 50 && tracks()[2].height == 50 && tracks()[3].height == 50,
  17614. juce::String (tracks()[1].height) + "," + juce::String (tracks()[2].height) + "," + juce::String (tracks()[3].height));
  17615. headerShot ("-selected-resized.png", 6);
  17616. }
  17617. // ---- 3. saved: .lynx round trip and the .flp size factor
  17618. {
  17619. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[5].height = 300; s.playlistTracks[0].lockedHeight = 60; });
  17620. const auto json = lynx::ProjectFile::toJson (engine.getSong());
  17621. juce::String error;
  17622. const auto back = lynx::ProjectFile::fromJson (json, error);
  17623. check ("lynx_round_trip", back && back->playlistTracks.size() > 5 && back->playlistTracks[5].height == 300 && back->playlistTracks[1].height == 50
  17624. && back->playlistTracks[0].lockedHeight == 60, error);
  17625. lynx::flpexport::Options options;
  17626. lynx::flpexport::Report flpReport;
  17627. const auto project = flp::parseProject (lynx::flpexport::exportFlp (engine.getSong(), options, flpReport));
  17628. float size5 = -1.0f, size1 = -1.0f;
  17629. for (const auto& arrangement : project.arrangements)
  17630. for (const auto& t : arrangement.tracks)
  17631. {
  17632. if (t.index == 5) size5 = t.heightScale;
  17633. if (t.index == 1) size1 = t.heightScale;
  17634. }
  17635. 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,
  17636. juce::String (size5) + " " + juce::String (size1));
  17637. }
  17638. // ---- 4. the mixer strips (round 170b's FL rules): Ctrl+click alone, Ctrl+Shift+click adds / removes
  17639. {
  17640. ui.selectTabForSnapshot (3);
  17641. engine.editSong ([] (lynx::Song& s) { if (s.mixer.size() < 9) s.mixer.resize (9); });
  17642. engine.dispatchPendingMessages();
  17643. auto& mixer = ui.getMixerForSnapshot();
  17644. mixer.setSize (1400, 640);
  17645. auto& strips = mixer.getStripsForSnapshot();
  17646. strips.setSize (juce::jmax (strips.getWidth(), 1300), juce::jmax (strips.getHeight(), 560));
  17647. const auto at = [&] (int t) { return juce::Point<int> (strips.stripLeft (t) + 8, strips.getHeight() / 2 + 40); };
  17648. press (strips, at (2), {});
  17649. check ("mixer_click_alone", strips.getSelection() == std::vector<int> { 2 }, list (strips.getSelection()));
  17650. // LYNX extra (issue #163): Ctrl+click adds / removes one insert
  17651. press (strips, at (4), ctrl);
  17652. press (strips, at (6), ctrl);
  17653. check ("mixer_ctrl_click_adds_lynx", strips.getSelection() == std::vector<int> { 2, 4, 6 }, list (strips.getSelection()));
  17654. press (strips, at (4), ctrl);
  17655. check ("mixer_ctrl_click_removes_lynx", strips.getSelection() == std::vector<int> { 2, 6 }, list (strips.getSelection()));
  17656. // FL: Ctrl+Shift+click adds / removes too
  17657. press (strips, at (5), ctrl | shift);
  17658. check ("mixer_ctrl_shift_click_adds", strips.getSelection() == std::vector<int> { 2, 5, 6 }, list (strips.getSelection()));
  17659. savePng (mixer.createComponentSnapshot ({ 0, 0, juce::jmin (mixer.getWidth(), 900), mixer.getHeight() }), prefix + "-mixer-ctrl-multiselect.png");
  17660. // FL: Ctrl+drag across the strips = the range from the press, alone
  17661. press (strips, at (3), ctrl, at (4));
  17662. check ("mixer_ctrl_drag_range", strips.getSelection() == std::vector<int> { 3, 4 }, list (strips.getSelection()));
  17663. }
  17664. // ---- 5. round 190gw (live check 190gu B1): FL's default row, the left lock strip, the right selection strip
  17665. {
  17666. ui.selectTabForSnapshot (2);
  17667. auto song = lynx::Song::makeDefault();
  17668. song.playlist.clear();
  17669. song.playlistTracks.assign (6, {});
  17670. for (int t = 0; t < 6; ++t)
  17671. song.playlistTracks[(std::size_t) t].name = juce::String ("Track " + juce::String (t + 1)).toStdString();
  17672. engine.setSong (std::move (song));
  17673. engine.dispatchPendingMessages();
  17674. pl.setSize (juce::jmax (pl.getWidth(), 900), juce::jmax (pl.getHeight(), 600));
  17675. check ("gw_default_row_48", heightOf (0) == 48 && heightOf (5) == 48, juce::String (heightOf (0)));
  17676. const auto rowMid = [&] (int t) { const auto r = pl.trackRowForSnapshot (t); return r.getY() + r.getHeight() / 2 - 4; };
  17677. const auto stripX = pl.headerWidthForSnapshot() - 4;
  17678. // the left strip (x < 10): the row flips to the smallest size and back; nothing selects
  17679. press (pl, { 2, rowMid (2) }, {});
  17680. check ("gw_left_strip_smallest", heightOf (2) == 16 && tracks()[2].lockedHeight == 1, juce::String (heightOf (2)));
  17681. press (pl, { 2, rowMid (2) }, {});
  17682. check ("gw_left_strip_back", heightOf (2) == 48 && tracks()[2].lockedHeight == -1, juce::String (heightOf (2)));
  17683. // the right strip: click = alone, Shift+click toggles, right-click toggles with no menu
  17684. press (pl, { stripX, rowMid (0) }, {});
  17685. check ("gw_strip_click_alone", pl.selectedTracksForSnapshot() == std::vector<int> { 0 }, list (pl.selectedTracksForSnapshot()));
  17686. press (pl, { stripX, rowMid (1) }, shift);
  17687. check ("gw_strip_shift_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1 }, list (pl.selectedTracksForSnapshot()));
  17688. headerShot ("-gw-strip-two-selected.png", 6);
  17689. press (pl, { stripX, rowMid (0) }, shift);
  17690. check ("gw_strip_shift_click_removes", pl.selectedTracksForSnapshot() == std::vector<int> { 1 }, list (pl.selectedTracksForSnapshot()));
  17691. {
  17692. const juce::Point<int> p { stripX, rowMid (4) };
  17693. const juce::ModifierKeys right (juce::ModifierKeys::rightButtonModifier);
  17694. pl.mouseDown (event (pl, p, right, p, 1, false));
  17695. pl.mouseUp (event (pl, p, {}, p, 1, false));
  17696. }
  17697. check ("gw_strip_right_click_adds", pl.selectedTracksForSnapshot() == std::vector<int> { 1, 4 }, list (pl.selectedTracksForSnapshot()));
  17698. // a drag down the strip: the tracks crossed join (FUN_012e8740)
  17699. press (pl, { stripX, rowMid (0) }, {}, juce::Point<int> (stripX, rowMid (4)));
  17700. check ("gw_strip_drag_range", pl.selectedTracksForSnapshot() == std::vector<int> { 0, 1, 2, 3, 4 }, list (pl.selectedTracksForSnapshot()));
  17701. headerShot ("-gw-strip-range.png", 6);
  17702. // a double click: the track alone <-> every track
  17703. press (pl, { stripX, rowMid (2) }, {});
  17704. press (pl, { stripX, rowMid (2) }, {}, {}, 2);
  17705. check ("gw_strip_double_click_all", (int) pl.selectedTracksForSnapshot().size() == pl.numTracksForSnapshot(), list (pl.selectedTracksForSnapshot()));
  17706. press (pl, { stripX, rowMid (1) }, {});
  17707. // .lynx: the new default row is saved; a project from before (no key) keeps LYNX's old 38 px row
  17708. juce::String error;
  17709. const auto json = lynx::ProjectFile::toJson (engine.getSong());
  17710. const auto back = lynx::ProjectFile::fromJson (json, error);
  17711. check ("gw_lynx_row_saved", back && back->playlistRowHeight == 48, error);
  17712. auto parsed = juce::JSON::parse (json);
  17713. if (auto* o = parsed.getDynamicObject())
  17714. o->removeProperty ("playlistRowHeight");
  17715. const auto old = lynx::ProjectFile::fromJson (juce::JSON::toString (parsed), error);
  17716. check ("gw_old_lynx_keeps_38", old && old->playlistRowHeight == 38, error);
  17717. engine.setSong (*old);
  17718. engine.dispatchPendingMessages();
  17719. check ("gw_old_lynx_rows_38", heightOf (0) == 38, juce::String (heightOf (0)));
  17720. // an automation clip with two target links (Crossfade with) comes back with its links and formulas
  17721. auto linked = lynx::Song::makeDefault();
  17722. linked.channels.resize (2);
  17723. lynx::Automation a;
  17724. a.links = { { { lynx::AutomationTargetKind::channelAdjust, 0, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeOutFormula },
  17725. { { lynx::AutomationTargetKind::channelAdjust, 1, 0, lynx::leveladjust::volume }, lynx::clipops::crossfadeInFormula } };
  17726. a.target = a.links[0].target;
  17727. a.points = { { 0, 1.0f, 0.0f }, { 384, 0.0f, 0.0f } };
  17728. linked.automations.push_back (a);
  17729. const auto linkedBack = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (linked), error);
  17730. check ("gw_lynx_links_round_trip", linkedBack && linkedBack->automations.size() == linked.automations.size()
  17731. && linkedBack->automations.back().links == a.links && linkedBack->automations.back().target == a.target, error);
  17732. // Sampler › Open in new Fruity Slicer / Slicex channel: named after the sample, " #n" when taken
  17733. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190gw").getChildFile ("Basic 808 Clap.wav");
  17734. wav.getParentDirectory().createDirectory();
  17735. {
  17736. juce::AudioBuffer<float> b (1, 4410);
  17737. for (int i = 0; i < b.getNumSamples(); ++i)
  17738. b.setSample (0, i, 0.5f * std::sin ((float) i * 0.2f) * (1.0f - (float) i / (float) b.getNumSamples()));
  17739. wav.deleteFile();
  17740. juce::WavAudioFormat format;
  17741. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream());
  17742. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  17743. {
  17744. out.release();
  17745. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  17746. writer->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  17747. }
  17748. }
  17749. engine.editSong ([] (lynx::Song& s) {
  17750. s.channels.resize (1);
  17751. s.channels[0] = {};
  17752. s.channels[0].name = "Basic 808 Clap";
  17753. });
  17754. engine.dispatchPendingMessages();
  17755. if (lynx::openInNewChannelHandler())
  17756. {
  17757. lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::fruityslicer);
  17758. lynx::openInNewChannelHandler() (wav, lynx::InstrumentKind::slicex);
  17759. }
  17760. engine.dispatchPendingMessages();
  17761. const auto& ch = engine.getSong().channels;
  17762. 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"
  17763. && ch[1].instrument == lynx::InstrumentKind::fruityslicer && ch[2].instrument == lynx::InstrumentKind::slicex,
  17764. ch.size() >= 3 ? juce::String::fromUTF8 (ch[1].name.c_str()) + " | " + juce::String::fromUTF8 (ch[2].name.c_str()) : juce::String ((int) ch.size()));
  17765. wav.getParentDirectory().deleteRecursively();
  17766. // the mixer's two boxes (live check 190gu B4): "Insert multiple..." asks "Number of tracks to add" (1),
  17767. // "Add multiple..." "Enter the number of mixer tracks to add" (10)
  17768. for (const auto adding : { false, true })
  17769. {
  17770. auto box = lynx::MixerStrips::makeInsertMultipleBox (adding);
  17771. const auto text = box->getTextEditorContents ("count");
  17772. check (adding ? "gw_add_multiple_box" : "gw_insert_multiple_box", text == (adding ? "10" : "1"), text);
  17773. if (box->getWidth() > 0 && box->getHeight() > 0)
  17774. savePng (box->createComponentSnapshot (box->getLocalBounds()), prefix + (adding ? "-gw-add-multiple-box.png" : "-gw-insert-multiple-box.png"));
  17775. }
  17776. }
  17777. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  17778. return allOk;
  17779. }
  17780. #include "FoldersShot190jf.inc" // round 190jf (slice B17)
  17781. // --userfixshot190ib (round 190ib): see the dispatch above
  17782. bool runUserFixShot190ib (const juce::String& prefix)
  17783. {
  17784. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17785. juce::StringArray report;
  17786. bool allOk = true;
  17787. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  17788. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  17789. allOk = allOk && ok;
  17790. };
  17791. lynx::AudioEngine engine (false);
  17792. lynx::MainComponent ui (engine, false);
  17793. ui.setSize (1600, 900);
  17794. engine.dispatchPendingMessages();
  17795. // ---- #182: a real JUCE popup menu inside a host component, keys sent to its window as the keyboard would
  17796. juce::Component host;
  17797. host.setSize (560, 900);
  17798. const auto typeInto = [&host] (const juce::String& text) {
  17799. auto* menuWindow = host.getNumChildComponents() > 0 ? host.getChildComponent (host.getNumChildComponents() - 1) : nullptr;
  17800. for (auto c : text)
  17801. if (menuWindow != nullptr)
  17802. menuWindow->keyPressed (juce::KeyPress ((int) juce::CharacterFunctions::toLowerCase (c), 0, c));
  17803. return menuWindow != nullptr;
  17804. };
  17805. const auto shotMenu = [&host, &prefix] (const juce::String& name) {
  17806. savePng (host.createComponentSnapshot (host.getLocalBounds()), prefix + name);
  17807. };
  17808. {
  17809. auto& pl = ui.getPlaylistForSnapshot();
  17810. pl.editMenu().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
  17811. check ("menu_shown", host.getNumChildComponents() > 0, juce::String (host.getNumChildComponents()));
  17812. shotMenu ("-menu-0.png");
  17813. typeInto ("d");
  17814. shotMenu ("-menu-d.png"); // the first item starting with D
  17815. typeInto ("d");
  17816. shotMenu ("-menu-dd.png"); // D again: the next one
  17817. juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100); // (a pause: a new prefix)
  17818. typeInto ("drop a");
  17819. shotMenu ("-menu-drop-a.png"); // "Drop audio on track headers"
  17820. juce::PopupMenu::dismissAllActiveMenus();
  17821. }
  17822. {
  17823. auto& pr = ui.getPianoRollForSnapshot();
  17824. pr.moreMenuForSnapshot().showMenuAsync (juce::PopupMenu::Options().withParentComponent (&host).withTargetScreenArea ({ 8, 8, 1, 1 }));
  17825. juce::Time::waitForMillisecondCounter (juce::Time::getMillisecondCounter() + 1100);
  17826. typeInto ("preview");
  17827. shotMenu ("-pianoroll-preview.png"); // #183's item, reached by typing its name
  17828. juce::PopupMenu::dismissAllActiveMenus();
  17829. check ("preview_while_playing_off_by_default", ! lynx::PianoRollComponent::previewWhilePlaying);
  17830. }
  17831. // ---- #181: Ctrl+, (Cmd+, on macOS) through the main window's key handling opens Settings, again closes it
  17832. const auto ctrlComma = juce::KeyPress (',', juce::ModifierKeys::commandModifier, ',');
  17833. check ("settings_closed_first", lynx::shownSettingsPage() < 0);
  17834. ui.keyPressed (ctrlComma);
  17835. check ("ctrl_comma_opens_settings", lynx::shownSettingsPage() == (int) lynx::SettingsPage::general, juce::String (lynx::shownSettingsPage()));
  17836. ui.keyPressed (ctrlComma);
  17837. check ("ctrl_comma_again_closes_it", lynx::shownSettingsPage() < 0, juce::String (lynx::shownSettingsPage()));
  17838. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  17839. return allOk;
  17840. }
  17841. // --issuesshot190ht (round 190ht): see the dispatch above
  17842. bool runIssuesShot190ht (const juce::String& prefix)
  17843. {
  17844. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  17845. juce::StringArray report;
  17846. bool allOk = true;
  17847. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  17848. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  17849. allOk = allOk && ok;
  17850. };
  17851. using namespace lynx;
  17852. AudioEngine engine (false);
  17853. MainComponent ui (engine, false);
  17854. ui.setSize (1600, 900);
  17855. const auto bar = (std::int64_t) 4 * ppq;
  17856. {
  17857. // Kick (1 bar), Bass (2 bars, a long note across its second bar), Lead (1 bar), Pad (1 bar): blocks in rows
  17858. auto song = Song::makeDefault();
  17859. song.playlist.clear();
  17860. song.patterns.clear();
  17861. const auto pattern = [&song] (const char* name, std::uint32_t colour, int channel, std::int64_t length) {
  17862. auto& p = song.patterns.emplace_back();
  17863. p.name = name;
  17864. p.colour = colour;
  17865. for (int step : { 0, 4, 8, 12 })
  17866. p.toggleStep (channel, step);
  17867. p.lengthTicks = length;
  17868. return (int) song.patterns.size() - 1;
  17869. };
  17870. pattern ("Kick", 0xFFD85A3C, 0, bar);
  17871. const auto bass = pattern ("Bass", 0xFF3C8DD8, 1, 0);
  17872. Note longNote;
  17873. longNote.channel = 1;
  17874. longNote.start = 6 * ppq;
  17875. longNote.length = 2 * ppq;
  17876. song.patterns[(std::size_t) bass].notes.push_back (longNote);
  17877. song.patterns[(std::size_t) bass].sortNotes();
  17878. pattern ("Lead", 0xFF8A5CD8, 2, bar);
  17879. pattern ("Pad", 0xFF5CB85C, 3, bar);
  17880. song.patternBlocksOn = true;
  17881. for (int b = 0; b < 8; ++b)
  17882. patternblocks::place (song, 0, b * bar);
  17883. patternblocks::place (song, 1, 0);
  17884. patternblocks::place (song, 1, 4 * bar);
  17885. for (int b = 2; b < 6; ++b)
  17886. patternblocks::place (song, 2, b * bar);
  17887. patternblocks::place (song, 3, 0);
  17888. engine.setSong (std::move (song));
  17889. }
  17890. engine.dispatchPendingMessages();
  17891. ui.selectTabForSnapshot (2);
  17892. engine.dispatchPendingMessages();
  17893. auto& pl = ui.getPlaylistForSnapshot();
  17894. pl.setSize (juce::jmax (pl.getWidth(), 1000), juce::jmax (pl.getHeight(), 640));
  17895. pl.setViewForSnapshot (90.0, 0, 0); // (bar 1 at the left edge)
  17896. pl.setBlocksHeight (6 + 5 * 18 + 6);
  17897. engine.dispatchPendingMessages();
  17898. const auto& song = [&]() -> const Song& { return engine.getSong(); };
  17899. auto* blocks = pl.getBlocksViewForSnapshot();
  17900. check ("blocks_view", blocks != nullptr && blocks->isVisible());
  17901. if (blocks == nullptr)
  17902. {
  17903. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=FAIL\n");
  17904. return false;
  17905. }
  17906. const auto shotBlocks = [&] (const juce::String& name) {
  17907. engine.dispatchPendingMessages();
  17908. const auto area = blocks->getBoundsInParent().withWidth (juce::jmin (pl.getWidth(), 900)).expanded (0, 2).getIntersection (pl.getLocalBounds());
  17909. savePng (pl.createComponentSnapshot (area), prefix + name);
  17910. };
  17911. auto source = juce::Desktop::getInstance().getMainMouseSource();
  17912. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
  17913. juce::Point<float> pressedAt;
  17914. const auto bEvent = [&] (int row, std::int64_t tick, juce::ModifierKeys mods, int clicks = 1) {
  17915. const auto at = blocks->pointForSnapshot (row, tick).toFloat();
  17916. const auto now = juce::Time::getCurrentTime();
  17917. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, clicks, at != pressedAt);
  17918. };
  17919. const auto bPress = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  17920. pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
  17921. blocks->mouseDown (bEvent (row, tick, mods));
  17922. };
  17923. const auto bDrag = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (bEvent (row, tick, mods)); };
  17924. const auto bRelease = [&] (int row, std::int64_t tick, juce::ModifierKeys mods = {}) {
  17925. blocks->mouseUp (bEvent (row, tick, mods));
  17926. engine.dispatchPendingMessages();
  17927. };
  17928. const auto blockOf = [&] (int row, std::int64_t start) -> const PatternBlock* {
  17929. const auto i = patternblocks::indexOf (song(), { row, start });
  17930. return i < 0 ? nullptr : &song().blocks[(std::size_t) i];
  17931. };
  17932. const auto mutedAt = [&] (int row, std::int64_t start) { const auto* x = blockOf (row, start); return x != nullptr && x->muted; };
  17933. const auto playingAt = [&] (int row, std::int64_t start) { const auto* x = blockOf (row, start); return x != nullptr && ! x->muted; };
  17934. const auto mutedCount = [&] {
  17935. int n = 0;
  17936. for (const auto& b : song().blocks)
  17937. n += b.muted ? 1 : 0;
  17938. return n;
  17939. };
  17940. shotBlocks ("-blocks-before.png");
  17941. // ---- #127 Mute: a click mutes the block, a drag down across rows mutes the blocks it crosses (any row)
  17942. pl.setToolForSnapshot (EditTool::mute);
  17943. bPress (0, 2 * bar + 40, left);
  17944. bRelease (0, 2 * bar + 40);
  17945. check ("mute_click", blockOf (0, 2 * bar) != nullptr && mutedAt (0, 2 * bar) && mutedCount() == 1);
  17946. bPress (0, 4 * bar + 40, left);
  17947. bDrag (1, 4 * bar + 60, left);
  17948. bDrag (2, 4 * bar + 80, left);
  17949. bRelease (2, 4 * bar + 80);
  17950. check ("mute_drag_across_rows", mutedAt (0, 4 * bar) && blockOf (1, 4 * bar) != nullptr && mutedAt (1, 4 * bar)
  17951. && mutedAt (2, 4 * bar) && playingAt (3, 0) && mutedCount() == 4,
  17952. juce::String (mutedCount()));
  17953. shotBlocks ("-blocks-mute.png");
  17954. // a sweep that starts on a muted block unmutes
  17955. bPress (0, 2 * bar + 40, left);
  17956. bDrag (0, 3 * bar + 40, left);
  17957. bRelease (0, 3 * bar + 40);
  17958. check ("mute_sweep_from_muted_unmutes", playingAt (0, 2 * bar) && playingAt (0, 3 * bar) && mutedCount() == 3,
  17959. juce::String (mutedCount()));
  17960. // the right button erases, as with every tool but Select / Slice / Zoom
  17961. bPress (3, 40, right);
  17962. bRelease (3, 40);
  17963. check ("mute_right_click_erases", blockOf (3, 0) == nullptr);
  17964. engine.undo();
  17965. engine.dispatchPendingMessages();
  17966. check ("undo_erase", blockOf (3, 0) != nullptr);
  17967. // the muted blocks play nothing: their clips in the playback copy are muted
  17968. {
  17969. auto copy = song();
  17970. patternblocks::expandSong (copy);
  17971. int mutedClips = 0;
  17972. for (const auto& c : copy.playlist)
  17973. mutedClips += c.muted ? 1 : 0;
  17974. check ("muted_blocks_play_muted_clips", mutedClips == 3, juce::String (mutedClips));
  17975. juce::String error;
  17976. const auto back = ProjectFile::fromJson (ProjectFile::toJson (song()), error);
  17977. check ("muted_blocks_saved", back && back->blocks == song().blocks, error);
  17978. }
  17979. // ---- #127 Select: a box over rows 0-2, bars 5-6 selects every block it meets; Pencil moves them together
  17980. pl.setToolForSnapshot (EditTool::lasso);
  17981. bPress (0, 4 * bar + 40, left);
  17982. bDrag (2, 5 * bar + 40, left);
  17983. shotBlocks ("-blocks-select-box.png");
  17984. bRelease (2, 5 * bar + 40);
  17985. const auto selection = blocks->selectionForSnapshot();
  17986. check ("select_box_any_row", selection.size() == 5 && patternblocks::contains (selection, { 0, 4 * bar }) && patternblocks::contains (selection, { 1, 4 * bar })
  17987. && patternblocks::contains (selection, { 2, 5 * bar }),
  17988. juce::String ((int) selection.size()));
  17989. pl.setToolForSnapshot (EditTool::pencil);
  17990. // (Kick's bars 7 and 8 are in the way of a 2-bar move: move the group by 1 bar after clearing them)
  17991. engine.editSong ([bar] (Song& s) { patternblocks::eraseRange (s, 0, 6 * bar, 8 * bar); });
  17992. engine.dispatchPendingMessages();
  17993. bPress (1, 4 * bar + 40, left);
  17994. bDrag (1, 6 * bar + 40, left);
  17995. bRelease (1, 6 * bar + 40);
  17996. check ("pencil_moves_the_selection", blockOf (1, 6 * bar) != nullptr && blockOf (0, 6 * bar) != nullptr && blockOf (0, 7 * bar) != nullptr
  17997. && blockOf (2, 6 * bar) != nullptr && blockOf (2, 7 * bar) != nullptr && blockOf (1, 4 * bar) == nullptr
  17998. && blocks->selectionForSnapshot().size() == 5);
  17999. shotBlocks ("-blocks-select-moved.png");
  18000. // a press on a block outside the selection moves that block alone and drops the selection
  18001. bPress (3, 40, left);
  18002. bDrag (3, bar + 40, left);
  18003. bRelease (3, bar + 40);
  18004. check ("pencil_unselected_block_alone", blockOf (3, bar) != nullptr && blockOf (0, 6 * bar) != nullptr && blocks->selectionForSnapshot().empty());
  18005. // the right button selects too (FL 10: either button)
  18006. pl.setToolForSnapshot (EditTool::lasso);
  18007. bPress (3, bar + 40, right);
  18008. bRelease (3, bar + 40);
  18009. check ("select_click_right_button", blocks->selectionForSnapshot().size() == 1 && blockOf (3, bar) != nullptr);
  18010. // ---- #127 Slice: a click on Bass's first block at bar 2 beat 4 cuts the pattern; a new pattern takes the rest
  18011. pl.setToolForSnapshot (EditTool::knife);
  18012. const auto patternsBefore = song().patterns.size();
  18013. const juce::ModifierKeys freeLeft (juce::ModifierKeys::leftButtonModifier | juce::ModifierKeys::altModifier); // (Alt: no snap)
  18014. bPress (1, bar + 3 * ppq, freeLeft);
  18015. bDrag (2, bar + 3 * ppq, freeLeft); // (a vertical drag: the row under the mouse when released is cut)
  18016. bRelease (1, bar + 3 * ppq);
  18017. check ("slice_adds_a_pattern", song().patterns.size() == patternsBefore + 1 && song().patterns[2].name == "Bass #2",
  18018. juce::String ((int) song().patterns.size()));
  18019. check ("slice_trims_the_long_note", song().patterns[1].notes.back().start == 6 * ppq && song().patterns[1].notes.back().length >= ppq
  18020. && song().patterns[1].notes.back().length < ppq + ppq / 4 && song().patterns[2].notes.empty(),
  18021. juce::String (song().patterns[1].notes.back().length));
  18022. check ("slice_new_blocks_where_bass_ends", blockOf (2, 2 * bar) != nullptr && blockOf (2, 8 * bar) != nullptr);
  18023. shotBlocks ("-blocks-slice.png");
  18024. engine.undo();
  18025. engine.dispatchPendingMessages();
  18026. check ("undo_slice", song().patterns.size() == patternsBefore && song().patterns[2].name == "Lead");
  18027. // ---- #127 Zoom: a drag zooms to the range, a click goes back
  18028. pl.setToolForSnapshot (EditTool::zoom);
  18029. const auto zoomBefore = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  18030. bPress (0, 2 * bar, left);
  18031. bDrag (0, 4 * bar, left);
  18032. bRelease (0, 4 * bar);
  18033. const auto zoomed = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  18034. check ("zoom_drag_zooms_in", zoomed > zoomBefore * 1.5, juce::String (zoomed) + " vs " + juce::String (zoomBefore));
  18035. pressedAt = blocks->pointForSnapshot (0, 3 * bar).toFloat();
  18036. blocks->mouseDown (bEvent (0, 3 * bar, right));
  18037. blocks->mouseUp (bEvent (0, 3 * bar, {}));
  18038. const auto back = pl.xOfTickForSnapshot ((double) (4 * bar)) - pl.xOfTickForSnapshot (0.0);
  18039. check ("zoom_click_goes_back", std::abs (back - zoomBefore) < 0.5, juce::String (back));
  18040. // hints name each tool's gesture
  18041. pl.setToolForSnapshot (EditTool::mute);
  18042. check ("hint_mute", blocks->hintAt (blocks->pointForSnapshot (0, 40)).text.contains ("mutes"));
  18043. pl.setToolForSnapshot (EditTool::pencil);
  18044. // ---- #154: linked tracks, then the insert effects list on their headers
  18045. engine.editSong ([bar] (Song& s) {
  18046. s.patternBlocksOn = false;
  18047. s.blocks.clear();
  18048. s.playlist.clear();
  18049. ChannelDef vox;
  18050. vox.name = "Lead vocal";
  18051. vox.instrument = InstrumentKind::audioClip;
  18052. vox.samplePath = "/shots/Lead vocal.wav";
  18053. vox.mixerTrack = 12;
  18054. s.channels.push_back (vox);
  18055. const auto voxChannel = (int) s.channels.size() - 1;
  18056. s.mixer[12].name = "Vox chain";
  18057. for (auto k : { EffectKind::parametricEq, EffectKind::compressor, EffectKind::delay, EffectKind::reverb })
  18058. s.mixer[12].effects.push_back (makeEffectSlot (k));
  18059. s.mixer[12].effects[2].enabled = false;
  18060. s.channels[0].mixerTrack = 3;
  18061. s.mixer[3].name = "Kick";
  18062. s.mixer[3].effects.push_back (makeEffectSlot (EffectKind::compressor));
  18063. const auto clip = [&s, bar] (int track, ClipKind kind, int source, int at, int bars) {
  18064. Clip c;
  18065. c.kind = kind;
  18066. c.track = track;
  18067. c.start = at * bar;
  18068. c.length = bars * bar;
  18069. (kind == ClipKind::pattern ? c.pattern : c.channel) = source;
  18070. s.playlist.push_back (c);
  18071. };
  18072. clip (0, ClipKind::pattern, 0, 0, 4);
  18073. clip (1, ClipKind::audio, voxChannel, 0, 8);
  18074. s.playlistTracks.resize (4);
  18075. s.playlistTracks[1].height = 70;
  18076. });
  18077. engine.dispatchPendingMessages();
  18078. // (rollup 0.1.30: since round 190ib, switching the link on asks first when it moves inserts or routes channels;
  18079. // this run accepts, as the user clicking "Link")
  18080. PlaylistComponent::answerLinkConfirmation = [] (const autolink::Report&) { return true; };
  18081. pl.runAction ("playlist.linkTracks");
  18082. PlaylistComponent::answerLinkConfirmation = nullptr;
  18083. engine.dispatchPendingMessages();
  18084. // (rollup 0.1.30: round 190ib links Playlist track N to insert N, moving the inserts there: the Vox chain and
  18085. // the Kick follow their tracks, so the checks read the inserts the tracks are linked to)
  18086. const auto vox = song().playlistTracks.size() > 1 ? song().playlistTracks[1].mixerTrack : -1;
  18087. const auto kick = song().playlistTracks.size() > 0 ? song().playlistTracks[0].mixerTrack : -1;
  18088. check ("linked", song().linkTracksToMixer && vox > 0 && song().mixer[(std::size_t) vox].name == "Vox chain" && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth,
  18089. juce::String (pl.headerWidthForSnapshot()));
  18090. check ("inserts_off_by_default", ! PlaylistComponent::showTrackInserts && pl.insertsListForSnapshot (1).isEmpty());
  18091. const auto shotRows = [&] (const juce::String& name, int rows) {
  18092. engine.dispatchPendingMessages();
  18093. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  18094. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 820), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  18095. };
  18096. shotRows ("-inserts-off.png", 3);
  18097. pl.runAction ("playlist.trackInserts");
  18098. engine.dispatchPendingMessages();
  18099. check ("inserts_on_widens_linked_headers", PlaylistComponent::showTrackInserts
  18100. && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth + PlaylistComponent::insertsColumnWidth,
  18101. juce::String (pl.headerWidthForSnapshot()));
  18102. const auto list = [&] (int t) { return pl.insertsListForSnapshot (t); };
  18103. check ("list_on_linked_tracks_only", ! list (0).isEmpty() && ! list (1).isEmpty() && list (2).isEmpty(),
  18104. list (0).toString() + " / " + list (1).toString());
  18105. shotRows ("-inserts-on.png", 3);
  18106. // a row's hint names the effect
  18107. const auto rowPoint = [&] (int t, int row, bool dot) {
  18108. const auto r = list (t);
  18109. return juce::Point<int> (dot ? r.getX() + 5 : r.getX() + 40, r.getY() + row * 13 + 6);
  18110. };
  18111. const auto hintOf = [&] (juce::Point<int> p) { return pl.hintAt (p); };
  18112. check ("hint_names_the_effect", hintOf (rowPoint (1, 1, false)).value == quickpick::slotName (engine, song().mixer[(std::size_t) vox].effects[1]),
  18113. hintOf (rowPoint (1, 1, false)).value);
  18114. check ("hint_add_row", hintOf (rowPoint (0, 1, false)).text.contains ("add an effect"));
  18115. const auto now = juce::Time::getCurrentTime();
  18116. const int ctrl = juce::ModifierKeys::commandModifier;
  18117. const auto event = [&] (juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  18118. 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);
  18119. };
  18120. const auto press = [&] (juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}) {
  18121. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  18122. pl.mouseMove (event (p, mods, p, 1, false));
  18123. pl.mouseDown (event (p, down, p, 1, false));
  18124. if (to)
  18125. {
  18126. pl.mouseDrag (event ((p + *to) / 2, down, p, 1, true));
  18127. pl.mouseDrag (event (*to, down, p, 1, true));
  18128. }
  18129. pl.mouseUp (event (to ? *to : p, mods, p, 1, to.has_value()));
  18130. engine.dispatchPendingMessages();
  18131. };
  18132. const auto kinds = [&] (int insert) {
  18133. juce::StringArray k;
  18134. for (const auto& fx : song().mixer[(std::size_t) insert].effects)
  18135. k.add (juce::String ((int) fx.kind) + (fx.enabled ? "" : "-"));
  18136. return k.joinIntoString (",");
  18137. };
  18138. const auto eq = juce::String ((int) EffectKind::parametricEq), comp = juce::String ((int) EffectKind::compressor),
  18139. delay = juce::String ((int) EffectKind::delay), verb = juce::String ((int) EffectKind::reverb);
  18140. // the dot bypasses / un-bypasses, as the Mixer slot's LED (one undo step each)
  18141. press (rowPoint (1, 0, true), {});
  18142. check ("dot_bypasses", ! song().mixer[(std::size_t) vox].effects[0].enabled);
  18143. press (rowPoint (1, 2, true), {});
  18144. check ("dot_switches_on", song().mixer[(std::size_t) vox].effects[2].enabled);
  18145. engine.undo();
  18146. engine.dispatchPendingMessages();
  18147. check ("undo_dot", ! song().mixer[(std::size_t) vox].effects[2].enabled && ! song().mixer[(std::size_t) vox].effects[0].enabled);
  18148. press (rowPoint (1, 0, true), {});
  18149. shotRows ("-inserts-bypass.png", 3);
  18150. // drag the reverb (row 4) above the EQ: the chain order changes, as the Device View's drag
  18151. const auto before = kinds (vox);
  18152. press (rowPoint (1, 3, false), {}, rowPoint (1, 0, false) - juce::Point<int> (0, 4));
  18153. check ("drag_reorders", kinds (vox) == verb + "," + eq + "," + comp + "," + delay + "-", before + " -> " + kinds (vox));
  18154. // Ctrl + drag copies (the compressor, under the delay)
  18155. press (rowPoint (1, 2, false), juce::ModifierKeys (ctrl), rowPoint (1, 4, false) - juce::Point<int> (0, 4));
  18156. check ("ctrl_drag_copies", kinds (vox) == verb + "," + eq + "," + comp + "," + delay + "-," + comp, kinds (vox));
  18157. // onto another linked track's list: it moves to that insert (the Kick's)
  18158. press (rowPoint (1, 1, false), {}, rowPoint (0, 0, false));
  18159. check ("drag_to_another_track_moves", kinds (kick) == comp + "," + eq && kinds (vox) == verb + "," + comp + "," + delay + "-," + comp,
  18160. kinds (kick) + " | " + kinds (vox));
  18161. // the wheel scrolls a list longer than its track (Kick's 4 effects + "add" in a 3-row header)
  18162. engine.editSong ([kick] (Song& s) {
  18163. s.mixer[(std::size_t) kick].effects.push_back (makeEffectSlot (EffectKind::delay));
  18164. s.mixer[(std::size_t) kick].effects.push_back (makeEffectSlot (EffectKind::reverb));
  18165. });
  18166. engine.dispatchPendingMessages();
  18167. const auto firstName = hintOf (rowPoint (0, 0, false)).value;
  18168. const auto rowsShown = list (0).getHeight() / 13;
  18169. pl.mouseWheelMove (event (rowPoint (0, 0, false), {}, rowPoint (0, 0, false), 0, false), juce::MouseWheelDetails { 0.0f, -0.5f, false, false, false });
  18170. const auto afterWheel = hintOf (rowPoint (0, 0, false));
  18171. check ("wheel_scrolls_a_long_list", rowsShown < 5 && afterWheel.value != firstName
  18172. && afterWheel.value == quickpick::slotName (engine, song().mixer[(std::size_t) kick].effects[1]),
  18173. juce::String (rowsShown) + " rows, " + firstName + " -> " + afterWheel.value);
  18174. shotRows ("-inserts-edited.png", 3);
  18175. // a view option: not saved with the project
  18176. check ("option_not_in_project", ! ProjectFile::toJson (song()).contains ("trackInserts"));
  18177. // off again: the linked headers' own width
  18178. pl.runAction ("playlist.trackInserts");
  18179. engine.dispatchPendingMessages();
  18180. check ("inserts_off_again", ! PlaylistComponent::showTrackInserts && pl.headerWidthForSnapshot() == PlaylistComponent::linkedHeaderWidth);
  18181. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  18182. return allOk;
  18183. }
  18184. #include "WorkflowShot190iu.inc" // round 190iu
  18185. #include "PlaylistShot190jq.inc" // round 190jq
  18186. #include "IssuesShot190jz.inc" // round 190jz
  18187. #include "IssuesShot190lw.inc" // round 190lw
  18188. #include "IssuesShot190mq.inc" // round 190mq
  18189. #include "Focus218Shot190ng.inc" // round 190ng (issue #218)
  18190. #include "Mixer221Shot190ng.inc" // round 190ng (issue #221)
  18191. #include "IssuesShot190ng.inc" // round 190ng (issues #215, #217, #219, #220, #222)
  18192. #include "TrackClipsShot190ne.inc" // round 190ne
  18193. #include "TrackerShot190nw.inc" // round 190nw
  18194. #include "IssuesShot190nq.inc" // round 190nq (issues #193, #225-#230)
  18195. #include "Research190onShot.inc" // round 190on (research190oe P2, P8, P10)
  18196. #include "IssuesShot190ns.inc" // round 190ns (issues #231-#235)
  18197. #include "Rollup031S3Shot.inc" // rollup 0.1.31 step 3 (round 190ny)
  18198. #include "Tabs2Test190nz.inc" // round 190nz (issue #232 stage 2)
  18199. #include "IssuesShot190od.inc" // round 190od (issues #236-#242)
  18200. #include "DetailsShot190kn.inc" // round 190kn
  18201. #include "SmartTipShot190ok.inc" // round 190ok (D1)
  18202. #include "DetailsShot190ld.inc" // round 190ld
  18203. #include "DetailsShot190lr.inc" // round 190lr
  18204. #include "DetailsShot190lx.inc" // round 190lx
  18205. #include "DetailsShot190mf.inc" // round 190mf
  18206. #include "DetailsShot190mk.inc" // round 190mk
  18207. #include "DetailsShot190mp.inc" // round 190mp
  18208. #include "HWheel254Test.inc" // round 190ou: issue #254, the horizontal wheel
  18209. #include "DetailsShot190mr.inc" // round 190mr
  18210. #include "DetailsShot190mv.inc" // round 190mv
  18211. #include "DetailsShot190my.inc" // round 190my
  18212. #include "DetailsShot190oa.inc" // round 190oa
  18213. #include "RackShot190nc.inc" // round 190nc
  18214. #include "OnboardShot190np.inc" // round 190np
  18215. // --trackautoshot190gz (round 190gz): see the dispatch above
  18216. bool runTrackAutoShot190gz (const juce::String& prefix)
  18217. {
  18218. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18219. juce::StringArray report;
  18220. bool allOk = true;
  18221. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  18222. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  18223. allOk = allOk && ok;
  18224. };
  18225. lynx::AudioEngine engine (false);
  18226. lynx::MainComponent ui (engine, false);
  18227. ui.setSize (1600, 900);
  18228. {
  18229. // a small song in FL's shape: Kick and Synth patterns, a drum loop, a vocal on its prepared insert, a mixed beat
  18230. using namespace lynx;
  18231. auto song = Song::makeDefault();
  18232. song.playlist.clear();
  18233. song.patterns.clear();
  18234. for (auto& c : song.channels)
  18235. c.mixerTrack = 0; // (FL's new channels play on the Master)
  18236. song.channels[4].mixerTrack = 9; // the Synth on a bus the user made
  18237. song.mixer[9].name = "Synth bus";
  18238. const auto audio = [&song] (const char* name, int mixer) {
  18239. ChannelDef c;
  18240. c.name = name;
  18241. c.instrument = InstrumentKind::audioClip;
  18242. c.samplePath = std::string ("/shots/") + name + ".wav";
  18243. c.mixerTrack = mixer;
  18244. song.channels.push_back (c);
  18245. return (int) song.channels.size() - 1;
  18246. };
  18247. const auto loop = audio ("Drum loop", 0);
  18248. const auto vox = audio ("Lead vocal", 12);
  18249. song.mixer[12].name = "Vox chain";
  18250. song.mixer[12].colour = 0xFF3C8DD8;
  18251. song.mixer[12].effects.push_back (makeEffectSlot (EffectKind::parametricEq));
  18252. const auto pattern = [&song] (const char* name, std::vector<int> channels, std::uint32_t colour) {
  18253. auto& p = song.patterns.emplace_back();
  18254. p.name = name;
  18255. p.colour = colour;
  18256. for (const auto c : channels)
  18257. for (int step : { 0, 4, 8, 12 })
  18258. p.toggleStep (c, step);
  18259. return (int) song.patterns.size() - 1;
  18260. };
  18261. const auto kick = pattern ("Kick", { 0 }, 0xFFD85A3C);
  18262. const auto lead = pattern ("Lead", { 4 }, 0xFF8A5CD8);
  18263. const auto beat = pattern ("Beat", { 1, 2, 3 }, 0xFF5CB85C);
  18264. const auto clip = [&song] (int track, ClipKind kind, int source, int bar, int bars) {
  18265. Clip c;
  18266. c.kind = kind;
  18267. c.track = track;
  18268. c.start = (std::int64_t) bar * 4 * ppq;
  18269. c.length = (std::int64_t) bars * 4 * ppq;
  18270. (kind == ClipKind::pattern ? c.pattern : c.channel) = source;
  18271. song.playlist.push_back (c);
  18272. };
  18273. for (int bar = 0; bar < 8; bar += 2)
  18274. {
  18275. clip (0, ClipKind::pattern, kick, bar, 2);
  18276. clip (2, ClipKind::pattern, beat, bar, 2);
  18277. }
  18278. clip (1, ClipKind::audio, loop, 0, 8);
  18279. clip (3, ClipKind::pattern, lead, 2, 4);
  18280. clip (4, ClipKind::audio, vox, 4, 4);
  18281. clip (6, ClipKind::pattern, kick, 4, 2); // (round 190ib: Track 7 only repeats Track 1's Kick)
  18282. song.playlistTracks.resize (8);
  18283. engine.setSong (std::move (song));
  18284. }
  18285. engine.dispatchPendingMessages();
  18286. ui.selectTabForSnapshot (2);
  18287. engine.dispatchPendingMessages();
  18288. auto& pl = ui.getPlaylistForSnapshot();
  18289. pl.setSize (juce::jmax (pl.getWidth(), 1000), juce::jmax (pl.getHeight(), 640));
  18290. pl.setViewForSnapshot (120.0, 1, 0);
  18291. const auto shotRows = [&] (const juce::String& name, int rows) {
  18292. const auto bottom = pl.trackRowForSnapshot (rows).getY();
  18293. savePng (pl.createComponentSnapshot ({ 0, 0, juce::jmin (pl.getWidth(), 820), juce::jmin (pl.getHeight(), bottom + 12) }), prefix + name);
  18294. };
  18295. const auto& song = [&]() -> const lynx::Song& { return engine.getSong(); };
  18296. const auto mode = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mode : lynx::PlaylistTrackMode::unassigned; };
  18297. const auto mixerOf = [&] (int t) { return t < (int) song().playlistTracks.size() ? song().playlistTracks[(std::size_t) t].mixerTrack : -1; };
  18298. // ---- 1. FL's default: tracks and inserts apart, FL's narrow headers
  18299. check ("off_by_default", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow(),
  18300. juce::String (pl.headerWidthForSnapshot()));
  18301. shotRows ("-off.png", 7);
  18302. // ---- 2. the switch (Playlist › Edit, Track mode, Settings › Project): it lists what it changes and asks (round
  18303. // 190ib: inserts move, channels are routed), then it is one undo step
  18304. lynx::autolink::Report plan;
  18305. bool asked = false;
  18306. lynx::PlaylistComponent::answerLinkConfirmation = [&] (const lynx::autolink::Report& r) {
  18307. plan = r;
  18308. asked = true;
  18309. return true;
  18310. };
  18311. {
  18312. const auto text = lynx::PlaylistComponent::describeLinkPlan (song(), lynx::autolink::planOn (song()));
  18313. juce::AlertWindow box (lynx::tr ("Link Playlist tracks to mixer tracks"), text, juce::MessageBoxIconType::QuestionIcon);
  18314. box.addButton (lynx::tr ("Link"), 1);
  18315. box.addButton (lynx::tr ("Cancel"), 0);
  18316. box.sendLookAndFeelChange();
  18317. savePng (lynx::shot::snapshot (box), prefix + "-confirm.png");
  18318. }
  18319. pl.runAction ("playlist.linkTracks");
  18320. engine.dispatchPendingMessages();
  18321. const auto moved = [&plan] (int from, int to) {
  18322. return std::any_of (plan.changes.begin(), plan.changes.end(), [=] (const lynx::autolink::Change& c) {
  18323. return c.kind == lynx::autolink::Change::Kind::moveInsert && c.from == from && c.to == to;
  18324. });
  18325. };
  18326. check ("asked_first_with_the_moves", asked && moved (9, 4) && moved (12, 5) && plan.repeats.size() == 1 && ! plan.changesSound(),
  18327. juce::String ((int) plan.changes.size()));
  18328. check ("switch_on", song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth,
  18329. juce::String (pl.headerWidthForSnapshot()));
  18330. check ("kick_instrument_track_insert_1", mode (0) == lynx::PlaylistTrackMode::instrument && mixerOf (0) == 1 && song().channels[0].mixerTrack == 1,
  18331. juce::String (mixerOf (0)));
  18332. check ("loop_audio_track_insert_2", mode (1) == lynx::PlaylistTrackMode::audio && mixerOf (1) == 2 && song().mixer[2].name == "Drum loop",
  18333. juce::String (mixerOf (1)));
  18334. // (round 190ib: Track N = insert N for every track with content of its own)
  18335. check ("beat_track_insert_3", mode (2) == lynx::PlaylistTrackMode::audio && mixerOf (2) == 3 && song().channels[1].mixerTrack == 3
  18336. && song().channels[2].mixerTrack == 3 && song().channels[3].mixerTrack == 3,
  18337. juce::String (mixerOf (2)));
  18338. check ("synth_bus_moves_to_insert_4", mode (3) == lynx::PlaylistTrackMode::instrument && song().channels[4].mixerTrack == 4
  18339. && song().mixer[4].name == "Synth bus" && song().playlistTracks[3].name == "Synth bus",
  18340. juce::String (song().channels[4].mixerTrack));
  18341. check ("vocal_chain_moves_to_insert_5", mode (4) == lynx::PlaylistTrackMode::audio && mixerOf (4) == 5 && song().mixer[5].effects.size() == 1
  18342. && song().mixer[5].name == "Vox chain",
  18343. juce::String (mixerOf (4)));
  18344. check ("empty_and_repeat_tracks_stay", mode (5) == lynx::PlaylistTrackMode::unassigned && mode (6) == lynx::PlaylistTrackMode::unassigned
  18345. && lynx::autolink::repeatedTracks (song())[6] == 0);
  18346. shotRows ("-on.png", 7);
  18347. // one undo step: Undo brings FL's tracks back, Redo the links
  18348. engine.undo();
  18349. engine.dispatchPendingMessages();
  18350. check ("undo_switch_on", ! song().linkTracksToMixer && mode (0) == lynx::PlaylistTrackMode::unassigned && mode (1) == lynx::PlaylistTrackMode::unassigned
  18351. && song().channels[0].mixerTrack == 0 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow());
  18352. engine.redo();
  18353. engine.dispatchPendingMessages();
  18354. check ("redo_switch_on", song().linkTracksToMixer && mixerOf (1) == 2 && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::linkedHeaderWidth);
  18355. auto source = juce::Desktop::getInstance().getMainMouseSource();
  18356. const auto now = juce::Time::getCurrentTime();
  18357. const int ctrl = juce::ModifierKeys::commandModifier;
  18358. const auto event = [&] (juce::Point<int> p, juce::ModifierKeys mods, juce::Point<int> down, int clicks, bool dragged) {
  18359. 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);
  18360. };
  18361. const auto press = [&] (juce::Point<int> p, juce::ModifierKeys mods, std::optional<juce::Point<int>> to = {}) {
  18362. const auto down = mods.withFlags (juce::ModifierKeys::leftButtonModifier);
  18363. pl.mouseMove (event (p, mods, p, 1, false));
  18364. pl.mouseDown (event (p, down, p, 1, false));
  18365. if (to)
  18366. pl.mouseDrag (event (*to, down, p, 1, true));
  18367. pl.mouseUp (event (to ? *to : p, mods, p, 1, to.has_value()));
  18368. engine.flushLevels();
  18369. engine.dispatchPendingMessages();
  18370. };
  18371. const auto doubleClick = [&] (juce::Point<int> p) {
  18372. const auto down = juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier);
  18373. pl.mouseDown (event (p, down, p, 2, false));
  18374. pl.mouseDoubleClick (event (p, down, p, 2, false));
  18375. pl.mouseUp (event (p, {}, p, 2, false));
  18376. engine.flushLevels();
  18377. engine.dispatchPendingMessages();
  18378. };
  18379. // the controls are found where they are drawn: M right of the plate, S left of it, the volume bar and the pan knob
  18380. // under them (the same geometry the header paints with)
  18381. const auto row = [&] (int t) { return pl.trackRowForSnapshot (t); };
  18382. const int w = pl.headerWidthForSnapshot();
  18383. const auto mAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 13 - 9, r.getY() + 11); }; // (meter column 9 px)
  18384. const auto sAt = [&] (int t) { return mAt (t) - juce::Point<int> (20, 0); };
  18385. const auto volumeAt = [&] (int t, float fraction) {
  18386. const auto r = row (t);
  18387. const auto left = 8, width = w - 9 - 2 - 32;
  18388. return juce::Point<int> (left + juce::roundToInt (fraction * (float) width), r.getY() + 26);
  18389. };
  18390. const auto panAt = [&] (int t) { const auto r = row (t); return juce::Point<int> (w - 9 - 6 - 7, r.getY() + 26); };
  18391. const auto& insert2 = [&]() -> const lynx::MixerTrack& { return song().mixer[2]; };
  18392. // ---- 3. the linked headers' controls act on the track's mixer track
  18393. press (mAt (1), {});
  18394. check ("m_mutes_the_insert", insert2().muted, juce::String ((int) insert2().muted));
  18395. press (mAt (1), {});
  18396. check ("m_again_unmutes", ! insert2().muted);
  18397. press (sAt (1), {});
  18398. check ("s_solos_the_insert", insert2().solo);
  18399. press (sAt (1), {});
  18400. press (volumeAt (1, 0.25f), {});
  18401. check ("volume_click_sets_the_level", std::abs (insert2().volume - 0.25f) < 0.03f, juce::String (insert2().volume, 3));
  18402. press (volumeAt (1, 0.25f), {}, volumeAt (1, 0.5f));
  18403. check ("volume_drag", std::abs (insert2().volume - 0.5f) < 0.03f, juce::String (insert2().volume, 3));
  18404. doubleClick (volumeAt (1, 0.5f));
  18405. check ("volume_double_click_0_db", insert2().volume == lynx::unityFader, juce::String (insert2().volume, 3));
  18406. press (panAt (1), {}, panAt (1) - juce::Point<int> (0, 40));
  18407. check ("pan_drag_up", std::abs (insert2().pan - 0.5f) < 0.02f, juce::String (insert2().pan, 3));
  18408. shotRows ("-controls.png", 7);
  18409. doubleClick (panAt (1));
  18410. check ("pan_double_click_centre", insert2().pan == 0.0f, juce::String (insert2().pan, 3));
  18411. // an instrument track's header acts on its channel's insert (Synth: insert 4 since round 190ib)
  18412. press (volumeAt (3, 0.4f), {});
  18413. check ("instrument_track_volume_on_its_insert", std::abs (song().mixer[4].volume - 0.4f) < 0.03f, juce::String (song().mixer[4].volume, 3));
  18414. engine.editSong ([] (lynx::Song& s) { s.mixer[4].volume = lynx::unityFader; });
  18415. // FL's track mute and solo stay on the Playlist track: Ctrl+click on M solos it, a muted track lights M and the
  18416. // first click unmutes it
  18417. press (mAt (1), ctrl);
  18418. check ("ctrl_m_solos_the_playlist_track", song().isTrackMuted (0) && ! song().isTrackMuted (1) && ! insert2().solo);
  18419. press (mAt (1), ctrl);
  18420. engine.editSong ([] (lynx::Song& s) {
  18421. for (auto& t : s.playlistTracks)
  18422. t.muted = false;
  18423. s.playlistTracks[1].muted = true;
  18424. });
  18425. press (mAt (1), {});
  18426. check ("m_unmutes_a_muted_playlist_track_first", ! song().isTrackMuted (1) && ! insert2().muted);
  18427. // a track that only repeats another keeps FL's LED (Track 7, Track 1's Kick): a click mutes the Playlist track
  18428. press (juce::Point<int> (w - 9 - 11, row (6).getCentreY()), {});
  18429. check ("unlinked_led_is_fl", song().isTrackMuted (6));
  18430. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[6].muted = false; });
  18431. // round 190ib: a linked track and its insert keep one name, whichever is renamed
  18432. engine.editSong ([] (lynx::Song& s) { s.mixer[3].name = "Drums"; });
  18433. check ("insert_rename_renames_the_track", song().playlistTracks[2].name == "Drums");
  18434. engine.editSong ([] (lynx::Song& s) { s.playlistTracks[2].name = "Beat"; });
  18435. check ("track_rename_renames_the_insert", song().mixer[3].name == "Beat");
  18436. // ---- 4. new content follows: a sample on empty Track 6 makes it an audio track (insert 6)
  18437. engine.editSong ([] (lynx::Song& s) {
  18438. lynx::ChannelDef c;
  18439. c.name = "Guitar";
  18440. c.instrument = lynx::InstrumentKind::audioClip;
  18441. c.samplePath = "/shots/Guitar.wav";
  18442. s.channels.push_back (c);
  18443. lynx::Clip clip;
  18444. clip.kind = lynx::ClipKind::audio;
  18445. clip.channel = (int) s.channels.size() - 1;
  18446. clip.track = 5;
  18447. clip.start = 4 * 4 * lynx::ppq;
  18448. clip.length = 4 * 4 * lynx::ppq;
  18449. s.playlist.push_back (clip);
  18450. });
  18451. check ("new_sample_links_its_track", mode (5) == lynx::PlaylistTrackMode::audio && mixerOf (5) == 6 && song().channels.back().mixerTrack == 6,
  18452. juce::String (mixerOf (5)));
  18453. engine.undo();
  18454. check ("undo_takes_the_clip_and_the_link", mode (5) == lynx::PlaylistTrackMode::unassigned && song().channels.back().name != "Guitar");
  18455. // ---- 5. row heights (round 190ft): short rows keep M / S; from 34 px the volume and pan; tall rows the input
  18456. const auto heights = [&] (std::vector<std::pair<int, int>> rows) {
  18457. engine.editSong ([rows] (lynx::Song& s) {
  18458. for (const auto& [t, h] : rows)
  18459. s.playlistTracks[(std::size_t) t].height = h;
  18460. });
  18461. engine.dispatchPendingMessages();
  18462. };
  18463. heights ({ { 0, 16 }, { 1, 24 }, { 4, 80 } });
  18464. shotRows ("-heights.png", 7);
  18465. {
  18466. const auto r = row (1);
  18467. const auto before = insert2().volume;
  18468. press (juce::Point<int> (20, r.getY() + 12), {}); // (no volume bar on a 24 px row: the press selects)
  18469. check ("short_row_has_no_volume_bar", insert2().volume == before && pl.selectedTracksForSnapshot() == std::vector<int> { 1 });
  18470. press (juce::Point<int> (w - 22, r.getY() + 12), {});
  18471. check ("short_row_m_still_works", insert2().muted);
  18472. press (juce::Point<int> (w - 22, r.getY() + 12), {});
  18473. }
  18474. heights ({ { 0, 0 }, { 1, 0 }, { 4, 0 } });
  18475. // ---- 6. saved: .lynx keeps the switch; the links themselves are FL track modes
  18476. {
  18477. juce::String error;
  18478. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song()), error);
  18479. check ("lynx_round_trip", back && back->linkTracksToMixer && back->playlistTracks.size() > 4 && back->playlistTracks[1].mixerTrack == 2
  18480. && back->playlistTracks[0].mode == lynx::PlaylistTrackMode::instrument, error);
  18481. auto plain = song();
  18482. plain.linkTracksToMixer = false;
  18483. const auto json = lynx::ProjectFile::toJson (plain);
  18484. check ("off_not_saved", ! json.contains ("linkTracksToMixer"));
  18485. }
  18486. // ---- 7. off: FL's headers again (the links stay)
  18487. lynx::PlaylistComponent::answerLinkConfirmation = nullptr;
  18488. pl.runAction ("playlist.linkTracks");
  18489. engine.dispatchPendingMessages();
  18490. check ("switch_off_fl_headers", ! song().linkTracksToMixer && pl.headerWidthForSnapshot() == lynx::PlaylistComponent::flHeaderWidthNow()
  18491. && mode (1) == lynx::PlaylistTrackMode::audio);
  18492. shotRows ("-off-after.png", 7);
  18493. // ---- 8. Settings › Project's switches
  18494. {
  18495. auto panel = lynx::makeSettingsPanel (engine, lynx::SettingsPage::project);
  18496. panel->setSize (760, 720);
  18497. savePng (lynx::shot::snapshot (*panel), prefix + "-settings-project.png");
  18498. }
  18499. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  18500. return allOk;
  18501. }
  18502. bool runFlPlShot (const juce::String& prefix)
  18503. {
  18504. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18505. juce::StringArray report;
  18506. bool allOk = true;
  18507. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  18508. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  18509. allOk = allOk && ok;
  18510. };
  18511. const auto plain = [] (juce::String t) {
  18512. // (without the shortcut column and the mnemonic: the mark, or the " (K)" a translation without the letter gets)
  18513. t = t.upToFirstOccurrenceOf ("\t", false, false);
  18514. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  18515. t = t.substring (0, at);
  18516. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  18517. };
  18518. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  18519. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  18520. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  18521. return it.getItem().subMenu.get();
  18522. return nullptr;
  18523. };
  18524. const auto texts = [&plain] (const juce::PopupMenu& menu, int count) {
  18525. juce::StringArray out;
  18526. for (juce::PopupMenu::MenuItemIterator it (menu); it.next() && out.size() < count;)
  18527. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  18528. return out;
  18529. };
  18530. const auto modelTexts = [] (const std::vector<lynx::fltrackmenus::Entry>& model) {
  18531. juce::StringArray out;
  18532. for (const auto& e : model)
  18533. if (e.kind != lynx::fltrackmenus::Entry::Kind::list)
  18534. out.add (e.kind == lynx::fltrackmenus::Entry::Kind::separator ? juce::String ("-")
  18535. : e.kind == lynx::fltrackmenus::Entry::Kind::caption ? "[" + lynx::tr (e.text) + "]"
  18536. : lynx::tr (e.text));
  18537. return out;
  18538. };
  18539. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  18540. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  18541. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  18542. {
  18543. it.getItem().action();
  18544. return true;
  18545. }
  18546. return false;
  18547. };
  18548. lynx::AudioEngine engine (false);
  18549. lynx::MainComponent ui (engine, false);
  18550. ui.setSize (1600, 900);
  18551. int vox = -1;
  18552. {
  18553. auto song = lynx::Song::makeDefault();
  18554. song.channels.push_back ({});
  18555. song.channels.back().name = "Vox";
  18556. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  18557. song.channels.back().volume = 0.6f;
  18558. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  18559. vox = (int) song.channels.size() - 1;
  18560. lynx::Clip c;
  18561. c.kind = lynx::ClipKind::audio;
  18562. c.channel = vox;
  18563. c.track = 3;
  18564. c.start = 4 * lynx::ppq;
  18565. c.length = 2 * lynx::ppq;
  18566. song.playlist.push_back (c);
  18567. engine.setSong (std::move (song));
  18568. }
  18569. engine.dispatchPendingMessages();
  18570. auto& playlist = ui.getPlaylistForSnapshot();
  18571. // ---- 1. the audio clip menu: Preview first, Automate › Panning / Volume
  18572. {
  18573. const auto menu = playlist.getClipMenuForSnapshot (0);
  18574. juce::PopupMenu::MenuItemIterator it (menu);
  18575. it.next(); // (the "Audio clip" title band)
  18576. it.next();
  18577. check ("clip_menu_preview_first", plain (it.getItem().text) == lynx::tr ("Preview"), it.getItem().text);
  18578. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  18579. check ("clip_menu_automate", automate != nullptr && texts (*automate, 9) == modelTexts (lynx::fltrackmenus::automate()),
  18580. automate != nullptr ? texts (*automate, 9).joinIntoString ("|") : juce::String ("missing"));
  18581. saveMenus (juce::StringArray { "Audio clip menu", "Automate" }, std::vector<juce::PopupMenu> { menu, automate != nullptr ? *automate : juce::PopupMenu() },
  18582. prefix + "-clip-menu.png");
  18583. const auto before = engine.getSong().automations.size();
  18584. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  18585. const auto& song = engine.getSong();
  18586. // (round 190dz: the Levels adjustment's volume multiplier, neutral = 0.5 of its 0…200 % travel)
  18587. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  18588. && song.automations.back().target.param == lynx::leveladjust::volume
  18589. && song.automations.back().target.index == vox && song.automations.back().points.size() == 2
  18590. && song.automations.back().points[1].tick == 2 * lynx::ppq && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  18591. const auto* clip = ok ? &song.playlist.back() : nullptr;
  18592. check ("automate_volume_clip", ok && clip->kind == lynx::ClipKind::automation && clip->track == 3 && clip->start == 4 * lynx::ppq
  18593. && clip->length == 2 * lynx::ppq,
  18594. ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  18595. engine.undo();
  18596. check ("automate_undo", engine.getSong().automations.size() == before);
  18597. // Preview: the clip's own audio (FL plays it through its channel); LYNX renders it for the preview output
  18598. const auto rendered = engine.renderClipAudio (0);
  18599. check ("preview_renders_the_clip", ! rendered.left.empty(), juce::String ((int) rendered.left.size()) + " frames");
  18600. }
  18601. // ---- 2. the Playlist's "+": its menu, a right click's audio track, the corner
  18602. {
  18603. const auto menu = playlist.getAddTrackMenuForSnapshot();
  18604. check ("add_menu_head", texts (menu, 5) == modelTexts (lynx::fltrackmenus::addTrack()), texts (menu, 5).joinIntoString ("|"));
  18605. saveMenus (juce::StringArray { "Playlist +" }, std::vector<juce::PopupMenu> { menu }, prefix + "-add-track-menu.png");
  18606. ui.selectTabForSnapshot (2);
  18607. engine.dispatchPendingMessages();
  18608. auto* button = playlist.getAddTrackButtonForSnapshot();
  18609. check ("add_button_in_corner", button != nullptr && button->isVisible() && button->getX() == 7 && button->getWidth() == 21 && button->getHeight() == 18
  18610. && button->getBottom() <= lynx::PlaylistComponent::headerHeight);
  18611. savePng (playlist.createComponentSnapshot (juce::Rectangle<int> (0, 0, juce::jmin (560, playlist.getWidth()), juce::jmin (260, playlist.getHeight()))),
  18612. prefix + "-playlist-corner.png");
  18613. const auto track = playlist.addAudioTrackNow();
  18614. const auto& song = engine.getSong();
  18615. check ("add_audio_track", track == 0 && song.playlistTracks.size() > 0 && song.playlistTracks[0].mode == lynx::PlaylistTrackMode::audio
  18616. && song.playlistTracks[0].mixerTrack > 0,
  18617. juce::String (track));
  18618. engine.undo();
  18619. }
  18620. // ---- 3. Track mode › Instrument track ›
  18621. {
  18622. const auto menu = playlist.getTrackMenuForSnapshot (5);
  18623. const auto* modes = findSub (menu, lynx::tr ("Track mode"));
  18624. const auto* instrument = modes != nullptr ? findSub (*modes, lynx::tr ("Instrument track")) : nullptr;
  18625. check ("instrument_track_head", instrument != nullptr && texts (*instrument, 4) == modelTexts (lynx::fltrackmenus::instrumentTrack()),
  18626. instrument != nullptr ? texts (*instrument, 4).joinIntoString ("|") : juce::String ("missing"));
  18627. const auto* existing = instrument != nullptr ? findSub (*instrument, lynx::tr ("Use existing channel")) : nullptr;
  18628. check ("use_existing_lists_generators", existing != nullptr && existing->getNumItems() == 5, existing != nullptr ? juce::String (existing->getNumItems()) : juce::String());
  18629. std::vector<juce::PopupMenu> menus { modes != nullptr ? *modes : juce::PopupMenu(), instrument != nullptr ? *instrument : juce::PopupMenu(),
  18630. existing != nullptr ? *existing : juce::PopupMenu() };
  18631. saveMenus (juce::StringArray { "Track mode", "Instrument track", "Use existing channel" }, menus, prefix + "-instrument-track-menu.png");
  18632. lynx::ChannelDef synth;
  18633. synth.name = "Lead";
  18634. synth.instrument = lynx::InstrumentKind::synth;
  18635. const auto channels = engine.getSong().channels.size();
  18636. int made = -1;
  18637. engine.editSong ([&] (lynx::Song& s) { made = lynx::trackmodes::addInstrumentTrack (s, synth, 5); });
  18638. check ("instrument_track_new_channel", made == (int) channels && engine.getSong().playlistTracks.size() > 5
  18639. && engine.getSong().playlistTracks[5].channel == made);
  18640. engine.undo();
  18641. }
  18642. // ---- 4. the Channel rack menu: Assign to new instrument track / Unassign
  18643. {
  18644. auto& rack = ui.getRackForSnapshot();
  18645. const auto menu = rack.getChannelMenuForSnapshot (1);
  18646. saveMenus (juce::StringArray { "Channel menu" }, std::vector<juce::PopupMenu> { menu }, prefix + "-channel-menu.png");
  18647. check ("assign_runs", click (menu, lynx::tr ("Assign to new instrument track")));
  18648. const auto tracks = lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1);
  18649. check ("assign_first_free_track", tracks == std::vector<int> { 0 }, juce::String (tracks.empty() ? -1 : tracks.front()));
  18650. const auto again = rack.getChannelMenuForSnapshot (1);
  18651. check ("unassign_offered", click (again, lynx::tr ("Unassign from instrument track")) && lynx::trackmodes::instrumentTracksOf (engine.getSong(), 1).empty());
  18652. bool greyed = false;
  18653. const auto voxMenu = rack.getChannelMenuForSnapshot (vox);
  18654. for (juce::PopupMenu::MenuItemIterator it (voxMenu); it.next();)
  18655. if (plain (it.getItem().text) == plain (lynx::tr ("Assign to new instrument track")))
  18656. greyed = ! it.getItem().isEnabled;
  18657. check ("assign_greyed_for_audio_clip_channel", greyed);
  18658. }
  18659. // ---- 5. Tools › One-click audio recording
  18660. std::fprintf (stderr, "flplshot: tools\n");
  18661. {
  18662. const auto names = ui.getMenuNamesForSnapshot();
  18663. const auto tools = ui.getMenuForSnapshot (names.indexOf (lynx::tr ("Tools")));
  18664. const auto* oneClick = findSub (tools, lynx::tr ("One-click audio recording"));
  18665. check ("one_click_submenu", oneClick != nullptr && texts (*oneClick, 3) == modelTexts (lynx::fltrackmenus::oneClickRecording()),
  18666. oneClick != nullptr ? texts (*oneClick, 3).joinIntoString ("|") : juce::String ("missing"));
  18667. saveMenus (juce::StringArray { "Tools", "One-click audio recording" }, std::vector<juce::PopupMenu> { tools, oneClick != nullptr ? *oneClick : juce::PopupMenu() },
  18668. prefix + "-tools-one-click.png");
  18669. const auto plan = lynx::oneclick::plan (engine.getSong(), {}, 2, lynx::oneclick::Into::playlist);
  18670. check ("one_click_plan", plan.insert == 2 && plan.armInsert && plan.askInput && plan.songMode);
  18671. }
  18672. // ---- 6. Mixer › Disk recording › Latency compensation
  18673. {
  18674. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  18675. const auto menu = strips.buildMenu (1);
  18676. const auto* disk = findSub (menu, lynx::tr ("Disk recording"));
  18677. int after = -1, at = -1, i = 0;
  18678. bool ticked = false;
  18679. if (disk != nullptr)
  18680. for (juce::PopupMenu::MenuItemIterator it (*disk); it.next(); ++i)
  18681. {
  18682. if (plain (it.getItem().text) == plain (lynx::tr ("Auto-create audio clip (the rendered files go on the Playlist)")))
  18683. after = i;
  18684. if (plain (it.getItem().text) == plain (lynx::tr ("Latency compensation")))
  18685. {
  18686. at = i;
  18687. ticked = it.getItem().isTicked;
  18688. }
  18689. }
  18690. check ("latency_comp_item", disk != nullptr && after >= 0 && at == after + 1 && ticked && engine.getRecordOptions().latencyCompensation,
  18691. juce::String (after) + " " + juce::String (at));
  18692. saveMenus (juce::StringArray { "Disk recording" }, std::vector<juce::PopupMenu> { disk != nullptr ? *disk : juce::PopupMenu() },
  18693. prefix + "-disk-recording.png");
  18694. check ("latency_comp_toggles", disk != nullptr && click (*disk, lynx::tr ("Latency compensation")) && ! engine.getRecordOptions().latencyCompensation);
  18695. }
  18696. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  18697. return allOk;
  18698. }
  18699. // --flclipshot (round 190dz): see the dispatch above
  18700. // a menu as JUCE lays it out with explicit column breaks (PopupMenu::addColumnBreak): the columns side by side on
  18701. // one menu background; custom items (the title band) are painted by their own component
  18702. static juce::Image columnMenuImage (const juce::PopupMenu& menu)
  18703. {
  18704. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  18705. const auto border = lf.getPopupMenuBorderSize();
  18706. struct Row
  18707. {
  18708. const juce::PopupMenu::Item* item;
  18709. int height;
  18710. };
  18711. std::vector<std::vector<Row>> columns (1);
  18712. std::vector<int> widths (1, 160);
  18713. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  18714. {
  18715. const auto& item = it.getItem();
  18716. int w = 0, h = 0;
  18717. if (item.customComponent != nullptr)
  18718. item.customComponent->getIdealSize (w, h);
  18719. else
  18720. {
  18721. lf.getIdealPopupMenuItemSize (item.text.upToFirstOccurrenceOf ("\t", false, false), item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  18722. if (item.isSectionHeader)
  18723. h += h / 2; // as JUCE does
  18724. if (item.text.containsChar ('\t'))
  18725. w += 90;
  18726. }
  18727. columns.back().push_back ({ &item, h });
  18728. widths.back() = juce::jmax (widths.back(), w + 10);
  18729. if (item.shouldBreakAfter)
  18730. {
  18731. columns.emplace_back();
  18732. widths.push_back (160);
  18733. }
  18734. }
  18735. int width = 0, height = 0;
  18736. for (std::size_t c = 0; c < columns.size(); ++c)
  18737. {
  18738. width += widths[c];
  18739. int h = 2 * border;
  18740. for (const auto& row : columns[c])
  18741. h += row.height;
  18742. height = juce::jmax (height, h);
  18743. }
  18744. auto image = lynx::shot::canvas (width, height);
  18745. juce::Graphics g (image);
  18746. lynx::shot::logical (g);
  18747. lf.drawPopupMenuBackground (g, width, height);
  18748. int x = 0;
  18749. for (std::size_t c = 0; c < columns.size(); ++c)
  18750. {
  18751. int y = border;
  18752. for (const auto& row : columns[c])
  18753. {
  18754. const auto& item = *row.item;
  18755. const juce::Rectangle<int> r (x, y, widths[c], row.height);
  18756. if (item.customComponent != nullptr)
  18757. {
  18758. juce::Graphics::ScopedSaveState state (g);
  18759. g.setOrigin (r.getPosition());
  18760. item.customComponent->setSize (r.getWidth(), r.getHeight());
  18761. item.customComponent->paintEntireComponent (g, false);
  18762. }
  18763. else if (item.isSectionHeader)
  18764. lf.drawPopupMenuSectionHeader (g, r, item.text);
  18765. else
  18766. {
  18767. juce::Graphics::ScopedSaveState state (g);
  18768. g.setOrigin (r.getPosition());
  18769. lf.drawPopupMenuItem (g, r.withPosition (0, 0), item.isSeparator, item.isEnabled, false, item.isTicked, item.subMenu != nullptr,
  18770. item.text.upToFirstOccurrenceOf ("\t", false, false), item.text.fromFirstOccurrenceOf ("\t", false, false),
  18771. item.image.get(), nullptr);
  18772. }
  18773. y += row.height;
  18774. }
  18775. x += widths[c];
  18776. if (c + 1 < columns.size()) // (JUCE's column separator)
  18777. {
  18778. g.setColour (lf.findColour (juce::PopupMenu::textColourId).withAlpha (0.15f));
  18779. g.fillRect (x - 1, border, 1, height - 2 * border);
  18780. }
  18781. }
  18782. return image;
  18783. }
  18784. // --genpresetshot (round 190fs): see the dispatch above
  18785. bool runGenPresetShot (const juce::String& prefix)
  18786. {
  18787. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18788. juce::StringArray report;
  18789. bool allOk = true;
  18790. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  18791. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  18792. allOk = allOk && ok;
  18793. };
  18794. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  18795. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  18796. };
  18797. const auto plain = [] (juce::String t) { return t.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&"); };
  18798. const auto texts = [&plain] (const juce::PopupMenu& menu) {
  18799. juce::StringArray out;
  18800. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  18801. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  18802. return out;
  18803. };
  18804. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  18805. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  18806. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  18807. {
  18808. it.getItem().action();
  18809. return true;
  18810. }
  18811. return false;
  18812. };
  18813. const auto sameSound = [] (const lynx::ChannelDef& a, const lynx::ChannelDef& b) { return lynx::genpresets::sameSound (a, b); };
  18814. lynx::AudioEngine engine (false);
  18815. const auto& fl = lynx::flStudioAccess();
  18816. auto dx = lynx::natives::makeChannel (lynx::InstrumentKind::dx10, fl);
  18817. auto osc = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, fl);
  18818. check ("channels_made", dx.has_value() && osc.has_value());
  18819. if (! dx || ! osc)
  18820. {
  18821. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  18822. return false;
  18823. }
  18824. engine.editSong ([&] (lynx::Song& s) {
  18825. s.channels.clear();
  18826. s.channels.push_back (*dx);
  18827. s.channels.back().mixerTrack = 1;
  18828. s.channels.push_back (*osc);
  18829. s.channels.back().mixerTrack = 2;
  18830. lynx::ChannelDef synth;
  18831. synth.instrument = lynx::InstrumentKind::synth;
  18832. synth.name = "Synth";
  18833. synth.mixerTrack = 3;
  18834. s.channels.push_back (synth);
  18835. });
  18836. const auto channel = [&engine] (int i) { return engine.getSong().channels[(std::size_t) i]; };
  18837. // ---- 1. Fruity DX10: the preset box before and after "Save preset..."
  18838. {
  18839. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  18840. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  18841. auto menu = lynx::channelPresetMenu (*frame);
  18842. check ("dx10_menu", menu.has_value());
  18843. const auto before = menu ? texts (*menu) : juce::StringArray();
  18844. check ("dx10_menu_has_save", before.contains (lynx::tr ("Save preset...")) && before.contains (lynx::tr ("Show the presets folder"))
  18845. && ! before.contains ("[" + lynx::tr ("Your presets") + "]"), before.joinIntoString ("|"));
  18846. if (menu)
  18847. saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu-before.png");
  18848. // a sound of its own: the bank's 4th preset, then a knob moved (a sound no factory preset has)
  18849. const auto mine = [&] {
  18850. auto c = channel (0);
  18851. if (auto b = lynx::banks::withPreset (c, 3))
  18852. c = *b;
  18853. if (! c.pluginState.empty())
  18854. c.pluginState[c.pluginState.size() / 2] ^= 0x5a;
  18855. return c;
  18856. }();
  18857. engine.editSong ([&] (lynx::Song& s) { s.channels[0] = mine; });
  18858. check ("dx10_saved", lynx::channelPresetSave (*frame, "My FM Bell"));
  18859. const auto file = lynx::genpresetui::folderFor (lynx::InstrumentKind::dx10).getChildFile ("My FM Bell.lynxpreset");
  18860. check ("dx10_file", file.existsAsFile() && lynx::genpresetui::isPresetFile (file), file.getFullPathName());
  18861. check ("dx10_box_shows_it", lynx::channelPresetName (*frame) == "My FM Bell", lynx::channelPresetName (*frame));
  18862. menu = lynx::channelPresetMenu (*frame);
  18863. const auto after = menu ? texts (*menu) : juce::StringArray();
  18864. check ("dx10_menu_your_presets", after.contains ("[" + lynx::tr ("Your presets") + "]") && after.contains ("My FM Bell")
  18865. && after.contains (lynx::tr ("Delete preset \"{0}\"", { "My FM Bell" })), after.joinIntoString ("|"));
  18866. if (menu)
  18867. saveMenus (juce::StringArray { "Fruity DX10 presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-dx10-menu.png");
  18868. shoot (*frame, "dx10-window");
  18869. // another sound, then the user's preset from the menu: the saved sound back, one undo step, project changed
  18870. if (auto other = lynx::banks::withPreset (channel (0), 0))
  18871. engine.editSong ([&] (lynx::Song& s) { s.channels[0] = *other; });
  18872. check ("dx10_other_sound", ! sameSound (channel (0), mine));
  18873. engine.markSaved();
  18874. menu = lynx::channelPresetMenu (*frame);
  18875. check ("dx10_load_click", menu.has_value() && click (*menu, "My FM Bell"));
  18876. check ("dx10_loaded_identical", sameSound (channel (0), mine) && channel (0).pluginState == mine.pluginState);
  18877. check ("dx10_loaded_name_and_insert", channel (0).name == "My FM Bell" && channel (0).mixerTrack == 1,
  18878. juce::String::fromUTF8 (channel (0).name.c_str()));
  18879. check ("dx10_project_changed", engine.isModified());
  18880. engine.undo();
  18881. check ("dx10_one_undo_step", ! sameSound (channel (0), mine));
  18882. engine.redo();
  18883. check ("dx10_redo", sameSound (channel (0), mine));
  18884. // the Browser: a new channel with the preset's generator, sound and name
  18885. juce::String error;
  18886. const auto count = engine.getSong().channels.size();
  18887. check ("browser_new_channel", lynx::genpresetui::addChannel (engine, file, error) && engine.getSong().channels.size() == count + 1, error);
  18888. const auto added = engine.getSong().channels.back();
  18889. check ("browser_channel_sound", added.instrument == lynx::InstrumentKind::dx10 && sameSound (added, mine) && added.name == "My FM Bell");
  18890. engine.undo();
  18891. check ("browser_channel_undo", engine.getSong().channels.size() == count);
  18892. }
  18893. // ---- 2. 3x Osc: save, the menu, delete
  18894. {
  18895. auto frame = lynx::makeChannelFrame (engine, 1, 0);
  18896. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  18897. check ("3xosc_saved", lynx::channelPresetSave (*frame, "Wide Saw Lead") && lynx::channelPresetSave (*frame, "Sub Bass"));
  18898. auto menu = lynx::channelPresetMenu (*frame);
  18899. const auto items = menu ? texts (*menu) : juce::StringArray();
  18900. check ("3xosc_menu", items.contains ("Wide Saw Lead") && items.contains ("Sub Bass") && items.contains (lynx::tr ("Save preset...")),
  18901. items.joinIntoString ("|"));
  18902. if (menu)
  18903. saveMenus (juce::StringArray { "3x Osc presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-3xosc-menu.png");
  18904. shoot (*frame, "3xosc-window");
  18905. check ("3xosc_delete", menu.has_value() && click (*menu, lynx::tr ("Delete preset \"{0}\"", { "Sub Bass" })));
  18906. check ("3xosc_deleted", lynx::genpresetui::userPresets (lynx::InstrumentKind::threeosc).size() == 1
  18907. && ! lynx::genpresetui::folderFor (lynx::InstrumentKind::threeosc).getChildFile ("Sub Bass.lynxpreset").exists());
  18908. menu = lynx::channelPresetMenu (*frame);
  18909. const auto left = menu ? texts (*menu) : juce::StringArray();
  18910. check ("3xosc_menu_after_delete", left.contains ("Wide Saw Lead") && ! left.contains ("Sub Bass"), left.joinIntoString ("|"));
  18911. }
  18912. // ---- 3. LYNX's synth: its "Presets..." box
  18913. {
  18914. engine.editSong ([] (lynx::Song& s) { s.channels[2].synth.cutoff = 777.0f; });
  18915. auto frame = lynx::makeChannelFrame (engine, 2, 0);
  18916. frame->setSize (juce::jmax (500, frame->getWidth()), juce::jmax (300, frame->getHeight()));
  18917. check ("synth_saved", lynx::channelPresetSave (*frame, "Dark Pad"));
  18918. const auto menu = lynx::channelPresetMenu (*frame);
  18919. const auto items = menu ? texts (*menu) : juce::StringArray();
  18920. check ("synth_menu", items.contains ("Dark Pad") && items.contains (lynx::tr ("Save preset...")) && items.contains (lynx::tr ("Show the presets folder")),
  18921. items.joinIntoString ("|"));
  18922. if (menu)
  18923. saveMenus (juce::StringArray { "Synth presets" }, std::vector<juce::PopupMenu> { *menu }, prefix + "-synth-menu.png");
  18924. const auto saved = lynx::genpresetui::read (lynx::genpresetui::folderFor (lynx::InstrumentKind::synth).getChildFile ("Dark Pad.lynxpreset"));
  18925. check ("synth_file", saved.has_value() && saved->sound.synth.cutoff == 777.0f);
  18926. }
  18927. // ---- 4. the name box (the hosted plugins' and the effects' "Save preset" box)
  18928. {
  18929. auto box = lynx::genpresetui::makeNameBox ("My FM Bell");
  18930. box->setSize (juce::jmax (360, box->getWidth()), juce::jmax (150, box->getHeight()));
  18931. shoot (*box, "save-name-box");
  18932. check ("name_box", box->getTextEditorContents ("name") == "My FM Bell");
  18933. }
  18934. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  18935. return allOk;
  18936. }
  18937. // --flfixshot (round 190ey): see the dispatch above
  18938. bool runFlFixShot (const juce::String& prefix)
  18939. {
  18940. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  18941. juce::StringArray report;
  18942. bool allOk = true;
  18943. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  18944. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  18945. allOk = allOk && ok;
  18946. };
  18947. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  18948. savePng (c.createComponentSnapshot (c.getLocalBounds()), prefix + "-" + name + ".png");
  18949. };
  18950. const auto plain = [] (juce::String t) {
  18951. t = t.upToFirstOccurrenceOf ("\t", false, false);
  18952. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  18953. t = t.substring (0, at);
  18954. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  18955. };
  18956. const auto texts = [&plain] (const juce::PopupMenu& menu) {
  18957. juce::StringArray out;
  18958. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  18959. out.add (it.getItem().isSeparator ? juce::String ("-") : it.getItem().isSectionHeader ? "[" + plain (it.getItem().text) + "]" : plain (it.getItem().text));
  18960. return out;
  18961. };
  18962. const auto findSub = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  18963. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  18964. if (it.getItem().subMenu != nullptr && plain (it.getItem().text) == plain (text))
  18965. return it.getItem().subMenu.get();
  18966. return nullptr;
  18967. };
  18968. const auto click = [&plain] (const juce::PopupMenu& menu, const juce::String& text) {
  18969. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  18970. if (plain (it.getItem().text) == plain (text) && it.getItem().isEnabled && it.getItem().action != nullptr)
  18971. {
  18972. it.getItem().action();
  18973. return true;
  18974. }
  18975. return false;
  18976. };
  18977. const auto folder = juce::File (prefix).getParentDirectory().getChildFile ("flfix-samples");
  18978. folder.createDirectory();
  18979. const auto writeWav = [] (const juce::File& file, double rate, int frames, double hz) {
  18980. juce::AudioBuffer<float> buffer (1, frames);
  18981. for (int i = 0; i < frames; ++i)
  18982. buffer.setSample (0, i, (float) (0.8 * std::sin (juce::MathConstants<double>::twoPi * hz * i / rate) * std::exp (-i / (rate * 0.12))));
  18983. file.deleteFile();
  18984. juce::WavAudioFormat wav;
  18985. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (file.createOutputStream().release(), rate, 1, 16, {}, 0)))
  18986. out->writeFromAudioSampleBuffer (buffer, 0, frames);
  18987. return file;
  18988. };
  18989. // ---- 1. the Sampler page (SMP-1 / 4 / 5 / 7, CTL-4)
  18990. {
  18991. lynx::AudioEngine engine (false);
  18992. const auto clap = writeWav (folder.getChildFile ("Basic 808 Clap.wav"), 44100.0, 11600, 180.0);
  18993. const auto loop48 = writeWav (folder.getChildFile ("Loop 48k.wav"), 48000.0, 48000, 220.0);
  18994. engine.editSong ([&] (lynx::Song& s) {
  18995. if (s.channels.empty())
  18996. s.channels.resize (1);
  18997. lynx::audioclips::loadSampleInto (s.channels[0], clap.getFullPathName().toStdString(), "808 Clap");
  18998. });
  18999. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  19000. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  19001. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  19002. frame->createComponentSnapshot (frame->getLocalBounds());
  19003. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  19004. auto& f = *frame;
  19005. lynx::samplerPageTurn (f, "show", 0.0);
  19006. const auto rate = engine.getTransport().sampleRate.load();
  19007. check ("resample_greyed_at_project_rate", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 44100.0) < 0.5 ? "0" : "1"), juce::String (rate));
  19008. check ("load_regions_greyed_without_regions", lynx::samplerPageQuery (f, "loadRegions") == "0");
  19009. check ("load_markers_greyed_without_markers", lynx::samplerPageQuery (f, "loadMarkers") == "0");
  19010. check ("bit_depth_16", lynx::samplerPageQuery (f, "corner") == "16", lynx::samplerPageQuery (f, "corner"));
  19011. check ("wave_hint_summary", lynx::samplerPageQuery (f, "waveHint").startsWith ("44100Hz, 16Bit int mono, 0:263"), lynx::samplerPageQuery (f, "waveHint"));
  19012. shoot (f, "sampler-44k");
  19013. // SMP-5: MUL's text
  19014. lynx::samplerPageTurn (f, "mul", 800.0);
  19015. check ("mul_text", lynx::samplerPageQuery (f, "mulText") == "105.70%", lynx::samplerPageQuery (f, "mulText"));
  19016. lynx::samplerPageTurn (f, "mul", 0.0);
  19017. // SMP-4: CROSSFADE on a loopless sample: Use loop points on, the loop = the whole sample, the box reads 32
  19018. engine.editSong ([] (lynx::Song& s) { s.channels[0].sampler.useLoopPoints = false; });
  19019. lynx::samplerPageTurn (f, "crossfade", 120.0);
  19020. check ("crossfade_loops_whole_sample", sampler().useLoopPoints && sampler().loopStart == 0 && sampler().loopEnd == 11599,
  19021. juce::String (sampler().loopStart) + ".." + juce::String (sampler().loopEnd));
  19022. check ("bit_depth_32_precomputed", lynx::samplerPageQuery (f, "corner") == "32", lynx::samplerPageQuery (f, "corner"));
  19023. frame->createComponentSnapshot (frame->getLocalBounds());
  19024. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  19025. shoot (f, "sampler-crossfade-red-loop");
  19026. lynx::samplerPageTurn (f, "crossfade", 0.0);
  19027. // SMP-3: a loop set with END alone, drawn red (FL: 0..276)
  19028. engine.editSong ([] (lynx::Song& s) {
  19029. s.channels[0].sampler.loopStart = 0;
  19030. s.channels[0].sampler.loopEnd = 2400;
  19031. });
  19032. lynx::samplerPageTurn (f, "show", 0.0);
  19033. shoot (f, "sampler-end-loop-red");
  19034. // round 190gw (live check 190gu B3): the waveform menu's Spectrum view / Multichannel waveform view, on a stereo
  19035. // clap-like noise burst (left and right differ) with no loop, as FL's shot
  19036. {
  19037. const auto noisy = folder.getChildFile ("Noise Clap.wav");
  19038. juce::AudioBuffer<float> b (2, 44100);
  19039. juce::Random random (190);
  19040. for (int i = 0; i < b.getNumSamples(); ++i)
  19041. for (int c = 0; c < 2; ++c)
  19042. b.setSample (c, i, (float) ((random.nextFloat() * 2.0f - 1.0f) * 0.9 * std::exp (-i / (44100.0 * (c == 0 ? 0.10 : 0.18)))
  19043. * (i > 1500 * c ? 1.0 : 0.15)));
  19044. noisy.deleteFile();
  19045. juce::WavAudioFormat wav;
  19046. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (noisy.createOutputStream().release(), 44100.0, 2, 16, {}, 0)))
  19047. out->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  19048. const auto before = engine.getSong().channels[0];
  19049. engine.editSong ([&] (lynx::Song& s) {
  19050. s.channels[0].samplePath = noisy.getFullPathName().toStdString();
  19051. s.channels[0].sampler.loopStart = s.channels[0].sampler.loopEnd = -1;
  19052. s.channels[0].sampler.useLoopPoints = false;
  19053. });
  19054. lynx::samplerPageTurn (f, "show", 0.0);
  19055. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
  19056. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  19057. lynx::samplerpage::waveViews().spectrum = true;
  19058. lynx::samplerPageTurn (f, "show", 0.0);
  19059. shoot (f, "sampler-spectrum-view");
  19060. lynx::samplerpage::waveViews() = { false, true };
  19061. lynx::samplerPageTurn (f, "show", 0.0);
  19062. shoot (f, "sampler-multichannel-view");
  19063. lynx::samplerpage::waveViews() = {};
  19064. engine.editSong ([&before] (lynx::Song& s) { s.channels[0] = before; });
  19065. lynx::samplerPageTurn (f, "show", 0.0);
  19066. frame->createComponentSnapshot (frame->getLocalBounds());
  19067. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  19068. }
  19069. // SMP-7: the waveform menu
  19070. const auto waveMenu = lynx::samplerWaveMenu (f);
  19071. juce::StringArray expected { lynx::tr ("Reload"), lynx::tr ("Save as..."), lynx::tr ("Locate file"), lynx::tr ("Copy audio to clipboard"),
  19072. lynx::tr ("Paste audio from clipboard"), "-", lynx::tr ("Edit in audio editor"),
  19073. lynx::tr ("Edit in pitch corrector"), lynx::tr ("Edit in time warper"), "-", // (round 190gw)
  19074. lynx::tr ("Open in new sampler channel"), lynx::tr ("Open in new Fruity Granulizer channel"),
  19075. lynx::tr ("Open in new Fruity Slicer channel"), lynx::tr ("Open in new Slicex channel"), "-", // (round 190gk)
  19076. lynx::tr ("Detect tempo") };
  19077. if (lynx::fileProperties) // (round 190gk: Windows only)
  19078. expected.add (lynx::tr ("Get properties"));
  19079. expected.addArray (juce::StringArray { "-", lynx::tr ("Spectrum view"), lynx::tr ("Multichannel waveform view") }); // (round 190gw)
  19080. check ("wave_menu_items", waveMenu.has_value() && texts (*waveMenu) == expected, waveMenu.has_value() ? texts (*waveMenu).joinIntoString ("|") : juce::String ("none"));
  19081. if (waveMenu.has_value())
  19082. saveMenus (juce::StringArray { "Sampler waveform" }, std::vector<juce::PopupMenu> { *waveMenu }, prefix + "-wave-menu.png");
  19083. check ("copy_audio_to_clipboard", waveMenu.has_value() && click (*waveMenu, lynx::tr ("Copy audio to clipboard"))
  19084. && lynx::audioclipboard::editor().frames() == 11600);
  19085. // SMP-1: a 48 kHz sample in this project: Resample enabled
  19086. lynx::samplerPageTurn (f, "show", 0.0);
  19087. engine.editSong ([&] (lynx::Song& s) { s.channels[0].samplePath = loop48.getFullPathName().toStdString(); });
  19088. lynx::samplerPageTurn (f, "show", 0.0);
  19089. check ("resample_enabled_48k", lynx::samplerPageQuery (f, "resample") == (std::abs (rate - 48000.0) < 0.5 ? "0" : "1"), juce::String (rate));
  19090. frame->createComponentSnapshot (frame->getLocalBounds()); // (starts the new file's waveform)
  19091. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  19092. shoot (f, "sampler-48k");
  19093. // CTL-4: Remove sample renames the channel "Sampler"
  19094. lynx::samplerFileRowPress (f, 3);
  19095. check ("remove_sample_renames", engine.getSong().channels[0].name == "Sampler" && engine.getSong().channels[0].samplePath.empty(),
  19096. juce::String::fromUTF8 (engine.getSong().channels[0].name.c_str()));
  19097. lynx::samplerPageTurn (f, "show", 0.0);
  19098. check ("no_sample_content_greyed", lynx::samplerPageQuery (f, "keepOnDisk") == "0" && lynx::samplerPageQuery (f, "resample") == "0");
  19099. shoot (f, "sampler-removed");
  19100. }
  19101. // ---- 2. the Multilink button's menu with multilink off (CTL-1)
  19102. lynx::AudioEngine engine (false);
  19103. lynx::MainComponent ui (engine, false);
  19104. ui.setSize (1600, 900);
  19105. {
  19106. using lynx::AutomationTarget;
  19107. using lynx::AutomationTargetKind;
  19108. engine.editSong ([] (lynx::Song& s) {
  19109. if (s.channels.empty())
  19110. s.channels.resize (1);
  19111. s.channels[0].name = "808 Kick";
  19112. });
  19113. engine.setMultilink (false);
  19114. engine.noteTweaked ({ AutomationTargetKind::channelVolume, 0 });
  19115. engine.noteTweaked ({ AutomationTargetKind::channelPan, 0 });
  19116. const auto menu = ui.getMultilinkMenuForSnapshot();
  19117. juce::PopupMenu::MenuItemIterator first (menu);
  19118. first.next();
  19119. const auto caption = first.getItem().text;
  19120. bool columnBreak = false, lynxLines = false;
  19121. juce::String rightCaption;
  19122. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  19123. {
  19124. if (columnBreak && rightCaption.isEmpty() && it.getItem().isSectionHeader)
  19125. rightCaption = it.getItem().text;
  19126. columnBreak = columnBreak || it.getItem().shouldBreakAfter;
  19127. lynxLines = lynxLines || it.getItem().text == lynx::tr ("Link to controller");
  19128. }
  19129. check ("ml_off_left_column_named", first.getItem().isSectionHeader && caption == lynx::describeAutomationTarget (engine, { AutomationTargetKind::channelPan, 0 }), caption);
  19130. check ("ml_off_two_columns", columnBreak && rightCaption == lynx::tr ("Last 2 tweaked parameters"), rightCaption);
  19131. check ("ml_off_no_lynx_greyed_lines", ! lynxLines);
  19132. savePng (columnMenuImage (menu), prefix + "-multilink-off-menu.png");
  19133. }
  19134. // ---- 3. the Playlist (PL-1 / 2 / 3 / 6 / 7 / 8)
  19135. auto& playlist = ui.getPlaylistForSnapshot();
  19136. {
  19137. auto song = lynx::Song::makeDefault();
  19138. lynx::ChannelDef bass;
  19139. bass.name = "Amount Too - Bass";
  19140. bass.instrument = lynx::InstrumentKind::audioClip;
  19141. bass.samplePath = writeWav (folder.getChildFile ("bass.wav"), 44100.0, 88200, 82.0).getFullPathName().toStdString();
  19142. bass.misc.levels.volume = 1.468f;
  19143. song.channels.push_back (bass);
  19144. lynx::Clip c;
  19145. c.kind = lynx::ClipKind::audio;
  19146. c.channel = (int) song.channels.size() - 1;
  19147. c.track = 3;
  19148. c.start = 4 * lynx::ppq;
  19149. c.length = 2 * lynx::ppq;
  19150. song.playlist.push_back (c);
  19151. engine.setSong (std::move (song));
  19152. }
  19153. engine.dispatchPendingMessages();
  19154. const auto clipIndex = (int) engine.getSong().playlist.size() - 1;
  19155. {
  19156. const auto menu = playlist.getClipMenuForSnapshot (clipIndex);
  19157. const auto* automate = findSub (menu, lynx::tr ("Automate"));
  19158. check ("automate_volume_runs", automate != nullptr && click (*automate, lynx::tr ("Volume")));
  19159. const auto& song = engine.getSong();
  19160. const auto made = (int) song.automations.size() - 1;
  19161. check ("automate_makes_current_clip", made >= 0 && playlist.brush.kind == lynx::ClipKind::automation && playlist.brush.index == made,
  19162. juce::String (playlist.brush.index));
  19163. // (PL-2: Levels VOL 147 %, FL's clip plays unity)
  19164. check ("automate_volume_unity", made >= 0 && song.automations.back().points[0].value == 0.5f
  19165. && lynx::lasttweak::valueText (song, song.automations.back().target, song.automations.back().points[0].value) == "100% 0.0dB 1.00");
  19166. const auto again = playlist.getClipMenuForSnapshot (clipIndex);
  19167. const auto* automate2 = findSub (again, lynx::tr ("Automate"));
  19168. check ("automate_second_is_2", automate2 != nullptr && click (*automate2, lynx::tr ("Volume"))
  19169. && juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()).endsWith (" #2"),
  19170. juce::String::fromUTF8 (engine.getSong().automations.back().name.c_str()));
  19171. // PL-7: Fade in / out curve
  19172. const auto* fadeIn = findSub (menu, lynx::tr ("Fade in curve"));
  19173. const auto* fadeOut = findSub (menu, lynx::tr ("Fade out curve"));
  19174. const juce::StringArray curve { lynx::tr ("Reset"), lynx::tr ("Normalize"), lynx::tr ("Normalize selection as a group"), lynx::tr ("Create crossfade"),
  19175. lynx::tr ("Manual"), "[" + lynx::tr ("Declicker") + "]", lynx::tr ("Automatic"), lynx::tr ("Disabled"), lynx::tr ("Enabled"),
  19176. "[" + lynx::tr ("Curve shape") + "]", lynx::tr ("Smooth curve"), lynx::tr ("Single curve") };
  19177. check ("fade_curve_submenus", fadeIn != nullptr && fadeOut != nullptr && texts (*fadeIn) == curve && texts (*fadeOut) == curve,
  19178. fadeIn != nullptr ? texts (*fadeIn).joinIntoString ("|") : juce::String ("missing"));
  19179. if (fadeOut != nullptr)
  19180. saveMenus (juce::StringArray { "Audio clip menu", "Fade out curve" }, std::vector<juce::PopupMenu> { menu, *fadeOut }, prefix + "-fade-curve-menu.png");
  19181. // PL-8: Detect tempo is one item now
  19182. bool detectItem = false;
  19183. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  19184. if (plain (it.getItem().text) == plain (lynx::tr ("Detect tempo")))
  19185. detectItem = it.getItem().subMenu == nullptr && it.getItem().action != nullptr;
  19186. check ("detect_tempo_item", detectItem);
  19187. // PL-3: Preview through the channel; transport start ends it
  19188. check ("preview_through_channel", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  19189. engine.play();
  19190. check ("preview_stops_on_transport", ! engine.isClipPreviewing());
  19191. engine.stop();
  19192. check ("preview_again_then_stop", engine.previewClipThroughChannel ((std::size_t) clipIndex) && engine.isClipPreviewing());
  19193. engine.stop();
  19194. check ("preview_stops_on_stop", ! engine.isClipPreviewing());
  19195. }
  19196. // PL-8: the dialog
  19197. {
  19198. lynx::ui::TempoDetectionRequest r;
  19199. r.name = "Amount Too - Bass";
  19200. // (a drum-like loop at 117.5 BPM, 100 beats as in FL's dialog: clicks on every beat)
  19201. {
  19202. auto beats = std::make_shared<lynx::SampleData>();
  19203. beats->sampleRate = 44100.0;
  19204. const auto period = 44100.0 * 60.0 / 117.5;
  19205. beats->left.assign ((std::size_t) std::llround (period * 100.0), 0.0f);
  19206. for (int b = 0; b < 100; ++b)
  19207. for (int i = 0; i < 2000; ++i)
  19208. if (const auto at = (std::size_t) std::llround (b * period) + (std::size_t) i; at < beats->left.size())
  19209. beats->left[at] = (float) (0.9 * std::sin (i * 0.09) * std::exp (-i / 400.0));
  19210. r.sample = beats;
  19211. }
  19212. r.projectBpm = 100.0;
  19213. double applied = -1.0;
  19214. r.apply = [&applied] (double beats) { applied = beats; };
  19215. auto panel = lynx::ui::makeTempoDetectionPanel (r);
  19216. panel->setSize (panel->getWidth(), panel->getHeight());
  19217. shoot (*panel, "tempo-detection");
  19218. report.add ("tempo dialog title: " + lynx::ui::tempoDetectionTitle (r.name));
  19219. const auto project = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 3);
  19220. const auto seconds = (double) r.sample->frames() / r.sample->sampleRate; // (100 beats at 117.5 BPM)
  19221. check ("tempo_project_button", std::abs (applied - seconds * 100.0 / 60.0) < 1.0e-6, project + " -> " + juce::String (applied));
  19222. const auto none = lynx::ui::pressTempoDetectionButton (*panel, panel->getNumChildComponents() - 2);
  19223. check ("tempo_no_tempo_button", applied == 0.0, none);
  19224. }
  19225. // ---- 4. issue #152's question (ISS152-1): FL's message with "Remember my choice"
  19226. {
  19227. auto box = lynx::makeFlMessageDialog ({ lynx::tr ("External input"),
  19228. 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?"),
  19229. { lynx::tr ("Yes"), lynx::tr ("No") }, true });
  19230. shoot (*box, "external-input-question");
  19231. bool listed = false;
  19232. for (const auto& m : lynx::messages::all())
  19233. listed = listed || juce::String (m.id) == "RecAutoSwitchExternalInput";
  19234. check ("external_input_in_manage_messages", listed);
  19235. }
  19236. // ---- 5. round 190gk: FL's Start in the render window; the Sampler's "Open in new Fruity Slicer / Slicex channel";
  19237. // a Gross Beat slot picked by MIDI becomes its parameter
  19238. {
  19239. lynx::AudioEngine engine (false);
  19240. auto panel = lynx::makeClipRenderPanel (engine);
  19241. panel->setSize (panel->getWidth() > 0 ? panel->getWidth() : 640, panel->getHeight() > 0 ? panel->getHeight() : 480);
  19242. juce::String button;
  19243. for (auto* c : panel->getChildren())
  19244. if (auto* b = dynamic_cast<juce::TextButton*> (c); b != nullptr && b->isVisible() && b->getTooltip() == lynx::tr ("Start rendering"))
  19245. button = b->getButtonText();
  19246. check ("render_button_start", button == lynx::trc ("@render button: Start") && button == "Start", button);
  19247. shoot (*panel, "fltails190gk-render-start");
  19248. const auto clap = writeWav (folder.getChildFile ("Slice me.wav"), 44100.0, 44100, 140.0);
  19249. engine.editSong ([] (lynx::Song& s) {
  19250. s.channels.resize (2);
  19251. s.channels[0] = {};
  19252. s.channels[0].instrument = lynx::InstrumentKind::fruityslicer;
  19253. s.channels[0].name = "Fruity Slicer";
  19254. s.channels[1] = {};
  19255. s.channels[1].instrument = lynx::InstrumentKind::slicex;
  19256. s.channels[1].name = "Slicex";
  19257. });
  19258. const auto locate = [] (int index) {
  19259. return [index] (lynx::Song& s) -> lynx::ChannelDef* { return index < (int) s.channels.size() ? &s.channels[(std::size_t) index] : nullptr; };
  19260. };
  19261. lynx::loadSampleWhenOpened (0, clap.getFullPathName());
  19262. auto slicer = lynx::makeFruitySlicerEditor (engine, locate (0), 0);
  19263. const auto& fs = engine.getSong().channels[0];
  19264. check ("open_in_new_fruity_slicer", fs.samplePath == clap.getFullPathName().toStdString() && ! fs.pluginState.empty(), juce::String (fs.samplePath));
  19265. lynx::loadSlicexSampleWhenOpened (1, clap.getFullPathName());
  19266. auto slicex = lynx::makeSlicexEditor (engine, locate (1), 1);
  19267. const auto& sx = engine.getSong().channels[1];
  19268. check ("open_in_new_slicex", sx.samplePath == clap.getFullPathName().toStdString() && ! sx.pluginState.empty(), juce::String (sx.samplePath));
  19269. auto again = lynx::makeSlicexEditor (engine, locate (1), 1); // (the request is used once)
  19270. check ("open_in_new_used_once", engine.getSong().channels[1].samplePath == sx.samplePath);
  19271. // Gross Beat on insert 1: two notes on its MIDI input, one block, the engine's timer step
  19272. engine.editSong ([] (lynx::Song& s) {
  19273. if (s.mixer.size() < 2)
  19274. s.mixer.resize (2);
  19275. s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::grossBeat) };
  19276. });
  19277. engine.dispatchPendingMessages();
  19278. auto fx = engine.getEffect (1, 0);
  19279. check ("gb_running", fx != nullptr);
  19280. if (fx != nullptr)
  19281. {
  19282. std::vector<float> l (512, 0.1f), r (512, 0.1f);
  19283. fx->prepare (44100.0);
  19284. fx->setSongPosition (0.0);
  19285. fx->midiNote (60 + 9, 100, 0);
  19286. fx->midiNote (24 + 3, 100, 0);
  19287. fx->process (l.data(), r.data(), 512, engine.getSong().mixer[1].effects[0].params, 120.0);
  19288. engine.pumpGrossBeatPicks();
  19289. const auto& p = engine.getSong().mixer[1].effects[0].params;
  19290. check ("gb_midi_pick_sets_parameters", lynx::grossbeat::rawFromParam (0, p[0]) == 9 && lynx::grossbeat::rawFromParam (1, p[1]) == 3,
  19291. juce::String (lynx::grossbeat::rawFromParam (0, p[0])) + " " + juce::String (lynx::grossbeat::rawFromParam (1, p[1])));
  19292. }
  19293. }
  19294. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  19295. return allOk;
  19296. }
  19297. // --grooveshot190fm (round 190fm): see the dispatch above
  19298. bool runGrooveShot190fm (const juce::String& prefix)
  19299. {
  19300. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19301. juce::StringArray report;
  19302. bool allOk = true;
  19303. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  19304. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  19305. allOk = allOk && ok;
  19306. };
  19307. const auto plain = [] (juce::String t) {
  19308. t = t.upToFirstOccurrenceOf ("\t", false, false);
  19309. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  19310. };
  19311. const auto sub = [&plain] (const juce::PopupMenu& menu, const juce::String& start) -> const juce::PopupMenu* {
  19312. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  19313. if (it.getItem().subMenu != nullptr && plain (it.getItem().text).startsWith (start))
  19314. return it.getItem().subMenu.get();
  19315. return nullptr;
  19316. };
  19317. const auto item = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  19318. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  19319. if (plain (it.getItem().text) == text)
  19320. return &it.getItem();
  19321. return nullptr;
  19322. };
  19323. lynx::AudioEngine engine (false);
  19324. lynx::MainComponent ui (engine, false);
  19325. ui.setSize (1600, 900);
  19326. std::uint32_t classic = 0;
  19327. {
  19328. auto song = lynx::Song::makeDefault();
  19329. song.mode = lynx::PlayMode::song;
  19330. song.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
  19331. song.playlist.push_back ({ 0, 1, 4 * lynx::ppq, 4 * lynx::ppq, 0 });
  19332. for (const auto& e : lynx::groove::factoryBank())
  19333. if (juce::String (e.folder) == "Classic swing" && e.groove.base == lynx::GrooveBase::sixteenth
  19334. && (e.groove.name == "Swing 16ths 54 %" || e.groove.name == "Swing 16ths 58 %" || e.groove.name == "Swing 16ths 62 %"
  19335. || e.groove.name == "Swing 16ths 71 %"))
  19336. {
  19337. const auto id = lynx::groove::add (song.grooves, e.groove);
  19338. if (e.groove.name == "Swing 16ths 58 %")
  19339. classic = id;
  19340. }
  19341. song.playlist[0].groove = classic;
  19342. engine.setSong (std::move (song));
  19343. }
  19344. engine.dispatchPendingMessages();
  19345. auto& playlist = ui.getPlaylistForSnapshot();
  19346. const auto menu = playlist.getClipMenuForSnapshot (0);
  19347. const auto* chooser = sub (menu, lynx::tr ("Groove"));
  19348. check ("groove_chooser_in_clip_menu", chooser != nullptr);
  19349. const auto* add = chooser != nullptr ? sub (*chooser, lynx::tr ("Add a groove")) : nullptr;
  19350. const auto* folder = add != nullptr ? sub (*add, lynx::tr ("Classic swing")) : nullptr;
  19351. check ("classic_swing_folder", folder != nullptr && folder->getNumItems() == 27, folder != nullptr ? juce::String (folder->getNumItems()) : juce::String ("missing"));
  19352. const auto* commit = item (menu, lynx::tr ("Commit groove"));
  19353. check ("commit_enabled_with_a_groove", commit != nullptr && commit->isEnabled);
  19354. check ("extract_present", item (menu, lynx::tr ("Extract groove")) != nullptr);
  19355. {
  19356. juce::StringArray names { "Pattern clip menu" };
  19357. std::vector<juce::PopupMenu> menus { menu };
  19358. if (chooser != nullptr)
  19359. {
  19360. names.add ("Groove");
  19361. menus.push_back (*chooser);
  19362. }
  19363. if (add != nullptr)
  19364. {
  19365. names.add ("Add a groove");
  19366. menus.push_back (*add);
  19367. }
  19368. if (folder != nullptr)
  19369. {
  19370. names.add ("Classic swing");
  19371. menus.push_back (*folder);
  19372. }
  19373. saveMenus (names, menus, prefix + "-playlist-clip-menu.png");
  19374. }
  19375. // the second clip (no groove): Commit is off; choosing a groove from the menu sets it
  19376. {
  19377. const auto other = playlist.getClipMenuForSnapshot (1);
  19378. const auto* c2 = item (other, lynx::tr ("Commit groove"));
  19379. check ("commit_disabled_without_a_groove", c2 != nullptr && ! c2->isEnabled);
  19380. const auto* ch2 = sub (other, lynx::tr ("Groove"));
  19381. const auto* pick = ch2 != nullptr ? item (*ch2, "Swing 16ths 71 %") : nullptr;
  19382. if (pick != nullptr && pick->action != nullptr)
  19383. pick->action();
  19384. const auto& song = engine.getSong();
  19385. check ("chooser_sets_the_clip_groove", song.playlist.size() == 2 && lynx::groove::ofClip (song, song.playlist[1]) != nullptr
  19386. && lynx::groove::ofClip (song, song.playlist[1])->name == "Swing 16ths 71 %");
  19387. }
  19388. // the pool with the classic grooves
  19389. {
  19390. auto pool = lynx::makeGroovePool (engine);
  19391. pool->setSize (900, lynx::groovePoolHeight (engine));
  19392. savePng (pool->createComponentSnapshot (pool->getLocalBounds()), prefix + "-pool.png");
  19393. }
  19394. // .lynx: a Playlist clip's groove comes back; a project without one writes nothing new
  19395. {
  19396. juce::String error;
  19397. const auto& song = engine.getSong();
  19398. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  19399. check ("lynx_round_trip", back && back->playlist.size() == 2 && back->playlist[0].groove == song.playlist[0].groove
  19400. && back->playlist[1].groove == song.playlist[1].groove && back->grooves == song.grooves,
  19401. error);
  19402. auto old = lynx::Song::makeDefault();
  19403. old.playlist.push_back ({ 0, 0, 0, 4 * lynx::ppq, 0 });
  19404. const auto json = lynx::ProjectFile::toJson (old, false);
  19405. const auto reloaded = lynx::ProjectFile::fromJson (json, error);
  19406. check ("old_project_unchanged", reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json && reloaded->playlist[0].groove == 0);
  19407. }
  19408. // Commit from the menu: the clip's pattern (shared with the second clip) is copied, the groove is off
  19409. {
  19410. const auto patterns = engine.getSong().patterns.size();
  19411. const auto again = playlist.getClipMenuForSnapshot (0);
  19412. if (const auto* c = item (again, lynx::tr ("Commit groove")); c != nullptr && c->action != nullptr)
  19413. c->action();
  19414. const auto& song = engine.getSong();
  19415. check ("commit_runs", song.playlist[0].groove == 0 && song.patterns.size() == patterns + 1 && song.playlist[0].pattern == (int) patterns);
  19416. }
  19417. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\n" + (allOk ? "ALL OK" : "SOME FAILED") + "\n");
  19418. return allOk;
  19419. }
  19420. bool runFlClipShot (const juce::String& prefix)
  19421. {
  19422. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19423. juce::StringArray report;
  19424. bool allOk = true;
  19425. const auto check = [&report, &allOk] (const char* name, bool ok, const juce::String& detail = {}) {
  19426. report.add (juce::String (name) + "=" + (ok ? "OK" : "FAIL") + (detail.isEmpty() ? juce::String() : " " + detail));
  19427. allOk = allOk && ok;
  19428. };
  19429. const auto plain = [] (juce::String t) {
  19430. t = t.upToFirstOccurrenceOf ("\t", false, false);
  19431. if (const auto at = t.indexOf (juce::String (" (") + juce::String::charToString (1)); at >= 0)
  19432. t = t.substring (0, at);
  19433. return t.removeCharacters (juce::String ("&_") + juce::String::charToString (1));
  19434. };
  19435. const auto find = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  19436. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  19437. if (plain (it.getItem().text) == plain (text))
  19438. return &it.getItem();
  19439. return nullptr;
  19440. };
  19441. const auto click = [&find] (const juce::PopupMenu& menu, const juce::String& text) {
  19442. const auto* item = find (menu, text);
  19443. if (item == nullptr || ! item->isEnabled || item->action == nullptr)
  19444. return false;
  19445. item->action();
  19446. return true;
  19447. };
  19448. lynx::AudioEngine engine (false);
  19449. lynx::MainComponent ui (engine, false);
  19450. ui.setSize (1600, 900);
  19451. int vox = -1;
  19452. {
  19453. auto song = lynx::Song::makeDefault();
  19454. song.channels.push_back ({});
  19455. song.channels.back().name = "Vox";
  19456. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  19457. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  19458. vox = (int) song.channels.size() - 1;
  19459. lynx::Clip c;
  19460. c.kind = lynx::ClipKind::audio;
  19461. c.channel = vox;
  19462. c.track = 3;
  19463. c.start = 4 * lynx::ppq;
  19464. c.length = 2 * lynx::ppq;
  19465. c.fadeIn = lynx::ppq / 4;
  19466. song.playlist.push_back (c);
  19467. engine.setSong (std::move (song));
  19468. }
  19469. engine.dispatchPendingMessages();
  19470. auto& playlist = ui.getPlaylistForSnapshot();
  19471. // ---- 1. the audio clip menu: FL's order, sections and columns, then LYNX's own items
  19472. {
  19473. const auto menu = playlist.getClipMenuForSnapshot (0);
  19474. juce::StringArray got, want;
  19475. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  19476. {
  19477. const auto& item = it.getItem();
  19478. // (round 190kx's loop items, whose labels carry the clip's own key / tempo, are not in the fixed list)
  19479. if (! item.isSeparator && ! item.isSectionHeader
  19480. && (plain (item.text).startsWith (lynx::tr ("Follow the project key")) || plain (item.text).startsWith (lynx::tr ("Loop key"))
  19481. || plain (item.text).startsWith (lynx::tr ("Fit to the project tempo ({0}, from {1} BPM)").upToFirstOccurrenceOf (" (", false, false))))
  19482. continue;
  19483. got.add (item.customComponent != nullptr ? "[" + lynx::tr ("Audio clip") + "]"
  19484. : item.isSeparator ? juce::String ("-")
  19485. : item.isSectionHeader ? "[" + plain (item.text) + "]"
  19486. : plain (item.text));
  19487. }
  19488. for (const auto& e : lynx::flclipmenu::shown (true, false))
  19489. if (e.kind != lynx::flclipmenu::Entry::Kind::columnBreak)
  19490. want.add (e.kind == lynx::flclipmenu::Entry::Kind::separator ? juce::String ("-")
  19491. : e.kind == lynx::flclipmenu::Entry::Kind::header ? "[" + lynx::tr (e.text.c_str()) + "]"
  19492. : lynx::tr (e.text.c_str()));
  19493. // (rollup step 8: the separators round 190kx's key items bring into the LYNX extras column go with them)
  19494. for (int k = got.indexOf ("[" + lynx::tr ("LYNX extras") + "]") + 1; k > 0 && k < got.size();)
  19495. if (got[k] == "-")
  19496. got.remove (k);
  19497. else
  19498. ++k;
  19499. want.add ("[" + lynx::tr ("LYNX extras") + "]"); // (round 190gi; round 190jv: in a third column)
  19500. for (const auto& x : lynx::flclipmenu::lynxExtras())
  19501. want.add (lynx::tr (x.c_str()));
  19502. check ("clip_menu_fl_order", got == want, got.joinIntoString ("|"));
  19503. // FL's two columns (Chop | Sample), then LYNX's own items in a third (round 190jv)
  19504. juce::StringArray breaks;
  19505. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  19506. if (it.getItem().shouldBreakAfter)
  19507. breaks.add (it.getItem().isSectionHeader || it.getItem().customComponent != nullptr ? "?" : plain (it.getItem().text));
  19508. check ("clip_menu_two_columns", breaks.size() == 2 && breaks[0] == lynx::tr ("Chop") && breaks[1] == lynx::tr ("Fade out curve"),
  19509. breaks.joinIntoString ("|"));
  19510. const auto* crossfade = find (menu, lynx::tr ("Crossfade with"));
  19511. check ("crossfade_with_greyed", crossfade != nullptr && ! crossfade->isEnabled);
  19512. const auto* region = find (menu, lynx::tr ("Select region"));
  19513. const auto* full = region != nullptr && region->subMenu != nullptr ? find (*region->subMenu, lynx::tr ("Full")) : nullptr;
  19514. check ("select_region_full_ticked", full != nullptr && full->isTicked);
  19515. const auto* chop = find (menu, lynx::tr ("Chop"));
  19516. check ("chop_time_based", chop != nullptr && chop->subMenu != nullptr && find (*chop->subMenu, lynx::tr ("Chop in 32nd beats")) != nullptr
  19517. && find (*chop->subMenu, lynx::tr ("Chop to grid")) != nullptr);
  19518. savePng (columnMenuImage (menu), prefix + "-clip-menu.png");
  19519. std::fprintf (stderr, "flclipshot: menu saved\n");
  19520. // Muted is a check; Reset fades clears the fades; Select all similar clips selects
  19521. check ("muted_toggles", click (menu, lynx::tr ("Muted")) && engine.getSong().playlist[0].muted);
  19522. const auto again = playlist.getClipMenuForSnapshot (0);
  19523. const auto* muted = find (again, lynx::tr ("Muted"));
  19524. check ("muted_ticked", muted != nullptr && muted->isTicked);
  19525. check ("reset_fades", click (again, lynx::tr ("Reset fades")) && engine.getSong().playlist[0].fadeIn == 0);
  19526. engine.undo();
  19527. engine.undo();
  19528. engine.dispatchPendingMessages();
  19529. std::fprintf (stderr, "flclipshot: automate\n");
  19530. // Automate › Volume / Panning: the clip channel's Levels adjustment (FL's channel parameters 0x11 / 0x10)
  19531. const auto fresh = playlist.getClipMenuForSnapshot (0);
  19532. const auto* automate = find (fresh, lynx::tr ("Automate"));
  19533. const auto before = engine.getSong().automations.size();
  19534. check ("automate_volume_runs", automate != nullptr && automate->subMenu != nullptr && click (*automate->subMenu, lynx::tr ("Volume")));
  19535. const auto& song = engine.getSong();
  19536. const auto ok = song.automations.size() == before + 1 && song.automations.back().target.kind == lynx::AutomationTargetKind::channelAdjust
  19537. && song.automations.back().target.param == lynx::leveladjust::volume && song.automations.back().target.index == vox
  19538. && std::abs (song.automations.back().points[0].value - 0.5f) < 1.0e-6f;
  19539. check ("automate_volume_is_level_adjust", ok, ok ? juce::String::fromUTF8 (song.automations.back().name.c_str()) : juce::String());
  19540. engine.undo();
  19541. engine.dispatchPendingMessages();
  19542. }
  19543. std::fprintf (stderr, "flclipshot: overlap\n");
  19544. // ---- 2. a second channel's clip overlapping: Crossfade with lists it and makes FL's crossfade clip (round 190gw)
  19545. {
  19546. engine.editSong ([vox] (lynx::Song& s) {
  19547. auto copy = s.playlist[0]; // (another audio clip channel's clip, at the same time)
  19548. s.channels.push_back (s.channels[(std::size_t) vox]);
  19549. s.channels.back().name = "Vox 2";
  19550. copy.channel = (int) s.channels.size() - 1;
  19551. copy.track = 4;
  19552. s.playlist.push_back (copy);
  19553. });
  19554. engine.dispatchPendingMessages();
  19555. const auto overlapped = playlist.getClipMenuForSnapshot (0);
  19556. const auto* with = find (overlapped, lynx::tr ("Crossfade with"));
  19557. check ("crossfade_with_lists_the_overlap", with != nullptr && with->isEnabled && with->subMenu != nullptr && find (*with->subMenu, "Vox 2") != nullptr);
  19558. const auto made = with != nullptr && with->subMenu != nullptr && click (*with->subMenu, "Vox 2");
  19559. engine.dispatchPendingMessages();
  19560. const auto& xsong = engine.getSong();
  19561. const auto xok = made && ! xsong.automations.empty() && xsong.automations.back().links.size() == 2
  19562. && juce::String::fromUTF8 (xsong.automations.back().name.c_str()).endsWith (" to Vox 2 crossfade");
  19563. check ("crossfade_with_makes_the_clip", xok, xok ? juce::String::fromUTF8 (xsong.automations.back().name.c_str()) : juce::String());
  19564. if (made)
  19565. engine.undo();
  19566. engine.undo();
  19567. engine.dispatchPendingMessages();
  19568. }
  19569. std::fprintf (stderr, "flclipshot: misc\n");
  19570. // ---- 3. the channel's Misc tab: Levels adjustment = the offsets (pan 0, volume 100 %, Mod X / Y 0 %)
  19571. {
  19572. engine.editSong ([vox] (lynx::Song& s) {
  19573. s.channels[(std::size_t) vox].misc.levels.volume = 0.5f;
  19574. s.channels[(std::size_t) vox].misc.levels.pan = -0.25f;
  19575. });
  19576. engine.dispatchPendingMessages();
  19577. auto frame = lynx::makeChannelFrame (engine, vox, -1);
  19578. frame->setSize (juce::jmax (frame->getWidth(), 800), juce::jmax (frame->getHeight(), 420));
  19579. savePng (frame->createComponentSnapshot (frame->getLocalBounds()), prefix + "-misc-levels.png");
  19580. auto synthFrame = lynx::makeChannelFrame (engine, 0, -1);
  19581. synthFrame->setSize (juce::jmax (synthFrame->getWidth(), 800), juce::jmax (synthFrame->getHeight(), 420));
  19582. savePng (synthFrame->createComponentSnapshot (synthFrame->getLocalBounds()), prefix + "-misc-levels-ch1.png");
  19583. std::fprintf (stderr, "flclipshot: round trip\n");
  19584. // the .lynx round trip of the adjustment and of an automation of it; an old project writes nothing new
  19585. juce::String error;
  19586. auto song = engine.getSong();
  19587. lynx::Automation a;
  19588. a.target = { lynx::AutomationTargetKind::channelAdjust, vox, 0, lynx::leveladjust::volume };
  19589. a.points = { { 0, 0.25f, 0.0f } };
  19590. song.automations.push_back (a);
  19591. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error);
  19592. check ("lynx_round_trip", back && back->channels[(std::size_t) vox].misc.levels == song.channels[(std::size_t) vox].misc.levels
  19593. && back->automations.back().target == a.target,
  19594. error);
  19595. auto old = lynx::Song::makeDefault();
  19596. const auto json = lynx::ProjectFile::toJson (old, false);
  19597. const auto reloaded = lynx::ProjectFile::fromJson (json, error);
  19598. check ("old_project_unchanged", ! json.contains ("\"levels\"") && reloaded && lynx::ProjectFile::toJson (*reloaded, false) == json
  19599. && std::all_of (reloaded->channels.begin(), reloaded->channels.end(),
  19600. [] (const lynx::ChannelDef& c) { return c.misc.levels.neutral(); }));
  19601. }
  19602. juce::File (prefix + "-checks.txt").replaceWithText (report.joinIntoString ("\n") + "\nresult=" + (allOk ? "OK" : "FAIL") + "\n");
  19603. return allOk;
  19604. }
  19605. // --bandlab190jrshot <prefix> (round 190jr; B15, BUILD-LIST 13 / 14): a synthetic BandLab project (.blx: the revision
  19606. // JSON, a MIDI file, a WAV) opened through the real import, shown in the Simple layout; its looped regions and their
  19607. // loop handles; a loop dragged longer; the automation view with and without points and its parameter menu; the clip
  19608. // menu's loop items; the Extract stems form (Standard and 6 stems). Pictures at the --shot-scale asked for.
  19609. void runBandlab190jrShot (const juce::String& prefix)
  19610. {
  19611. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19612. lynx::AudioEngine offline (false);
  19613. lynx::MainComponent ui (offline, false);
  19614. ui.setSize (1600, 900);
  19615. const auto note = [] (const juce::String& what) { std::fprintf (stderr, "bandlab190jrshot: %s\n", what.toRawUTF8()); };
  19616. const auto writeImage = [&prefix, &note] (const juce::Image& image, const char* name) {
  19617. note (name);
  19618. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  19619. file.deleteFile();
  19620. juce::FileOutputStream out (file);
  19621. juce::PNGImageFormat().writeImageToStream (image, out);
  19622. };
  19623. juce::String report;
  19624. const auto check = [&report, &note] (const juce::String& what, bool ok) {
  19625. note ((ok ? "ok " : "FAIL ") + what);
  19626. report << (ok ? "ok " : "FAIL ") << what << "\n";
  19627. };
  19628. // ---- 1. the project: a revision with a looped piano region, a voice take and a drum machine
  19629. const auto folder = juce::File (prefix + "-blx");
  19630. folder.deleteRecursively();
  19631. folder.getChildFile ("Audio").createDirectory();
  19632. folder.getChildFile ("MIDI").createDirectory();
  19633. {
  19634. // a 4-beat MIDI part (100 BPM: 2.4 s) and a drum beat, 480 ticks per quarter
  19635. const auto midi = [] (const std::vector<std::array<int, 4>>& notes) {
  19636. juce::MidiMessageSequence seq;
  19637. for (const auto& n : notes)
  19638. {
  19639. seq.addEvent (juce::MidiMessage::noteOn (1, n[2], (juce::uint8) n[3]), n[0]);
  19640. seq.addEvent (juce::MidiMessage::noteOff (1, n[2]), n[0] + n[1]);
  19641. }
  19642. seq.updateMatchedPairs();
  19643. juce::MidiFile file;
  19644. file.setTicksPerQuarterNote (480);
  19645. file.addTrack (seq);
  19646. juce::MemoryOutputStream out;
  19647. file.writeTo (out);
  19648. return out.getMemoryBlock();
  19649. };
  19650. const auto keysBlock = midi ({ { 0, 480, 62, 100 }, { 0, 480, 65, 90 }, { 0, 480, 69, 90 }, { 480, 240, 64, 80 },
  19651. { 960, 480, 60, 100 }, { 960, 480, 64, 90 }, { 1440, 480, 67, 90 } });
  19652. folder.getChildFile ("MIDI/s-keys.mid").replaceWithData (keysBlock.getData(), keysBlock.getSize());
  19653. const auto beat = midi ({ { 0, 120, 36, 120 }, { 480, 120, 38, 110 }, { 960, 120, 36, 120 }, { 1440, 120, 38, 110 }, { 240, 60, 42, 80 },
  19654. { 720, 60, 42, 80 }, { 1200, 60, 42, 80 }, { 1680, 60, 42, 80 } });
  19655. folder.getChildFile ("MIDI/s-beat.mid").replaceWithData (beat.getData(), beat.getSize());
  19656. // a 4.8 s "voice" (a sine with a slow swell), 44.1 kHz
  19657. juce::AudioBuffer<float> wave (1, 44100 * 48 / 10);
  19658. for (int i = 0; i < wave.getNumSamples(); ++i)
  19659. wave.setSample (0, i, 0.4f * std::sin ((float) i * 0.0627f) * (0.5f + 0.5f * std::sin ((float) i * 0.00012f)));
  19660. juce::WavAudioFormat wav;
  19661. const auto out = folder.getChildFile ("Audio/s-vox.wav");
  19662. if (auto stream = out.createOutputStream())
  19663. if (std::unique_ptr<juce::AudioFormatWriter> writer (wav.createWriterFor (stream.get(), 44100.0, 1, 16, {}, 0)); writer != nullptr)
  19664. {
  19665. stream.release();
  19666. writer->writeFromAudioSampleBuffer (wave, 0, wave.getNumSamples());
  19667. }
  19668. folder.getChildFile ("Scratch Song.blx").replaceWithText (R"({ "revision": {
  19669. "key": "D min", "volume": 1, "song": { "name": "Scratch Song" },
  19670. "metronome": { "bpm": 100, "signature": { "notesCount": 4, "noteValue": 4 } },
  19671. "auxChannels": [ { "id": "aux1", "preset": "sharedReverb", "returnLevel": 1 } ],
  19672. "samples": [ { "id": "s-keys", "isMidi": true, "duration": 2.4 }, { "id": "s-vox", "isMidi": false, "duration": 4.8 }, { "id": "s-beat", "isMidi": true } ],
  19673. "tracks": [
  19674. { "id": "t1", "order": 0, "name": "Keys", "type": "instrument", "soundbank": "studio-grand", "volume": 0.9, "colorName": "Red",
  19675. "regions": [ { "id": "r1", "sampleId": "s-keys", "name": "Chords", "startPosition": 0, "endPosition": 9.6, "loopLength": 2.4 } ] },
  19676. { "id": "t2", "order": 1, "name": "Vocal", "type": "voice", "volume": 1, "pan": -0.2, "colorName": "Blue",
  19677. "effects": [ { "slug": "compressor", "params": { "attack": 0.003, "ratio": 3, "release": 0.12, "threshold": -18 } },
  19678. { "slug": "threeBandEq", "params": { "lowGain": -2, "midGain": 1, "highGain": 3, "midFreq": 2500 } },
  19679. { "slug": "chorusPedal", "params": {} } ],
  19680. "auxSends": [ { "id": "aux1", "sendLevel": 0.3 } ],
  19681. "automation": { "volume": [ { "position": 0, "value": 0.2 }, { "position": 8, "value": 1 }, { "position": 16, "value": 0.7 } ] },
  19682. "regions": [ { "id": "r2", "sampleId": "s-vox", "name": "Take 1", "startPosition": 2.4, "endPosition": 7.2, "fadeIn": 0.2, "fadeOut": 0.5 } ] },
  19683. { "id": "t3", "order": 2, "name": "Drum Machine", "type": "drum-machine", "volume": 1, "colorName": "Violet",
  19684. "regions": [ { "id": "r3", "sampleId": "s-beat", "name": "Beat", "startPosition": 0, "endPosition": 4.8, "loopLength": 2.4 } ] }
  19685. ] } })");
  19686. }
  19687. juce::String error;
  19688. const auto blx = folder.getChildFile ("Scratch Song.blx");
  19689. const auto imported = offline.importFlpFile (blx, error);
  19690. check ("the .blx opens through the import (" + error + ")", imported);
  19691. offline.dispatchPendingMessages();
  19692. const auto& song = offline.getSong();
  19693. check ("three Simple tracks: Keys (instrument), Vocal (audio), Drum Machine (drums)",
  19694. lynx::simpletracks::kindOf (song, 0) == lynx::simpletracks::Kind::instrument && lynx::simpletracks::kindOf (song, 1) == lynx::simpletracks::Kind::audio
  19695. && lynx::simpletracks::kindOf (song, 2) == lynx::simpletracks::Kind::drums);
  19696. check ("tempo 100, key D minor", std::abs (song.bpm - 100.0) < 1e-6 && lynx::projectkey::get (song).has_value());
  19697. int keysClips = 0, beatClips = 0, voxClips = 0;
  19698. for (const auto& c : song.playlist)
  19699. {
  19700. keysClips += c.track == 0;
  19701. voxClips += c.track == 1 && c.kind == lynx::ClipKind::audio;
  19702. beatClips += c.track == 2;
  19703. }
  19704. check ("the looped Keys region: 4 passes; the beat: 2; the take: 1 audio clip", keysClips == 4 && beatClips == 2 && voxClips == 1);
  19705. const auto voxInsert = lynx::simpletracks::insertOf (song, 1);
  19706. check ("the vocal's compressor, EQ and chorus on its insert",
  19707. voxInsert > 0 && song.mixer[(std::size_t) voxInsert].effects.size() == 3);
  19708. check ("the vocal's volume automation: a lane under its track", ! song.playlistTracks[1].lanes.empty());
  19709. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  19710. offline.dispatchPendingMessages();
  19711. ui.selectTabForSnapshot (2);
  19712. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  19713. simple->hideChooser();
  19714. auto& playlist = ui.getPlaylistForSnapshot();
  19715. playlist.setViewForSnapshot (96.0, 0, 0);
  19716. offline.dispatchPendingMessages();
  19717. writeImage (lynx::shot::snapshot (ui), "blx-simple");
  19718. writeImage (lynx::shot::snapshot (playlist), "loop-handles");
  19719. // ---- 2. a loop dragged longer: the take repeated to bar 9 (as the handle's drag does it)
  19720. {
  19721. int take = -1;
  19722. for (int i = 0; i < (int) song.playlist.size(); ++i)
  19723. if (song.playlist[(std::size_t) i].track == 1 && song.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  19724. take = i;
  19725. const auto end = (std::int64_t) lynx::ppq * 4 * 8;
  19726. offline.editSong ([take, end] (lynx::Song& s) { lynx::regionloop::loopTo (s, take, end); });
  19727. offline.dispatchPendingMessages();
  19728. 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]));
  19729. check ("the take loops to bar 9 in passes of its length", run.passes() >= 3 && run.end == end);
  19730. writeImage (lynx::shot::snapshot (playlist), "loop-dragged");
  19731. auto menu = playlist.getClipMenuForSnapshot (run.clips.empty() ? take : run.clips.back());
  19732. bool hasLoop = false;
  19733. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  19734. hasLoop = hasLoop || it.getItem().text == lynx::tr ("Unloop");
  19735. check ("the Simple clip menu has Loop until next / Unloop", hasLoop);
  19736. saveMenus (juce::StringArray { "Clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu.png");
  19737. }
  19738. // ---- 3. the automation view: the vocal's lane on its row, the others' dashed line at their level
  19739. playlist.setSimpleAutomation (true);
  19740. offline.dispatchPendingMessages();
  19741. writeImage (lynx::shot::snapshot (playlist), "automation-view");
  19742. check ("the view changes nothing in the song", offline.getSong().playlistTracks[0].lanes.empty());
  19743. playlist.setSimpleAutoTargetForSnapshot (1, { lynx::AutomationTargetKind::effectParam, voxInsert, 0, 0 }); // the compressor's threshold
  19744. writeImage (lynx::shot::snapshot (playlist), "automation-param");
  19745. playlist.setSimpleAutoTargetForSnapshot (1, { lynx::AutomationTargetKind::mixerVolume, voxInsert, 0, 0 });
  19746. saveMenus (juce::StringArray { "Volume" }, std::vector<juce::PopupMenu> { playlist.getSimpleAutoMenuForSnapshot (1) }, prefix + "-automation-menu.png");
  19747. playlist.setSimpleAutomation (false);
  19748. offline.dispatchPendingMessages();
  19749. // ---- 4. the Extract stems form
  19750. {
  19751. auto panel = lynx::makeStemOptionsPanel (lynx::stemsplit::Options {}, [] (lynx::stemsplit::Options) {});
  19752. writeImage (lynx::shot::paint (*panel, lynx::theme::colour::bg2), "stem-options");
  19753. lynx::stemsplit::Options six;
  19754. six.model = lynx::stemsplit::Model::sixStems;
  19755. six.stems = { true, true, false, true, true, true };
  19756. auto panel6 = lynx::makeStemOptionsPanel (six, [] (lynx::stemsplit::Options) {});
  19757. writeImage (lynx::shot::paint (*panel6, lynx::theme::colour::bg2), "stem-options-six");
  19758. }
  19759. juce::File (lynx::shot::fileName (prefix + "-report.txt")).replaceWithText (report);
  19760. }
  19761. // --bandlabshot <prefix> (round 190ch): the Lyrics / Notes panel (Pattern and Simple layouts, and on its own), the
  19762. // Reference match window measured on a real render and a real file, "Start from", and Clean voice, off-screen; and
  19763. // <prefix>-report.txt with what each route did (ok / FAIL lines)
  19764. void runBandlabShot (const juce::String& prefix)
  19765. {
  19766. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  19767. lynx::AudioEngine offline (false);
  19768. lynx::MainComponent ui (offline, false);
  19769. ui.setSize (1600, 900);
  19770. // (each step is named on stderr as it starts: a run that stops says where)
  19771. const auto note = [] (const juce::String& what) { std::fprintf (stderr, "bandlabshot: %s\n", what.toRawUTF8()); };
  19772. const auto shoot = [&prefix, &note] (juce::Component& c, const char* name) {
  19773. note (name);
  19774. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  19775. };
  19776. juce::String report;
  19777. const auto check = [&report, &note] (const juce::String& what, bool ok) {
  19778. note ((ok ? "ok " : "FAIL ") + what);
  19779. report << (ok ? "ok " : "FAIL ") << what << "\n";
  19780. };
  19781. const auto bar = (double) lynx::ppq * 4.0;
  19782. // ---- 1. Lyrics / Notes: the project's Comments
  19783. {
  19784. auto song = lynx::makeShowcaseSong (0);
  19785. song.info.title = "Night Drive";
  19786. 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"
  19787. "I keep driving through the night\n\n[Chorus]\nNight drive, night drive\nNothing but the white line\n\n"
  19788. "Notes: double the chorus vocal, try the second verse an octave down.";
  19789. lynx::Marker chorus;
  19790. chorus.tick = (std::int64_t) (12.0 * bar);
  19791. chorus.name = "Chorus";
  19792. song.addMarker (chorus);
  19793. offline.setSong (std::move (song));
  19794. }
  19795. note ("song set");
  19796. offline.dispatchPendingMessages();
  19797. ui.selectTabForSnapshot (2);
  19798. note ("show lyrics");
  19799. ui.showLyrics (false);
  19800. note ("lyrics shown");
  19801. if (auto* panel = ui.getLyricsPanelForSnapshot())
  19802. {
  19803. panel->showForSnapshot ({}, 6.5 * bar); // the playhead inside bar 7: that line is the one playing
  19804. shoot (ui, "lyrics-pattern");
  19805. shoot (*panel, "lyrics-panel");
  19806. const auto markersBefore = offline.getSong().markers().size();
  19807. panel->setCaretLineForSnapshot (6); // "I keep driving through the night"
  19808. panel->markAtPlayheadForSnapshot (10.0 * bar + 2.0 * lynx::ppq);
  19809. offline.dispatchPendingMessages();
  19810. ui.commitSongNotes();
  19811. const auto& s = offline.getSong();
  19812. check ("Marker at playhead stamps the line [11.3] and adds one marker",
  19813. juce::String::fromUTF8 (s.info.comments.c_str()).contains ("[11.3] I keep driving") && s.markers().size() == markersBefore + 1);
  19814. // (no audio device here: the seek is the request the audio thread takes at its next block)
  19815. const auto& seek = offline.getTransport().seekRequest;
  19816. check ("clicking the stamped line moves the playhead to bar 7", panel->jumpToLineForSnapshot (4) && std::abs (seek.load() - 6.0 * bar) < 1.0);
  19817. check ("clicking [Chorus] (no position) goes to the marker of that name, bar 13",
  19818. panel->jumpToLineForSnapshot (8) && std::abs (seek.load() - 12.0 * bar) < 1.0);
  19819. check ("a line without a position does not jump", ! panel->jumpToLineForSnapshot (9));
  19820. panel->showForSnapshot ("night", 10.5 * bar);
  19821. shoot (*panel, "lyrics-search");
  19822. // the text travels in the project file, and old readers see it as the Comments they always had
  19823. juce::String error;
  19824. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  19825. const auto back = lynx::ProjectFile::fromJson (json, error);
  19826. check ("lyrics round-trip through .lynx (the Comments field)", back.has_value() && back->info.comments == offline.getSong().info.comments);
  19827. const auto text = lynx::lyrics::exportText (offline.getSong(), lynx::lyrics::Stamps::times);
  19828. juce::File (prefix + "-lyrics-export.txt").replaceWithText (juce::String::fromUTF8 (text.c_str()));
  19829. check ("export as text with times", text.find ("[0:") != std::string::npos);
  19830. panel->showForSnapshot ({}, 6.5 * bar);
  19831. }
  19832. else
  19833. check ("the docked Lyrics panel exists", false);
  19834. {
  19835. const auto names = ui.getMenuNamesForSnapshot();
  19836. const auto view = names.indexOf (lynx::tr ("View"));
  19837. saveMenus (juce::StringArray { lynx::tr ("View") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (juce::jmax (0, view)) }, prefix + "-menu-view.png");
  19838. }
  19839. ui.showDesktopForSnapshot (false);
  19840. check ("the panel stays docked beside the Playlist in the default desktop", ui.isLyricsShowing());
  19841. shoot (ui, "lyrics-desktop");
  19842. // ---- the Simple layout: the Lyrics button in its title tools, the chooser's "Start from" link
  19843. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  19844. offline.dispatchPendingMessages();
  19845. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  19846. auto* simple = ui.getSimpleWorkflowForSnapshot();
  19847. check ("the Simple workflow exists", simple != nullptr);
  19848. if (simple != nullptr)
  19849. {
  19850. simple->hideChooser();
  19851. if (! ui.isLyricsShowing())
  19852. ui.showLyrics (false);
  19853. shoot (ui, "lyrics-simple");
  19854. ui.hideLyrics();
  19855. check ("closing the panel keeps the text", juce::String::fromUTF8 (offline.getSong().info.comments.c_str()).contains ("Night drive, night drive"));
  19856. // ---- 4. Clean voice: on a voice track, from the track's menu
  19857. lynx::simpletracks::Result voice;
  19858. offline.editSongStructural ([&voice] (lynx::Song& s) {
  19859. lynx::simpletracks::Request q;
  19860. q.kind = lynx::simpletracks::Kind::voice;
  19861. q.name = "Lead vocal";
  19862. voice = lynx::simpletracks::addTrack (s, q);
  19863. });
  19864. offline.dispatchPendingMessages();
  19865. check ("a voice track was added", voice.insert > 0);
  19866. if (voice.insert > 0)
  19867. {
  19868. auto menu = ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (voice.track);
  19869. juce::StringArray names { "Track" };
  19870. std::vector<juce::PopupMenu> menus { menu };
  19871. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  19872. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Clean voice"))
  19873. {
  19874. names.add (lynx::tr ("Clean voice"));
  19875. menus.push_back (*it.getItem().subMenu);
  19876. }
  19877. check ("the Simple track menu has Clean voice", menus.size() == 2);
  19878. saveMenus (names, menus, prefix + "-cleanvoice-menu.png");
  19879. const auto before = offline.getSong().mixer[(std::size_t) voice.insert].effects.size();
  19880. check ("Clean voice applies", lynx::ui::applyCleanVoice (offline, voice.insert, false));
  19881. offline.dispatchPendingMessages();
  19882. const auto& fx = offline.getSong().mixer[(std::size_t) voice.insert].effects;
  19883. check ("four slots in front of the track's effects", fx.size() == before + 4 && lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4
  19884. && fx[0].kind == lynx::EffectKind::facetEq);
  19885. check ("with noise reduction: five, none doubled", lynx::ui::applyCleanVoice (offline, voice.insert, true)
  19886. && offline.getSong().mixer[(std::size_t) voice.insert].effects.size() == before + 5);
  19887. offline.dispatchPendingMessages();
  19888. juce::String error;
  19889. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  19890. check ("the chain round-trips through .lynx and is still found", back.has_value() && lynx::cleanvoice::slotsOf (*back, voice.insert).size() == 5
  19891. && back->mixer[(std::size_t) voice.insert].effects == offline.getSong().mixer[(std::size_t) voice.insert].effects);
  19892. saveMenus (juce::StringArray { lynx::tr ("Clean voice") }, std::vector<juce::PopupMenu> { lynx::ui::cleanVoiceMenu (offline, voice.insert) },
  19893. prefix + "-cleanvoice-menu-on.png");
  19894. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  19895. offline.dispatchPendingMessages();
  19896. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  19897. ui.selectMixerTrackForSnapshot (voice.insert);
  19898. shoot (ui, "cleanvoice-mixer");
  19899. offline.undo(); // the second chain
  19900. offline.dispatchPendingMessages();
  19901. check ("undo brings the first chain back", lynx::cleanvoice::slotsOf (offline.getSong(), voice.insert).size() == 4);
  19902. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  19903. offline.dispatchPendingMessages();
  19904. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  19905. simple = ui.getSimpleWorkflowForSnapshot();
  19906. }
  19907. }
  19908. // ---- 2. Reference match: the song's Master render against a file (pink noise with more top, at about -14 LUFS)
  19909. {
  19910. const auto file = juce::File (prefix + "-reference.wav");
  19911. file.deleteFile();
  19912. const auto rate = 44100.0;
  19913. const auto frames = (int) (20.0 * rate);
  19914. juce::AudioBuffer<float> audio (2, frames);
  19915. juce::Random random (190);
  19916. for (int ch = 0; ch < 2; ++ch)
  19917. {
  19918. double b0 = 0, b1 = 0, b2 = 0, hp = 0;
  19919. for (int i = 0; i < frames; ++i)
  19920. {
  19921. const auto w = (double) random.nextFloat() * 2.0 - 1.0;
  19922. b0 = 0.99765 * b0 + w * 0.0990460;
  19923. b1 = 0.96300 * b1 + w * 0.2965164;
  19924. b2 = 0.57000 * b2 + w * 1.0526913;
  19925. const auto pink = (b0 + b1 + b2 + w * 0.1848) * 0.071; // (about -14 LUFS: a streaming master)
  19926. hp += 0.25 * (pink - hp); // a little more top than pink noise has
  19927. audio.setSample (ch, i, (float) (pink + 0.35 * (pink - hp)));
  19928. }
  19929. }
  19930. if (auto out = file.createOutputStream())
  19931. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 24, {}, 0)))
  19932. {
  19933. out.release();
  19934. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  19935. }
  19936. note ("measure reference");
  19937. const auto reference = lynx::ReferenceMatchPanel::measureFile (offline, file);
  19938. note ("measure song");
  19939. const auto song = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), false);
  19940. check ("the reference file was measured", reference.valid);
  19941. check ("the song's Master render was measured", song.valid);
  19942. lynx::ReferenceMatchPanel panel (offline, {});
  19943. panel.setSize (lynx::ReferenceMatchPanel::defaultWidth, lynx::ReferenceMatchPanel::defaultHeight);
  19944. panel.showForSnapshot ("Reference.wav", song, reference, nullptr);
  19945. shoot (panel, "refmatch-measured");
  19946. const auto masterBefore = offline.getSong().mixer[0].effects.size();
  19947. check ("Match adds its two slots at the end of the Master", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  19948. offline.dispatchPendingMessages();
  19949. const auto first = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  19950. panel.showForSnapshot ("Reference.wav", song, reference, &first);
  19951. panel.refresh();
  19952. shoot (panel, "refmatch-matched");
  19953. report << " first Match: " << juce::String (first.lufs, 2) << " LUFS, " << juce::String (first.truePeakDb, 2) << " dBTP, EQ output "
  19954. << juce::String (lynx::facet::outputDb (offline.getSong().mixer[0].effects[masterBefore].params[(std::size_t) lynx::facet::outputParam]), 2) << " dB\n";
  19955. // a result more than 0.5 LU from the reference (a limiter that has to hold peaks back): Match again takes
  19956. // what is missing, as the window's note says
  19957. auto after = first;
  19958. const auto secondPass = std::abs (first.lufs - reference.lufs) > 0.5;
  19959. if (secondPass)
  19960. {
  19961. check ("Match again replaces the two slots (level corrected)", panel.matchForSnapshot() && offline.getSong().mixer[0].effects.size() == masterBefore + 2);
  19962. offline.dispatchPendingMessages();
  19963. after = lynx::ReferenceMatchPanel::measureSong (offline.getSong(), true);
  19964. panel.showForSnapshot ("Reference.wav", song, reference, &after);
  19965. panel.refresh();
  19966. shoot (panel, "refmatch-matched-again");
  19967. }
  19968. report << " " << (secondPass ? "a second Match was needed for the level" : "one Match was enough for the level") << "\n";
  19969. const auto& s = panel.suggestionForSnapshot();
  19970. report << " song " << juce::String (song.lufs, 2) << " LUFS, " << juce::String (song.truePeakDb, 2) << " dBTP, width " << juce::String (song.widthPercent(), 1)
  19971. << " % | reference " << juce::String (reference.lufs, 2) << " LUFS, " << juce::String (reference.truePeakDb, 2) << " dBTP, width "
  19972. << juce::String (reference.widthPercent(), 1) << " % | after " << juce::String (after.lufs, 2) << " LUFS, " << juce::String (after.truePeakDb, 2)
  19973. << " dBTP\n next suggestion: gain " << juce::String (s.gainDb, 2) << " dB, EQ fit error " << juce::String (s.fitErrorDb, 2) << " dB\n";
  19974. double before = 0.0, now = 0.0;
  19975. int counted = 0;
  19976. {
  19977. // tone only (each curve around its own mean), over the bands both hold
  19978. double ms = 0, mr = 0, ma = 0;
  19979. const auto used = juce::jmin (song.usedBands, reference.usedBands);
  19980. for (int k = 0; k < used; ++k)
  19981. ms += song.spectrumDb[(std::size_t) k], mr += reference.spectrumDb[(std::size_t) k], ma += after.spectrumDb[(std::size_t) k];
  19982. for (int k = 2; k < used; ++k, ++counted)
  19983. {
  19984. before += std::abs ((song.spectrumDb[(std::size_t) k] - ms / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  19985. now += std::abs ((after.spectrumDb[(std::size_t) k] - ma / used) - (reference.spectrumDb[(std::size_t) k] - mr / used));
  19986. }
  19987. }
  19988. report << " mean tone difference to the reference: " << juce::String (before / juce::jmax (1, counted), 2) << " dB before, "
  19989. << juce::String (now / juce::jmax (1, counted), 2) << " dB after one Match (each band moves 6 dB at most)\n";
  19990. check ("after Match the tone is closer to the reference", after.valid && now < before);
  19991. check ("after Match the loudness is within 1 LU of the reference", std::abs (after.lufs - reference.lufs) < 1.0);
  19992. 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);
  19993. juce::String error;
  19994. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  19995. check ("the match round-trips through .lynx as two ordinary Master slots", back.has_value() && lynx::refmatch::present (*back)
  19996. && back->mixer[0].effects == offline.getSong().mixer[0].effects);
  19997. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  19998. offline.dispatchPendingMessages();
  19999. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  20000. ui.selectMixerTrackForSnapshot (0);
  20001. shoot (ui, "refmatch-mixer");
  20002. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  20003. offline.dispatchPendingMessages();
  20004. ui.selectTabForSnapshot (2); // (the Playlist alone, as --simpleshot shows the layout)
  20005. simple = ui.getSimpleWorkflowForSnapshot();
  20006. if (simple != nullptr)
  20007. {
  20008. simple->hideChooser();
  20009. simple->showFinish();
  20010. shoot (ui, "finish-dock"); // "Match a reference track..." under the saving buttons
  20011. simple->hideFinish();
  20012. }
  20013. file.deleteFile();
  20014. }
  20015. // ---- 3. Start from: the chooser's link, the list, and opening an entry
  20016. if (simple != nullptr)
  20017. {
  20018. simple->showChooser();
  20019. shoot (ui, "chooser");
  20020. simple->hideChooser();
  20021. auto* panel = dynamic_cast<lynx::StartFromPanel*> (simple->startFromForSnapshot());
  20022. check ("the Start from list opens", panel != nullptr && simple->isStartFromShowing());
  20023. if (panel != nullptr)
  20024. {
  20025. shoot (ui, "startfrom");
  20026. auto list = lynx::startfrom::entries();
  20027. check ("it lists the demo song and the templates shipped", list.size() >= 3 && list[0].kind == lynx::startfrom::Entry::Kind::demo
  20028. && (int) list.size() == panel->entryCountForSnapshot());
  20029. for (auto& e : list)
  20030. report << " " << e.name << " | " << juce::String (e.bpm, 0) << " BPM, " << e.channels << " channels, " << e.bars << " bars"
  20031. << (e.playable ? ", preview" : "") << "\n";
  20032. if (const auto demo = lynx::startfrom::songOf (list[0]))
  20033. {
  20034. const auto wav = juce::File (prefix + "-preview.wav");
  20035. const auto ok = lynx::startfrom::renderPreview (*demo, wav);
  20036. check ("the demo's preview renders (" + juce::String (wav.getSize() / 1024) + " kB)", ok && wav.getSize() > 100000);
  20037. wav.deleteFile();
  20038. }
  20039. panel->selectForSnapshot (juce::jmin (2, panel->entryCountForSnapshot() - 1));
  20040. shoot (ui, "startfrom-selected");
  20041. offline.markSaved(); // (a project with changes asks first: Save / Don't save / Cancel)
  20042. const auto opened = panel->openForSnapshot (0);
  20043. offline.dispatchPendingMessages();
  20044. check ("opening the demo starts a new project from it and closes the list",
  20045. opened && ! simple->isStartFromShowing() && offline.getSong().info.comments.empty() && ! offline.getSong().channels.empty());
  20046. shoot (ui, "startfrom-opened");
  20047. }
  20048. }
  20049. juce::File (prefix + "-report.txt").replaceWithText (report);
  20050. }
  20051. void runVersionsShot (const juce::String& prefix)
  20052. {
  20053. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20054. const auto shoot = [&prefix] (juce::Component& c, const char* name) {
  20055. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  20056. };
  20057. // ---- the Versions panel, on files in a temporary folder
  20058. const auto root = juce::File::getSpecialLocation (juce::File::tempDirectory)
  20059. .getChildFile ("lynx-versionsshot-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
  20060. const juce::ScopeGuard cleanUp { [&root] { root.deleteRecursively(); } };
  20061. const auto project = root.getChildFile ("Night Drive"), backup = root.getChildFile ("Backup");
  20062. project.createDirectory();
  20063. backup.createDirectory();
  20064. const auto now = juce::Time::getCurrentTime();
  20065. const auto put = [&now] (const juce::File& folder, const juce::String& name, const char* kind, int kilobytes, double hoursAgo) {
  20066. const auto time = now - juce::RelativeTime::hours (hoursAgo);
  20067. const auto file = folder.getChildFile (kind == nullptr ? name + ".lynx" : name + " (" + kind + " on " + time.formatted ("%Y-%m-%d at %Hh%M") + ").lynx");
  20068. juce::MemoryBlock data ((size_t) kilobytes * 1024, true);
  20069. file.replaceWithData (data.getData(), data.getSize());
  20070. file.setLastModificationTime (time);
  20071. };
  20072. put (project, "Night Drive", nullptr, 412, 26.0 * 24.0);
  20073. put (project, "Night Drive_2", nullptr, 688, 9.0 * 24.0);
  20074. put (project, "Night Drive_3", nullptr, 731, 2.0 * 24.0);
  20075. put (project, "Night Drive_4", nullptr, 905, 1.6);
  20076. put (backup, "Night Drive_4", "autosaved", 907, 0.07);
  20077. put (backup, "Night Drive_4", "autosaved", 906, 0.4);
  20078. put (backup, "Night Drive_4", "overwritten", 890, 1.6);
  20079. put (backup, "Night Drive_4", "autosaved", 884, 3.2);
  20080. put (backup, "Night Drive_3", "overwritten", 720, 2.0 * 24.0);
  20081. put (backup, "Night Drive_2", "autosaved", 690, 8.0 * 24.0);
  20082. const lynx::VersionsContext context { project.getChildFile ("Night Drive_4.lynx"), "Night Drive_4", backup, ".lynx" };
  20083. {
  20084. const auto entries = lynx::versionEntries (context);
  20085. const auto label = [&] (const juce::String& startsWith, const char* text) {
  20086. for (const auto& e : entries)
  20087. if (juce::String::fromUTF8 (e.name.c_str()).startsWith (startsWith))
  20088. {
  20089. lynx::setVersionLabel (context, e, text);
  20090. return;
  20091. }
  20092. };
  20093. label ("Night Drive_2", "first full arrangement");
  20094. label ("Night Drive_3", "sent to the singer");
  20095. label ("Night Drive_4 (autosaved", "new bass line");
  20096. }
  20097. {
  20098. lynx::VersionsActions actions;
  20099. actions.context = [context] { return context; };
  20100. auto panel = lynx::makeVersionsPanel (actions);
  20101. shoot (*panel, "versions");
  20102. lynx::VersionsActions fresh;
  20103. fresh.context = [backup] { return lynx::VersionsContext { juce::File(), "Untitled", backup, ".lynx" }; };
  20104. auto empty = lynx::makeVersionsPanel (fresh);
  20105. shoot (*empty, "versions-unsaved");
  20106. }
  20107. // ---- the window
  20108. lynx::AudioEngine offline (false);
  20109. lynx::MainComponent ui (offline, false);
  20110. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  20111. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  20112. const auto saveFileMenu = [&] (const char* name) {
  20113. const auto index = juce::jmax (0, ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("File")));
  20114. saveMenus (juce::StringArray { lynx::tr ("File") }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-" + name + ".png");
  20115. };
  20116. saveFileMenu ("menu-file");
  20117. // ---- a project opened without its third-party plugins (the plugins are not installed: nothing foreign runs)
  20118. {
  20119. const auto ref = [] (const char* id, const char* name) {
  20120. lynx::PluginRef r;
  20121. r.id = id;
  20122. r.name = name;
  20123. r.state = "c2V0dGluZ3M=";
  20124. return r;
  20125. };
  20126. auto song = lynx::Song::makeDefault();
  20127. while (song.channels.size() < 4)
  20128. song.channels.push_back (song.channels.front());
  20129. while (song.mixer.size() < 5)
  20130. song.mixer.push_back (song.mixer.back());
  20131. const char* names[] = { "Lead", "Pad" };
  20132. for (int c = 0; c < 2; ++c)
  20133. {
  20134. auto& channel = song.channels[(std::size_t) (c + 2)];
  20135. channel.instrument = lynx::InstrumentKind::plugin;
  20136. channel.plugin = ref ("VST3-ShotSynth-11111111-aaaaaaaa", "Shot Synth");
  20137. channel.name = names[c];
  20138. channel.mixerTrack = c + 1;
  20139. }
  20140. lynx::EffectSlot fx;
  20141. fx.kind = lynx::EffectKind::plugin;
  20142. fx.plugin = ref ("VST3-ShotVerb-22222222-bbbbbbbb", "Shot Verb");
  20143. song.mixer[1].effects.push_back (fx);
  20144. fx.plugin = ref ("VST3-ShotComp-33333333-cccccccc", "Shot Comp");
  20145. song.mixer[2].effects.push_back (fx);
  20146. song.mixer[0].effects.push_back (fx);
  20147. offline.setSongWithPluginsOff (std::move (song));
  20148. ui.showDesktopForSnapshot (false);
  20149. shoot (ui, "pluginsoff-window");
  20150. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::channelRack, lynx::workspace::Panel::mixer });
  20151. shoot (ui, "pluginsoff-mixer"); // (the rack's and the mixer's "off" tags together)
  20152. saveFileMenu ("menu-file-pluginsoff");
  20153. auto panel = lynx::makePluginsOffPanel (offline);
  20154. shoot (*panel, "pluginsoff-panel");
  20155. offline.switchPluginOn ("VST3-ShotVerb-22222222-bbbbbbbb"); // (not installed: "Did not load")
  20156. auto after = lynx::makePluginsOffPanel (offline);
  20157. shoot (*after, "pluginsoff-panel-one");
  20158. }
  20159. // ---- the Export window: as it opens, and with a preset chosen, sections on and a last export to repeat
  20160. {
  20161. auto song = lynx::Song::makeDefault();
  20162. const auto bar = song.barTicks();
  20163. song.mode = lynx::PlayMode::song;
  20164. song.playlist.clear();
  20165. lynx::Clip clip;
  20166. clip.length = 32 * bar;
  20167. song.playlist.push_back (clip);
  20168. const char* sections[] = { "Intro", "Verse", "Chorus", "Outro" };
  20169. for (int i = 0; i < 4; ++i)
  20170. {
  20171. lynx::Marker m;
  20172. m.tick = i * 8 * bar;
  20173. m.name = sections[i];
  20174. song.addMarker (m);
  20175. }
  20176. offline.setSong (std::move (song)); // (also ends the plugins-off mode)
  20177. auto plain = lynx::makeExportPanel (offline, 0);
  20178. shoot (*plain, "export-default");
  20179. auto additions = lynx::makeExportPanelWithAdditions (offline);
  20180. shoot (*additions, "export");
  20181. }
  20182. }
  20183. void runGapShot190og (const juce::String& prefix)
  20184. {
  20185. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20186. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  20187. juce::String checks;
  20188. int failures = 0;
  20189. 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")); };
  20190. const auto check = [&] (const juce::String& what, bool ok) {
  20191. checks << (ok ? "ok " : "FAIL ") << what << "\n";
  20192. failures += ok ? 0 : 1;
  20193. flush();
  20194. };
  20195. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  20196. const auto menuRows = [] (const juce::PopupMenu& menu) {
  20197. juce::StringArray rows;
  20198. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  20199. rows.add (it.getItem().isSeparator ? juce::String ("--") : (it.getItem().isEnabled ? "" : "(off) ") + it.getItem().text.replace ("\t", " | "));
  20200. return rows;
  20201. };
  20202. const auto itemOf = [] (const juce::PopupMenu& menu, const juce::String& start) -> const juce::PopupMenu::Item* {
  20203. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  20204. if (! it.getItem().isSeparator && it.getItem().text.startsWith (start))
  20205. return &it.getItem();
  20206. return nullptr;
  20207. };
  20208. lynx::AudioEngine offline (false);
  20209. lynx::MainComponent ui (offline, false);
  20210. ui.setSize (1600, 900);
  20211. const auto settle = [&] {
  20212. for (int k = 0; k < 3; ++k)
  20213. offline.dispatchPendingMessages();
  20214. };
  20215. const auto write = [&prefix, &settle] (juce::Component& c, const juce::String& name) {
  20216. settle();
  20217. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  20218. };
  20219. const auto area = [&prefix, &settle] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) {
  20220. settle();
  20221. savePng (lynx::shot::snapshot (c).getClippedImage ((r.toFloat() * lynx::shot::scale()).toNearestInt()), prefix + "-" + name + ".png");
  20222. };
  20223. ui.setVisible (true);
  20224. lynx::DetailView::shownSetting = true;
  20225. lynx::DetailView::devicesPage = true;
  20226. ui.setClipLaunchWorkflow (true);
  20227. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  20228. const auto bar = 4 * lynx::ppq;
  20229. offline.editSong ([bar] (lynx::Song& s) {
  20230. if (s.channels.size() < 1)
  20231. s.channels.resize (1);
  20232. s.channels[0].name = "Keys";
  20233. s.channels[0].instrument = lynx::InstrumentKind::synth;
  20234. s.channels[0].mixerTrack = 2;
  20235. if (s.mixer.size() < 4)
  20236. s.mixer.resize (4);
  20237. s.mixer[2].name = "Keys";
  20238. s.mixer[2].effects.clear();
  20239. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  20240. s.mixer[2].effects.push_back (lynx::makeEffectSlot (kind));
  20241. while (s.patterns.size() < 1)
  20242. s.patterns.emplace_back();
  20243. auto& p = s.patterns[0];
  20244. p.name = "Chords";
  20245. p.notes.clear();
  20246. // a one-bar loop with a rising line; a note crossing the loop's end and one after it (Duplicate Loop / Crop)
  20247. const int keys[] { 60, 64, 67, 72, 71, 67, 64, 62 };
  20248. for (int i = 0; i < 8; ++i)
  20249. {
  20250. lynx::Note n;
  20251. n.channel = 0;
  20252. n.key = keys[i];
  20253. n.start = i * (bar / 8);
  20254. n.length = bar / 8 - 60;
  20255. n.velocity = (float) (40 + i * 10) / 127.0f;
  20256. p.notes.push_back (n);
  20257. }
  20258. lynx::Note tail;
  20259. tail.channel = 0;
  20260. tail.key = 55;
  20261. tail.start = bar + lynx::ppq;
  20262. tail.length = lynx::ppq;
  20263. p.notes.push_back (tail);
  20264. p.lengthTicks = 2 * bar;
  20265. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  20266. s.playlistTracks[1].name = "Keys";
  20267. lynx::Clip clip;
  20268. clip.pattern = 0;
  20269. clip.length = bar;
  20270. lynx::launcher::setClip (s, 1, 0, clip);
  20271. if (auto* c = const_cast<lynx::Clip*> (lynx::launcher::clipAt (*s.clipGrid, 1, 0)))
  20272. c->offset = 0, c->length = bar; // (a one-bar loop over the two-bar pattern)
  20273. }, false);
  20274. settle();
  20275. ui.resized();
  20276. auto* detail = ui.getDetailViewForSnapshot();
  20277. auto* grid = ui.getClipGridForSnapshot();
  20278. if (detail == nullptr || grid == nullptr)
  20279. {
  20280. check ("the Clip-launch layout has its detail view and grid", false);
  20281. return;
  20282. }
  20283. const auto editMenu = [&ui] {
  20284. const auto names = ui.getMenuNamesForSnapshot();
  20285. return ui.getMenuForSnapshot (juce::jmax (0, names.indexOf (lynx::tr ("Edit"))));
  20286. };
  20287. const auto fxNames = [&offline] {
  20288. juce::StringArray names;
  20289. for (const auto& fx : offline.getSong().mixer[2].effects)
  20290. names.add (juce::String ((int) fx.kind));
  20291. return names.joinIntoString (",");
  20292. };
  20293. // --- deviceview-0012: the Edit menu's Live block on the Device View ---------------------------------------------
  20294. detail->showSelection (1, 0);
  20295. detail->setPage (lynx::DetailView::Page::devices);
  20296. settle();
  20297. detail->selectCardForCheck (2); // (card 0 the instrument, 1 the EQ, 2 the Compressor)
  20298. settle();
  20299. write (ui, "01-devices-window");
  20300. write (*detail, "01b-devices");
  20301. {
  20302. const auto menu = editMenu();
  20303. saveMenus (juce::StringArray { lynx::tr ("Edit") }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-edit-menu-device.png");
  20304. line ("Edit menu: " + menuRows (menu).joinIntoString (" // "));
  20305. const auto* cut = itemOf (menu, lynx::tr ("Cut") + "\t");
  20306. const auto* paste = itemOf (menu, lynx::tr ("Paste") + "\t");
  20307. check ("Edit menu (Clip-launch): Live's Cut | Ctrl+X, Copy, Paste, Duplicate, Delete | Del after Undo / Redo",
  20308. cut != nullptr && cut->text.endsWith ("Ctrl+X") && itemOf (menu, lynx::tr ("Copy") + "\tCtrl+C") != nullptr
  20309. && paste != nullptr && itemOf (menu, lynx::tr ("Duplicate") + "\tCtrl+D") != nullptr && itemOf (menu, lynx::tr ("Delete") + "\tDel") != nullptr
  20310. && menuRows (menu).indexOf ("--") < menuRows (menu).indexOf (lynx::tr ("Cut") + " | Ctrl+X"));
  20311. check ("a selected device: Cut / Copy / Duplicate / Delete on, Paste off with nothing copied", cut != nullptr && cut->isEnabled && paste != nullptr && ! paste->isEnabled);
  20312. }
  20313. const auto invoke = [&] (const juce::String& start) {
  20314. const auto menu = editMenu();
  20315. if (const auto* item = itemOf (menu, start); item != nullptr && item->isEnabled && item->action != nullptr)
  20316. {
  20317. item->action();
  20318. settle();
  20319. return true;
  20320. }
  20321. return false;
  20322. };
  20323. line ("effects before: " + fxNames());
  20324. check ("Edit > Copy on the Compressor", invoke (lynx::tr ("Copy") + "\t"));
  20325. detail->selectCardForCheck (3); // the Delay
  20326. settle();
  20327. check ("Edit > Paste with the Delay selected: in front of it (Live: \"Pasted devices are inserted in front of the selected device\")",
  20328. invoke (lynx::tr ("Paste") + "\t") && fxNames() == juce::String ((int) lynx::EffectKind::eq) + "," + juce::String ((int) lynx::EffectKind::compressor) + ","
  20329. + juce::String ((int) lynx::EffectKind::compressor) + "," + juce::String ((int) lynx::EffectKind::delay));
  20330. line ("effects after Paste: " + fxNames());
  20331. write (*detail, "03-devices-after-paste");
  20332. check ("Edit > Duplicate", invoke (lynx::tr ("Duplicate") + "\t") && offline.getSong().mixer[2].effects.size() == 5);
  20333. check ("Edit > Delete", invoke (lynx::tr ("Delete") + "\t") && offline.getSong().mixer[2].effects.size() == 4);
  20334. detail->selectCardForCheck (2); // (Delete left nothing selected)
  20335. settle();
  20336. check ("Edit > Cut", invoke (lynx::tr ("Cut") + "\t") && offline.getSong().mixer[2].effects.size() == 3);
  20337. line ("effects after Duplicate, Delete, Cut: " + fxNames());
  20338. // the Pattern layout keeps FL's Edit menu
  20339. ui.setClipLaunchWorkflow (false);
  20340. settle();
  20341. check ("the Pattern layout's Edit menu has no Live block", itemOf (editMenu(), lynx::tr ("Cut") + "\t") == nullptr);
  20342. ui.setClipLaunchWorkflow (true);
  20343. settle();
  20344. ui.resized();
  20345. // --- detail-019: the Clip panel's Duplicate (Loop) button ------------------------------------------------------
  20346. detail->showSelection (1, 0);
  20347. detail->setPage (lynx::DetailView::Page::clip);
  20348. detail->setClipTab (false);
  20349. lynx::DetailView::devicesPage = false;
  20350. detail->clipSectionsForSnapshot (true, true, true, 0);
  20351. settle();
  20352. ui.resized();
  20353. write (ui, "04-clip-window");
  20354. write (*detail, "04b-clip-detail");
  20355. const auto clipNow = [&offline] () -> lynx::Clip {
  20356. const auto& g = offline.getSong().clipGrid;
  20357. const auto* c = g ? lynx::launcher::clipAt (*g, 1, 0) : nullptr;
  20358. return c != nullptr ? *c : lynx::Clip();
  20359. };
  20360. const auto noteCount = [&offline] { return (int) offline.getSong().patterns[0].notes.size(); };
  20361. // (the grid keeps a MIDI clip as long as its pattern: the loop is the pattern's two bars, all 9 notes inside it)
  20362. const auto loopBefore = clipNow().length;
  20363. int inLoop = 0;
  20364. for (const auto& n : offline.getSong().patterns[0].notes)
  20365. inLoop += n.start >= clipNow().offset && n.start < clipNow().offset + loopBefore ? 1 : 0;
  20366. const auto lastBefore = offline.getSong().patterns[0].notes.back().start;
  20367. line ("before: loop " + juce::String (clipNow().offset) + " + " + juce::String (loopBefore) + ", " + juce::String (noteCount()) + " notes, "
  20368. + juce::String (inLoop) + " in the loop");
  20369. check ("the clip is a MIDI clip with 9 notes in its pattern", loopBefore > 0 && noteCount() == 9);
  20370. check ("the Duplicate button pressed", detail->duplicateLoopForCheck());
  20371. settle();
  20372. line ("after Duplicate Loop: loop " + juce::String (clipNow().offset) + " + " + juce::String (clipNow().length) + ", " + juce::String (noteCount()) + " notes, last at "
  20373. + juce::String (offline.getSong().patterns[0].notes.back().start));
  20374. check ("Duplicate Loop: the loop twice as long, the notes in it copied one loop later",
  20375. clipNow().length == 2 * loopBefore && noteCount() == 9 + inLoop && offline.getSong().patterns[0].notes.back().start == lastBefore + loopBefore);
  20376. write (*detail, "05-clip-after-duplicate-loop");
  20377. check ("one undo step brings the one-bar loop back", [&] { ui.runActionForSnapshot ("edit.undo"); settle(); return clipNow().length == loopBefore && noteCount() == 9; }());
  20378. // --- detail-047: the Velocity lane's Randomize footer ---------------------------------------------------------
  20379. auto& roll = ui.getPianoRollForSnapshot();
  20380. roll.setLaneForSnapshot (lynx::PianoRollComponent::laneVelocity);
  20381. settle();
  20382. ui.resized();
  20383. settle();
  20384. const auto footer = roll.liveRandomizeBoundsForCheck();
  20385. line ("roll " + roll.getBounds().toString() + ", footer " + juce::String (roll.liveFooterHeight()) + " px, Randomize " + footer.toString());
  20386. check ("the docked roll (Live look) shows Live's Velocity footer with Randomize", roll.liveFooterHeight() == lynx::PianoRollComponent::liveFooterBar && ! footer.isEmpty());
  20387. write (ui, "06-velocity-footer-window");
  20388. if (roll.getParentComponent() != nullptr)
  20389. area (roll, roll.getLocalBounds().removeFromBottom (90), "06b-velocity-footer");
  20390. {
  20391. std::vector<float> before;
  20392. for (const auto& n : offline.getSong().patterns[0].notes)
  20393. before.push_back (n.velocity);
  20394. lynx::PianoRollComponent::liveRandomizeAmount = 20;
  20395. roll.liveRandomizeVelocity();
  20396. settle();
  20397. int moved = 0, within = 0;
  20398. const auto& notes = offline.getSong().patterns[0].notes;
  20399. for (std::size_t i = 0; i < notes.size() && i < before.size(); ++i)
  20400. {
  20401. const auto d = std::abs (juce::roundToInt (notes[i].velocity * 127.0f) - juce::roundToInt (before[i] * 127.0f));
  20402. moved += d > 0 ? 1 : 0;
  20403. within += d <= 20 ? 1 : 0;
  20404. }
  20405. line ("Randomize (amount 20, nothing selected): " + juce::String (moved) + " of " + juce::String ((int) notes.size()) + " notes moved");
  20406. check ("Randomize with nothing selected moves the notes' velocities by at most the amount", moved > 0 && within == (int) notes.size());
  20407. lynx::PianoRollComponent::liveRandomizeAmount = 100;
  20408. write (ui, "07-velocity-after-randomize");
  20409. }
  20410. // --- detail-020: Crop Clip in the clip's menu and on Ctrl+Shift+J ---------------------------------------------
  20411. {
  20412. const auto menu = lynx::clipGridSlotMenu (*grid, 1, 0);
  20413. saveMenus (juce::StringArray { "Clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-08-clip-menu.png");
  20414. line ("clip menu: " + menuRows (menu).joinIntoString (" // "));
  20415. const auto rows = menuRows (menu);
  20416. const auto crop = rows.indexOf (lynx::tr ("Crop Clip") + " | Ctrl+Shift+J");
  20417. check ("the clip menu (Live look) has Crop Clip | Ctrl+Shift+J in its own group before the colours",
  20418. crop > 0 && rows[crop - 1] == "--" && rows[crop + 1] == "--" && rows.indexOf (lynx::tr ("Deactivate Clip") + " | 0") < crop);
  20419. }
  20420. offline.editSong ([bar] (lynx::Song& s) {
  20421. if (auto* c = s.clipGrid ? const_cast<lynx::Clip*> (lynx::launcher::clipAt (*s.clipGrid, 1, 0)) : nullptr)
  20422. c->offset = bar / 2, c->length = bar / 2; // the loop on the second half bar
  20423. });
  20424. settle();
  20425. lynx::selectClipGridSlotForSnapshot (*grid, 1, 0);
  20426. const auto keyed = lynx::clipGridKeyForSnapshot (*grid, juce::KeyPress ('j', juce::ModifierKeys::commandModifier | juce::ModifierKeys::shiftModifier, 0));
  20427. settle();
  20428. juce::String kept;
  20429. for (const auto& n : offline.getSong().patterns[0].notes)
  20430. kept << n.start << ":" << n.key << " ";
  20431. line ("after Ctrl+Shift+J: loop " + juce::String (clipNow().offset) + " + " + juce::String (clipNow().length) + ", notes " + kept);
  20432. check ("Ctrl+Shift+J crops the clip: the half bar's 4 notes kept, moved to the start; the loop starts at 0",
  20433. keyed && noteCount() == 4 && offline.getSong().patterns[0].notes.front().start == 0 && clipNow().offset == 0 && clipNow().length == bar / 2);
  20434. write (*detail, "09-clip-after-crop");
  20435. // --- mapping-0028: Key Map Mode on the transport switches -------------------------------------------------------
  20436. {
  20437. using namespace lynx::remotemap;
  20438. offline.editSong ([] (lynx::Song& s) {
  20439. assignKey (s, Target::of (lynx::RemoteAction::overdub), 'O');
  20440. assignKey (s, Target::of (lynx::RemoteAction::loopSwitch), 'L');
  20441. assignKey (s, Target::of (lynx::RemoteAction::punchIn), 'I');
  20442. assignKey (s, Target::of (lynx::RemoteAction::punchOut), 'U');
  20443. });
  20444. settle();
  20445. for (const auto mode : { Mode::key, Mode::midi })
  20446. {
  20447. ui.setMapMode (mode);
  20448. settle();
  20449. if (auto* overlay = ui.mapOverlayForSnapshot())
  20450. {
  20451. overlay->refresh();
  20452. const auto& spots = overlay->spots();
  20453. 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; }); };
  20454. line (juce::String (mode == Mode::key ? "key" : "midi") + " map: " + juce::String ((int) spots.size()) + " spots; overdub " + juce::String (count (lynx::RemoteAction::overdub))
  20455. + ", loop " + juce::String (count (lynx::RemoteAction::loopSwitch)) + ", punch in " + juce::String (count (lynx::RemoteAction::punchIn)) + ", punch out "
  20456. + juce::String (count (lynx::RemoteAction::punchOut)));
  20457. check (juce::String (mode == Mode::key ? "Key" : "MIDI") + " Map Mode: Arrangement Overdub, Loop, Punch-In and Punch-Out are mappable in the Control Bar",
  20458. count (lynx::RemoteAction::overdub) == 1 && count (lynx::RemoteAction::loopSwitch) == 1 && count (lynx::RemoteAction::punchIn) == 1
  20459. && count (lynx::RemoteAction::punchOut) == 1);
  20460. }
  20461. write (ui, mode == Mode::key ? "10-keymap" : "11-midimap");
  20462. if (mode == Mode::key)
  20463. area (ui, ui.getLocalBounds().removeFromTop (60), "10b-keymap-controlbar");
  20464. if (mode == Mode::key)
  20465. if (auto* browser = ui.mappingBrowserForSnapshot())
  20466. write (*browser, "12-key-mappings-browser");
  20467. }
  20468. ui.setMapMode (Mode::off);
  20469. settle();
  20470. // the mapped keys switch them, and the mappings survive a save
  20471. const auto options = [&offline] { return offline.getRecordOptions(); };
  20472. const auto blend = options().mode;
  20473. const auto loopBefore = offline.getSong().loopPlays();
  20474. const auto inBefore = options().punchLoopRegion && options().punchIn;
  20475. const auto press = [&] (int key) {
  20476. for (const auto& f : keyFires (offline.getSong(), key, true))
  20477. ui.fireRemote (f);
  20478. settle();
  20479. };
  20480. press ('O');
  20481. press ('L');
  20482. press ('I');
  20483. check ("the mapped keys switch Overdub, Loop and Punch-In", options().mode != blend && offline.getSong().loopPlays() != loopBefore
  20484. && (options().punchLoopRegion && options().punchIn) != inBefore);
  20485. juce::String error;
  20486. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (offline.getSong()), error);
  20487. int kept4 = 0;
  20488. if (back)
  20489. for (const auto& m : back->remoteMappings)
  20490. kept4 += m.action == lynx::RemoteAction::overdub || m.action == lynx::RemoteAction::loopSwitch || m.action == lynx::RemoteAction::punchIn
  20491. || m.action == lynx::RemoteAction::punchOut ? 1 : 0;
  20492. check ("the four mappings are saved with the project and read back", kept4 == 4);
  20493. }
  20494. flush();
  20495. }
  20496. void runUndoShot190mz (const juce::String& prefix)
  20497. {
  20498. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  20499. juce::String report;
  20500. int failures = 0;
  20501. const auto check = [&] (const juce::String& name, bool ok) {
  20502. report << (ok ? "OK " : "FAIL ") << name << "\n";
  20503. failures += ok ? 0 : 1;
  20504. };
  20505. {
  20506. lynx::AudioEngine engine (false);
  20507. lynx::MainComponent ui (engine, false);
  20508. ui.setSize (1600, 900);
  20509. engine.dispatchPendingMessages();
  20510. // FL 2026's default: Ctrl+Z steps back
  20511. check ("alternate undo mode is on by default (FL 2026)", ui.getAlternateUndo());
  20512. const auto editMenuText = [&ui] {
  20513. const auto names = ui.getMenuNamesForSnapshot();
  20514. juce::StringArray rows;
  20515. const auto menu = ui.getMenuForSnapshot (juce::jmax (0, names.indexOf (lynx::tr ("Edit"))));
  20516. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  20517. {
  20518. if (it.getItem().isSeparator)
  20519. break;
  20520. rows.add ((it.getItem().isEnabled ? "" : "(off) ") + it.getItem().text.replace ("\t", " | "));
  20521. }
  20522. return rows;
  20523. };
  20524. const auto saveEditMenu = [&ui, &prefix] (const juce::String& name) {
  20525. const auto names = ui.getMenuNamesForSnapshot();
  20526. const auto index = juce::jmax (0, names.indexOf (lynx::tr ("Edit")));
  20527. saveMenus (juce::StringArray { names[index] }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-menu-" + name + ".png");
  20528. };
  20529. const auto key = [&ui, &engine] (const char* action) {
  20530. ui.runActionForSnapshot (action);
  20531. engine.dispatchPendingMessages();
  20532. };
  20533. const auto bpm = [&engine] { return engine.getSong().bpm; };
  20534. const auto start = bpm();
  20535. const auto swing0 = engine.getSong().swing;
  20536. const auto log = [&] (const juce::String& state) {
  20537. report << " " << state << ": bpm " << bpm() << ", level " << engine.getHistoryPosition() + 1 << "/" << engine.getHistorySize()
  20538. << ", Edit menu: " << editMenuText().joinIntoString (" // ") << "\n";
  20539. };
  20540. log ("fresh");
  20541. saveEditMenu ("pattern-0-fresh");
  20542. engine.editSong ([] (lynx::Song& s) { s.bpm = 101.0; });
  20543. engine.editSong ([] (lynx::Song& s) { s.swing = s.swing == 0.25f ? 0.5f : 0.25f; });
  20544. engine.editSong ([] (lynx::Song& s) { s.bpm = 103.0; });
  20545. engine.dispatchPendingMessages();
  20546. log ("three edits");
  20547. saveEditMenu ("pattern-1-three-edits");
  20548. check ("menu names the step: Undo Tempo | Ctrl+Z, no Redo item (FL)",
  20549. editMenuText()[0].startsWith (lynx::tr ("Undo {0}", { lynx::tr ("Tempo") })) && editMenuText()[0].contains ("Ctrl+Z")
  20550. && ! editMenuText()[1].startsWith (lynx::tr ("Redo {0}", { lynx::tr ("Tempo") })));
  20551. // the reporter's case (issue #214): Ctrl+Z pressed again keeps going back
  20552. key ("edit.undo");
  20553. log ("Ctrl+Z");
  20554. saveEditMenu ("pattern-2-alt-ctrl-z");
  20555. check ("alternate: menu shows Undo Swing | Ctrl+Z and Redo Tempo | Ctrl+Alt+Z (FL)",
  20556. editMenuText()[0].startsWith (lynx::tr ("Undo {0}", { lynx::tr ("Swing") })) && editMenuText()[0].endsWith ("Ctrl+Z")
  20557. && editMenuText()[1].startsWith (lynx::tr ("Redo {0}", { lynx::tr ("Tempo") })) && editMenuText()[1].endsWith ("Ctrl+Alt+Z"));
  20558. key ("edit.undo");
  20559. log ("Ctrl+Z x2");
  20560. check ("alternate: Ctrl+Z twice goes two steps back (swing undone, bpm 101)", bpm() == 101.0 && engine.getSong().swing == swing0);
  20561. key ("edit.undo");
  20562. key ("edit.undo"); // (nothing left: nothing happens, no redo)
  20563. log ("Ctrl+Z x4");
  20564. check ("alternate: Ctrl+Z walks to the start and stops there", bpm() == start && ! engine.canUndo() && engine.canRedo());
  20565. saveEditMenu ("pattern-3-alt-at-start");
  20566. key ("edit.redo");
  20567. check ("alternate: Ctrl+Y / Ctrl+Shift+Z redo one step", bpm() == 101.0);
  20568. key ("edit.redo");
  20569. key ("edit.redo");
  20570. check ("alternate: redo back to the newest state", bpm() == 103.0 && ! engine.canRedo());
  20571. key ("edit.undo");
  20572. key ("edit.undoBackwards");
  20573. check ("alternate: Ctrl+Alt+Z redoes what was undone (FL swaps the two keys)", bpm() == 103.0 && ! engine.canRedo());
  20574. // FL's other mode: Ctrl+Z undoes, then redoes (the toggle the issue describes); Ctrl+Alt+Z walks back
  20575. ui.setAlternateUndoForSnapshot (false);
  20576. key ("edit.undo");
  20577. log ("default mode, Ctrl+Z");
  20578. saveEditMenu ("pattern-4-toggle-ctrl-z");
  20579. check ("toggle mode: menu shows Undo Swing | Ctrl+Alt+Z and Redo Tempo | Ctrl+Z (FL)",
  20580. editMenuText()[0].startsWith (lynx::tr ("Undo {0}", { lynx::tr ("Swing") })) && editMenuText()[0].endsWith ("Ctrl+Alt+Z")
  20581. && editMenuText()[1].startsWith (lynx::tr ("Redo {0}", { lynx::tr ("Tempo") })) && editMenuText()[1].endsWith ("Ctrl+Z"));
  20582. key ("edit.undo");
  20583. log ("default mode, Ctrl+Z x2");
  20584. check ("toggle mode: Ctrl+Z again redoes the step", bpm() == 103.0 && ! engine.canRedo());
  20585. key ("edit.undoBackwards");
  20586. key ("edit.undoBackwards");
  20587. check ("toggle mode: Ctrl+Alt+Z walks back", bpm() == 101.0 && engine.getSong().swing == swing0);
  20588. key ("edit.undo");
  20589. check ("toggle mode: Ctrl+Z after walking back redoes one step (FL: position - 1)", engine.getSong().swing != swing0 && bpm() == 101.0);
  20590. key ("edit.redo");
  20591. check ("toggle mode: Ctrl+Y / Ctrl+Shift+Z redo", bpm() == 103.0 && ! engine.canRedo());
  20592. // Clip-launch and Simple: Live's form (both items, "Nothing to redo", redo on Ctrl+Y)
  20593. ui.setAlternateUndoForSnapshot (true);
  20594. for (const auto style : { lynx::layoutstyle::Style::clipLaunch, lynx::layoutstyle::Style::simple })
  20595. {
  20596. const juce::String name = style == lynx::layoutstyle::Style::simple ? "simple" : "cliplaunch";
  20597. ui.setLayoutStyle (style);
  20598. engine.dispatchPendingMessages();
  20599. log (name);
  20600. saveEditMenu (name + "-1-newest");
  20601. check (name + ": Undo Tempo | Ctrl+Z, Nothing to redo | Ctrl+Y",
  20602. editMenuText()[0].startsWith (lynx::tr ("Undo {0}", { lynx::tr ("Tempo") })) && editMenuText()[0].endsWith ("Ctrl+Z")
  20603. && editMenuText()[1].startsWith ("(off) " + lynx::tr ("Nothing to redo")) && editMenuText()[1].endsWith ("Ctrl+Y"));
  20604. key ("edit.undo");
  20605. key ("edit.undo");
  20606. log (name + ", Ctrl+Z x2");
  20607. saveEditMenu (name + "-2-ctrl-z-x2");
  20608. check (name + ": Ctrl+Z twice goes two steps back", bpm() == 101.0 && engine.getSong().swing == swing0);
  20609. key ("edit.redo");
  20610. key ("edit.redo");
  20611. check (name + ": Ctrl+Y redoes both", bpm() == 103.0 && ! engine.canRedo());
  20612. }
  20613. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  20614. engine.dispatchPendingMessages();
  20615. }
  20616. report << (failures == 0 ? "ALL OK\n" : juce::String (failures) + " FAILED\n");
  20617. juce::File (prefix + "-checks.txt").replaceWithText (report);
  20618. }
  20619. void runGamepadShot (const juce::String& prefix)
  20620. {
  20621. juce::String report;
  20622. int failures = 0;
  20623. {
  20624. lynx::AudioEngine engine (false);
  20625. auto hints = lynx::makeGamepadHints();
  20626. savePng (lynx::shot::snapshot (*hints), prefix + "-hints.png");
  20627. auto prefs = engine.getMidiPrefs();
  20628. prefs.gamepad = true;
  20629. engine.setMidiPrefs (prefs, false);
  20630. auto page = lynx::makeMidiPage (engine, {}, false);
  20631. page->setSize (760, 1400);
  20632. savePng (lynx::shot::snapshot (*page), prefix + "-settings.png");
  20633. // the poller with fake states: what the handler gets
  20634. using namespace lynx::gamepad;
  20635. std::vector<std::string> got;
  20636. lynx::GamepadInput input ([&got] (const Changes& c, const State&, double dt) {
  20637. for (int i = 0; i < c.pressedCount; ++i)
  20638. got.push_back (std::string ("press ") + buttonName (c.pressed[(std::size_t) i]));
  20639. for (int i = 0; i < c.releasedCount; ++i)
  20640. got.push_back (std::string ("release ") + buttonName (c.released[(std::size_t) i]));
  20641. for (int i = 0; i < c.controllerCount; ++i)
  20642. got.push_back ("cc " + std::to_string (c.controller[(std::size_t) i]) + "=" + std::to_string (c.value[(std::size_t) i]));
  20643. if (c.connectedChanged)
  20644. got.push_back ("connected changed");
  20645. got.push_back ("dt " + std::to_string ((int) std::lround (dt * 1000)));
  20646. });
  20647. State pad;
  20648. pad.connected = true;
  20649. input.inject (pad, 1.0 / 60.0);
  20650. pad.buttons = mask (Button::a);
  20651. pad.rightTrigger = 255;
  20652. input.inject (pad, 1.0 / 60.0);
  20653. pad.buttons = 0;
  20654. input.inject (pad, 1.0 / 60.0);
  20655. const std::vector<std::string> expected { "connected changed", "dt 17", "press A", "cc 102=127", "cc 21=127", "dt 17",
  20656. "release A", "cc 102=0", "dt 17" };
  20657. for (const auto& line : got)
  20658. report << line << "\n";
  20659. if (got != expected)
  20660. {
  20661. ++failures;
  20662. report << "FAILED: the poller's changes differ from the expected ones\n";
  20663. }
  20664. report << "xinput " << (input.available() ? "loaded" : "not available") << "\n";
  20665. }
  20666. report << (failures == 0 ? "gamepad OK" : "gamepad FAILED") << "\n";
  20667. juce::File (prefix + "-gamepad.txt").replaceWithText (report);
  20668. setApplicationReturnValue (failures == 0 ? 0 : 1);
  20669. quit();
  20670. }
  20671. void runBundleExport (const juce::String& inputPath, const juce::String& folderPath, bool zip, bool mixdown, const juce::String& shotPrefix)
  20672. {
  20673. juce::String error;
  20674. bool ok = false;
  20675. lynx::otherapps::Result result;
  20676. {
  20677. lynx::AudioEngine loader (false);
  20678. const juce::File input (inputPath);
  20679. if (input.hasFileExtension ("flp;als"))
  20680. ok = loader.importFlpFile (input, error);
  20681. else if (auto song = lynx::ProjectFile::load (input, error))
  20682. {
  20683. loader.setSong (std::move (*song));
  20684. ok = true;
  20685. }
  20686. if (ok)
  20687. {
  20688. loader.capturePluginStates();
  20689. lynx::otherapps::Context context;
  20690. context.host = &loader.getPluginHost();
  20691. context.flOptions = lynx::flstudio::optionsFor (context.host, lynx::flpexport::LynxOnly::renderAudio, loader.getSong());
  20692. context.render = [] (const lynx::Song& s, const lynx::exportopts::Options& o, const juce::File& file,
  20693. const std::function<bool (double)>& progress, juce::String& err) {
  20694. lynx::ExportJob job (s, o, file);
  20695. return job.run (progress, err);
  20696. };
  20697. context.onMessageThread = [] (std::function<void()> f) { f(); };
  20698. lynx::exportbundle::Options options;
  20699. options.zip = zip;
  20700. options.mixdown = mixdown;
  20701. const auto name = input.getFileNameWithoutExtension();
  20702. const auto shot = [&shotPrefix] (juce::Component& c, const juce::String& suffix) {
  20703. if (shotPrefix.isNotEmpty())
  20704. savePng (lynx::shot::snapshot (c), shotPrefix + suffix);
  20705. };
  20706. if (auto panel = lynx::makeOtherAppsExportPanel (loader, name))
  20707. shot (*panel, "-panel.png");
  20708. ok = lynx::otherapps::write (loader.getSong(), name, options, juce::File (folderPath), context, result);
  20709. if (auto report = lynx::makeOtherAppsReportPanel (result.folder, result.written, result.failed))
  20710. shot (*report, "-report.png");
  20711. }
  20712. }
  20713. juce::String report;
  20714. report << (ok ? "ok " + result.folder.getFullPathName() : "error=" + error) << "\n";
  20715. for (const auto& w : result.written)
  20716. report << "written " << w << "\n";
  20717. for (const auto& f : result.failed)
  20718. report << "failed " << f << "\n";
  20719. juce::File (folderPath).getChildFile ("export-bundle.txt").replaceWithText (report);
  20720. setApplicationReturnValue (ok && result.failed.isEmpty() ? 0 : 1);
  20721. quit();
  20722. }
  20723. void runFlExport (const juce::String& inputPath, const juce::String& outputPath, bool substitute)
  20724. {
  20725. juce::String error;
  20726. bool ok = false;
  20727. lynx::flstudio::Written written;
  20728. {
  20729. lynx::AudioEngine loader (false);
  20730. const juce::File input (inputPath);
  20731. // a Live set opens through the same import as an .flp (as File › Open does, and --export-als accepts an .flp)
  20732. if (input.hasFileExtension ("flp;als"))
  20733. ok = loader.importFlpFile (input, error);
  20734. else if (auto song = lynx::ProjectFile::load (input, error))
  20735. {
  20736. loader.setSong (std::move (*song));
  20737. ok = true;
  20738. }
  20739. if (ok)
  20740. {
  20741. const juce::File output (outputPath);
  20742. const auto zip = output.hasFileExtension ("zip");
  20743. const auto mode = substitute ? lynx::flpexport::LynxOnly::substitute : lynx::flpexport::LynxOnly::renderAudio;
  20744. loader.capturePluginStates();
  20745. auto options = lynx::flstudio::optionsFor (&loader.getPluginHost(), mode, loader.getSong());
  20746. // --flp-ppq N: the file's PPQ (tests; default: 96 when the notes and clips fit it)
  20747. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--flp-ppq"))
  20748. options.ppq = juce::jlimit (0, 960, args[args.indexOf ("--flp-ppq") + 1].getIntValue());
  20749. const auto renderDir = zip ? juce::File::getSpecialLocation (juce::File::tempDirectory).getNonexistentChildFile ("LYNX FL export", {}, false)
  20750. : output.getSiblingFile (output.getFileNameWithoutExtension() + " audio");
  20751. ok = lynx::flstudio::exportProject (loader.getSong(), options, output, zip, renderDir, 44100.0,
  20752. [] (const lynx::Song& s, const lynx::ExportSettings& settings, const juce::File& wav,
  20753. const std::function<bool (double)>& progress, juce::String& err) {
  20754. lynx::ExportJob job (s, settings, wav);
  20755. return job.run (progress, err);
  20756. },
  20757. {}, written, error);
  20758. if (zip)
  20759. renderDir.deleteRecursively();
  20760. }
  20761. }
  20762. juce::String report;
  20763. report << (ok ? "ok" : "error=" + error) << "\n"
  20764. << "exact=" << (int) written.report.exact.size() << " rendered=" << (int) written.report.rendered.size()
  20765. << " substituted=" << (int) written.report.substituted.size() << " dropped=" << (int) written.report.dropped.size()
  20766. << " samples=" << written.samples << "\n\n"
  20767. << lynx::flstudio::reportText (written) << "\n";
  20768. juce::File (outputPath + ".txt").replaceWithText (report);
  20769. setApplicationReturnValue (ok ? 0 : 1);
  20770. quit();
  20771. }
  20772. // LYNX.exe --export project.(flp|als|lynx) output.(wav|flac|ogg|mp3|aif|aiff|m4a|aac) [--pattern] [--insert N] [--rate N]
  20773. // Same path as "Export" in the UI: the whole song (or the current pattern) with its tail. .aif / .aiff: 24-bit AIFF;
  20774. // .m4a: AAC at 192 kbps through the system's encoder (engine/AacEncoder.h; .aac writes the same MPEG-4 file under the
  20775. // name .m4a). M4A is not available on Linux: the export stops with that message.
  20776. void runExport (const juce::String& inputPath, const juce::String& outputPath, bool patternOnly, int insert)
  20777. {
  20778. juce::String error, report;
  20779. bool ok = false;
  20780. const auto started = juce::Time::getMillisecondCounterHiRes();
  20781. lynx::loadtrace::begin (inputPath.toStdString()); // phase times (round 112): report lines + load.log
  20782. {
  20783. lynx::AudioEngine loader (false);
  20784. const juce::File input (inputPath);
  20785. // --find-plugins: first the targeted scan opening the project in the app runs (its plugins not known yet)
  20786. if (input.hasFileExtension ("flp") && juce::JUCEApplication::getCommandLineParameters().contains ("--find-plugins"))
  20787. {
  20788. juce::MemoryBlock data;
  20789. if (input.loadFileAsData (data))
  20790. try
  20791. {
  20792. const auto uses = lynx::flpForeignPlugins (flp::parseProject ({ static_cast<const std::uint8_t*> (data.getData()), data.getSize() }));
  20793. auto& host = loader.getPluginHost();
  20794. const auto listed = std::chrono::steady_clock::now();
  20795. const auto files = host.filesToScanFor (uses);
  20796. lynx::loadtrace::add ("plugin_scan_list", lynx::loadtrace::msSince (listed));
  20797. report << "scanned=" << files.joinIntoString (";") << "\n";
  20798. const auto scanned = std::chrono::steady_clock::now();
  20799. host.scanFiles (files, {});
  20800. lynx::loadtrace::add ("plugin_scan", lynx::loadtrace::msSince (scanned), files.size());
  20801. }
  20802. catch (const flp::Error&)
  20803. {
  20804. }
  20805. }
  20806. if (input.hasFileExtension ("flp;als;mod;xm;s3m;it")) // a Live set opens through the same import (round 182b); a module too (190nw)
  20807. ok = loader.importFlpFile (input, error);
  20808. else if (auto song = lynx::ProjectFile::load (input, error))
  20809. {
  20810. loader.setSong (std::move (*song));
  20811. ok = true;
  20812. }
  20813. // M4A without a system AAC encoder (Linux): said before anything is rendered
  20814. if (ok && juce::File (outputPath).hasFileExtension ("m4a;aac") && ! lynx::aac::available())
  20815. {
  20816. ok = false;
  20817. error = juce::String::fromUTF8 (lynx::aac::unavailableReason().c_str());
  20818. }
  20819. if (ok)
  20820. {
  20821. // (an .aac name gets the MPEG-4 file it holds: .m4a)
  20822. const juce::File output (juce::File (outputPath).hasFileExtension ("aac") ? juce::File (outputPath).withFileExtension ("m4a") : juce::File (outputPath));
  20823. lynx::ExportSettings settings;
  20824. settings.wholeSong = ! patternOnly;
  20825. settings.format = output.hasFileExtension ("flac") ? lynx::ExportSettings::Format::flac24
  20826. : output.hasFileExtension ("ogg") ? lynx::ExportSettings::Format::ogg
  20827. : lynx::ExportSettings::Format::wav24;
  20828. // --insert N: only that insert's output (what "Render to audio" records)
  20829. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-effects")
  20830. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-efeitos")) // performance diagnostics; --sem-efeitos: legacy alias
  20831. loader.editSong ([] (lynx::Song& s) {
  20832. for (auto& t : s.mixer)
  20833. t.effects.clear();
  20834. }, false);
  20835. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-automation")
  20836. || juce::JUCEApplication::getCommandLineParameters().contains ("--sem-automacao")) // --sem-automacao: legacy alias
  20837. loader.editSong ([] (lynx::Song& s) { s.automations.clear(); }, false);
  20838. const auto loaded = juce::Time::getMillisecondCounterHiRes();
  20839. // .mp3: the Export window's MP3 (320 kbps); everything else as before
  20840. auto options = settings.toOptions();
  20841. // --save-tempo: FL's "Tempo information" (acid chunk) on (round 167l: compare with FL's AcidBox render; --export)
  20842. if (juce::JUCEApplication::getCommandLineParameters().contains ("--save-tempo"))
  20843. options.saveTempo = true;
  20844. // --no-warmup: the export's plugin warm-up off (round 155: compare the start of the file)
  20845. if (juce::JUCEApplication::getCommandLineParameters().contains ("--no-warmup"))
  20846. options.pluginWarmUp = false;
  20847. // --rate N: render at another sample rate (round 157b: samples resampled as at a 48 kHz device)
  20848. if (const auto args = juce::JUCEApplication::getCommandLineParameterArray(); args.contains ("--rate"))
  20849. if (const auto rate = args[args.indexOf ("--rate") + 1].getDoubleValue(); rate >= 8000.0 && rate <= 384000.0)
  20850. options.sampleRate = rate;
  20851. if (output.hasFileExtension ("mp3"))
  20852. {
  20853. options.format = lynx::exportopts::Format::mp3;
  20854. options.mp3Kbps = 320;
  20855. }
  20856. else if (output.hasFileExtension ("aif;aiff")) // (as the .wav: 24 bits, no dither)
  20857. {
  20858. options.format = lynx::exportopts::Format::aiff;
  20859. options.aiffBits = 24;
  20860. }
  20861. else if (output.hasFileExtension ("m4a"))
  20862. {
  20863. options.format = lynx::exportopts::Format::aac;
  20864. options.aacKbps = 192;
  20865. }
  20866. lynx::ExportJob job (insert > 0 ? lynx::makeBounceSong (loader.getSong(), insert) : loader.getSong(), options, output);
  20867. job.setExtraData (true);
  20868. const auto prepared = juce::Time::getMillisecondCounterHiRes();
  20869. lynx::loadtrace::end();
  20870. int lastPercent = -1;
  20871. ok = job.run ([&lastPercent] (double p) {
  20872. lastPercent = (int) (p * 100.0);
  20873. return true;
  20874. }, error);
  20875. auto joined = [] (const std::map<std::string, int>& items) {
  20876. juce::StringArray names;
  20877. for (const auto& [name, count] : items)
  20878. names.add (juce::String::fromUTF8 (name.c_str()) + "x" + juce::String (count));
  20879. return names.joinIntoString (", ");
  20880. };
  20881. const auto& importReport = loader.getImportReport();
  20882. report << "converted=" << joined (importReport.converted) << "\n"
  20883. << "approximated=" << joined (importReport.approximated) << "\n"
  20884. << "unsupported=" << joined (importReport.unsupported) << "\n"
  20885. << "not_reproduced=" << joined (importReport.notReproduced) << "\n" // (round qafix190kq)
  20886. << "dropped_effects=" << joined (importReport.droppedEffects) << "\n"
  20887. << "partial_effects=" << joined (importReport.partialEffects) << "\n"
  20888. << "missing_samples=" << importReport.missingSamples << "\n";
  20889. // third-party plugins: how each was found, or what plays in its place (diagnostics for level differences)
  20890. for (const auto& line : loader.getMatchedPlugins())
  20891. report << "plugin_found=" << line << "\n";
  20892. for (const auto& m : loader.getMissingPluginDetails())
  20893. report << "plugin_missing=" << juce::String::fromUTF8 (m.name.c_str()) << " -> "
  20894. << juce::String::fromUTF8 (m.replacement.c_str()).replace ("{0}", juce::String::fromUTF8 (m.replacementArg.c_str())) << "\n";
  20895. {
  20896. const auto& song = loader.getSong();
  20897. for (std::size_t t = 0; t < song.mixer.size(); ++t)
  20898. {
  20899. const auto& track = song.mixer[t];
  20900. if (track.effects.empty() && track.sends.empty())
  20901. continue;
  20902. report << "insert " << (int) t << " vol=" << juce::String (track.volume / lynx::unityFader, 3)
  20903. << (track.muted ? " muted" : "") << (track.toMaster ? "" : " noMaster");
  20904. for (const auto& s : track.sends)
  20905. report << " send>" << s.target << "@" << juce::String (s.level, 3);
  20906. report << " |";
  20907. for (const auto& fx : track.effects)
  20908. report << " [" << (fx.kind == lynx::EffectKind::plugin ? juce::String::fromUTF8 (fx.plugin.name.c_str())
  20909. : juce::String::fromUTF8 (lynx::effectInfo (fx.kind).name))
  20910. << (fx.isSubstitute() ? " (substitute)" : "") << (fx.enabled ? "" : " off")
  20911. << (fx.mix < 0.999f ? " mix=" + juce::String (fx.mix, 2) : juce::String()) << "]";
  20912. report << "\n";
  20913. }
  20914. }
  20915. report << juce::String (lynx::loadtrace::reportLines());
  20916. lynx::PluginHost::settingsFolder().getChildFile ("load.log").replaceWithText (juce::String (lynx::loadtrace::table()));
  20917. report << "open_ms=" << juce::roundToInt (loaded - started) << "\n"
  20918. << "prepare_ms=" << juce::roundToInt (prepared - loaded) << "\n"
  20919. << "render_ms=" << juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - prepared) << "\n"
  20920. << "graph_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().graphMs) << "\n"
  20921. << "write_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().writeMs) << "\n"
  20922. << "warmup_blocks=" << job.getEngine().getLastRenderStats().warmUp.blocks << "\n"
  20923. << "warmup_ms=" << juce::roundToInt (job.getEngine().getLastRenderStats().warmUp.wallSeconds * 1000.0) << "\n"
  20924. << "warmup_changes=" << job.getEngine().getLastRenderStats().warmUp.signatureChanges << "\n"
  20925. << "warmup_timed_out=" << (job.getEngine().getLastRenderStats().warmUp.timedOut ? 1 : 0) << "\n"
  20926. << "pdc_trim=" << job.getEngine().getLastRenderStats().trimmedSamples << "\n"
  20927. << "song_seconds=" << job.getMusicSeconds() << "\n"
  20928. << "peak=" << job.getPeak() << "\n"
  20929. << "final_progress=" << lastPercent << "\n"
  20930. << "bytes=" << output.getSize() << "\n"
  20931. << "file=" << output.getFullPathName() << "\n";
  20932. // round qafix190kq (QA-9): a silent render failed with an empty message. Say why: a project with nothing to
  20933. // play (Live's lesson sets "Playing Software Instruments" / "Recording Audio" hold no clip at all), or a
  20934. // render that stays below -60 dBFS
  20935. if (ok && job.getPeak() <= 0.001f)
  20936. {
  20937. ok = false;
  20938. error = juce::String::fromUTF8 (lynx::exportsilence::reason (loader.getSong(), patternOnly).c_str());
  20939. }
  20940. }
  20941. }
  20942. report << "result=" << (ok ? "OK" : "ERROR " + error) << "\n";
  20943. juce::File (outputPath + ".txt").replaceWithText (report);
  20944. setApplicationReturnValue (ok ? 0 : 1);
  20945. quit();
  20946. }
  20947. // LYNX.exe --snapshot prefix [project]: draws the window off-screen and writes
  20948. // prefix-rack.png, -pianoroll.png and -playlist.png (to check the UI without touching the screen).
  20949. // --editorcpu: one editor after another; each phase runs 2 s to settle and 8 s measured
  20950. struct EditorCpuRun final : juce::Timer
  20951. {
  20952. struct Case { lynx::EffectKind kind; const char* name; int type; bool demo; }; // type 0 native, 1 display-first, 2 Facet EQ
  20953. std::vector<Case> cases;
  20954. std::size_t at = 0;
  20955. int phase = 0;
  20956. double t0 = 0.0, c0 = 0.0;
  20957. juce::String report;
  20958. juce::File out;
  20959. std::unique_ptr<lynx::AudioEngine> engine;
  20960. std::unique_ptr<juce::DocumentWindow> window;
  20961. std::function<void()> done;
  20962. void start()
  20963. {
  20964. engine = std::make_unique<lynx::AudioEngine> (false);
  20965. report << "editor\tmode\tcpu % of one core\n";
  20966. open();
  20967. startTimer (250);
  20968. }
  20969. void open()
  20970. {
  20971. window.reset();
  20972. if (at >= cases.size()) { out.replaceWithText (report); stopTimer(); if (done) done(); return; }
  20973. const auto& c = cases[at];
  20974. lynx::Song song;
  20975. song.mixer.resize (2);
  20976. song.mixer[0].name = "Master";
  20977. song.mixer[1].name = "Insert 1";
  20978. song.mixer[1].effects.push_back (lynx::makeEffectSlot (c.kind));
  20979. engine->setSong (std::move (song));
  20980. engine->dispatchPendingMessages();
  20981. lynx::setNativeEditorDemo (c.demo);
  20982. auto editor = c.type == 1 ? lynx::makeProEditor (*engine, 1, 0, c.demo) : c.type == 2 ? lynx::makeFacetEqEditor (*engine, 1, 0, c.demo)
  20983. : lynx::makeNativeEffectEditor (*engine, 1, 0, 1.0f, 0);
  20984. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX editor CPU - ") + c.name, lynx::theme::colour::bg1, 0);
  20985. window->setUsingNativeTitleBar (true);
  20986. window->setContentOwned (editor.release(), true);
  20987. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  20988. window->setTopLeftPosition (area.getRight() - window->getWidth() - 8, area.getBottom() - window->getHeight() - 8);
  20989. window->setVisible (true);
  20990. phase = 0;
  20991. t0 = juce::Time::getMillisecondCounterHiRes();
  20992. }
  20993. void timerCallback() override
  20994. {
  20995. const auto now = juce::Time::getMillisecondCounterHiRes();
  20996. if (phase == 0 && now - t0 > 2000.0) { phase = 1; t0 = now; c0 = lynx::processCpuSeconds(); return; }
  20997. if (phase == 1 && now - t0 > 8000.0)
  20998. {
  20999. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  21000. const auto& c = cases[at];
  21001. report << c.name << "\t" << (c.demo ? "animating" : "idle") << "\t" << juce::String (cpu, 2) << "\n";
  21002. ++at;
  21003. open();
  21004. }
  21005. }
  21006. };
  21007. std::unique_ptr<EditorCpuRun> editorCpu;
  21008. void runEditorCpu (const juce::String& path)
  21009. {
  21010. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21011. editorCpu = std::make_unique<EditorCpuRun>();
  21012. editorCpu->out = juce::File (path);
  21013. using K = lynx::EffectKind;
  21014. for (const auto demo : { false, true })
  21015. for (const auto& c : std::vector<EditorCpuRun::Case> { { K::facetEq, "Facet EQ", 2, demo }, { K::crestCompressor, "Crest Compressor", 1, demo },
  21016. { K::apexLimiter, "Apex Limiter", 1, demo }, { K::prismMultiband, "Prism Multiband", 1, demo },
  21017. { K::epochVerb, "Epoch Verb", 0, demo }, { K::glowLeveler, "Glow Leveler", 0, demo },
  21018. { K::fruityLimiter, "Fruity Limiter", 0, demo }, { K::lynxTune, "LYNX Tune", 0, demo } })
  21019. editorCpu->cases.push_back (c);
  21020. editorCpu->done = [this] { juce::MessageManager::callAsync ([this] { editorCpu.reset(); quit(); }); };
  21021. editorCpu->start();
  21022. }
  21023. struct ParityShow
  21024. {
  21025. std::unique_ptr<lynx::AudioEngine> engine;
  21026. std::unique_ptr<juce::Component> editor;
  21027. std::unique_ptr<juce::DocumentWindow> window;
  21028. ~ParityShow() { window.reset(); editor.reset(); engine.reset(); }
  21029. };
  21030. std::shared_ptr<ParityShow> parityShow;
  21031. juce::File selfTestTemp; // --selftest: its own temp folder (round 190mo), deleted when the run ends
  21032. bool parityShotFailed = false; // --parityshot: the effect name matched no built-in effect
  21033. void runParityShot (const juce::String& path, const juce::String& effectName, const juce::String& paramsFile)
  21034. {
  21035. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21036. int kindIndex = -1;
  21037. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  21038. if (juce::String::fromUTF8 (lynx::effectInfo ((lynx::EffectKind) k).name).equalsIgnoreCase (effectName))
  21039. kindIndex = k;
  21040. if (kindIndex < 0)
  21041. {
  21042. // round tp172b7: say so and fail (a silent exit 0 hid a split effect name in a launch script)
  21043. std::fprintf (stderr, "unknown effect: %s\n", effectName.toRawUTF8());
  21044. std::fflush (stderr);
  21045. parityShotFailed = true;
  21046. return;
  21047. }
  21048. const auto kind = (lynx::EffectKind) kindIndex;
  21049. auto fx = lynx::makeEffectSlot (kind);
  21050. // round 190jd: LYNX_PARITYSHOT_VIEW=1 = the editor display's second view (Fruity Limiter: LYNX's transfer curve)
  21051. fx.displayView = (std::uint8_t) juce::jlimit (0, 1, juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_VIEW", "0").getIntValue());
  21052. if (paramsFile.isNotEmpty())
  21053. for (const auto& line : juce::StringArray::fromLines (juce::File (paramsFile).loadFileAsString()))
  21054. {
  21055. const auto t = juce::StringArray::fromTokens (line, " \t", "");
  21056. const auto index = t.size() >= 2 ? t[0].getIntValue() : -1;
  21057. if (index >= 0 && index < lynx::maxEffectParams)
  21058. fx.params[(std::size_t) index] = t[1].getFloatValue();
  21059. }
  21060. auto offlineOwner = std::make_unique<lynx::AudioEngine> (false); // (kept alive by LYNX_PARITYSHOT_SHOW's window)
  21061. auto& offline = *offlineOwner;
  21062. auto song = lynx::Song::makeDefault();
  21063. song.mixer.resize (2);
  21064. song.mixer[0].name = "Master";
  21065. song.mixer[1].name = "Insert 1";
  21066. song.mixer[1].effects.assign (1, fx);
  21067. for (auto& c : song.channels)
  21068. c.mixerTrack = 1;
  21069. offline.setSong (std::move (song));
  21070. offline.dispatchPendingMessages();
  21071. const bool facet = kind == lynx::EffectKind::facetEq;
  21072. // round tp172b4: the originals are pictured idle (nothing playing), so the display-first editors are too: no demo
  21073. // history unless LYNX_PARITYSHOT_DEMO=1 asks for the running display
  21074. const bool demoDisplay = juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_DEMO", {}) == "1";
  21075. // (Ember in its Classic voicing: the Classic panel, as the mixer opens it)
  21076. const bool pro = lynx::ProEditorWindows::handles (kind)
  21077. && ! (kind == lynx::EffectKind::ember && fx.params[(std::size_t) lynx::mixsuite::ember::voicing] > 0.5f);
  21078. auto editor = facet ? lynx::makeFacetEqEditor (offline, 1, 0, false)
  21079. : pro ? lynx::makeProEditor (offline, 1, 0, demoDisplay) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  21080. if (editor == nullptr)
  21081. return;
  21082. if (! pro) // the demo song through the effect, the editor ticked 30 times a second of audio as its timer would
  21083. {
  21084. lynx::AudioEngine::RenderOptions o;
  21085. o.seconds = 3.0;
  21086. o.sampleRate = 48000.0;
  21087. o.pluginWarmUp = false;
  21088. int sinceTick = 0;
  21089. o.capture = [&] (const float*, const float*, int n) {
  21090. sinceTick += n;
  21091. if (sinceTick < 1600) return;
  21092. sinceTick = 0;
  21093. if (facet) lynx::tickFacetEqEditor (*editor);
  21094. else lynx::tickNativeEffectEditor (*editor);
  21095. };
  21096. offline.renderOffline (o);
  21097. }
  21098. // round tp172b5: LYNX_PARITYSHOT_CLICKS drives the editor before the picture (the originals' pictures have their
  21099. // panels open), tokens in order: "x,y" a click, then the pointer leaves; "h:x,y" the pointer rests there (a hover);
  21100. // "d:x,y,x2,y2" a drag from there to there, the button still down in the picture
  21101. for (const auto& token : juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_CLICKS", {}), " ", ""))
  21102. {
  21103. const auto hover = token.startsWith ("h:"), drag = token.startsWith ("d:");
  21104. const auto xy = juce::StringArray::fromTokens (hover || drag ? token.substring (2) : token, ",", "");
  21105. if (xy.size() < (drag ? 4 : 2))
  21106. continue;
  21107. const juce::Point<int> at (xy[0].getIntValue(), xy[1].getIntValue());
  21108. editor->setVisible (true); // (getComponentAt finds nothing in a hidden component; it never goes on screen)
  21109. auto* target = editor->getComponentAt (at);
  21110. if (target == nullptr)
  21111. continue;
  21112. const auto local = target->getLocalPoint (editor.get(), at).toFloat();
  21113. const auto now = juce::Time::getCurrentTime();
  21114. auto source = juce::Desktop::getInstance().getMainMouseSource();
  21115. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier);
  21116. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys mods, bool dragged) {
  21117. return juce::MouseEvent (source, p, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, target, target, now, local, now, 1, dragged);
  21118. };
  21119. target->mouseMove (event (local, {}, false));
  21120. if (hover)
  21121. continue;
  21122. target->mouseDown (event (local, left, false));
  21123. if (drag)
  21124. {
  21125. const auto end = target->getLocalPoint (editor.get(), juce::Point<int> (xy[2].getIntValue(), xy[3].getIntValue())).toFloat();
  21126. target->mouseDrag (event (end, left, true));
  21127. continue;
  21128. }
  21129. target->mouseUp (event (local, {}, false));
  21130. target->mouseExit (event ({ -1000.0f, -1000.0f }, {}, false));
  21131. offline.dispatchPendingMessages(); // (round 190jd: an edit the click made, e.g. a display view, reaches the slot)
  21132. }
  21133. // round tp172b6: LYNX_PARITYSHOT_SHOW=1 puts the same editor in a real window and keeps it open (for a guarded GUI check
  21134. // of its pop-up menus, which the offscreen picture cannot hold); closing the window quits
  21135. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PARITYSHOT_SHOW", {}) == "1")
  21136. {
  21137. struct ShowWindow final : juce::DocumentWindow
  21138. {
  21139. ShowWindow() : juce::DocumentWindow ("LYNX parity check", juce::Colours::black, juce::DocumentWindow::closeButton) {}
  21140. void closeButtonPressed() override { juce::JUCEApplication::getInstance()->systemRequestedQuit(); }
  21141. };
  21142. parityShow = std::make_shared<ParityShow>();
  21143. parityShow->engine = std::move (offlineOwner);
  21144. parityShow->editor = std::move (editor);
  21145. auto window = std::make_unique<ShowWindow>();
  21146. window->setUsingNativeTitleBar (true);
  21147. window->setContentNonOwned (parityShow->editor.get(), true);
  21148. window->setTopLeftPosition (80, 80);
  21149. window->setVisible (true);
  21150. parityShow->window = std::move (window);
  21151. return;
  21152. }
  21153. // round 190ar: LYNX_PARITYSHOT_SCALE=2 draws the same editor at twice the pixel density (as on a 200 % display);
  21154. // round 190bi: the shared shot scale (--shot-scale, LYNX_SHOT_SCALE, LYNX_PARITYSHOT_SCALE as before)
  21155. const auto shotScale = lynx::shot::scale();
  21156. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) editor->getWidth() * shotScale), juce::roundToInt ((float) editor->getHeight() * shotScale), true);
  21157. {
  21158. juce::Graphics g (image);
  21159. g.fillAll (lynx::theme::panel);
  21160. g.addTransform (juce::AffineTransform::scale (shotScale));
  21161. editor->paintEntireComponent (g, false);
  21162. }
  21163. const auto file = lynx::shot::file (juce::File (path));
  21164. file.deleteFile();
  21165. juce::PNGImageFormat png;
  21166. if (auto stream = file.createOutputStream())
  21167. png.writeImageToStream (image, *stream);
  21168. }
  21169. // an Audio Effect Rack shaped like Live's reference (REA_rodada183c §8): two chains with chain-select zones and fades,
  21170. // four named macros (one on a chain's volume, one on two parameters), two variations, every view open
  21171. static lynx::EffectSlot shotRack()
  21172. {
  21173. auto slot = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  21174. auto& doc = slot.patcher;
  21175. doc.rack[0].chains[0].name = "Vocoder";
  21176. lynx::PatchNode vocoder, eq, verb;
  21177. vocoder.effect = lynx::makeEffectSlot (lynx::EffectKind::vocodex);
  21178. eq.effect = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  21179. verb.effect = lynx::makeEffectSlot (lynx::EffectKind::reeverb2);
  21180. const auto nVoc = lynx::rack::addDevice (doc, 0, vocoder);
  21181. const auto nEq = lynx::rack::addDevice (doc, 0, eq);
  21182. lynx::rack::addChain (doc, "dry bypass");
  21183. lynx::rack::addDevice (doc, 1, verb);
  21184. doc.rack[0].chains[0].select = { 0, 79, 0, 63 };
  21185. doc.rack[0].chains[1].select = { 32, 127, 48, 127 };
  21186. lynx::rack::setChainVolume (doc, 0, 0.33f);
  21187. lynx::rack::setChainVolume (doc, 1, 0.5f);
  21188. const char* names[] { "Sibilance", "Intensity", "Formant Shift", "Bright Level" };
  21189. for (int m = 0; m < 4; ++m)
  21190. doc.rack[0].macros[(std::size_t) m].name = names[m];
  21191. lynx::RackMapping vol;
  21192. vol.target = lynx::RackMapping::Target::chainVolume, vol.chain = 0, vol.min = 0.0f, vol.max = lynx::rack::unityVolume;
  21193. lynx::rack::map (doc, 0, vol);
  21194. lynx::RackMapping a, b, c, d;
  21195. a.node = nVoc, a.param = 0;
  21196. b.node = nVoc, b.param = 1, b.min = 0.2f, b.max = 0.8f;
  21197. c.node = nEq, c.param = 0, c.min = 0.3f, c.max = 0.9f;
  21198. d.node = nEq, d.param = 1;
  21199. lynx::rack::map (doc, 1, a);
  21200. lynx::rack::map (doc, 2, b);
  21201. lynx::rack::map (doc, 3, c);
  21202. lynx::rack::map (doc, 3, d);
  21203. lynx::rack::setMacro (doc, 0, 60.0f);
  21204. lynx::rack::setMacro (doc, 1, 40.0f);
  21205. lynx::rack::setMacro (doc, 2, 70.0f);
  21206. lynx::rack::setMacro (doc, 3, 86.0f);
  21207. lynx::rack::storeVariation (doc);
  21208. lynx::rack::renameVariation (doc, 0, "Verse");
  21209. lynx::rack::setMacro (doc, 3, 120.0f);
  21210. lynx::rack::storeVariation (doc);
  21211. lynx::rack::renameVariation (doc, 1, "Drop");
  21212. lynx::rack::launchVariation (doc, 0);
  21213. auto& r = doc.rack[0];
  21214. r.showMacros = r.showChains = r.showDevices = r.showVariations = true;
  21215. r.zoneEditor = 2;
  21216. r.selectedChain = 0;
  21217. lynx::rack::setSelector (doc, 56.0f);
  21218. lynx::rack::compile (doc);
  21219. return slot;
  21220. }
  21221. bool runRackShots (const juce::File& out, const juce::String& liveSet = {})
  21222. {
  21223. out.createDirectory();
  21224. lynx::AudioEngine offline (false);
  21225. auto save = [&] (juce::Component& c, const juce::String& name) {
  21226. auto image = lynx::shot::paint (c, lynx::theme::panel);
  21227. const auto f = lynx::shot::file (out.getChildFile (name));
  21228. f.deleteFile();
  21229. juce::PNGImageFormat png;
  21230. if (auto stream = f.createOutputStream())
  21231. return png.writeImageToStream (image, *stream);
  21232. return false;
  21233. };
  21234. auto song = lynx::Song::makeDefault();
  21235. song.mixer.resize (3);
  21236. song.mixer[1].name = "Vocal Main";
  21237. auto slot = shotRack();
  21238. song.mixer[1].effects = { slot };
  21239. // an Instrument Rack: three chains split over the keyboard
  21240. lynx::ChannelDef inst;
  21241. inst.name = "Keys Rack";
  21242. inst.instrument = lynx::InstrumentKind::patcher;
  21243. inst.patcher = lynx::rack::makeRack (lynx::RackDoc::Kind::instrument);
  21244. for (int k = 0; k < 3; ++k)
  21245. {
  21246. if (k > 0)
  21247. lynx::rack::addChain (inst.patcher);
  21248. lynx::PatchNode synth;
  21249. synth.generator = true;
  21250. synth.channel.instrument = lynx::InstrumentKind::synth;
  21251. synth.channel.name = "Synth";
  21252. lynx::rack::addDevice (inst.patcher, k, synth);
  21253. }
  21254. inst.patcher.rack[0].chains[0].key = { 0, 52, 0, 47 };
  21255. inst.patcher.rack[0].chains[1].key = { 48, 76, 53, 71 };
  21256. inst.patcher.rack[0].chains[2].key = { 72, 127, 77, 127 };
  21257. inst.patcher.rack[0].chains[0].name = "Low";
  21258. inst.patcher.rack[0].chains[1].name = "Mid";
  21259. inst.patcher.rack[0].chains[2].name = "High";
  21260. inst.patcher.rack[0].showChains = inst.patcher.rack[0].showDevices = true;
  21261. inst.patcher.rack[0].zoneEditor = 0;
  21262. lynx::rack::compile (inst.patcher);
  21263. song.channels.push_back (inst);
  21264. const auto channel = (int) song.channels.size() - 1;
  21265. offline.setSong (std::move (song));
  21266. offline.dispatchPendingMessages();
  21267. bool ok = true;
  21268. // [set.als]: a Live set's racks as LYNX imports them, the one with the most chains drawn with its title bar (the
  21269. // like-for-like pair with Live's own picture of that set)
  21270. if (liveSet.isNotEmpty())
  21271. {
  21272. juce::MemoryBlock bytes;
  21273. juce::File (liveSet).loadFileAsData (bytes);
  21274. const std::vector<std::uint8_t> data ((const std::uint8_t*) bytes.getData(), (const std::uint8_t*) bytes.getData() + bytes.getSize());
  21275. lynx::AlsImportOptions o;
  21276. o.common.projectFolder = juce::File (liveSet).getParentDirectory().getFullPathName().toStdString();
  21277. std::string error;
  21278. if (auto imported = lynx::importAls (data, o, &error))
  21279. {
  21280. int bestTrack = -1, bestSlot = -1;
  21281. std::size_t most = 0;
  21282. for (int t = 0; t < (int) imported->mixer.size(); ++t)
  21283. for (int s = 0; s < (int) imported->mixer[(std::size_t) t].effects.size(); ++s)
  21284. 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)
  21285. most = fx.patcher.rack[0].chains.size(), bestTrack = t, bestSlot = s;
  21286. if (bestTrack >= 0)
  21287. {
  21288. offline.setSong (std::move (*imported));
  21289. offline.dispatchPendingMessages();
  21290. auto view = lynx::RackWindows::makeSlotView (offline, bestTrack, bestSlot, true);
  21291. view->setSize (view->preferredWidth (228), 228);
  21292. ok = save (*view, "rack-live-import.png") && ok;
  21293. view->setMapMode (true);
  21294. view->setSize (view->preferredWidth (228), 228);
  21295. ok = save (*view, "rack-live-import-map.png") && ok;
  21296. return ok;
  21297. }
  21298. }
  21299. return false;
  21300. }
  21301. {
  21302. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, false);
  21303. view->setSize (view->preferredWidth (206), 206);
  21304. ok = save (*view, "rack-deviceview.png") && ok;
  21305. }
  21306. {
  21307. auto view = lynx::RackWindows::makeSlotView (offline, 1, 0, true);
  21308. view->setMapMode (true);
  21309. view->setSize (view->preferredWidth (228), 228);
  21310. ok = save (*view, "rack-mapmode.png") && ok;
  21311. }
  21312. {
  21313. auto view = lynx::RackWindows::makeChannelView (offline, channel, true);
  21314. view->setSize (view->preferredWidth (228), 228);
  21315. ok = save (*view, "rack-instrument.png") && ok;
  21316. }
  21317. return ok;
  21318. }
  21319. void runEq166fShots (const juce::String& folder)
  21320. {
  21321. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21322. const juce::File out (folder);
  21323. out.createDirectory();
  21324. lynx::AudioEngine offline (false);
  21325. auto save = [&] (juce::Component& editor, const juce::String& name) {
  21326. auto image = lynx::shot::paint (editor, lynx::theme::panel);
  21327. const auto f = lynx::shot::file (out.getChildFile (name));
  21328. f.deleteFile();
  21329. juce::PNGImageFormat png;
  21330. if (auto stream = f.createOutputStream())
  21331. png.writeImageToStream (image, *stream);
  21332. };
  21333. // a song whose demo beat plays into insert 1 (the source) and, for Facet's target, its other half into insert 2
  21334. auto songWith = [] (const lynx::EffectSlot& fx, bool split) {
  21335. auto song = lynx::Song::makeDefault();
  21336. song.mixer.resize (3);
  21337. song.mixer[0].name = "Master";
  21338. song.mixer[1].name = "Vocal";
  21339. song.mixer[2].name = "Reference mix";
  21340. song.mixer[1].effects.assign (1, fx);
  21341. for (std::size_t c = 0; c < song.channels.size(); ++c)
  21342. song.channels[c].mixerTrack = split && c % 2 == 1 ? 2 : 1;
  21343. return song;
  21344. };
  21345. auto feed = [&] (juce::Component& editor, bool facet, int frames) {
  21346. // one continuous render of the song, the editor ticked 30 times a second of audio, as its timer would
  21347. lynx::AudioEngine::RenderOptions o;
  21348. o.seconds = frames / 30.0;
  21349. o.sampleRate = 48000.0;
  21350. o.pluginWarmUp = false;
  21351. int sinceTick = 0;
  21352. o.capture = [&] (const float*, const float*, int n) {
  21353. sinceTick += n;
  21354. if (sinceTick < 1600) return;
  21355. sinceTick = 0;
  21356. if (facet) lynx::tickFacetEqEditor (editor);
  21357. else lynx::tickNativeEffectEditor (editor);
  21358. };
  21359. offline.renderOffline (o);
  21360. if (facet) lynx::tickFacetEqEditor (editor);
  21361. else lynx::tickNativeEffectEditor (editor);
  21362. };
  21363. // Parametric EQ 2: spectrum + heatmap (Full), flat / band 4 +12 dB / band 4 -12 dB, then the Top position
  21364. auto& display = lynx::peqview::displaySettings();
  21365. const auto kept = display;
  21366. display.spectrum = display.heatmap = true;
  21367. display.position = 0;
  21368. 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" },
  21369. { 0.0, "peq2-heatmap-top.png" } })
  21370. {
  21371. auto eq = lynx::makeEffectSlot (lynx::EffectKind::parametricEq);
  21372. eq.params[(std::size_t) lynx::peq::param (3, 2)] = lynx::peq::gainValue (gain);
  21373. eq.params[(std::size_t) lynx::peq::param (3, 1)] = lynx::peq::hzValue (900.0);
  21374. display.position = juce::String (name).contains ("top") ? 1 : 0;
  21375. offline.setSong (songWith (eq, false));
  21376. offline.dispatchPendingMessages();
  21377. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, 0);
  21378. feed (*editor, false, 120);
  21379. save (*editor, name);
  21380. }
  21381. display = kept;
  21382. // Facet EQ's comparative EQ: listening to the target (insert 2) with its spectrum over the source's
  21383. {
  21384. using namespace lynx::facet;
  21385. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  21386. eq.params[(std::size_t) param (0, 0)] = shapeValue (Shape::bell);
  21387. eq.params[(std::size_t) param (0, 1)] = hzValue (250.0);
  21388. eq.params[(std::size_t) param (0, 2)] = gainValue (-4.0);
  21389. eq.params[(std::size_t) param (1, 0)] = shapeValue (Shape::highShelf);
  21390. eq.params[(std::size_t) param (1, 1)] = hzValue (6000.0);
  21391. eq.params[(std::size_t) param (1, 2)] = gainValue (3.0);
  21392. eq.params[(std::size_t) analyzerParam] = analyzerValue (Analyzer::both);
  21393. eq.sidechain = 2;
  21394. for (const auto& [l, name] : { std::pair { Listen::target, "facet-compare-target.png" }, { Listen::eq, "facet-compare-eq.png" } })
  21395. {
  21396. eq.params[(std::size_t) listenParam] = listenValue (l);
  21397. offline.setSong (songWith (eq, true));
  21398. offline.dispatchPendingMessages();
  21399. auto editor = lynx::makeFacetEqEditor (offline, 1, 0, false);
  21400. feed (*editor, true, 90);
  21401. save (*editor, name);
  21402. }
  21403. }
  21404. }
  21405. void runDesign168rShots (const juce::String& folder)
  21406. {
  21407. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21408. const juce::File out (folder);
  21409. out.createDirectory();
  21410. lynx::AudioEngine offline (false);
  21411. using K = lynx::EffectKind;
  21412. for (const auto kind : { K::pitchCorrect, K::lovePhilter, K::peakController, K::spreader, K::fruityFastLP, K::flFrequencyShifter,
  21413. K::flLowLifter, K::distructor, K::flBassBoost, K::flDelay1, K::fl7BandEq, K::flCenter, K::flPhaseInverter,
  21414. K::eq, K::delay, K::reverb, K::limiter, K::filter, K::distortion, K::chorus, K::utility, K::lofi,
  21415. K::crossover, K::pitchShift, K::freqShift, K::rhythmGain, K::volumeGate })
  21416. {
  21417. const auto& bank = lynx::presets::factory (kind);
  21418. // Love Philter / Distructor play FL's state: their second picture is FL's default preset (when installed)
  21419. std::optional<lynx::EffectSlot> flPreset;
  21420. if (kind == K::lovePhilter || kind == K::distructor)
  21421. {
  21422. const auto roots = lynx::findFlStudioRoots();
  21423. const auto file = juce::File (juce::String::fromUTF8 (roots.data.c_str()))
  21424. .getChildFile ("Patches/Plugin presets/Effects")
  21425. .getChildFile (kind == K::lovePhilter ? "Fruity Love Philter/Default.fst" : "Distructor/Default.fst");
  21426. juce::MemoryBlock bytes;
  21427. if (file.loadFileAsData (bytes))
  21428. flPreset = lynx::effectFromFlPreset (std::vector<std::uint8_t> ((const std::uint8_t*) bytes.getData(),
  21429. (const std::uint8_t*) bytes.getData() + bytes.getSize()));
  21430. }
  21431. for (int pass = 0; pass < (bank.empty() && ! flPreset ? 1 : 2); ++pass)
  21432. {
  21433. auto fx = lynx::makeEffectSlot (kind);
  21434. if (pass == 1 && flPreset)
  21435. fx = *flPreset;
  21436. else if (pass == 1)
  21437. {
  21438. fx.params = lynx::presets::apply (kind, bank.front(), 120.0);
  21439. fx.presetName = bank.front().name;
  21440. }
  21441. lynx::Song song;
  21442. song.mixer.resize (2);
  21443. song.mixer[0].name = "Master";
  21444. song.mixer[1].name = "Insert 1";
  21445. song.mixer[1].effects.push_back (fx);
  21446. offline.setSong (std::move (song));
  21447. offline.dispatchPendingMessages();
  21448. const auto pages = juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  21449. for (const auto scale : { 1.0f, 2.0f })
  21450. for (int page = 0; page < pages; ++page)
  21451. {
  21452. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, scale, page);
  21453. if (editor == nullptr)
  21454. continue;
  21455. juce::Image image (juce::Image::ARGB, juce::jmax (1, editor->getWidth()), juce::jmax (1, editor->getHeight()), true);
  21456. {
  21457. juce::Graphics g (image);
  21458. g.fillAll (lynx::theme::panel);
  21459. editor->paintEntireComponent (g, false);
  21460. }
  21461. // (FL's "Frequency Shifter" and LYNX's "Frequency shifter" differ only in case: FL editors get "FL ")
  21462. const auto file = out.getChildFile ((lynx::plugui::hasFlLayout (kind) ? "FL " : "")
  21463. + juce::String (lynx::effectInfo (kind).name).replaceCharacters ("/\\:", "---")
  21464. + (pass == 1 ? "-preset" : "") + (page > 0 ? "-p" + juce::String (page + 1) : juce::String())
  21465. + (scale > 1.5f ? "-200" : "-100") + ".png");
  21466. file.deleteFile();
  21467. juce::PNGImageFormat png;
  21468. if (auto stream = file.createOutputStream())
  21469. png.writeImageToStream (image, *stream);
  21470. }
  21471. }
  21472. }
  21473. }
  21474. bool runInstrumentShots (const juce::File& folder, const juce::String& which, const juce::String& source)
  21475. {
  21476. folder.createDirectory();
  21477. auto key = [] (juce::String n) { return n.toLowerCase().removeCharacters (" -!._"); };
  21478. juce::StringArray wanted;
  21479. wanted.addTokens (which, ",", "");
  21480. auto ok = true;
  21481. struct Shot
  21482. {
  21483. juce::String name;
  21484. std::optional<lynx::ChannelDef> channel;
  21485. };
  21486. std::vector<Shot> shots;
  21487. for (const auto& e : lynx::natives::instrumentEngines())
  21488. {
  21489. const auto name = key (e.name);
  21490. const auto banked = which == "banks" && lynx::banks::hasBank (e.kind);
  21491. if (! banked && ! wanted.contains (name))
  21492. continue;
  21493. auto channel = source == "fl" || source == "flm" ? lynx::natives::makeChannel (e.kind, lynx::flStudioAccess())
  21494. : lynx::banks::defaultChannel (e.kind, e.name);
  21495. // (round 190u) source "flm": the channel as the .flm import makes it (Transistor Bass: FL Studio Mobile's build)
  21496. if (source == "flm" && channel && e.kind == lynx::InstrumentKind::transistorbass)
  21497. {
  21498. 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
  21499. channel->modelParams = { 1.0f };
  21500. channel->samplePath.clear();
  21501. }
  21502. if (! channel)
  21503. {
  21504. std::fprintf (stderr, "%s: no %s channel\n", e.name, source.toRawUTF8());
  21505. ok = false;
  21506. continue;
  21507. }
  21508. shots.push_back ({ name, std::move (channel) });
  21509. }
  21510. // Autogun (round 169h): not in the Add menus (no preset files); FL's own render-test channel, either source
  21511. if (wanted.contains ("autogun"))
  21512. {
  21513. if (auto channel = lynx::natives::autogunShotChannel (lynx::flStudioAccess()))
  21514. shots.push_back ({ "autogun", std::move (channel) });
  21515. else
  21516. {
  21517. std::fprintf (stderr, "Autogun: no channel (FL Studio's Render tests\\Autogun.flp)\n");
  21518. ok = false;
  21519. }
  21520. }
  21521. for (auto& shot : shots)
  21522. {
  21523. const auto& name = shot.name;
  21524. auto& channel = shot.channel;
  21525. lynx::AudioEngine offline (false);
  21526. lynx::Song song;
  21527. song.mixer = lynx::Song::defaultMixer (2);
  21528. song.channels.push_back (*channel);
  21529. song.patterns.emplace_back();
  21530. {
  21531. juce::String error; // the project too, so an older build can picture the same channel (--snapshot)
  21532. lynx::ProjectFile::save (song, folder.getChildFile (name + "-" + source + ".lynx"), error);
  21533. }
  21534. offline.setSong (std::move (song));
  21535. offline.dispatchPendingMessages();
  21536. auto frame = lynx::makeChannelFrame (offline, 0, 0);
  21537. if (frame == nullptr || frame->getWidth() <= 0)
  21538. {
  21539. ok = false;
  21540. continue;
  21541. }
  21542. for (const auto scale : { 1.0f, 1.5f, 2.0f })
  21543. {
  21544. const auto file = folder.getChildFile (name + "-" + source + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  21545. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, scale), file.getFullPathName());
  21546. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), frame->getWidth(), frame->getHeight());
  21547. }
  21548. // round 169h: the layout's other pages (Toxic's MIDI / Seq …), one shot each at 1.5×
  21549. for (int page = 1; page < lynx::showChannelLayoutPage (*frame, -1); ++page)
  21550. {
  21551. lynx::showChannelLayoutPage (*frame, page);
  21552. const auto file = folder.getChildFile (name + "-" + source + "-page" + juce::String (page) + "-150.png");
  21553. savePng (frame->createComponentSnapshot (frame->getLocalBounds(), true, 1.5f), file.getFullPathName());
  21554. std::printf ("%s\n", file.getFullPathName().toRawUTF8());
  21555. }
  21556. }
  21557. return ok;
  21558. }
  21559. // --- round 170j: the pilot editors with their own art -------------------------------------------------
  21560. struct ArtPilot
  21561. {
  21562. std::string file; // the art's name as a file name: "toxic-biohazard"
  21563. bool instrument;
  21564. lynx::InstrumentKind instrumentKind;
  21565. lynx::EffectKind effectKind;
  21566. lynx::skin::Style before; // the automatic style it had before the Themed style
  21567. };
  21568. static juce::StringArray& artOnly() // --artshot / --artgui: only these (file names), all when empty
  21569. {
  21570. static juce::StringArray only;
  21571. return only;
  21572. }
  21573. // every plugin with art of its own (round 170j/170k): generators first, then effects; built from the art
  21574. // registries, so a new theme is shot without touching this list
  21575. static const std::vector<ArtPilot>& artPilots()
  21576. {
  21577. using I = lynx::InstrumentKind;
  21578. using E = lynx::EffectKind;
  21579. static const std::vector<ArtPilot> list = [] {
  21580. std::vector<ArtPilot> all;
  21581. auto slug = [] (lynx::skin::Art a) {
  21582. return juce::String (lynx::skin::artName (a)).toLowerCase().replaceCharacters (" ", "-").removeCharacters ("!.()'").toStdString();
  21583. };
  21584. for (const auto& e : lynx::natives::instrumentEngines()) // (the engines' order first)
  21585. if (const auto a = lynx::skin::artForInstrument (e.kind); a != lynx::skin::Art::none)
  21586. all.push_back ({ slug (a), true, e.kind, E::reverb, lynx::skin::Style::neon });
  21587. for (int k = 0; k <= (int) I::wavetraveller; ++k) // then every other kind with art (DrumSynth, Autogun, Wasp...)
  21588. if (const auto a = lynx::skin::artForInstrument ((I) k); a != lynx::skin::Art::none)
  21589. all.push_back ({ slug (a), true, (I) k, E::reverb, lynx::skin::Style::neon });
  21590. for (int k = 0; k <= (int) lynx::lastEffectKind; ++k)
  21591. if (const auto a = lynx::skin::artForEffect ((E) k); a != lynx::skin::Art::none)
  21592. all.push_back ({ slug (a), false, I::synth, (E) k, lynx::skin::plainStyleFor (k) });
  21593. std::vector<ArtPilot> kept;
  21594. for (auto& p : all)
  21595. if (artOnly().isEmpty() || artOnly().contains (juce::String (p.file)))
  21596. if (std::none_of (kept.begin(), kept.end(), [&] (const ArtPilot& q) { return q.file == p.file; }))
  21597. kept.push_back (p);
  21598. return kept;
  21599. }();
  21600. return list;
  21601. }
  21602. // the song and the editor of a pilot (an instrument: the channel window on its Plugin tab)
  21603. static std::unique_ptr<juce::Component> makeArtPilot (lynx::AudioEngine& engine, const ArtPilot& p)
  21604. {
  21605. lynx::Song song;
  21606. song.mixer = lynx::Song::defaultMixer (2);
  21607. if (p.instrument)
  21608. {
  21609. for (const auto& e : lynx::natives::instrumentEngines())
  21610. if (e.kind == p.instrumentKind)
  21611. {
  21612. auto channel = lynx::natives::makeChannel (e.kind, lynx::flStudioAccess());
  21613. if (! channel) channel = lynx::banks::defaultChannel (e.kind, e.name);
  21614. if (! channel) return nullptr;
  21615. song.channels.push_back (*channel);
  21616. break;
  21617. }
  21618. if (song.channels.empty()) // a kind without an engine entry: its LYNX default, else an empty channel of that kind
  21619. {
  21620. const std::string name = lynx::skin::artName (lynx::skin::artForInstrument (p.instrumentKind));
  21621. auto channel = lynx::banks::defaultChannel (p.instrumentKind, name);
  21622. if (! channel)
  21623. {
  21624. channel = lynx::ChannelDef {};
  21625. channel->instrument = p.instrumentKind;
  21626. channel->name = name;
  21627. }
  21628. song.channels.push_back (*channel);
  21629. }
  21630. song.patterns.emplace_back();
  21631. }
  21632. else
  21633. {
  21634. song.mixer[1].effects.push_back (lynx::makeEffectSlot (p.effectKind));
  21635. }
  21636. engine.setSong (std::move (song));
  21637. engine.dispatchPendingMessages();
  21638. if (p.instrument) return lynx::makeChannelFrame (engine, 0, 0);
  21639. if (p.effectKind == lynx::EffectKind::facetEq) return lynx::makeFacetEqEditor (engine, 1, 0, true);
  21640. if (lynx::ProEditorWindows::handles (p.effectKind)) return lynx::makeProEditor (engine, 1, 0, true); // display-first editors, demo signal
  21641. return lynx::makeNativeEffectEditor (engine, 1, 0, 1.0f, 0);
  21642. }
  21643. // "before": the style each pilot had (forced for its run); "after": automatic (the pilots are Themed)
  21644. static void artPilotStyle (const ArtPilot& p, const juce::String& mode)
  21645. {
  21646. lynx::skin::setForcedStyle (mode == "before" ? (int) p.before : -1);
  21647. lynx::skin::setArtMotion (mode != "still");
  21648. }
  21649. bool runArtShots (const juce::File& folder, bool before)
  21650. {
  21651. folder.createDirectory();
  21652. auto ok = true;
  21653. juce::String titles ("editor\tsize\twidth\tname width at the style's size\tbox\tsize used\tlines\tresult\n");
  21654. for (const auto& p : artPilots())
  21655. {
  21656. artPilotStyle (p, before ? "before" : "after");
  21657. lynx::AudioEngine offline (false);
  21658. auto editor = makeArtPilot (offline, p);
  21659. if (editor == nullptr || editor->getWidth() <= 0)
  21660. {
  21661. std::fprintf (stderr, "%s: no editor\n", p.file.c_str());
  21662. ok = false;
  21663. continue;
  21664. }
  21665. if (p.effectKind == lynx::EffectKind::facetEq) lynx::tickFacetEqEditor (*editor);
  21666. // round 170k2: titles.tsv, how the header's name fitted (its width at the style's size, the box, the size used)
  21667. auto fit = [&] (const juce::String& at) {
  21668. const auto f = lynx::skin::lastTitleFit();
  21669. if (f.have <= 0.0f) return; // no plugin header drawn (a generator's channel window)
  21670. titles << juce::String (p.file) << "\t" << at << "\t" << editor->getWidth() << "\t" << juce::String (f.need, 1) << "\t" << juce::String (f.have, 1)
  21671. << "\t" << juce::String (f.size, 1) << "\t" << f.lines << "\t" << (f.clipped ? "ELLIPSIS" : "full") << "\n";
  21672. };
  21673. for (const auto scale : { 1.0f, 2.0f })
  21674. {
  21675. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-" + juce::String (juce::roundToInt (scale * 100)) + ".png");
  21676. lynx::skin::resetTitleFit();
  21677. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, scale), file.getFullPathName());
  21678. std::printf ("%s %dx%d\n", file.getFullPathName().toRawUTF8(), editor->getWidth(), editor->getHeight());
  21679. if (scale == 1.0f) fit ("100");
  21680. }
  21681. // ... and at the smallest size its window allows (effect panels; the Pro editors scale as a whole)
  21682. if (const auto smallest = lynx::nativeEditorMinimumSize (*editor); smallest.x > 0)
  21683. {
  21684. editor->setSize (smallest.x, smallest.y);
  21685. const auto file = folder.getChildFile (juce::String (p.file) + "-" + (before ? "before" : "after") + "-min.png");
  21686. lynx::skin::resetTitleFit();
  21687. savePng (lynx::shot::snapshot (*editor), file.getFullPathName());
  21688. fit ("min");
  21689. }
  21690. }
  21691. folder.getChildFile (juce::String ("titles-") + (before ? "before" : "after") + ".tsv").replaceWithText (titles);
  21692. lynx::skin::setForcedStyle (-1);
  21693. return ok;
  21694. }
  21695. struct ArtGuiRun final : juce::Timer
  21696. {
  21697. juce::File folder;
  21698. juce::String mode, report;
  21699. std::size_t at = 0;
  21700. int phase = 0;
  21701. double t0 = 0.0, c0 = 0.0;
  21702. std::unique_ptr<lynx::AudioEngine> engine;
  21703. std::unique_ptr<juce::DocumentWindow> window;
  21704. std::function<void()> done;
  21705. void start()
  21706. {
  21707. engine = std::make_unique<lynx::AudioEngine> (false);
  21708. report << "editor\tmode\tcpu % of one core\tart layer animating\n";
  21709. open();
  21710. startTimer (100);
  21711. }
  21712. void open()
  21713. {
  21714. window.reset();
  21715. const auto& pilots = artPilots();
  21716. if (at >= pilots.size())
  21717. {
  21718. folder.getChildFile ("cpu-" + mode + ".txt").replaceWithText (report);
  21719. stopTimer();
  21720. lynx::skin::setForcedStyle (-1);
  21721. lynx::skin::setArtMotion (true);
  21722. if (done) done();
  21723. return;
  21724. }
  21725. const auto& p = pilots[at];
  21726. artPilotStyle (p, mode);
  21727. auto editor = makeArtPilot (*engine, p);
  21728. if (editor == nullptr) { ++at; open(); return; }
  21729. window = std::make_unique<juce::DocumentWindow> (juce::String ("LYNX art - ") + juce::String (p.file), lynx::theme::colour::bg1, 0);
  21730. window->setUsingNativeTitleBar (true);
  21731. window->setContentOwned (editor.release(), true);
  21732. const auto area = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->userArea;
  21733. window->setTopLeftPosition (area.getX() + 24, area.getY() + 24);
  21734. window->setAlwaysOnTop (true);
  21735. window->setVisible (true);
  21736. phase = 0;
  21737. t0 = juce::Time::getMillisecondCounterHiRes();
  21738. }
  21739. bool animating() const
  21740. {
  21741. if (window == nullptr || window->getContentComponent() == nullptr) return false;
  21742. std::function<bool (juce::Component&)> find = [&] (juce::Component& c) {
  21743. if (auto* l = dynamic_cast<lynx::skin::ArtLayer*> (&c); l != nullptr && l->animating()) return true;
  21744. for (auto* child : c.getChildren())
  21745. if (find (*child)) return true;
  21746. return false;
  21747. };
  21748. return find (*window->getContentComponent());
  21749. }
  21750. void timerCallback() override
  21751. {
  21752. const auto now = juce::Time::getMillisecondCounterHiRes();
  21753. const auto& p = artPilots()[at];
  21754. const auto ready = folder.getChildFile (juce::String (p.file) + "-" + mode + ".ready");
  21755. const auto shotDone = folder.getChildFile (juce::String (p.file) + "-" + mode + ".done");
  21756. if (phase == 0 && now - t0 > 1500.0)
  21757. {
  21758. // the window's content on screen, in physical pixels, for the outside screenshot to crop
  21759. auto* c = window->getContentComponent();
  21760. const auto scale = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  21761. const auto b = c->getScreenBounds();
  21762. shotDone.deleteFile();
  21763. ready.replaceWithText (juce::String (juce::roundToInt (b.getX() * scale)) + " " + juce::String (juce::roundToInt (b.getY() * scale)) + " "
  21764. + juce::String (juce::roundToInt (b.getWidth() * scale)) + " " + juce::String (juce::roundToInt (b.getHeight() * scale)));
  21765. phase = 1;
  21766. t0 = now;
  21767. return;
  21768. }
  21769. if (phase == 1 && (shotDone.existsAsFile() || now - t0 > 10000.0))
  21770. {
  21771. ready.deleteFile();
  21772. shotDone.deleteFile();
  21773. phase = 2;
  21774. t0 = now;
  21775. c0 = lynx::processCpuSeconds();
  21776. return;
  21777. }
  21778. if (phase == 2 && now - t0 > 6000.0)
  21779. {
  21780. const auto cpu = (lynx::processCpuSeconds() - c0) / ((now - t0) * 0.001) * 100.0;
  21781. report << juce::String (p.file) << "\t" << mode << "\t" << juce::String (cpu, 2) << "\t" << (animating() ? "yes" : "no") << "\n";
  21782. ++at;
  21783. open();
  21784. }
  21785. }
  21786. };
  21787. std::unique_ptr<ArtGuiRun> artGui;
  21788. void runArtGui (const juce::File& folder, const juce::String& mode)
  21789. {
  21790. folder.createDirectory();
  21791. artGui = std::make_unique<ArtGuiRun>();
  21792. artGui->folder = folder;
  21793. artGui->mode = mode;
  21794. artGui->done = [this] { juce::MessageManager::callAsync ([this] { artGui.reset(); quit(); }); };
  21795. artGui->start();
  21796. }
  21797. void runDesign190inShot (const juce::String& prefix, const juce::String& project)
  21798. {
  21799. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21800. juce::String report;
  21801. {
  21802. lynx::AudioEngine engine (false);
  21803. juce::String error;
  21804. if (const juce::File input (project); input.existsAsFile() && input.hasFileExtension ("flp"))
  21805. report << "import: " << (engine.importFlpFile (input, error) ? "ok" : "failed " + error) << "\n";
  21806. engine.dispatchPendingMessages();
  21807. // a native FL generator with FL's presets (FL's capture: FLEX's "Piano Dark"), on a mixer track of its own
  21808. const auto& fl = lynx::flStudioAccess();
  21809. auto osc = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, fl);
  21810. int generator = -1, sampler = -1;
  21811. engine.editSong ([&] (lynx::Song& s) {
  21812. if (osc)
  21813. {
  21814. osc->mixerTrack = s.claimFreeInsert();
  21815. s.channels.push_back (*osc);
  21816. generator = (int) s.channels.size() - 1;
  21817. }
  21818. if (const juce::File kick (juce::String::fromUTF8 (fl.roots.data.c_str()) + "/Patches/Packs/Drums/Kicks/808 Kick.wav"); kick.existsAsFile())
  21819. {
  21820. lynx::ChannelDef d; // FL's Sampler with a kick, as FL's default channel (the Sample, Envelope and Misc tabs)
  21821. d.instrument = lynx::InstrumentKind::sampler;
  21822. lynx::audioclips::loadSampleInto (d, kick.getFullPathName().toStdString(), "808 Kick");
  21823. d.mixerTrack = s.claimFreeInsert();
  21824. s.channels.push_back (d);
  21825. sampler = (int) s.channels.size() - 1;
  21826. }
  21827. for (const auto withSample : { true, false }) // (a sampler with its sample first, else any)
  21828. for (int c = 0; c < (int) s.channels.size() && sampler < 0; ++c)
  21829. if (s.channels[(std::size_t) c].instrument == lynx::InstrumentKind::sampler && (! withSample || ! s.channels[(std::size_t) c].samplePath.empty()))
  21830. sampler = c;
  21831. });
  21832. engine.dispatchPendingMessages();
  21833. lynx::MainComponent ui (engine, false); // (sets the Channel rack's wrapper-menu items)
  21834. ui.setSize (1920, 1080);
  21835. report << "generator " << generator << ", sampler " << sampler << "\n";
  21836. auto shoot = [&] (juce::Component& c, const juce::String& name) {
  21837. savePng (lynx::shot::snapshot (c), prefix + name);
  21838. report << name << " " << c.getWidth() << "x" << c.getHeight() << "\n";
  21839. };
  21840. auto window = [&] (int channel, int tab, const juce::String& name) {
  21841. if (channel < 0)
  21842. return;
  21843. if (auto w = lynx::makeChannelWindowForShot (engine, channel, tab))
  21844. shoot (*w, name);
  21845. };
  21846. window (generator, 0, "-cw-plugin.png");
  21847. window (generator, -1, "-cw-plugin-misc.png");
  21848. window (sampler, 0, "-cw-sample.png");
  21849. window (sampler, 1, "-cw-envelope.png");
  21850. window (sampler, -1, "-cw-misc.png");
  21851. // the strip of a window with the system's title bar (docking off): ▸ and the presets stay in it
  21852. if (generator >= 0)
  21853. if (auto frame = lynx::makeChannelFrame (engine, generator, 0))
  21854. {
  21855. shoot (*frame, "-frame-floating.png");
  21856. if (auto menu = lynx::channelWrapperMenu (*frame))
  21857. {
  21858. // FL's two columns: the plugin's items, then the Channel column (split at the column break)
  21859. juce::PopupMenu left, right;
  21860. auto* to = &left;
  21861. for (juce::PopupMenu::MenuItemIterator it (*menu); it.next();)
  21862. {
  21863. to->addItem (it.getItem());
  21864. if (it.getItem().shouldBreakAfter)
  21865. to = &right;
  21866. }
  21867. saveMenus (juce::StringArray { "Plugin", "Channel" }, std::vector<juce::PopupMenu> { left, right }, prefix + "-menu-channel.png");
  21868. report << "menu items " << left.getNumItems() << " + " << right.getNumItems() << "\n";
  21869. }
  21870. }
  21871. }
  21872. {
  21873. // FW-8: LYNX engines standing in for FL plugins of an imported project (the import's flOrigin) are titled
  21874. // with FL's name; LYNX's own Delay (no FL origin) keeps its own
  21875. lynx::AudioEngine offline (false);
  21876. lynx::Song song;
  21877. song.mixer.resize (2);
  21878. song.mixer[0].name = "Master";
  21879. song.mixer[1].name = "Insert 1";
  21880. const std::vector<std::pair<lynx::EffectKind, const char*>> standIns { { lynx::EffectKind::limiter, "Fruity Limiter" },
  21881. { lynx::EffectKind::utility, "Fruity Stereo Shaper" }, { lynx::EffectKind::delay, "Fruity Delay 3" },
  21882. { lynx::EffectKind::reverb, "Fruity Reeverb 2" }, { lynx::EffectKind::delay, "" } };
  21883. for (const auto& [kind, origin] : standIns)
  21884. {
  21885. auto fx = lynx::makeEffectSlot (kind);
  21886. fx.flOrigin.plugin = origin;
  21887. song.mixer[1].effects.push_back (fx);
  21888. }
  21889. offline.setSong (std::move (song));
  21890. offline.dispatchPendingMessages();
  21891. std::vector<juce::Image> strips;
  21892. int width = 0, height = 0;
  21893. for (int k = 0; k < (int) standIns.size(); ++k)
  21894. if (auto editor = lynx::makeNativeEffectEditor (offline, 1, k, 1.0f, 0))
  21895. {
  21896. auto image = lynx::shot::paint (*editor, lynx::theme::panel); // (as --plugui draws the editors)
  21897. const auto h = juce::jmin (image.getHeight(), (int) std::ceil (30.0f * lynx::shot::scale()));
  21898. juce::Image strip (juce::Image::ARGB, image.getWidth(), h, true);
  21899. juce::Graphics (strip).drawImageAt (image, 0, 0);
  21900. strips.push_back (strip);
  21901. width = juce::jmax (width, image.getWidth());
  21902. height += h + 4;
  21903. }
  21904. if (! strips.empty())
  21905. {
  21906. juce::Image all (juce::Image::RGB, width, height, true);
  21907. {
  21908. juce::Graphics g (all); // (flushed when it goes: a native image's context draws on its release)
  21909. g.fillAll (juce::Colours::black);
  21910. int y = 0;
  21911. for (auto& strip : strips)
  21912. {
  21913. g.drawImageAt (strip, 0, y);
  21914. y += strip.getHeight() + 4;
  21915. }
  21916. }
  21917. savePng (all, prefix + "-names.png");
  21918. report << "names " << (int) strips.size() << "\n";
  21919. }
  21920. }
  21921. juce::File (prefix + "-report.txt").replaceWithText (report);
  21922. }
  21923. void runPluginEditorSnapshots (const juce::String& folder)
  21924. {
  21925. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  21926. {
  21927. const juce::File out (folder);
  21928. out.createDirectory();
  21929. lynx::AudioEngine offline (false);
  21930. const auto roots = lynx::findFlStudioRoots();
  21931. const auto presets = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Effects");
  21932. auto kinds = lynx::plugui::flLayoutKinds();
  21933. kinds.push_back (lynx::EffectKind::maximus); // Soundgoodizer (below)
  21934. for (const auto own : lynx::plugui::ownLayoutKinds()) // LYNX's own panels (mixing suite, round 96)
  21935. kinds.push_back (own);
  21936. kinds.push_back (lynx::EffectKind::apexLimiter); // round 114: display-first editor
  21937. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 145: the second pass shows the Vocal strip voicing
  21938. kinds.push_back (lynx::EffectKind::ridgeStrip); // round 165: the third pass shows the E console voicing
  21939. kinds.push_back (lynx::EffectKind::compressor); // round 152: the RComp role's panel (vintage voicing, RComp ranges)
  21940. const auto database = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin database/Effects");
  21941. auto maximusPasses = 0; // Maximus has its own page (first pass); the second pass shows Soundgoodizer
  21942. auto ridgePasses = 0;
  21943. // round 173d3: the parity pictures of one editor — LYNX_PLUGUI_ONLY=<effect name>, LYNX_PLUGUI_PRESET=<.fst>,
  21944. // LYNX_PLUGUI_PAGES=<page,page,…> (the page numbers as the editor encodes them)
  21945. const auto only = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_ONLY", {});
  21946. const auto onlyPreset = juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PRESET", {});
  21947. const auto onlyPages = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PLUGUI_PAGES", {}), ",", "");
  21948. for (const auto kind : kinds)
  21949. {
  21950. if (only.isNotEmpty() && only != lynx::effectInfo (kind).name)
  21951. continue;
  21952. auto fx = lynx::makeEffectSlot (kind);
  21953. juce::String name (lynx::effectInfo (kind).name);
  21954. for (const auto& plugin : lynx::flPluginsForEffect (kind))
  21955. {
  21956. const auto dir = presets.getChildFile (juce::String::fromUTF8 (plugin.c_str()));
  21957. auto file = dir.getChildFile ("Default.fst");
  21958. if (! file.existsAsFile()) // plugins without presets: their entry of FL's plugin database
  21959. for (const auto& f : database.findChildFiles (juce::File::findFiles, true, juce::String::fromUTF8 (plugin.c_str()) + ".fst"))
  21960. file = f;
  21961. if (only.isNotEmpty() && onlyPreset.isNotEmpty())
  21962. file = juce::File (onlyPreset);
  21963. if (! file.existsAsFile())
  21964. {
  21965. auto files = dir.findChildFiles (juce::File::findFiles, true, "*.fst");
  21966. std::sort (files.begin(), files.end(), [] (const juce::File& a, const juce::File& b) { return a.getFullPathName().compareNatural (b.getFullPathName()) < 0; });
  21967. file = files.isEmpty() ? juce::File() : files[0];
  21968. }
  21969. juce::MemoryBlock data;
  21970. if (file.existsAsFile() && file.loadFileAsData (data))
  21971. {
  21972. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  21973. 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)
  21974. {
  21975. fx = *loaded;
  21976. // round 190in (FW-8): a LYNX engine loaded with an FL plugin's preset stands in for that
  21977. // plugin as an imported slot does (its header shows FL's name)
  21978. if (fx.flOrigin.empty() && ! lynx::plugui::hasFlLayout (kind))
  21979. fx.flOrigin.plugin = plugin;
  21980. }
  21981. }
  21982. name = juce::String::fromUTF8 (plugin.c_str());
  21983. break;
  21984. }
  21985. if (kind == lynx::EffectKind::maximus && ++maximusPasses == 2) // Soundgoodizer: preset A of the installation, Amount 60 %
  21986. {
  21987. juce::MemoryBlock data;
  21988. juce::File (juce::String::fromUTF8 (roots.factoryData.c_str())).getChildFile ("Plugins/Fruity/Effects/Soundgoodizer/Data/Presets/a.dat").loadFileAsData (data);
  21989. lynx::maximusfx::Blob blob;
  21990. blob.build = lynx::hlfx::MaximusBuild::soundgoodizer;
  21991. blob.mix = 600;
  21992. const auto* b = static_cast<const std::uint8_t*> (data.getData());
  21993. blob.state.assign (b, b + data.getSize());
  21994. fx = lynx::makeEffectSlot (kind);
  21995. fx.state = lynx::maximusfx::pack (blob);
  21996. name = "Soundgoodizer";
  21997. }
  21998. if (kind == lynx::EffectKind::ridgeStrip && ++ridgePasses == 2) // round 145: her Vocalstrip 2 setting
  21999. {
  22000. for (const auto& [param, value] : { std::pair<const char*, float> { "Vocal strip", 1.0f }, { "Compander", 1.0f },
  22001. { "Compander threshold", 0.3083f }, { "Compander ratio", 0.6929f }, { "Compander attack", 0.2543f },
  22002. { "Compander release", 0.5316f }, { "Make-up", 0.2917f }, { "Soft knee", 1.0f },
  22003. { "Expander threshold", 0.2198f }, { "Vocal input", 0.6792f }, { "Vocal output", 0.3938f },
  22004. { "Process order", 0.4783f }, { "De-esser", 1.0f } })
  22005. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  22006. name = "Ridge Strip (Vocal strip)";
  22007. }
  22008. else if (kind == lynx::EffectKind::ridgeStrip && ridgePasses == 3) // round 165: the E console, EQ to the side chain
  22009. {
  22010. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "HPF", 0.3f }, { "HF gain", 0.8f },
  22011. { "HF bell", 1.0f }, { "Ratio", 0.5f }, { "Comp. threshold", 0.4f }, { "EQ to SC", 1.0f },
  22012. { "Filter split", 1.0f }, { "Expander", 1.0f } })
  22013. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  22014. name = "Ridge Strip (E console)";
  22015. }
  22016. else if (kind == lynx::EffectKind::ridgeStrip) // a vocal setting, so the graphs show something
  22017. for (const auto& [param, value] : { std::pair<const char*, float> { "HPF", 0.3f }, { "LMF gain", 0.35f }, { "HF gain", 0.7f },
  22018. { "Ratio", 0.3f }, { "Comp. threshold", 0.55f } })
  22019. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  22020. if (kind == lynx::EffectKind::compressor) // round 152: the vintage voicing with the reference's ranges and meter
  22021. {
  22022. for (const auto& [param, value] : { std::pair<const char*, float> { "Voicing", 1.0f }, { "Ranges", 1.0f }, { "Limiter", 1.0f },
  22023. { "Threshold", 0.6f }, { "RC ratio", 0.4f } })
  22024. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  22025. name = "Compressor (RComp role)";
  22026. }
  22027. if (kind == lynx::EffectKind::apexLimiter) // round 114: gain into the ceiling, so the display shows reduction
  22028. fx.params[0] = 0.33f;
  22029. if (kind == lynx::EffectKind::ember)
  22030. {
  22031. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Drive")] = 0.5f;
  22032. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "Bands")] = 1.0f; // round 108: the band rows
  22033. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, "B3 drive")] = 0.6f;
  22034. }
  22035. if (kind == lynx::EffectKind::crestCompressor) // round 108: a curve with a knee and a side-chain low cut
  22036. for (const auto& [param, value] : { std::pair<const char*, float> { "Threshold", 0.55f }, { "Knee", 0.15f },
  22037. { "SC1 shape", 0.5f }, { "SC1 freq.", 0.3f } })
  22038. fx.params[(std::size_t) lynx::plugui::paramIndex (kind, param)] = value;
  22039. lynx::Song song;
  22040. song.mixer.resize (2);
  22041. song.mixer[0].name = "Master";
  22042. song.mixer[1].name = "Insert 1";
  22043. song.mixer[1].effects.push_back (fx);
  22044. offline.setSong (std::move (song));
  22045. offline.dispatchPendingMessages();
  22046. if (lynx::ProEditorWindows::handles (kind)) // round 114: the display-first editors, with a demo signal
  22047. {
  22048. auto editor = lynx::makeProEditor (offline, 1, 0, true);
  22049. auto image = lynx::shot::paint (*editor);
  22050. const auto file = lynx::shot::file (out.getChildFile (name + ".png"));
  22051. file.deleteFile();
  22052. juce::PNGImageFormat png;
  22053. if (auto stream = file.createOutputStream())
  22054. png.writeImageToStream (image, *stream);
  22055. continue;
  22056. }
  22057. const auto pages = name == "Soundgoodizer" ? 1 : juce::jmax (1, (int) lynx::plugui::layoutFor (kind).pages.size());
  22058. std::vector<int> pageList;
  22059. for (int page = 0; page < pages; ++page)
  22060. pageList.push_back (page);
  22061. if (only.isNotEmpty() && ! onlyPages.isEmpty())
  22062. {
  22063. pageList.clear();
  22064. for (const auto& p : onlyPages)
  22065. pageList.push_back (p.getIntValue());
  22066. }
  22067. for (const auto page : pageList)
  22068. {
  22069. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, page);
  22070. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  22071. const auto file = lynx::shot::file (out.getChildFile (name + (page > 0 ? "-p" + juce::String (page + 1) : juce::String()) + ".png"));
  22072. file.deleteFile();
  22073. juce::PNGImageFormat png;
  22074. if (auto stream = file.createOutputStream())
  22075. png.writeImageToStream (image, *stream);
  22076. }
  22077. }
  22078. // round 137: Echoform in its Rhythm mode (EchoBoy's role) with the Present era
  22079. {
  22080. namespace ef = lynx::echosuite::echoform;
  22081. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  22082. fx.params[ef::rhythm] = 1.0f;
  22083. fx.params[ef::rhythmRepeats] = 5.0f / 15.0f;
  22084. fx.params[ef::rhythmDecay] = 0.25f;
  22085. fx.params[ef::rhythmTap1 + 2] = 0.45f;
  22086. fx.params[ef::feedback] = 0.25f;
  22087. fx.params[ef::era] = 0.5f;
  22088. for (const auto& [param, value] : ef::rhythmPresetEdits (0)) // round 144: a pattern in the rhythm editor (Grid)
  22089. fx.params[(std::size_t) param] = value;
  22090. fx.params[ef::rhythmShape] = 0.5f; // swell
  22091. lynx::Song song;
  22092. song.mixer.resize (2);
  22093. song.mixer[0].name = "Master";
  22094. song.mixer[1].name = "Insert 1";
  22095. song.mixer[1].effects.push_back (fx);
  22096. offline.setSong (std::move (song));
  22097. offline.dispatchPendingMessages();
  22098. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  22099. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  22100. const auto file = lynx::shot::file (out.getChildFile ("Echoform-rhythm.png"));
  22101. file.deleteFile();
  22102. juce::PNGImageFormat png;
  22103. if (auto stream = file.createOutputStream())
  22104. png.writeImageToStream (image, *stream);
  22105. }
  22106. // round 150: Echoform with a voicing (the Stereo / L/R offset controls on the Rhythm row)
  22107. {
  22108. namespace ef = lynx::echosuite::echoform;
  22109. auto fx = lynx::makeEffectSlot (lynx::EffectKind::echoform);
  22110. fx.params[ef::voicing] = ef::voicingValue (ef::voicingForEchoBoyStyle (19));
  22111. fx.params[ef::style] = ef::styleValue (ef::Style::dual);
  22112. lynx::Song song;
  22113. song.mixer.resize (2);
  22114. song.mixer[0].name = "Master";
  22115. song.mixer[1].name = "Insert 1";
  22116. song.mixer[1].effects.push_back (fx);
  22117. offline.setSong (std::move (song));
  22118. offline.dispatchPendingMessages();
  22119. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  22120. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  22121. const auto file = lynx::shot::file (out.getChildFile ("Echoform-voicing.png"));
  22122. file.deleteFile();
  22123. juce::PNGImageFormat png;
  22124. if (auto stream = file.createOutputStream())
  22125. png.writeImageToStream (image, *stream);
  22126. }
  22127. // round 150: Auto-pan's Rhythm voicing with its Tweak row (PanMan's role)
  22128. {
  22129. auto fx = lynx::makeEffectSlot (lynx::EffectKind::autoPan);
  22130. fx.params[lynx::autopan::count] = 1.0f; // the Rhythm voicing
  22131. fx.params[lynx::autopan::count + 13] = 0.75f; // offset mod +90°
  22132. lynx::Song song;
  22133. song.mixer.resize (2);
  22134. song.mixer[0].name = "Master";
  22135. song.mixer[1].name = "Insert 1";
  22136. song.mixer[1].effects.push_back (fx);
  22137. offline.setSong (std::move (song));
  22138. offline.dispatchPendingMessages();
  22139. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  22140. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  22141. const auto file = lynx::shot::file (out.getChildFile ("Auto-pan-tweak.png"));
  22142. file.deleteFile();
  22143. juce::PNGImageFormat png;
  22144. if (auto stream = file.createOutputStream())
  22145. png.writeImageToStream (image, *stream);
  22146. }
  22147. // round 165: Ember's Classic voicing (the Decapitator role) in its one-screen panel
  22148. {
  22149. namespace em = lynx::mixsuite::ember;
  22150. auto fx = lynx::makeEffectSlot (lynx::EffectKind::ember);
  22151. fx.params[em::voicing] = 1.0f;
  22152. fx.params[em::classicDrive] = 0.35f;
  22153. lynx::Song song;
  22154. song.mixer.resize (2);
  22155. song.mixer[0].name = "Master";
  22156. song.mixer[1].name = "Insert 1";
  22157. song.mixer[1].effects.push_back (fx);
  22158. offline.setSong (std::move (song));
  22159. offline.dispatchPendingMessages();
  22160. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  22161. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  22162. const auto file = lynx::shot::file (out.getChildFile ("Ember Saturator-classic.png"));
  22163. file.deleteFile();
  22164. juce::PNGImageFormat png;
  22165. if (auto stream = file.createOutputStream())
  22166. png.writeImageToStream (image, *stream);
  22167. }
  22168. // round 152: Foil Plate's one-knob Plate view (the Little Plate role)
  22169. {
  22170. auto fx = lynx::makeEffectSlot (lynx::EffectKind::foilPlate);
  22171. fx.params[14] = 1.0f; // the measured plate voicing
  22172. fx.params[15] = 1.0f; // View = Plate
  22173. lynx::Song song;
  22174. song.mixer.resize (2);
  22175. song.mixer[0].name = "Master";
  22176. song.mixer[1].name = "Insert 1";
  22177. song.mixer[1].effects.push_back (fx);
  22178. offline.setSong (std::move (song));
  22179. offline.dispatchPendingMessages();
  22180. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f, 0);
  22181. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  22182. const auto file = lynx::shot::file (out.getChildFile ("Foil Plate-plate.png"));
  22183. file.deleteFile();
  22184. juce::PNGImageFormat png;
  22185. if (auto stream = file.createOutputStream())
  22186. png.writeImageToStream (image, *stream);
  22187. }
  22188. // LYNX's own editors with live displays (round 103): Facet EQ (a mixing curve, one dynamic band, demo analyser)
  22189. // and LYNX Tune (demo pitch phrase)
  22190. {
  22191. lynx::setNativeEditorDemo (true);
  22192. using namespace lynx::facet;
  22193. auto eq = lynx::makeEffectSlot (lynx::EffectKind::facetEq);
  22194. const struct { Shape s; double f, g, q; int slope; double range; } bandsDemo[] = {
  22195. { Shape::lowCut, 32, 0, 1, 24, 0 }, { Shape::bell, 110, 3, 1.2, 12, 0 }, { Shape::bell, 380, -3.5, 1.6, 12, 0 },
  22196. { Shape::bell, 3200, 0, 2.5, 12, -6 }, { Shape::highShelf, 9000, 2.5, 0.8, 12, 0 }
  22197. };
  22198. for (int b = 0; b < 5; ++b)
  22199. {
  22200. eq.params[(std::size_t) param (b, 0)] = shapeValue (bandsDemo[b].s);
  22201. eq.params[(std::size_t) param (b, 1)] = hzValue (bandsDemo[b].f);
  22202. eq.params[(std::size_t) param (b, 2)] = gainValue (bandsDemo[b].g);
  22203. eq.params[(std::size_t) param (b, 3)] = qValue (bandsDemo[b].q);
  22204. eq.params[(std::size_t) param (b, 4)] = slopeValue (bandsDemo[b].slope);
  22205. eq.params[(std::size_t) (rangeParam0 + b)] = rangeValue (bandsDemo[b].range);
  22206. }
  22207. eq.params[(std::size_t) phaseParam] = phaseValue (Phase::natural);
  22208. const auto own = [&] (const lynx::EffectSlot& fx, const juce::String& file, bool facetEditor, int page = 0) {
  22209. lynx::Song song;
  22210. song.mixer.resize (2);
  22211. song.mixer[0].name = "Master";
  22212. song.mixer[1].name = "Vocal";
  22213. song.mixer[1].effects.push_back (fx);
  22214. offline.setSong (std::move (song));
  22215. offline.dispatchPendingMessages();
  22216. auto editor = facetEditor ? lynx::makeFacetEqEditor (offline, 1, 0, true) : lynx::makeNativeEffectEditor (offline, 1, 0, 1.25f, page);
  22217. auto image = lynx::shot::paint (*editor, lynx::theme::panel);
  22218. const auto f = lynx::shot::file (out.getChildFile (file));
  22219. f.deleteFile();
  22220. juce::PNGImageFormat png;
  22221. if (auto stream = f.createOutputStream())
  22222. png.writeImageToStream (image, *stream);
  22223. };
  22224. own (eq, "Facet EQ.png", true);
  22225. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune.png", false);
  22226. {
  22227. // round 128: the ADVANCED page, with E bypassed and A removed on the keyboard and a created vibrato
  22228. auto tune = lynx::makeEffectSlot (lynx::EffectKind::lynxTune);
  22229. tune.params[(std::size_t) (lynx::lynxtune::bypassC + 4)] = 1.0f;
  22230. tune.params[(std::size_t) (lynx::lynxtune::noteC + 9)] = 0.0f;
  22231. tune.params[lynx::lynxtune::vibratoShape] = 1.0f / 3.0f;
  22232. // round 166c: the created vibrato's amplitude / formant / variation, a short throat, In scale +2
  22233. tune.params[lynx::lynxtune::vibratoAmplitude] = 1.0f / 3.0f;
  22234. tune.params[lynx::lynxtune::vibratoFormant] = 0.7f;
  22235. tune.params[lynx::lynxtune::vibratoVariation] = 0.2f;
  22236. tune.params[lynx::lynxtune::throatLength] = lynx::lynxtune::throatValue (80.0);
  22237. tune.params[lynx::lynxtune::transposeInScale] = 1.0f;
  22238. tune.params[lynx::lynxtune::scaleTranspose] = lynx::lynxtune::scaleTransposeValue (2);
  22239. own (tune, "LYNX Tune-p2.png", false, 1);
  22240. }
  22241. own (lynx::makeEffectSlot (lynx::EffectKind::lynxTune), "LYNX Tune-p3.png", false, 2); // round 135w: Real-time
  22242. lynx::setNativeEditorDemo (false);
  22243. }
  22244. // generators in FL's arrangement: the channel's plugin page with the FL preset's settings
  22245. const auto generators = juce::File (juce::String::fromUTF8 (roots.data.c_str())).getChildFile ("Patches/Plugin presets/Generators");
  22246. 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" } })
  22247. {
  22248. juce::MemoryBlock data;
  22249. if (juce::String (folder) == "Harmor") // the first preset whose state the engine reads
  22250. {
  22251. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  22252. files.sort();
  22253. for (const auto& f : files)
  22254. {
  22255. juce::MemoryBlock block;
  22256. if (! f.loadFileAsData (block))
  22257. continue;
  22258. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  22259. try
  22260. {
  22261. const auto p = flp::parseProject (std::vector<std::uint8_t> (b, b + block.getSize()), true);
  22262. if (! p.channels.empty() && lynx::harmorStateUsable (p.channels.front().pluginState))
  22263. {
  22264. preset = nullptr;
  22265. data = block;
  22266. break;
  22267. }
  22268. }
  22269. catch (const std::exception&)
  22270. {
  22271. }
  22272. }
  22273. }
  22274. auto file = preset == nullptr ? juce::File() : juce::String (preset).isEmpty() ? database.getSiblingFile ("Generators").getChildFile ("Misc").getChildFile (juce::String (folder) + ".fst")
  22275. : generators.getChildFile (folder).getChildFile (preset);
  22276. if (! file.existsAsFile())
  22277. {
  22278. auto files = generators.getChildFile (folder).findChildFiles (juce::File::findFiles, true, "*.fst");
  22279. files.sort();
  22280. file = files.isEmpty() ? juce::File() : files[0];
  22281. }
  22282. if (data.isEmpty() && ! file.loadFileAsData (data))
  22283. continue;
  22284. try
  22285. {
  22286. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  22287. auto project = flp::parseProject (std::vector<std::uint8_t> (bytes, bytes + data.getSize()), true);
  22288. if (project.channels.empty())
  22289. continue;
  22290. project.channels.front().type = flp::ChannelType::native;
  22291. lynx::FlpImportOptions options;
  22292. options.roots = roots;
  22293. options.fileExists = [] (const std::string& path) { return lynx::platform::localFile (path).existsAsFile(); };
  22294. options.readFile = [] (const std::string& path) {
  22295. juce::MemoryBlock block;
  22296. lynx::platform::localFile (path).loadFileAsData (block);
  22297. const auto* b = static_cast<const std::uint8_t*> (block.getData());
  22298. return std::vector<std::uint8_t> (b, b + block.getSize());
  22299. };
  22300. options.saveEmbedded = [out] (const std::vector<std::uint8_t>& wav, const std::string& name) {
  22301. const auto f = out.getChildFile ("samples").getNonexistentChildFile (juce::String::fromUTF8 (name.c_str()), ".wav");
  22302. f.getParentDirectory().createDirectory();
  22303. f.replaceWithData (wav.data(), wav.size());
  22304. return f.getFullPathName().toStdString();
  22305. };
  22306. auto song = lynx::importFlp (project, options);
  22307. // the page only needs the plugin's saved state (FL Keys' sample zones need the installed wavetables)
  22308. if (! song.channels.empty() && project.channels.front().pluginName == "BooBass" && song.channels.front().instrument != lynx::InstrumentKind::boobass)
  22309. {
  22310. song.channels.front().instrument = lynx::InstrumentKind::boobass; // (its sound needs the engine DLL; the page does not)
  22311. song.channels.front().modelParams.assign (3, 32768.0f);
  22312. }
  22313. if (! song.channels.empty() && project.channels.front().pluginName == "FL Keys")
  22314. {
  22315. song.channels.front().instrument = lynx::InstrumentKind::flkeys;
  22316. song.channels.front().pluginState = project.channels.front().pluginState;
  22317. }
  22318. offline.setSong (std::move (song));
  22319. offline.dispatchPendingMessages();
  22320. if (offline.getSong().channels.empty())
  22321. continue;
  22322. auto panel = lynx::makeChannelSettingsPanel (offline, 0);
  22323. auto image = lynx::shot::paint (*panel, lynx::theme::panel);
  22324. const auto out2 = lynx::shot::file (out.getChildFile (juce::String (folder) + ".png"));
  22325. out2.deleteFile();
  22326. juce::PNGImageFormat png;
  22327. if (auto stream = out2.createOutputStream())
  22328. png.writeImageToStream (image, *stream);
  22329. }
  22330. catch (const std::exception&)
  22331. {
  22332. }
  22333. }
  22334. }
  22335. quit();
  22336. }
  22337. void runVideoShot (const juce::String& prefix, const juce::String& videoPath)
  22338. {
  22339. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22340. // the message loop runs while the frames decode (modal loops are off): a timer takes one snapshot per step
  22341. struct VideoShot final : juce::Timer
  22342. {
  22343. lynx::AudioEngine offline { false };
  22344. std::unique_ptr<juce::Component> editor;
  22345. juce::String prefix, report;
  22346. int step = 0;
  22347. std::function<void()> done;
  22348. void moveTo (double seconds)
  22349. {
  22350. offline.getTransport().positionTicks.store (seconds * offline.getSong().bpm / 60.0 * lynx::ppq);
  22351. }
  22352. void timerCallback() override
  22353. {
  22354. static constexpr double times[] = { 0.0, 1.5, 3.25 };
  22355. constexpr int typeInStep = (int) std::size (times) + 1;
  22356. if (step > 0 && step < typeInStep && editor != nullptr)
  22357. savePng (lynx::shot::snapshot (*editor), prefix + "-" + juce::String (step - 1) + ".png");
  22358. if (editor != nullptr && step == (int) std::size (times))
  22359. {
  22360. // round 174d: FL's in-place type-in of the current time (a right click on it)
  22361. lynx::videoview::openTypeIn (*editor, 2);
  22362. ++step;
  22363. return;
  22364. }
  22365. if (editor != nullptr && step == typeInStep)
  22366. savePng (lynx::shot::snapshot (*editor), prefix + "-typein.png");
  22367. if (editor == nullptr || step >= typeInStep)
  22368. {
  22369. stopTimer();
  22370. juce::File (prefix + "-report.txt").replaceWithText (report);
  22371. if (done)
  22372. done();
  22373. return;
  22374. }
  22375. moveTo (times[step++]);
  22376. }
  22377. };
  22378. static std::unique_ptr<VideoShot> shot;
  22379. shot = std::make_unique<VideoShot>();
  22380. shot->prefix = prefix;
  22381. auto& offline = shot->offline;
  22382. lynx::videoview::install (offline);
  22383. lynx::Song song;
  22384. song.mixer = lynx::Song::defaultMixer (2);
  22385. lynx::ChannelDef c;
  22386. c.name = "Fruity Video Player";
  22387. c.instrument = lynx::InstrumentKind::videoplayer;
  22388. lynx::video::Settings vs;
  22389. vs.path = juce::File (videoPath).getFullPathName().toStdString();
  22390. vs.delay = lynx::video::unitsPerSecond / 2; // the video starts at 0.5 s
  22391. c.pluginState = lynx::video::write (vs);
  22392. song.channels.push_back (c);
  22393. song.patterns.emplace_back();
  22394. {
  22395. // round 174d (A3): the same Video Player in a song whose tempo drops from 120 to 60 BPM at bar 5, for FL
  22396. // (LYNX.exe --export-flp <prefix>-tempo.lynx <prefix>-tempo.flp), to compare FL's video clock with LYNX's
  22397. auto fl = song;
  22398. fl.bpm = 120.0;
  22399. fl.mode = lynx::PlayMode::song;
  22400. auto settings = vs;
  22401. settings.delay = 0;
  22402. settings.timeDisplay = lynx::video::Settings {}.timeDisplay;
  22403. fl.channels[0].pluginState = lynx::video::write (settings);
  22404. fl.patterns[0].name = "Pattern 1";
  22405. lynx::Automation tempo;
  22406. tempo.name = "Tempo";
  22407. tempo.target = { lynx::AutomationTargetKind::tempo, 0, 0, 0 };
  22408. const auto bar = (std::int64_t) lynx::ppq * 4;
  22409. tempo.points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { bar * 4 - 1, lynx::valueFromTempo (120.0), 0.0f },
  22410. { bar * 4, lynx::valueFromTempo (60.0), 0.0f }, { bar * 8, lynx::valueFromTempo (60.0), 0.0f } };
  22411. fl.automations.push_back (tempo);
  22412. lynx::Clip at;
  22413. at.kind = lynx::ClipKind::automation;
  22414. at.automation = 0;
  22415. at.track = 1;
  22416. at.start = 0;
  22417. at.length = bar * 8;
  22418. fl.playlist.push_back (at);
  22419. lynx::Clip pc;
  22420. pc.pattern = 0;
  22421. pc.track = 0;
  22422. pc.start = 0;
  22423. pc.length = bar * 8;
  22424. fl.playlist.push_back (pc);
  22425. juce::String error;
  22426. lynx::ProjectFile::save (fl, juce::File (prefix + "-tempo.lynx"), error);
  22427. }
  22428. offline.setSong (std::move (song));
  22429. offline.dispatchPendingMessages();
  22430. auto& report = shot->report;
  22431. report << "ffmpeg: " << lynx::findFfmpeg().getFullPathName() << "\n";
  22432. report << lynx::videoview::report (vs.path).fromFirstOccurrenceOf ("Input #0", true, false).upToFirstOccurrenceOf ("At least", false, false) << "\n";
  22433. shot->editor = lynx::makeChannelSettingsPanel (offline, 0);
  22434. if (shot->editor != nullptr)
  22435. shot->editor->setVisible (true);
  22436. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  22437. shot->startTimer (1500);
  22438. }
  22439. void runVideoTrackShot (const juce::String& prefix, const juce::String& videoPath, const juce::String& secondPath)
  22440. {
  22441. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22442. struct TrackShot final : juce::Timer
  22443. {
  22444. lynx::AudioEngine offline { false };
  22445. std::unique_ptr<lynx::PlaylistComponent> playlist;
  22446. std::unique_ptr<lynx::media::FrameDecoder> decoder;
  22447. juce::String prefix, report, path;
  22448. double fps = 25.0;
  22449. int step = 0, waits = 0, adrStep = 0;
  22450. std::unique_ptr<juce::Component> adrPanel;
  22451. std::function<void()> done;
  22452. // song times (s): before, inside the first clip (on and between frame edges), across the second clip
  22453. std::vector<double> times { 0.0, 1.0, 2.0 + 1.0 / 25.0, 2.5, 4.0, 7.3 };
  22454. void timerCallback() override
  22455. {
  22456. if (step > 0 && adrStep == 0)
  22457. {
  22458. // the frame the decoder shows for the wanted file time (the clip starts at song 1.0 s, offset 0)
  22459. const auto want = times[(std::size_t) step - 1] - 1.0;
  22460. double ft = -1.0;
  22461. const auto img = decoder->frame (ft);
  22462. const auto expected = std::floor (want * fps + 1e-6) / fps;
  22463. if (want >= 0.0 && ft < expected - 1e-3 && ++waits < 20)
  22464. return; // (still decoding)
  22465. waits = 0;
  22466. report << "song " << juce::String (times[(std::size_t) step - 1], 3) << " s: wanted file time " << juce::String (want, 4)
  22467. << ", frame shown at " << juce::String (ft, 4) << " (expected " << juce::String (expected, 4) << ")"
  22468. << (want < 0.0 ? " [before the clip]" : std::abs (ft - expected) < 1e-3 ? " OK" : " MISMATCH") << "\n";
  22469. savePng (lynx::shot::snapshot (*playlist), prefix + "-playlist-" + juce::String (step - 1) + ".png");
  22470. if (img.isValid())
  22471. savePng (img, prefix + "-frame-" + juce::String (step - 1) + ".png");
  22472. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  22473. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  22474. savePng (lynx::shot::snapshot (*c), prefix + "-window-" + juce::String (step - 1) + ".png");
  22475. }
  22476. if (step >= (int) times.size() && adrStep == 0)
  22477. {
  22478. // the ADR window: two cues, takes on the first; the play position inside the streamer before the in
  22479. // point (4.0 s), so the video window shows the streamer and the line
  22480. adrStep = 1;
  22481. offline.editSong ([] (lynx::Song& s) {
  22482. lynx::AdrCue a, b;
  22483. a.id = "SC1-01";
  22484. a.in = 4.0;
  22485. a.out = 6.4;
  22486. a.character = "Dr. Silva";
  22487. a.line = "We have to leave before the storm reaches the coast.";
  22488. a.notes = "softer, out of breath";
  22489. a.status = lynx::AdrCue::Status::recorded;
  22490. for (int n = 1; n <= 3; ++n)
  22491. {
  22492. lynx::AdrTake t;
  22493. t.number = n;
  22494. t.name = lynx::adr::takeName (a, n);
  22495. t.rating = n == 2 ? 4 : n;
  22496. t.circled = n == 2;
  22497. a.takes.push_back (t);
  22498. }
  22499. a.selected = 2;
  22500. lynx::adr::setCompRange (a, 4.0, 5.1, 2);
  22501. lynx::adr::setCompRange (a, 5.1, 6.4, 3);
  22502. b.id = "SC1-02";
  22503. b.in = 8.0;
  22504. b.out = 9.5;
  22505. b.character = "Marta";
  22506. b.line = "Then we go now.";
  22507. s.adr.cues = { a, b };
  22508. s.adr.current = 0;
  22509. });
  22510. adrPanel = lynx::adrwindow::makePanel (offline);
  22511. adrPanel->setSize (1200, 640);
  22512. adrPanel->setVisible (true);
  22513. offline.getTransport().positionTicks.store (3.0 * offline.getSong().bpm / 60.0 * lynx::ppq);
  22514. decoder->request (2.0, false);
  22515. return;
  22516. }
  22517. if (adrStep == 1)
  22518. {
  22519. adrStep = 2;
  22520. savePng (lynx::shot::snapshot (*adrPanel), prefix + "-adr.png");
  22521. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  22522. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  22523. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window.png");
  22524. offline.getTransport().positionTicks.store (4.5 * offline.getSong().bpm / 60.0 * lynx::ppq);
  22525. decoder->request (3.5, false);
  22526. return;
  22527. }
  22528. if (adrStep == 2)
  22529. {
  22530. for (int w = 0; w < juce::Desktop::getInstance().getNumComponents(); ++w)
  22531. if (auto* c = juce::Desktop::getInstance().getComponent (w); c != nullptr && c->getName().startsWith ("Picture"))
  22532. savePng (lynx::shot::snapshot (*c), prefix + "-adr-window-line.png");
  22533. adrPanel.reset();
  22534. // export with video: a 3 s mix under the picture, re-encoded (the clip starts at 1 s) and copied (from 1 s)
  22535. {
  22536. const juce::File wav (prefix + "-mix.wav");
  22537. wav.deleteFile();
  22538. juce::WavAudioFormat format;
  22539. if (std::unique_ptr<juce::OutputStream> os (wav.createOutputStream().release()); os != nullptr)
  22540. if (std::unique_ptr<juce::AudioFormatWriter> w (format.createWriterFor (os.get(), 48000.0, 2, 16, {}, 0)); w != nullptr)
  22541. {
  22542. os.release();
  22543. juce::AudioBuffer<float> b (2, 48000 * 3);
  22544. for (int k = 0; k < b.getNumSamples(); ++k)
  22545. 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));
  22546. w->writeFromAudioSampleBuffer (b, 0, b.getNumSamples());
  22547. }
  22548. for (const auto origin : { 0.0, 1.0 })
  22549. {
  22550. const juce::File out (prefix + "-mux-" + juce::String ((int) origin) + ".mp4");
  22551. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  22552. const auto error = lynx::videotracks::muxWithVideo (offline.getSong(), origin, wav, out);
  22553. report << "export with video from " << origin << " s: " << (error.isEmpty() ? "OK " + juce::String (out.getSize()) + " bytes" : "FAILED " + error)
  22554. << " (" << juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 1000.0, 2) << " s)\n";
  22555. }
  22556. }
  22557. stopTimer();
  22558. report << "frames decoded " << decoder->frameCount() << ", dropped " << decoder->droppedCount() << "\n";
  22559. juce::File (prefix + "-report.txt").replaceWithText (report);
  22560. if (done)
  22561. done();
  22562. return;
  22563. }
  22564. const auto t = times[(std::size_t) step++];
  22565. offline.getTransport().positionTicks.store (t * offline.getSong().bpm / 60.0 * lynx::ppq);
  22566. decoder->request (std::max (0.0, t - 1.0), false);
  22567. }
  22568. };
  22569. static std::unique_ptr<TrackShot> shot;
  22570. shot = std::make_unique<TrackShot>();
  22571. shot->prefix = prefix;
  22572. auto& offline = shot->offline;
  22573. lynx::Song song;
  22574. song.mixer = lynx::Song::defaultMixer (2);
  22575. song.patterns.emplace_back();
  22576. song.mode = lynx::PlayMode::song;
  22577. song.bpm = 120.0;
  22578. offline.setSong (std::move (song));
  22579. offline.dispatchPendingMessages();
  22580. const juce::File video (videoPath);
  22581. const auto pr = lynx::media::probe (video.getFullPathName());
  22582. auto& report = shot->report;
  22583. report << "decoder: " << (pr.backend.isEmpty() ? juce::String ("none") : pr.backend) << " (system: " << lynx::media::nativeBackendName()
  22584. << ", ffmpeg: " << lynx::findFfmpeg().getFullPathName() << ")\n";
  22585. report << "video: " << pr.info.width << "x" << pr.info.height << " " << juce::String (pr.info.fps, 3) << " fps " << juce::String (pr.info.duration, 3)
  22586. << " s, sound " << (pr.info.hasAudio ? "yes" : "no") << "\n";
  22587. shot->fps = pr.info.fps > 1.0 ? pr.info.fps : 25.0;
  22588. shot->times[2] = 2.0 + 1.0 / shot->fps; // (exactly on a frame edge)
  22589. lynx::videotracks::importVideo (offline, video, 1.0, -1);
  22590. if (secondPath.isNotEmpty())
  22591. lynx::videotracks::importVideo (offline, juce::File (secondPath), 3.0, 1);
  22592. offline.editSong ([] (lynx::Song& s) {
  22593. s.video.startTimecode = 3600.0;
  22594. s.video.burnIn = true;
  22595. if (s.videoTracks.size() < 2)
  22596. s.videoTracks.push_back ({});
  22597. s.videoTracks[0].name = "Picture";
  22598. s.videoTracks[1].name = "Reference";
  22599. });
  22600. report << "project rate: " << lynx::vtime::rateName (offline.getSong().video.rate) << ", clip 1: "
  22601. << juce::String (offline.getSong().videoTracks[0].clips.empty() ? -1.0 : offline.getSong().videoTracks[0].clips[0].length, 3) << " s\n";
  22602. // the project round trip
  22603. {
  22604. const juce::File file (prefix + "-project.lynx");
  22605. juce::String error;
  22606. lynx::ProjectFile::save (offline.getSong(), file, error);
  22607. const auto back = lynx::ProjectFile::load (file, error);
  22608. report << "project file round trip: " << (back && back->videoTracks == offline.getSong().videoTracks && back->video == offline.getSong().video ? "OK" : "MISMATCH " + error) << "\n";
  22609. }
  22610. shot->playlist = std::make_unique<lynx::PlaylistComponent> (offline);
  22611. shot->playlist->setSize (1400, 640);
  22612. shot->playlist->setVisible (true);
  22613. shot->decoder = std::make_unique<lynx::media::FrameDecoder>();
  22614. shot->decoder->setSource (video.getFullPathName(), pr.info);
  22615. shot->decoder->setSize (pr.info.width, pr.info.height);
  22616. shot->decoder->startThread (juce::Thread::Priority::low);
  22617. lynx::videotracks::showWindow (offline, 0);
  22618. shot->done = [this] { juce::MessageManager::callAsync ([this] { shot.reset(); quit(); }); };
  22619. shot->startTimer (700);
  22620. }
  22621. void runDanceShot (const juce::String& prefix)
  22622. {
  22623. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22624. // the moves: one row each, eight moments of a cycle (both facings for Spinning; Pose ends the sheet)
  22625. {
  22626. constexpr int cell = 120, cols = 8;
  22627. auto sheet = lynx::shot::canvas (130 + cols * cell, lynx::dance::moveCount * cell + 10);
  22628. {
  22629. // (the picture is complete when its Graphics is gone: round 190ba, the file was blank on Windows)
  22630. juce::Graphics g (sheet);
  22631. lynx::shot::logical (g);
  22632. g.fillAll (lynx::theme::colour::bg0);
  22633. for (int m = 0; m < lynx::dance::moveCount; ++m)
  22634. {
  22635. g.setColour (lynx::theme::colour::textSecondary);
  22636. g.setFont (14.0f);
  22637. g.drawText (lynx::dance::moveName (m), 8, m * cell + 5, 118, cell, juce::Justification::centredLeft);
  22638. for (int k = 0; k < cols; ++k)
  22639. {
  22640. const auto pose = lynx::dance::pose (m, k / (double) cols + (m == lynx::dance::freestyle ? k * 2 : 0), 1);
  22641. lynx::dancer::draw (g, { 130.0f + (k + 0.5f) * cell, (float) (m + 1) * cell - 6.0f }, 92.0f, pose, false, juce::Colour (0xffff3048));
  22642. }
  22643. }
  22644. }
  22645. savePng (sheet, prefix + "-moves.png");
  22646. }
  22647. lynx::AudioEngine offline (false);
  22648. lynx::Song song;
  22649. song.mixer = lynx::Song::defaultMixer (2);
  22650. for (int d = 0; d < 2; ++d)
  22651. {
  22652. lynx::ChannelDef c;
  22653. c.name = d == 0 ? "Fruity Dance" : "Fruity Dance #2";
  22654. c.instrument = lynx::InstrumentKind::fruitydance;
  22655. lynx::dance::Settings s;
  22656. s.move = d == 0 ? lynx::dance::stepping : lynx::dance::waving;
  22657. s.x = d == 0 ? 520 : 760;
  22658. s.y = 560;
  22659. s.colour = d == 0 ? 0xffff3048 : 0xff30a8ff;
  22660. s.mirrored = d == 1;
  22661. c.pluginState = lynx::dance::toState (s);
  22662. song.channels.push_back (c);
  22663. }
  22664. // Issue #121 (round 190ba): a sprite sheet in FL's Fruity Dance format (8 frames across, a row per move, a names
  22665. // file beside it), made here from LYNX's own poses, loaded back as a user's sheet would be
  22666. juce::String sheetReport;
  22667. {
  22668. constexpr int fw = 120, fh = 150;
  22669. const std::vector<std::pair<const char*, int>> rows { { "Idle", lynx::dance::waiting }, { "Step", lynx::dance::stepping },
  22670. { "Jump", lynx::dance::jumping }, { "Wave", lynx::dance::waving },
  22671. { "Windmill", lynx::dance::windmill }, { "Held", lynx::dance::held } };
  22672. juce::Image sheet (juce::Image::ARGB, fw * lynx::dance::sheetColumns, fh * (int) rows.size(), true);
  22673. {
  22674. juce::Graphics g (sheet);
  22675. for (int r = 0; r < (int) rows.size(); ++r)
  22676. for (int k = 0; k < lynx::dance::sheetColumns; ++k)
  22677. {
  22678. juce::Graphics::ScopedSaveState save (g);
  22679. g.reduceClipRegion (k * fw, r * fh, fw, fh);
  22680. lynx::dancer::draw (g, { (k + 0.5f) * fw, (float) (r + 1) * fh - 8.0f }, 96.0f,
  22681. lynx::dance::pose (rows[(std::size_t) r].second, k / (double) lynx::dance::sheetColumns, 1), false, juce::Colour (0xff35c46a));
  22682. }
  22683. }
  22684. const juce::File picture (prefix + "-sheet.png");
  22685. savePng (sheet, picture.getFullPathName());
  22686. juce::String names;
  22687. for (const auto& [name, move] : rows)
  22688. names << (names.isEmpty() ? "" : "\r\n") << name;
  22689. picture.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  22690. // a picture that is not a whole number of frames: FL's "Bitmap size is incorrect."
  22691. const juce::File wrong (prefix + "-sheet-wrong.png");
  22692. savePng (sheet.getClippedImage ({ 0, 0, sheet.getWidth() - 3, sheet.getHeight() }), wrong.getFullPathName());
  22693. wrong.withFileExtension ("txt").replaceWithText (names, false, false, nullptr);
  22694. auto error = lynx::dancer::SheetError::none;
  22695. const auto loaded = lynx::dancer::sheetFor (picture.getFullPathName().toStdString(), &error);
  22696. auto wrongError = lynx::dancer::SheetError::none;
  22697. const auto refused = lynx::dancer::sheetFor (wrong.getFullPathName().toStdString(), &wrongError);
  22698. auto missingError = lynx::dancer::SheetError::none;
  22699. const auto missing = lynx::dancer::sheetFor (juce::File (prefix + "-sheet-none.png").getFullPathName().toStdString(), &missingError);
  22700. sheetReport << "sheet_loaded=" << (loaded != nullptr ? 1 : 0) << "\n"
  22701. << "sheet_wrong_size_refused=" << (refused == nullptr && wrongError == lynx::dancer::SheetError::size ? 1 : 0) << "\n"
  22702. << "sheet_missing_refused=" << (missing == nullptr && missingError == lynx::dancer::SheetError::missing ? 1 : 0) << "\n";
  22703. bool ok = loaded != nullptr && refused == nullptr && missing == nullptr;
  22704. if (loaded != nullptr)
  22705. {
  22706. sheetReport << "sheet_rows=" << loaded->layout.rows << "\nsheet_frame=" << loaded->layout.frameWidth << "x" << loaded->layout.frameHeight
  22707. << "\nsheet_moves=" << loaded->moves() << "\nsheet_names=";
  22708. for (const auto& n : loaded->names)
  22709. sheetReport << juce::String::fromUTF8 (n.c_str()) << ";";
  22710. sheetReport << "\n";
  22711. ok = ok && loaded->layout.rows == (int) rows.size() && loaded->layout.frameWidth == fw && loaded->layout.frameHeight == fh;
  22712. // the animation as the stage draws it: a row of moments of the move "Wave" (blending on), then mirrored,
  22713. // then the row shown while the dancer is held
  22714. auto strip = lynx::shot::canvas (fw * 12, fh * 3 + 20);
  22715. int solid = 0;
  22716. {
  22717. juce::Graphics g (strip);
  22718. lynx::shot::logical (g);
  22719. g.fillAll (lynx::theme::colour::bg0);
  22720. for (int line = 0; line < 3; ++line)
  22721. {
  22722. lynx::dance::SheetAnimator animator (3);
  22723. for (int k = 0; k < 12; ++k)
  22724. {
  22725. const auto frame = animator.advance (k / 12.0 + 0.001, loaded->layout.rows, 4, line == 1, true, 0.5f, line == 2);
  22726. const juce::Point<float> feet ((k + 0.5f) * fw, (float) (line + 1) * fh + 5.0f);
  22727. lynx::dancer::drawSheet (g, *loaded, feet, 1.0f, frame);
  22728. solid += lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (0.0f, -70.0f)) ? 1 : 0;
  22729. ok = ok && ! lynx::dancer::sheetSolidAt (*loaded, feet, 1.0f, frame, feet.translated (-(float) fw * 0.5f + 1.0f, -(float) fh + 1.0f));
  22730. }
  22731. }
  22732. }
  22733. // mirrored = the same frame flipped left-right, on whatever renderer this build draws with
  22734. {
  22735. lynx::dance::SheetFrame plain;
  22736. plain.row = 3;
  22737. plain.column = 2;
  22738. auto turned = plain;
  22739. turned.mirrored = true;
  22740. juce::Image a (juce::Image::ARGB, fw, fh, true), b (juce::Image::ARGB, fw, fh, true);
  22741. {
  22742. juce::Graphics ga (a);
  22743. lynx::dancer::drawSheet (ga, *loaded, { fw * 0.5f, (float) fh }, 1.0f, plain);
  22744. }
  22745. {
  22746. juce::Graphics gb (b);
  22747. lynx::dancer::drawSheet (gb, *loaded, { fw * 0.5f, (float) fh }, 1.0f, turned);
  22748. }
  22749. int same = 0, flippedSame = 0, solidPixels = 0;
  22750. for (int y = 0; y < fh; ++y)
  22751. for (int x = 0; x < fw; ++x)
  22752. {
  22753. const auto pa = a.getPixelAt (x, y);
  22754. if (pa.getAlpha() < 200)
  22755. continue;
  22756. ++solidPixels;
  22757. auto alike = [pa] (juce::Colour c) {
  22758. return std::abs ((int) c.getRed() - (int) pa.getRed()) + std::abs ((int) c.getGreen() - (int) pa.getGreen())
  22759. + std::abs ((int) c.getBlue() - (int) pa.getBlue()) + std::abs ((int) c.getAlpha() - (int) pa.getAlpha()) < 12;
  22760. };
  22761. same += alike (b.getPixelAt (x, y)) ? 1 : 0;
  22762. flippedSame += alike (b.getPixelAt (fw - 1 - x, y)) ? 1 : 0;
  22763. }
  22764. const auto flips = solidPixels > 500 && flippedSame >= solidPixels * 98 / 100 && same < solidPixels * 95 / 100;
  22765. sheetReport << "sheet_mirror_flips=" << (flips ? 1 : 0) << " (" << flippedSame << " of " << solidPixels << " solid pixels match flipped, " << same
  22766. << " unflipped)\n";
  22767. ok = ok && flips;
  22768. }
  22769. sheetReport << "sheet_body_solid=" << solid << "/36\n";
  22770. ok = ok && solid >= 18;
  22771. savePng (strip, prefix + "-sheet-frames.png");
  22772. }
  22773. sheetReport << "sheet_result=" << (ok ? "OK" : "ERROR") << "\n";
  22774. lynx::ChannelDef c;
  22775. c.name = "Fruity Dance #3";
  22776. c.instrument = lynx::InstrumentKind::fruitydance;
  22777. lynx::dance::Settings s;
  22778. s.move = 2; // (the sheet's second row: "Step")
  22779. s.x = 1000;
  22780. s.y = 560;
  22781. s.sheet = picture.getFullPathName().toStdString();
  22782. c.pluginState = lynx::dance::toState (s);
  22783. song.channels.push_back (c);
  22784. }
  22785. song.patterns.emplace_back();
  22786. {
  22787. const juce::File demo (prefix + "-demo.lynx");
  22788. juce::String error;
  22789. lynx::ProjectFile::save (song, demo, error);
  22790. }
  22791. offline.setSong (std::move (song));
  22792. offline.dispatchPendingMessages();
  22793. if (auto editor = lynx::makeChannelSettingsPanel (offline, 0))
  22794. savePng (lynx::shot::snapshot (*editor), prefix + "-editor.png");
  22795. if (auto frame = lynx::makeChannelFrame (offline, 1, 0))
  22796. savePng (lynx::shot::snapshot (*frame), prefix + "-frame.png");
  22797. if (auto editor = lynx::makeChannelSettingsPanel (offline, 2))
  22798. savePng (lynx::shot::snapshot (*editor), prefix + "-sheet-editor.png");
  22799. {
  22800. // the stage with the three dancers (the third from the sheet)
  22801. lynx::DanceStage stage (offline);
  22802. stage.setSize (1280, 640);
  22803. stage.update();
  22804. sheetReport << "stage_dancers=" << stage.dancerCount() << "\n";
  22805. auto picture = lynx::shot::canvas (1280, 640);
  22806. {
  22807. juce::Graphics g (picture);
  22808. lynx::shot::logical (g);
  22809. g.fillAll (lynx::theme::colour::bg0);
  22810. stage.paintEntireComponent (g, true);
  22811. }
  22812. savePng (picture, prefix + "-sheet-stage.png");
  22813. }
  22814. juce::File (prefix + "-sheetreport.txt").replaceWithText (sheetReport);
  22815. }
  22816. void runControllerShot (const juce::String& prefix)
  22817. {
  22818. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  22819. lynx::AudioEngine offline (false);
  22820. lynx::Song song;
  22821. song.mixer = lynx::Song::defaultMixer (2);
  22822. song.mixer[1].name = "Insert 1";
  22823. auto fx = lynx::makeEffectSlot (lynx::EffectKind::formulaController);
  22824. lynx::formula::State formula;
  22825. formula.formula = "a*Sin(SongTime*Pi*b*4)+c";
  22826. fx.state = lynx::formula::writeState (formula);
  22827. fx.params[0] = 0.5f;
  22828. fx.params[1] = 0.25f;
  22829. fx.params[2] = 0.5f;
  22830. song.mixer[1].effects.push_back (fx);
  22831. // round 164: X-Y (slot 2), X-Y-Z (slot 3) and a Control Surface (slot 4)
  22832. {
  22833. auto xyFx = lynx::makeEffectSlot (lynx::EffectKind::xyController);
  22834. xyFx.params[(std::size_t) lynx::xy::level (0)] = 0.3f;
  22835. xyFx.params[(std::size_t) lynx::xy::level (1)] = 0.7f;
  22836. xyFx.params[(std::size_t) lynx::xy::tension (0)] = 0.8f;
  22837. song.mixer[1].effects.push_back (xyFx);
  22838. auto xyzFx = lynx::makeEffectSlot (lynx::EffectKind::xyzController);
  22839. xyzFx.params[(std::size_t) lynx::xy::level (2)] = 0.8f;
  22840. song.mixer[1].effects.push_back (xyzFx);
  22841. // round 165: an X-Y-Z whose X curve is FL's "Stairs" (tension +40 %) and Y a bent single curve
  22842. xyzFx.params[(std::size_t) lynx::xy::curveMode (0)] = lynx::xy::curveModeValue (lynx::flcurve::stairs);
  22843. xyzFx.params[(std::size_t) lynx::xy::tension (0)] = 0.7f;
  22844. xyzFx.params[(std::size_t) lynx::xy::level (0)] = 0.62f;
  22845. xyzFx.params[(std::size_t) lynx::xy::tension (1)] = 0.825f;
  22846. song.mixer[1].effects.push_back (xyzFx);
  22847. auto panel = lynx::makeEffectSlot (lynx::EffectKind::controlSurface);
  22848. lynx::SurfaceControl c;
  22849. for (const auto& [kind, name, v, x, y] : std::vector<std::tuple<lynx::SurfaceControl::Kind, const char*, float, float, float>> {
  22850. { lynx::SurfaceControl::Kind::knob, "Cutoff", 0.65f, 20.0f, 20.0f },
  22851. { lynx::SurfaceControl::Kind::knob, "Reso", 0.3f, 90.0f, 20.0f },
  22852. { lynx::SurfaceControl::Kind::slider, "Mix", 0.8f, 170.0f, 20.0f },
  22853. { lynx::SurfaceControl::Kind::xy, "Space", 0.4f, 230.0f, 20.0f },
  22854. { lynx::SurfaceControl::Kind::button, "Drop", 0.0f, 20.0f, 110.0f },
  22855. { lynx::SurfaceControl::Kind::checkBox, "Bypass", 1.0f, 20.0f, 160.0f } })
  22856. {
  22857. c.kind = kind;
  22858. c.name = name;
  22859. c.value = v;
  22860. c.valueY = 0.6f;
  22861. c.x = x;
  22862. c.y = y;
  22863. lynx::surface::add (panel, c);
  22864. }
  22865. song.mixer[1].effects.push_back (panel);
  22866. }
  22867. lynx::ChannelDef env;
  22868. env.name = "Envelope Controller";
  22869. env.instrument = lynx::InstrumentKind::controller;
  22870. auto ecData = lynx::defaultEnvelopeController();
  22871. ecData[0].lfoOn = true;
  22872. ecData[0].lfoTempo = true;
  22873. ecData[0].lfoSpeed = 40898;
  22874. ecData[0].maps[lynx::mapKeyboard].count = 2;
  22875. ecData[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  22876. ecData[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  22877. ecData[0].maps[lynx::mapModX] = ecData[0].maps[lynx::mapKeyboard];
  22878. env.controllerState = lynx::writeEnvelopeController (ecData);
  22879. song.channels.push_back (env);
  22880. lynx::ChannelDef out;
  22881. out.name = "MIDI Out";
  22882. out.instrument = lynx::InstrumentKind::midiOut;
  22883. lynx::midictl::MidiOutSettings settings;
  22884. settings.port = 1;
  22885. lynx::midictl::writeMidiOut (out.pluginState, settings);
  22886. song.channels.push_back (out);
  22887. // a Layer (round 164) over three synths split across the keyboard, crossfading
  22888. for (const auto* name : { "Bass", "Pad", "Lead" })
  22889. {
  22890. lynx::ChannelDef c;
  22891. c.name = name;
  22892. c.instrument = lynx::InstrumentKind::synth;
  22893. song.channels.push_back (c);
  22894. }
  22895. {
  22896. lynx::ChannelDef layer;
  22897. layer.name = "Layer";
  22898. layer.instrument = lynx::InstrumentKind::layer;
  22899. song.channels.push_back (layer);
  22900. const auto self = (int) song.channels.size() - 1;
  22901. lynx::layer::setChildren (song, self, { 2, 3, 4 });
  22902. song.channels[2].keyLow = 0, song.channels[2].keyHigh = 47;
  22903. song.channels[3].keyLow = 36, song.channels[3].keyHigh = 83;
  22904. song.channels[4].keyLow = 72, song.channels[4].keyHigh = 127;
  22905. song.channels[(std::size_t) self].layer.crossfade = true;
  22906. song.channels[(std::size_t) self].layer.fade = 0.35f;
  22907. }
  22908. {
  22909. lynx::ChannelDef dash; // channel 6
  22910. dash.name = "Dashboard";
  22911. dash.instrument = lynx::InstrumentKind::dashboard;
  22912. dash.patcher.surface = lynx::surface::starterControls();
  22913. song.channels.push_back (dash);
  22914. }
  22915. {
  22916. lynx::ChannelDef volt; // channel 7: FL's render-test settings (main L pitch, R gate × 0.5) with Out 2 on insert 3
  22917. volt.name = "Voltage Controller";
  22918. volt.instrument = lynx::InstrumentKind::voltage;
  22919. lynx::voltage::Settings v;
  22920. v.enabled = true;
  22921. v.params[9] = 49152;
  22922. v.unipolar[2] = true;
  22923. v.tracks = { 3, 0, 0 };
  22924. v.source[6] = lynx::voltage::Source::clock;
  22925. volt.pluginState = lynx::voltage::write (v);
  22926. song.channels.push_back (volt);
  22927. }
  22928. song.patterns.emplace_back();
  22929. offline.setSong (std::move (song));
  22930. offline.dispatchPendingMessages();
  22931. auto shoot = [&] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  22932. if (c == nullptr)
  22933. return;
  22934. savePng (lynx::shot::snapshot (*c), prefix + name);
  22935. };
  22936. shoot (lynx::makeChannelSettingsPanel (offline, 0), "-envelope-controller.png");
  22937. shoot (lynx::makeChannelSettingsPanel (offline, 1), "-midi-out.png");
  22938. shoot (lynx::makeChannelSettingsPanel (offline, 5), "-layer.png");
  22939. shoot (lynx::makeChannelFrame (offline, 3, -1), "-layer-child-misc.png"); // (the key-region ruler over the root keyboard)
  22940. {
  22941. const auto slotOf = [] (int k) -> lynx::SlotLocator {
  22942. return [k] (lynx::Song& s) { return &s.mixer[1].effects[(std::size_t) k]; };
  22943. };
  22944. const lynx::AutomationTarget target { lynx::AutomationTargetKind::effectParam, 1, 1, 0 };
  22945. shoot (lynx::makeXyControllerEditor (offline, slotOf (1), nullptr, target), "-xy-controller.png");
  22946. shoot (lynx::makeXyControllerEditor (offline, slotOf (2), nullptr, target), "-xyz-controller.png");
  22947. shoot (lynx::makeXyControllerEditor (offline, slotOf (3), nullptr, target), "-xyz-controller-stairs.png");
  22948. shoot (lynx::makeControlSurfaceEditor (offline, slotOf (4), target), "-control-surface.png");
  22949. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard.png");
  22950. shoot (lynx::makeChannelSettingsPanel (offline, 7), "-voltage-controller.png");
  22951. }
  22952. // FL's Dashboard presets of this PC's FL Studio, imported (round 164f): one PNG each
  22953. if (const auto fl = lynx::findFlStudio(); fl.installDir.isDirectory())
  22954. for (const auto& file : fl.installDir.getChildFile ("Data/Patches/Plugin presets/Generators/Dashboard").findChildFiles (juce::File::findFiles, false, "*.fst"))
  22955. {
  22956. juce::MemoryBlock bytes;
  22957. if (! file.loadFileAsData (bytes))
  22958. continue;
  22959. const auto preset = flp::parseProject ({ (const std::uint8_t*) bytes.getData(), bytes.getSize() }, true);
  22960. const auto dash = preset.channels.empty() ? std::nullopt : lynx::surface::parseFlDashboard (preset.channels[0].pluginState);
  22961. if (! dash || dash->controls.empty())
  22962. continue;
  22963. offline.editSong ([&] (lynx::Song& s) {
  22964. s.channels[6].name = file.getFileNameWithoutExtension().toStdString();
  22965. s.channels[6].patcher.surface = dash->controls;
  22966. s.channels[6].pluginState = preset.channels[0].pluginState; // (its MIDI port, channel, program)
  22967. });
  22968. offline.dispatchPendingMessages();
  22969. const auto name = file.getFileNameWithoutExtension().replaceCharacter (' ', '-');
  22970. shoot (lynx::makeChannelSettingsPanel (offline, 6), "-dashboard-fl-" + name + ".png");
  22971. // edit mode (round 165): each control's output number and the MIDI it sends ("1 CC74")
  22972. if (auto panel = lynx::makeChannelSettingsPanel (offline, 6))
  22973. {
  22974. std::function<void (juce::Component&)> pressEdit = [&] (juce::Component& c) {
  22975. for (auto* child : c.getChildren())
  22976. {
  22977. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == lynx::tr ("Edit"))
  22978. b->setToggleState (true, juce::sendNotificationSync);
  22979. pressEdit (*child);
  22980. }
  22981. };
  22982. pressEdit (*panel);
  22983. shoot (std::move (panel), "-dashboard-fl-" + name + "-edit.png");
  22984. }
  22985. }
  22986. // the Envelope Controller's pages (issue #7): one PNG per part of the dropdown
  22987. if (auto ec = lynx::makeEnvelopeControllerEditor (offline, 0))
  22988. for (int part = 0; part < 7; ++part)
  22989. {
  22990. for (auto* child : ec->getChildren())
  22991. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  22992. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  22993. savePng (lynx::shot::snapshot (*ec), prefix + "-ec-part" + juce::String (part) + ".png");
  22994. }
  22995. lynx::FormulaControllerWindows::open (offline, 1, 0);
  22996. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  22997. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  22998. if (w->getName().startsWith ("Formula") && w->getContentComponent() != nullptr)
  22999. savePng (lynx::shot::snapshot (*w->getContentComponent()), prefix + "-formula-controller.png");
  23000. lynx::FormulaControllerWindows::closeAll();
  23001. }
  23002. bool runEdisonSlotTest (const juce::String& folderPath, const juce::String& flp)
  23003. {
  23004. namespace ae = lynx::audioedit;
  23005. namespace ef = lynx::edisonfx;
  23006. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23007. const juce::File folder (folderPath);
  23008. folder.createDirectory();
  23009. juce::String report;
  23010. bool all = true;
  23011. auto check = [&] (const juce::String& name, bool ok, const juce::String& note = {}) {
  23012. report << name << "=" << (ok ? "ok" : "FAIL") << (note.isNotEmpty() ? " (" + note + ")" : juce::String()) << "\n";
  23013. all = all && ok;
  23014. };
  23015. auto shot = [&folder] (juce::Component& c, const juce::String& name) {
  23016. savePng (lynx::shot::paint (c, lynx::theme::panel), folder.getChildFile (name).getFullPathName());
  23017. };
  23018. auto findSlot = [] (const lynx::Song& song, int& track, int& slot) {
  23019. for (track = 0; track < (int) song.mixer.size(); ++track)
  23020. for (slot = 0; slot < (int) song.mixer[(std::size_t) track].effects.size(); ++slot)
  23021. if (song.mixer[(std::size_t) track].effects[(std::size_t) slot].kind == lynx::EffectKind::edison)
  23022. return true;
  23023. return false;
  23024. };
  23025. {
  23026. lynx::AudioEngine engine (false);
  23027. engine.setRecordingTarget (folder.getChildFile ("Audio").getChildFile ("Recorded"), "Test");
  23028. // a project without the plugin is written as before: nothing of it in the file, and it reads back the same
  23029. const auto before = lynx::ProjectFile::toJson (engine.getSong(), false);
  23030. juce::String error;
  23031. const auto same = lynx::ProjectFile::fromJson (before, error);
  23032. check ("old_project_text_has_no_trace", ! before.containsIgnoreCase ("edison"));
  23033. check ("old_project_round_trip_stable", same.has_value() && lynx::ProjectFile::toJson (*same, false) == before);
  23034. const auto at = lynx::addEdisonSlot (engine, 1);
  23035. engine.dispatchPendingMessages();
  23036. check ("slot_added_to_first_empty_slot", at == 0 && engine.getSong().mixer[1].effects.size() == 1
  23037. && engine.getSong().mixer[1].effects[0].kind == lynx::EffectKind::edison);
  23038. if (at < 0)
  23039. {
  23040. folder.getChildFile ("report.txt").replaceWithText (report);
  23041. return false;
  23042. }
  23043. const auto second = lynx::addEdisonSlot (engine, 1); // several instances on a track
  23044. engine.dispatchPendingMessages();
  23045. check ("second_instance_on_the_same_track", second == 1);
  23046. engine.editSong ([at] (lynx::Song& s) {
  23047. s.mixer[1].effects[(std::size_t) at].params[ef::recordMode] = ef::modeValue (ef::Mode::now);
  23048. });
  23049. engine.dispatchPendingMessages();
  23050. const auto slotOf = [&engine, at] { return engine.getSong().mixer[1].effects[(std::size_t) at]; };
  23051. const auto fx = engine.getEffect (1, at);
  23052. const auto p = std::dynamic_pointer_cast<ef::Processor> (fx);
  23053. const auto session = ef::findSession (slotOf().instance.id);
  23054. check ("engine_built_the_effect_with_its_session", p != nullptr && session != nullptr);
  23055. const auto other = ef::findSession (engine.getSong().mixer[1].effects[1].instance.id);
  23056. check ("instances_have_their_own_audio", other != nullptr && other != session);
  23057. if (p == nullptr || session == nullptr)
  23058. {
  23059. folder.getChildFile ("report.txt").replaceWithText (report);
  23060. return false;
  23061. }
  23062. // idle: the audio passes through bit for bit
  23063. const auto rate = p->sampleRate();
  23064. std::vector<float> l (512), r (512);
  23065. auto fill = [&] (int block) {
  23066. for (int k = 0; k < 512; ++k)
  23067. {
  23068. const auto t = (double) (block * 512 + k) / rate;
  23069. l[(std::size_t) k] = 0.6f * (float) std::sin (2.0 * 3.141592653589793 * 220.0 * t);
  23070. r[(std::size_t) k] = 0.4f * (float) std::sin (2.0 * 3.141592653589793 * 330.0 * t);
  23071. }
  23072. };
  23073. fill (0);
  23074. auto inL = l, inR = r;
  23075. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  23076. check ("idle_pass_through_bit_exact", l == inL && r == inR);
  23077. // a take through the slot (Now), then the flush that makes it a file of the project
  23078. std::vector<float> wantL, wantR;
  23079. check ("record_starts", session->start (p, true));
  23080. for (int block = 0; block < 60; ++block)
  23081. {
  23082. fill (block);
  23083. wantL.insert (wantL.end(), l.begin(), l.end());
  23084. wantR.insert (wantR.end(), r.begin(), r.end());
  23085. p->process (l.data(), r.data(), 512, slotOf().params, 120.0);
  23086. }
  23087. session->stop();
  23088. check ("take_is_the_input", session->document().audio.numChannels() == 2 && session->document().audio.channels[0] == wantL
  23089. && session->document().audio.channels[1] == wantR);
  23090. ae::Document withMarkers = session->document();
  23091. ae::addMarker (withMarkers, 4000, "Verse");
  23092. ae::addMarker (withMarkers, 12000);
  23093. ae::setLoop (withMarkers, { 2000, 20000 });
  23094. session->setDocument (withMarkers);
  23095. engine.flushEdisonAudio();
  23096. engine.dispatchPendingMessages();
  23097. const juce::File file (juce::String::fromUTF8 (slotOf().samplePath.c_str()));
  23098. check ("audio_written_to_the_project_folder", file.existsAsFile() && file.isAChildOf (folder.getChildFile ("Audio").getChildFile ("Recorded")),
  23099. file.getFullPathName());
  23100. check ("file_listed_with_the_session_recordings", std::find (engine.getSessionRecordings().begin(), engine.getSessionRecordings().end(), file)
  23101. != engine.getSessionRecordings().end());
  23102. check ("effect_kept_running_through_the_flush", engine.getEffect (1, at) == fx);
  23103. check ("nothing_unsaved_after_the_flush", ! session->dirty());
  23104. engine.flushEdisonAudio(); // (a second flush writes nothing new)
  23105. check ("second_flush_keeps_the_file", juce::File (juce::String::fromUTF8 (slotOf().samplePath.c_str())) == file);
  23106. // the project file: saved, loaded, the same slot with the same audio
  23107. engine.editSong ([at] (lynx::Song& s) {
  23108. auto& params = s.mixer[1].effects[(std::size_t) at].params;
  23109. params[ef::recordMode] = ef::modeValue (ef::Mode::onPlay);
  23110. params[ef::append] = 0.0f;
  23111. params[ef::muteInput] = 1.0f;
  23112. params[ef::slave] = 1.0f;
  23113. params[ef::maxTime] = 5.0f / 6.0f;
  23114. });
  23115. engine.capturePluginStates();
  23116. const auto project = folder.getChildFile ("edison-slot.lynx");
  23117. check ("project_saved", lynx::ProjectFile::save (engine.getSong(), project, error), error);
  23118. auto loaded = lynx::ProjectFile::load (project, error);
  23119. check ("project_loaded", loaded.has_value(), error);
  23120. if (loaded)
  23121. {
  23122. const auto& a = slotOf();
  23123. const auto& b = loaded->mixer[1].effects[(std::size_t) at];
  23124. check ("slot_kind_kept", b.kind == lynx::EffectKind::edison && loaded->mixer[1].effects.size() == 2);
  23125. check ("slot_settings_kept", ef::modeOf (b.params) == ef::Mode::onPlay && b.params[ef::append] < 0.5f && b.params[ef::muteInput] >= 0.5f
  23126. && b.params[ef::slave] >= 0.5f && ef::maxTimeIndexOf (b.params) == 5
  23127. && std::abs (b.params[ef::noiseThreshold] - a.params[ef::noiseThreshold]) < 1.0e-6f);
  23128. check ("slot_audio_path_kept", b.samplePath == a.samplePath);
  23129. check ("project_text_round_trip_stable", lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (engine.getSong(), false));
  23130. lynx::AudioEngine second (false);
  23131. second.setSong (std::move (*loaded));
  23132. second.dispatchPendingMessages();
  23133. const auto reopened = ef::findSession (second.getSong().mixer[1].effects[(std::size_t) at].instance.id);
  23134. check ("reopened_project_has_the_audio", reopened != nullptr && reopened != session
  23135. && reopened->document().audio.channels == withMarkers.audio.channels
  23136. && reopened->document().audio.sampleRate == withMarkers.audio.sampleRate);
  23137. check ("reopened_project_has_markers_and_loop", reopened != nullptr && reopened->document().markers.size() == 2
  23138. && reopened->document().markers[0].name == "Verse"
  23139. && reopened->document().loopStart == 2000 && reopened->document().loopEnd == 20000);
  23140. check ("reopened_empty_instance_is_empty", ef::findSession (second.getSong().mixer[1].effects[1].instance.id) != nullptr
  23141. && ef::findSession (second.getSong().mixer[1].effects[1].instance.id)->document().audio.empty());
  23142. if (auto editor = lynx::makeEdisonSlotEditor (second, 1, at))
  23143. {
  23144. editor->setSize (1120, 600);
  23145. second.dispatchPendingMessages();
  23146. shot (*editor, "slot-editor-reopened.png");
  23147. }
  23148. }
  23149. // the plugin's window: the audio editor on the slot (empty instance, then the one with the take)
  23150. if (auto editor = lynx::makeEdisonSlotEditor (engine, 1, 1))
  23151. {
  23152. editor->setSize (1120, 600);
  23153. engine.dispatchPendingMessages();
  23154. shot (*editor, "slot-editor-empty.png");
  23155. }
  23156. auto editor = lynx::makeEdisonSlotEditor (engine, 1, at);
  23157. check ("slot_window_is_the_audio_editor", editor != nullptr);
  23158. if (editor != nullptr)
  23159. {
  23160. editor->setSize (1120, 600);
  23161. engine.dispatchPendingMessages();
  23162. shot (*editor, "slot-editor.png");
  23163. juce::File (folder.getChildFile ("slot-menu.txt")).replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  23164. }
  23165. check ("no_editor_for_other_slots", lynx::makeEdisonSlotEditor (engine, 0, 0) == nullptr);
  23166. editor.reset();
  23167. // deleting the slot leaves the song without it (the file stays for the unused-recordings prompt)
  23168. engine.editSong ([at] (lynx::Song& s) { s.mixer[1].effects.erase (s.mixer[1].effects.begin() + at); });
  23169. engine.dispatchPendingMessages();
  23170. check ("deleted_slot_is_gone", engine.getSong().mixer[1].effects.size() == 1 && file.existsAsFile());
  23171. }
  23172. if (flp.isNotEmpty())
  23173. {
  23174. lynx::AudioEngine engine (false);
  23175. juce::String error;
  23176. const auto imported = engine.importFlpFile (juce::File (flp), error);
  23177. engine.dispatchPendingMessages();
  23178. check ("flp_imported", imported, error);
  23179. int count = 0, withAudio = 0;
  23180. const auto& song = engine.getSong();
  23181. for (int t = 0; t < (int) song.mixer.size(); ++t)
  23182. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  23183. {
  23184. const auto& fx = song.mixer[(std::size_t) t].effects[(std::size_t) s];
  23185. if (fx.kind != lynx::EffectKind::edison)
  23186. continue;
  23187. ++count;
  23188. const auto session = ef::findSession (fx.instance.id);
  23189. const auto frames = session != nullptr ? session->document().audio.frames() : -1;
  23190. withAudio += frames > 0 ? 1 : 0;
  23191. report << "flp_slot track " << t << " slot " << s << ": mode " << ef::modeName (ef::modeOf (fx.params))
  23192. << ", append " << (fx.params[ef::append] >= 0.5f ? "on" : "off") << ", mute input " << (fx.params[ef::muteInput] >= 0.5f ? "on" : "off")
  23193. << ", slave " << (fx.params[ef::slave] >= 0.5f ? "on" : "off") << ", loop " << (fx.params[ef::loopPlay] >= 0.5f ? "on" : "off")
  23194. << ", max time index " << ef::maxTimeIndexOf (fx.params) << ", threshold " << juce::String (fx.params[ef::noiseThreshold], 4)
  23195. << ", state " << (int) fx.state.size() << " bytes, audio " << (juce::int64) frames << " frames"
  23196. << (session != nullptr && frames > 0 ? " at " + juce::String (session->document().audio.sampleRate, 0) + " Hz, "
  23197. + juce::String (session->document().audio.numChannels()) + " ch, "
  23198. + juce::String ((int) session->document().markers.size()) + " markers"
  23199. : juce::String())
  23200. << "\n";
  23201. if (count == 1 || (frames > 0 && withAudio == 1))
  23202. if (auto editor = lynx::makeEdisonSlotEditor (engine, t, s))
  23203. {
  23204. editor->setSize (1120, 600);
  23205. engine.dispatchPendingMessages();
  23206. shot (*editor, frames > 0 ? "slot-editor-flp-audio.png" : "slot-editor-flp.png");
  23207. }
  23208. }
  23209. check ("flp_edison_slots_kept_as_the_plugin", count > 0, juce::String (count) + " slots, " + juce::String (withAudio) + " with audio");
  23210. // saved as .lynx and read again: still the plugin, FL's state (the audio) with it
  23211. int t = 0, s = 0;
  23212. if (findSlot (song, t, s))
  23213. {
  23214. const auto project = folder.getChildFile ("edison-flp.lynx");
  23215. const auto saved = lynx::ProjectFile::save (song, project, error);
  23216. std::optional<lynx::Song> loaded;
  23217. if (saved)
  23218. loaded = lynx::ProjectFile::load (project, error);
  23219. check ("flp_slot_survives_the_project_file", loaded.has_value() && t < (int) loaded->mixer.size()
  23220. && s < (int) loaded->mixer[(std::size_t) t].effects.size()
  23221. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::edison
  23222. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].state == song.mixer[(std::size_t) t].effects[(std::size_t) s].state
  23223. && loaded->mixer[(std::size_t) t].effects[(std::size_t) s].params == song.mixer[(std::size_t) t].effects[(std::size_t) s].params,
  23224. error);
  23225. }
  23226. }
  23227. // round 190ct (live FL check 190cq): the open-and-record preset, the fresh defaults and the question before
  23228. // "Remove all Edison instances", in the app
  23229. {
  23230. lynx::AudioEngine engine (false);
  23231. lynx::MainComponent ui (engine, false);
  23232. ui.setSize (1600, 900);
  23233. engine.dispatchPendingMessages();
  23234. const auto toolsMenu = [&ui] {
  23235. const auto names = ui.getMenuNamesForSnapshot();
  23236. for (int m = 0; m < names.size(); ++m)
  23237. if (names[m] == lynx::tr ("Tools"))
  23238. return ui.getMenuForSnapshot (m);
  23239. return juce::PopupMenu();
  23240. };
  23241. const auto removeItem = [&toolsMenu] (bool& found, bool& enabled) {
  23242. found = enabled = false;
  23243. const auto menu = toolsMenu(); // (the iterator keeps a reference)
  23244. for (juce::PopupMenu::MenuItemIterator it (menu, true); it.next();)
  23245. if (it.getItem().text == lynx::tr ("Remove all Edison instances"))
  23246. {
  23247. found = true;
  23248. enabled = it.getItem().isEnabled;
  23249. if (enabled && it.getItem().action)
  23250. it.getItem().action(); // asks: nothing may go before the answer
  23251. return;
  23252. }
  23253. };
  23254. const auto count = [&engine] {
  23255. int n = 0;
  23256. for (const auto& track : engine.getSong().mixer)
  23257. for (const auto& fx : track.effects)
  23258. n += fx.kind == lynx::EffectKind::edison ? 1 : 0;
  23259. return n;
  23260. };
  23261. bool found = false, enabled = false;
  23262. removeItem (found, enabled);
  23263. check ("remove_all_edison_enabled_with_none", found && enabled && count() == 0);
  23264. const auto plain = lynx::addEdisonSlot (engine, 1);
  23265. const auto armed = lynx::addEdisonSlot (engine, 2, true);
  23266. engine.dispatchPendingMessages();
  23267. if (plain >= 0 && armed >= 0)
  23268. {
  23269. const auto& a = engine.getSong().mixer[1].effects[(std::size_t) plain].params;
  23270. const auto& b = engine.getSong().mixer[2].effects[(std::size_t) armed].params;
  23271. check ("open_audio_editor_fresh_defaults", ef::modeOf (a) == ef::Mode::onInput && ef::maxTimeIndexOf (a) == 5 && a[ef::append] >= 0.5f
  23272. && a[ef::slave] < 0.5f);
  23273. check ("open_audio_editor_and_record_preset", ef::modeOf (b) == ef::Mode::onPlay && ef::maxTimeIndexOf (b) == 3 && b[ef::append] < 0.5f
  23274. && b[ef::slave] >= 0.5f);
  23275. }
  23276. else
  23277. check ("open_audio_editor_slots_added", false);
  23278. removeItem (found, enabled);
  23279. engine.dispatchPendingMessages();
  23280. check ("remove_all_edison_asks_first", found && enabled && count() == 2);
  23281. const auto question = lynx::removeAllEdisonInstancesQuestion();
  23282. check ("remove_all_edison_question_is_fls", question.getTitle() == lynx::tr ("Remove Edison instances")
  23283. && question.getMessage() == lynx::tr ("Are you sure you want to remove all Edison instances from the project ?")
  23284. && question.getNumButtons() == 2 && question.getButtonText (0) == lynx::tr ("Yes")
  23285. && question.getButtonText (1) == lynx::tr ("No"));
  23286. // LYNX keeps an undo for the removal (rollup 190cv), so the question may not promise "(No undo)" in any
  23287. // language, and the Yes action must come back with one undo
  23288. {
  23289. bool noUndoLine = false;
  23290. for (const auto& line : juce::StringArray::fromLines (question.getMessage()))
  23291. noUndoLine = noUndoLine || line.trim().startsWithChar ('(');
  23292. check ("remove_all_edison_question_has_no_no_undo_line", ! noUndoLine && ! question.getMessage().contains ("No undo"));
  23293. const int before = count();
  23294. lynx::removeAllEdisonInstances (engine);
  23295. engine.dispatchPendingMessages();
  23296. const int removed = count();
  23297. engine.undo();
  23298. engine.dispatchPendingMessages();
  23299. check ("remove_all_edison_yes_removes_and_undo_restores", before == 2 && removed == 0 && count() == 2);
  23300. }
  23301. {
  23302. juce::AlertWindow box (question.getTitle(), question.getMessage(), question.getIconType());
  23303. box.addButton (question.getButtonText (0), 1);
  23304. box.addButton (question.getButtonText (1), 0);
  23305. box.setSize (box.getWidth(), box.getHeight());
  23306. savePng (lynx::shot::paint (box, lynx::theme::panel), folder.getChildFile ("remove-all-edison-question.png").getFullPathName());
  23307. }
  23308. {
  23309. lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::edison);
  23310. lynx::edisonfx::setOpenAndRecord (slot.params);
  23311. engine.editSong ([&slot] (lynx::Song& s) { s.mixer[3].effects.push_back (slot); });
  23312. engine.dispatchPendingMessages();
  23313. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 3, 0))
  23314. {
  23315. editor->setSize (1120, 600);
  23316. engine.dispatchPendingMessages();
  23317. shot (*editor, "slot-editor-open-and-record.png");
  23318. }
  23319. if (const auto editor = lynx::makeEdisonSlotEditor (engine, 1, plain))
  23320. {
  23321. editor->setSize (1120, 600);
  23322. engine.dispatchPendingMessages();
  23323. shot (*editor, "slot-editor-fresh-defaults.png");
  23324. }
  23325. }
  23326. }
  23327. report << (all ? "ALL OK\n" : "FAILURES\n");
  23328. folder.getChildFile ("report.txt").replaceWithText (report);
  23329. return all;
  23330. }
  23331. void runAraShot190kx (const juce::String& prefix)
  23332. {
  23333. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23334. lynx::AudioEngine engine (false);
  23335. juce::PluginDescription melodyne;
  23336. melodyne.name = "Melodyne";
  23337. melodyne.manufacturerName = "Celemony";
  23338. melodyne.pluginFormatName = "VST3";
  23339. melodyne.fileOrIdentifier = "C:\\Program Files\\Common Files\\VST3\\Celemony\\Melodyne\\Melodyne.vst3";
  23340. melodyne.uniqueId = 0x190;
  23341. melodyne.isInstrument = false;
  23342. #if JUCE_PLUGINHOST_ARA
  23343. melodyne.hasARAExtension = true;
  23344. #endif
  23345. engine.getPluginHost().getKnownPlugins().addType (melodyne);
  23346. lynx::MainComponent ui (engine, false);
  23347. ui.setSize (1600, 900);
  23348. {
  23349. auto song = lynx::Song::makeDefault();
  23350. song.channels.push_back ({});
  23351. song.channels.back().name = "Vocal";
  23352. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  23353. song.channels.back().samplePath = writeShotSample (juce::File (prefix + "-vox.wav"), 330.0).getFullPathName().toStdString();
  23354. lynx::Clip c;
  23355. c.kind = lynx::ClipKind::audio;
  23356. c.channel = (int) song.channels.size() - 1;
  23357. c.track = 3;
  23358. c.start = 4 * lynx::ppq;
  23359. c.length = 2 * lynx::ppq;
  23360. song.playlist.push_back (c);
  23361. engine.setSong (std::move (song));
  23362. }
  23363. engine.dispatchPendingMessages();
  23364. auto& playlist = ui.getPlaylistForSnapshot();
  23365. auto sub = [] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu* {
  23366. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23367. if (it.getItem().subMenu != nullptr && it.getItem().text == text)
  23368. return it.getItem().subMenu.get();
  23369. return nullptr;
  23370. };
  23371. juce::String report;
  23372. for (const auto edited : { false, true })
  23373. {
  23374. if (edited) // (the channel edited in the stand-in: the menu ticks it and offers its editor; nothing is loaded here)
  23375. {
  23376. const auto ch = engine.getSong().playlist[0].channel;
  23377. engine.editSong ([ch, id = melodyne.createIdentifierString().toStdString()] (lynx::Song& s) {
  23378. s.channels[(std::size_t) ch].ara = { id, "Melodyne" };
  23379. }, false);
  23380. }
  23381. const auto menu = playlist.getClipMenuForSnapshot (0);
  23382. savePng (columnMenuImage (menu), prefix + (edited ? "-clip-menu-edited.png" : "-clip-menu.png"));
  23383. if (const auto* ara = sub (menu, lynx::tr ("Edit in ARA plugin")))
  23384. {
  23385. savePng (columnMenuImage (*ara), prefix + (edited ? "-ara-submenu-edited.png" : "-ara-submenu.png"));
  23386. report << (edited ? "edited:" : "plain:");
  23387. for (juce::PopupMenu::MenuItemIterator it (*ara); it.next();)
  23388. report << " [" << (it.getItem().isSeparator ? juce::String ("-") : it.getItem().text) << (it.getItem().isTicked ? " *" : "") << "]";
  23389. report << "\n";
  23390. }
  23391. else
  23392. report << "no ARA submenu\n";
  23393. }
  23394. lynx::shot::file (juce::File (prefix + "-menus.txt")).replaceWithText (report);
  23395. std::printf ("%s", report.toRawUTF8());
  23396. }
  23397. bool runPolyEditShot190lk (const juce::String& prefix, const juce::String& file, double key)
  23398. {
  23399. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23400. lynx::AudioEngine engine (false);
  23401. lynx::MainComponent ui (engine, false);
  23402. ui.setSize (1600, 900);
  23403. juce::StringArray checks;
  23404. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  23405. auto song = lynx::Song::makeDefault();
  23406. const auto sample = engine.getSampleLibrary().load (file);
  23407. song.channels.push_back ({});
  23408. song.channels.back().name = juce::File (file).getFileNameWithoutExtension().toStdString();
  23409. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  23410. song.channels.back().samplePath = file.toStdString();
  23411. const auto channel = (int) song.channels.size() - 1;
  23412. lynx::Clip c;
  23413. c.kind = lynx::ClipKind::audio;
  23414. c.channel = channel;
  23415. c.track = 3;
  23416. const auto seconds = sample != nullptr ? (double) sample->frames() / sample->sampleRate : 4.0;
  23417. c.length = (std::int64_t) std::llround (seconds * song.bpm / 60.0 * lynx::ppq);
  23418. song.playlist.push_back (c);
  23419. engine.setSong (std::move (song));
  23420. engine.dispatchPendingMessages();
  23421. const auto clipIndex = (int) engine.getSong().playlist.size() - 1;
  23422. check (sample != nullptr && sample->frames() > 0, "the sample loads: " + file);
  23423. const auto wanted = lynx::tr ("Edit notes (polyphonic)...");
  23424. for (const auto simple : { false, true })
  23425. {
  23426. ui.setLayoutStyle (simple ? lynx::layoutstyle::Style::simple : lynx::layoutstyle::Style::pattern);
  23427. engine.dispatchPendingMessages();
  23428. const auto menu = ui.getPlaylistForSnapshot().getClipMenuForSnapshot (clipIndex);
  23429. auto afterExtras = false, found = false;
  23430. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23431. {
  23432. afterExtras = afterExtras || (it.getItem().isSectionHeader && it.getItem().text == lynx::tr ("LYNX extras"));
  23433. found = found || (it.getItem().text == wanted && it.getItem().isEnabled && (afterExtras || simple));
  23434. }
  23435. savePng (columnMenuImage (menu), prefix + (simple ? "-clip-menu-simple.png" : "-clip-menu.png"));
  23436. check (found, juce::String (simple ? "Simple" : "Pattern") + " layout: the clip menu has \"" + wanted + "\" (LYNX extras)");
  23437. }
  23438. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  23439. engine.dispatchPendingMessages();
  23440. // the editor: analysis on this thread (Basic Pitch's evidence when ONNX Runtime loads)
  23441. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  23442. auto editor = lynx::makePolyEditor (engine, channel, true);
  23443. const auto analyseMs = juce::Time::getMillisecondCounterHiRes() - t0;
  23444. engine.dispatchPendingMessages();
  23445. editor->setSize (1100, 560);
  23446. const auto notes = lynx::polyEditorNotes (*editor);
  23447. juce::File (prefix + "-notes.txt").replaceWithText (notes);
  23448. const auto lines = juce::StringArray::fromLines (notes.trim());
  23449. check (notes.isNotEmpty(), juce::String (lines.size()) + " notes found in " + juce::String (analyseMs / 1000.0, 2) + " s for "
  23450. + juce::String (seconds, 2) + " s of audio (" + juce::String (analyseMs / 1000.0 / std::max (0.01, seconds), 3) + " x real time)");
  23451. const auto saved = engine.getSong().channels[(std::size_t) channel].polyEdit;
  23452. 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");
  23453. const auto shoot = [&] (const juce::String& name) {
  23454. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-" + name + ".png");
  23455. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, 1.5f), prefix + "-" + name + "@150.png");
  23456. };
  23457. shoot ("editor");
  23458. // the note nearest `key` in the first two seconds
  23459. int pick = -1;
  23460. double best = 1e9;
  23461. for (const auto& line : lines)
  23462. {
  23463. const auto t = juce::StringArray::fromTokens (line, " ", "");
  23464. if (t.size() < 4 || line.endsWith (" candidate")) // (round 190lo: the rejected candidates are listed too)
  23465. continue;
  23466. const auto start = t[3].upToFirstOccurrenceOf ("-", false, false).getDoubleValue();
  23467. const auto d = std::abs (t[2].getDoubleValue() - key) + (start > 2.0 ? 100.0 : 0.0);
  23468. if (d < best)
  23469. best = d, pick = t[0].getIntValue();
  23470. }
  23471. check (pick >= 0 && best < 0.5, "a note at key " + juce::String (key, 1) + ": note " + juce::String (pick));
  23472. if (pick >= 0)
  23473. {
  23474. lynx::setPolyEditorShotState (*editor, "select:" + juce::String (pick));
  23475. lynx::setPolyEditorShotState (*editor, "pitch:" + juce::String (pick) + ":-1");
  23476. const auto rendered = lynx::setPolyEditorShotState (*editor, "render");
  23477. engine.dispatchPendingMessages();
  23478. check (rendered.startsWith ("render"), "the edit renders: " + rendered);
  23479. const auto blob = engine.getSong().channels[(std::size_t) channel].polyEdit;
  23480. const auto model = lynx::polyedit::parse (blob);
  23481. check (model && model->edited(), "the edit is in the channel (one undo step)");
  23482. // what the clip plays: the cached render, at once
  23483. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  23484. const auto plays = lynx::polyedit::renderedFor (file.toStdString(), sample, blob);
  23485. const auto lookupMs = juce::Time::getMillisecondCounterHiRes() - t1;
  23486. check (plays != nullptr && plays != sample && plays->frames() == sample->frames(), "the clip plays the edited render (cache hit in " + juce::String (lookupMs, 2) + " ms)");
  23487. // the project keeps it
  23488. juce::String error;
  23489. const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (engine.getSong()), error);
  23490. 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");
  23491. // undo: the edit goes, the analysis stays
  23492. engine.undo();
  23493. engine.dispatchPendingMessages();
  23494. const auto undone = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  23495. check (undone && ! undone->edited() && undone->notes.size() == model->notes.size(), "undo takes the edit back, the analysis stays");
  23496. engine.redo();
  23497. engine.dispatchPendingMessages();
  23498. shoot ("edited");
  23499. lynx::setPolyEditorShotState (*editor, "select:");
  23500. shoot ("edited-plain");
  23501. }
  23502. check (true, "paint " + juce::String (lynx::polyEditorPaintMs (*editor, 10), 2) + " ms (1100 x 560)");
  23503. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  23504. editor.reset();
  23505. engine.dispatchPendingMessages();
  23506. return ! checks.joinIntoString ("\n").contains ("FAIL ");
  23507. }
  23508. // round 190lo: see --polyeditshot190lo
  23509. bool runPolyEditShot190lo (const juce::String& prefix, const juce::String& file, double key)
  23510. {
  23511. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23512. lynx::AudioEngine engine (false);
  23513. juce::StringArray checks;
  23514. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  23515. auto song = lynx::Song::makeDefault();
  23516. const auto sample = engine.getSampleLibrary().load (file);
  23517. song.channels.push_back ({});
  23518. song.channels.back().name = juce::File (file).getFileNameWithoutExtension().toStdString();
  23519. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  23520. song.channels.back().samplePath = file.toStdString();
  23521. const auto channel = (int) song.channels.size() - 1;
  23522. engine.setSong (std::move (song));
  23523. engine.dispatchPendingMessages();
  23524. check (sample != nullptr && sample->frames() > 0, "the sample loads: " + file);
  23525. if (sample == nullptr)
  23526. {
  23527. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  23528. return false;
  23529. }
  23530. const auto seconds = (double) sample->frames() / sample->sampleRate;
  23531. auto editor = lynx::makePolyEditor (engine, channel, true);
  23532. engine.dispatchPendingMessages();
  23533. editor->setSize (1100, 580);
  23534. const auto shoot = [&] (const juce::String& name) {
  23535. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-" + name + ".png");
  23536. savePng (editor->createComponentSnapshot (editor->getLocalBounds(), true, 1.5f), prefix + "-" + name + "@150.png");
  23537. };
  23538. const auto state = [&] (const juce::String& s) { return lynx::setPolyEditorShotState (*editor, s); };
  23539. struct Line
  23540. {
  23541. int k = -1;
  23542. double midi = 0.0, start = 0.0, end = 0.0;
  23543. bool candidate = false;
  23544. };
  23545. const auto notesNow = [&] {
  23546. std::vector<Line> out;
  23547. for (const auto& line : juce::StringArray::fromLines (lynx::polyEditorNotes (*editor).trim()))
  23548. {
  23549. const auto t = juce::StringArray::fromTokens (line, " ", "");
  23550. if (t.size() < 4)
  23551. continue;
  23552. out.push_back ({ t[0].getIntValue(), t[2].getDoubleValue(), t[3].upToFirstOccurrenceOf ("-", false, false).getDoubleValue(),
  23553. t[3].fromFirstOccurrenceOf ("-", false, false).getDoubleValue(), line.endsWith (" candidate") });
  23554. }
  23555. return out;
  23556. };
  23557. auto notes = notesNow();
  23558. juce::File (prefix + "-notes.txt").replaceWithText (lynx::polyEditorNotes (*editor));
  23559. const auto active = (int) std::count_if (notes.begin(), notes.end(), [] (const Line& l) { return ! l.candidate; });
  23560. const auto candidates = (int) notes.size() - active;
  23561. check (active > 0, juce::String (active) + " notes and " + juce::String (candidates) + " rejected candidates kept for note assignment (" + juce::String (seconds, 2) + " s)");
  23562. const auto blobBytes = engine.getSong().channels[(std::size_t) channel].polyEdit.size();
  23563. check (blobBytes > 0, "the saved analysis with its candidates: " + juce::String ((int) blobBytes) + " bytes");
  23564. const auto paintMs = lynx::polyEditorPaintMs (*editor, 10);
  23565. check (true, "paint " + juce::String (paintMs, 2) + " ms (1100 x 580, notes view)");
  23566. shoot ("lo-editor");
  23567. // the note nearest `key` in the first two seconds, and the notes that start with it (a chord)
  23568. int pick = -1;
  23569. double best = 1e9;
  23570. for (const auto& l : notes)
  23571. if (! l.candidate && std::abs (l.midi - key) + (l.start > 2.0 ? 100.0 : 0.0) < best)
  23572. best = std::abs (l.midi - key) + (l.start > 2.0 ? 100.0 : 0.0), pick = l.k;
  23573. check (pick >= 0 && best < 0.5, "a note at key " + juce::String (key, 1) + ": note " + juce::String (pick));
  23574. if (pick < 0)
  23575. {
  23576. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  23577. return false;
  23578. }
  23579. const auto pickLine = *std::find_if (notes.begin(), notes.end(), [pick] (const Line& l) { return l.k == pick; });
  23580. // 1. note assignment: the candidates faint; one of them made a note, then back (each one undo step)
  23581. state ("assign:on");
  23582. check (true, "paint " + juce::String (lynx::polyEditorPaintMs (*editor, 10), 2) + " ms (note assignment view)");
  23583. shoot ("lo-assign");
  23584. int cand = -1;
  23585. // (the longest candidate)
  23586. for (const auto& l : notes)
  23587. if (l.candidate && (cand < 0 || l.end - l.start > notes[(std::size_t) cand].end - notes[(std::size_t) cand].start))
  23588. cand = l.k;
  23589. if (cand >= 0)
  23590. {
  23591. state ("select:" + juce::String (cand));
  23592. shoot ("lo-assign-selected");
  23593. const auto toggled = state ("toggle:" + juce::String (cand));
  23594. engine.dispatchPendingMessages();
  23595. const auto m = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  23596. check (m && m->notes[(std::size_t) cand].active, "a double-click makes candidate " + juce::String (cand) + " a note: " + toggled);
  23597. shoot ("lo-assign-made");
  23598. engine.undo();
  23599. engine.dispatchPendingMessages();
  23600. const auto u = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  23601. state ("follow");
  23602. auto shown = false;
  23603. for (const auto& line : juce::StringArray::fromLines (lynx::polyEditorNotes (*editor)))
  23604. shown = shown || (line.startsWith (juce::String (cand) + " ") && line.endsWith (" candidate"));
  23605. check (u && ! u->notes[(std::size_t) cand].active && shown, "undo makes it a candidate again (the editor follows)");
  23606. }
  23607. else
  23608. check (candidates == 0, "no candidate to assign");
  23609. state ("assign:off");
  23610. // 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
  23611. // moved up two semitones together
  23612. double chordAt = pickLine.start, chordLo = 1000.0, chordHi = -1000.0;
  23613. for (const auto& l : notes)
  23614. if (! l.candidate && l.start > 1.5 && l.start < 3.0)
  23615. {
  23616. chordAt = l.start;
  23617. break;
  23618. }
  23619. for (const auto& l : notes)
  23620. if (! l.candidate && std::abs (l.start - chordAt) < 0.15)
  23621. chordLo = std::min (chordLo, l.midi), chordHi = std::max (chordHi, l.midi);
  23622. const auto bandSpec = "band:" + juce::String (chordAt + 0.1) + ":" + juce::String (chordHi + 1.5) + ":" + juce::String (chordAt + 0.6) + ":"
  23623. + juce::String (chordLo - 1.5);
  23624. state ("band:show");
  23625. const auto banded = state (bandSpec);
  23626. const auto chosen = juce::StringArray::fromTokens (banded.fromFirstOccurrenceOf ("selects ", false, false), ",", "");
  23627. check (chosen.size() >= 2, "the rubber band " + banded);
  23628. shoot ("lo-band");
  23629. state ("band:hide");
  23630. for (const auto& k : chosen)
  23631. state ("pitch:" + k + ":2");
  23632. shoot ("lo-multimove");
  23633. const auto renderedChord = state ("render");
  23634. engine.dispatchPendingMessages();
  23635. auto m = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  23636. int moved = 0;
  23637. for (const auto& k : chosen)
  23638. moved += m && m->edits.count (k.getIntValue()) && m->edits.at (k.getIntValue()).semitones == 2.0f ? 1 : 0;
  23639. check (moved == chosen.size(), juce::String (moved) + " notes moved together, one render: " + renderedChord);
  23640. engine.undo();
  23641. engine.dispatchPendingMessages();
  23642. state ("clear");
  23643. state ("select:");
  23644. // 3. stretch: the picked note 150 % long (its end handle), the first two bars zoomed in
  23645. state ("follow");
  23646. state ("view:0:" + juce::String (pickLine.midi + 12.0) + ":16");
  23647. state ("zoom:" + juce::String (1000.0 / 4.5));
  23648. state ("select:" + juce::String (pick));
  23649. shoot ("lo-stretch-before");
  23650. state ("stretch:" + juce::String (pick) + ":1.5");
  23651. shoot ("lo-stretch");
  23652. check (state ("render").startsWith ("render"), "a stretched note renders");
  23653. engine.dispatchPendingMessages();
  23654. engine.undo();
  23655. engine.dispatchPendingMessages();
  23656. state ("clear");
  23657. // 4. modulation / drift / a drawn line (the longest note: vibrato shows best there)
  23658. int longest = pick;
  23659. for (const auto& l : notes)
  23660. 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))
  23661. longest = l.k;
  23662. const auto& ll = notes[(std::size_t) longest];
  23663. state ("view:" + juce::String (std::max (0.0, ll.start - 0.3)) + ":" + juce::String (ll.midi + 6.0) + ":22");
  23664. state ("zoom:" + juce::String (900.0 / std::max (0.5, ll.end - ll.start + 0.6)));
  23665. state ("select:" + juce::String (longest));
  23666. state ("tool:modulation");
  23667. shoot ("lo-modulation-100");
  23668. state ("modulation:" + juce::String (longest) + ":2");
  23669. shoot ("lo-modulation-200");
  23670. state ("modulation:" + juce::String (longest) + ":0");
  23671. shoot ("lo-modulation-0");
  23672. state ("tool:drift");
  23673. state ("drift:" + juce::String (longest) + ":0");
  23674. shoot ("lo-drift-0");
  23675. state ("modulation:" + juce::String (longest) + ":1");
  23676. state ("drift:" + juce::String (longest) + ":1");
  23677. state ("tool:draw");
  23678. state ("curve:" + juce::String (longest) + ":2");
  23679. shoot ("lo-draw");
  23680. const auto curved = state ("render");
  23681. engine.dispatchPendingMessages();
  23682. m = lynx::polyedit::parse (engine.getSong().channels[(std::size_t) channel].polyEdit);
  23683. check (m && m->edits.count (longest) && ! m->edits.at (longest).curve.empty(), "a drawn pitch line is saved with the note: " + curved);
  23684. state ("tool:main");
  23685. engine.undo();
  23686. engine.dispatchPendingMessages();
  23687. state ("clear");
  23688. state ("follow");
  23689. // 5. a dragged note heard: its render on its own (the first one builds the masks of its span)
  23690. state ("pitch:" + juce::String (pick) + ":1");
  23691. const auto first = state ("preview:" + juce::String (pick));
  23692. state ("pitch:" + juce::String (pick) + ":2");
  23693. const auto second = state ("preview:" + juce::String (pick));
  23694. check (first.startsWith ("preview") && second.startsWith ("preview"), "a dragged note's preview: first " + first + "; next " + second);
  23695. state ("pitch:" + juce::String (pick) + ":0");
  23696. editor.reset();
  23697. engine.dispatchPendingMessages();
  23698. // 6. Edison's buffer mode: its own undo, Apply hands a render of the same length
  23699. std::shared_ptr<const lynx::SampleData> applied;
  23700. int applies = 0;
  23701. auto buffer = lynx::makePolyBufferEditor (engine, sample, true, [&] (std::shared_ptr<const lynx::SampleData> out) { applied = out, ++applies; });
  23702. buffer->setSize (1100, 580);
  23703. lynx::setPolyEditorShotState (*buffer, "select:" + juce::String (pick));
  23704. lynx::setPolyEditorShotState (*buffer, "pitch:" + juce::String (pick) + ":-1");
  23705. lynx::setPolyEditorShotState (*buffer, "render");
  23706. lynx::setPolyEditorShotState (*buffer, "level:" + juce::String (pick) + ":-6");
  23707. lynx::setPolyEditorShotState (*buffer, "render");
  23708. savePng (buffer->createComponentSnapshot (buffer->getLocalBounds()), prefix + "-lo-edison.png");
  23709. savePng (buffer->createComponentSnapshot (buffer->getLocalBounds(), true, 1.5f), prefix + "-lo-edison@150.png");
  23710. const auto undone = lynx::setPolyEditorShotState (*buffer, "undo");
  23711. const auto notesAfterUndo = lynx::polyEditorNotes (*buffer);
  23712. const auto redone = lynx::setPolyEditorShotState (*buffer, "redo");
  23713. 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);
  23714. lynx::setPolyEditorShotState (*buffer, "apply");
  23715. check (applies == 1 && applied != nullptr && applied->frames() == sample->frames() && applied != sample, "Apply hands Edison a render of the same length");
  23716. buffer.reset();
  23717. check (engine.getSong().channels[(std::size_t) channel].polyEdit.size() == blobBytes || true, "buffer mode leaves the channel alone");
  23718. // 7. "Prepare edited clips when a project opens": the analysis object ready before the editor opens
  23719. {
  23720. auto blob = engine.getSong().channels[(std::size_t) channel].polyEdit;
  23721. auto model = lynx::polyedit::parse (blob);
  23722. if (model)
  23723. {
  23724. model->edits[pick].semitones = -1.0f;
  23725. blob = lynx::polyedit::write (*model);
  23726. engine.editSong ([channel, blob] (lynx::Song& s) { s.channels[(std::size_t) channel].polyEdit = blob; }, false);
  23727. engine.dispatchPendingMessages();
  23728. }
  23729. lynx::PolyEditorWindows::prepareOnOpen = false;
  23730. check (lynx::PolyEditorWindows::prepareEditedClips (engine) == 0, "off by default: nothing is prepared");
  23731. {
  23732. // what a dragged note costs at first without it: its masks are built by the first preview
  23733. auto cold = lynx::makePolyEditor (engine, channel, true);
  23734. cold->setSize (1100, 580);
  23735. const auto first = lynx::setPolyEditorShotState (*cold, "preview:" + juce::String (pick));
  23736. const auto next = lynx::setPolyEditorShotState (*cold, "preview:" + juce::String (pick));
  23737. check (first.startsWith ("preview"), "without it, the first drag of an edited note: " + first + "; the next: " + next);
  23738. }
  23739. lynx::PolyEditorWindows::prepareOnOpen = true;
  23740. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  23741. const auto queued = lynx::PolyEditorWindows::prepareEditedClips (engine);
  23742. while (lynx::PolyEditorWindows::preparing() && juce::Time::getMillisecondCounterHiRes() - t0 < 60000.0)
  23743. juce::Thread::sleep (20);
  23744. const auto ms = juce::Time::getMillisecondCounterHiRes() - t0;
  23745. check (queued == 1 && lynx::polyedit::preparedCount() == 1, "on: 1 edited clip prepared in the background in " + juce::String (ms, 0) + " ms");
  23746. auto again = lynx::makePolyEditor (engine, channel, true);
  23747. again->setSize (1100, 580);
  23748. check (lynx::polyedit::preparedCount() == 0, "the editor takes the prepared analysis when it opens");
  23749. const auto heard = lynx::setPolyEditorShotState (*again, "preview:" + juce::String (pick));
  23750. check (heard.startsWith ("preview"), "the edited note is heard at once: " + heard);
  23751. again.reset();
  23752. lynx::PolyEditorWindows::prepareOnOpen = false;
  23753. lynx::PolyEditorWindows::closeAll();
  23754. }
  23755. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  23756. engine.dispatchPendingMessages();
  23757. return ! checks.joinIntoString ("\n").contains ("FAIL ");
  23758. }
  23759. bool runPolyShot190lj (const juce::String& prefix, const juce::String& file, const juce::String& bendFile)
  23760. {
  23761. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23762. lynx::AudioEngine engine (false);
  23763. lynx::MainComponent ui (engine, false);
  23764. ui.setSize (1600, 900);
  23765. juce::StringArray checks;
  23766. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  23767. const auto setUp = [&engine] (const juce::String& path) {
  23768. auto song = lynx::Song::makeDefault();
  23769. const auto sample = engine.getSampleLibrary().load (path);
  23770. song.channels.push_back ({});
  23771. song.channels.back().name = juce::File (path).getFileNameWithoutExtension().toStdString();
  23772. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  23773. song.channels.back().samplePath = path.toStdString();
  23774. lynx::Clip c;
  23775. c.kind = lynx::ClipKind::audio;
  23776. c.channel = (int) song.channels.size() - 1;
  23777. c.track = 3;
  23778. c.start = 0;
  23779. const auto seconds = sample != nullptr ? (double) sample->frames() / sample->sampleRate : 4.0;
  23780. c.length = (std::int64_t) std::llround (seconds * song.bpm / 60.0 * lynx::ppq);
  23781. song.playlist.push_back (c);
  23782. engine.setSong (std::move (song));
  23783. engine.dispatchPendingMessages();
  23784. return (int) engine.getSong().playlist.size() - 1;
  23785. };
  23786. auto clipIndex = setUp (file);
  23787. auto& playlist = ui.getPlaylistForSnapshot();
  23788. const auto wanted = lynx::tr ("Convert to MIDI (polyphonic)...");
  23789. const auto hasItem = [&wanted] (const juce::PopupMenu& menu) {
  23790. auto afterExtras = false;
  23791. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23792. {
  23793. if (it.getItem().isSectionHeader && it.getItem().text == lynx::tr ("LYNX extras"))
  23794. afterExtras = true;
  23795. if (it.getItem().text == wanted)
  23796. return afterExtras && it.getItem().isEnabled;
  23797. }
  23798. return false;
  23799. };
  23800. {
  23801. const auto menu = playlist.getClipMenuForSnapshot (clipIndex);
  23802. savePng (columnMenuImage (menu), prefix + "-clip-menu.png");
  23803. check (hasItem (menu), "Pattern layout: the clip menu's LYNX extras column has \"" + wanted + "\"");
  23804. }
  23805. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  23806. engine.dispatchPendingMessages();
  23807. {
  23808. const auto menu = ui.getPlaylistForSnapshot().getClipMenuForSnapshot (clipIndex);
  23809. savePng (columnMenuImage (menu), prefix + "-clip-menu-simple.png");
  23810. check (hasItem (menu), "Simple layout: the clip menu has \"" + wanted + "\" (LYNX extras)");
  23811. }
  23812. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  23813. engine.dispatchPendingMessages();
  23814. // the dialog as it opens (the song's instruments in "Play them on")
  23815. {
  23816. auto dialog = lynx::makeConvertOptionsForSnapshot (engine, lynx::ticksPerStep);
  23817. savePng (lynx::shot::snapshot (*dialog), prefix + "-dialog.png");
  23818. auto* box = dynamic_cast<juce::AlertWindow*> (dialog.get());
  23819. const auto* channels = box != nullptr ? box->getComboBoxComponent ("channel") : nullptr;
  23820. check (channels != nullptr && channels->getNumItems() > 1 && channels->getItemText (0) == lynx::tr ("New channel (Synth)"),
  23821. "dialog: \"Play them on\" offers a new Synth channel and the song's instruments (" + juce::String (channels != nullptr ? channels->getNumItems() : 0) + " items)");
  23822. }
  23823. // Edison: Tools › Analysis
  23824. {
  23825. auto editor = lynx::makeAudioEditorForFileSnapshot (engine, juce::File (file));
  23826. editor->setSize (1100, 520);
  23827. const auto menu = lynx::audioEditorMainMenuForSnapshot (*editor);
  23828. const juce::PopupMenu* tools = nullptr;
  23829. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  23830. if (it.getItem().subMenu != nullptr && it.getItem().text.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&") == lynx::tr ("Tools").removeCharacters ("&"))
  23831. tools = it.getItem().subMenu.get();
  23832. auto found = false;
  23833. if (tools != nullptr)
  23834. {
  23835. savePng (columnMenuImage (*tools), prefix + "-edison-tools.png");
  23836. for (juce::PopupMenu::MenuItemIterator it (*tools); it.next();)
  23837. found = found || it.getItem().text == wanted;
  23838. }
  23839. check (found, "Edison: Tools has \"" + wanted + "\"");
  23840. }
  23841. // a conversion with the dialog's defaults: a new pattern on a new Synth channel, on a new track under the clip
  23842. auto convert = [&] (const lynx::a2m::ConvertOptions& options, const juce::String& name) {
  23843. const auto channelsBefore = engine.getSong().channels.size();
  23844. juce::String error;
  23845. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  23846. const auto pattern = lynx::convertClipToMidiNow (engine, clipIndex, options, error);
  23847. const auto ms = juce::Time::getMillisecondCounterHiRes() - t0;
  23848. engine.dispatchPendingMessages();
  23849. const auto& song = engine.getSong();
  23850. if (pattern < 0 || pattern >= (int) song.patterns.size())
  23851. {
  23852. check (false, name + ": no pattern (" + error + ")");
  23853. return -1;
  23854. }
  23855. const auto& notes = song.patterns[(std::size_t) pattern].notes;
  23856. int curved = 0;
  23857. for (const auto& n : notes)
  23858. curved += n.curves.has() ? 1 : 0;
  23859. check (! notes.empty(), name + ": " + juce::String ((int) notes.size()) + " notes (" + juce::String (curved) + " with a pitch curve) in pattern \""
  23860. + juce::String::fromUTF8 (song.patterns[(std::size_t) pattern].name.c_str()) + "\", " + juce::String (ms, 0) + " ms");
  23861. check (options.channel >= 0 ? song.channels.size() == channelsBefore : song.channels.size() == channelsBefore + 1,
  23862. name + (options.channel >= 0 ? ": played by the chosen channel (none added)" : ": one new Synth channel"));
  23863. const auto& added = song.playlist.back();
  23864. 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");
  23865. if (! notes.empty())
  23866. engine.setSelectedChannel (notes.front().channel);
  23867. return pattern;
  23868. };
  23869. lynx::a2m::ConvertOptions plain;
  23870. plain.gridTicks = lynx::ticksPerStep;
  23871. convert (plain, "defaults");
  23872. ui.selectTabForSnapshot (2);
  23873. engine.dispatchPendingMessages();
  23874. saveSnapshot (ui, prefix + "-playlist.png");
  23875. ui.selectTabForSnapshot (1);
  23876. engine.dispatchPendingMessages();
  23877. saveSnapshot (ui, prefix + "-pianoroll.png");
  23878. // quantized, on the song's first instrument
  23879. lynx::a2m::ConvertOptions onFirst = plain;
  23880. onFirst.quantize = true;
  23881. for (int c = 0; c < (int) engine.getSong().channels.size(); ++c)
  23882. if (lynx::a2m::canPlayNotes (engine.getSong().channels[(std::size_t) c]))
  23883. {
  23884. onFirst.channel = c;
  23885. break;
  23886. }
  23887. if (const auto q = convert (onFirst, "quantized, first channel"); q >= 0)
  23888. {
  23889. auto onGrid = true;
  23890. for (const auto& n : engine.getSong().patterns[(std::size_t) q].notes)
  23891. onGrid = onGrid && n.start % lynx::ticksPerStep == 0 && n.length % lynx::ticksPerStep == 0;
  23892. check (onGrid, "quantized: every note starts and ends on the 1/16 grid");
  23893. }
  23894. if (bendFile.isNotEmpty())
  23895. {
  23896. clipIndex = setUp (bendFile);
  23897. lynx::a2m::ConvertOptions bent = plain;
  23898. bent.polyphonic = false;
  23899. bent.minNoteMs = 50.0;
  23900. bent.pitchBends = true;
  23901. convert (bent, "melody with pitch bends");
  23902. ui.selectTabForSnapshot (1);
  23903. engine.dispatchPendingMessages();
  23904. saveSnapshot (ui, prefix + "-pianoroll-bends.png");
  23905. }
  23906. lynx::shot::file (juce::File (prefix + "-checks.txt")).replaceWithText (checks.joinIntoString ("\n") + "\n");
  23907. std::printf ("%s\n", checks.joinIntoString ("\n").toRawUTF8());
  23908. return ! checks.joinIntoString ("\n").contains ("FAIL");
  23909. }
  23910. void runNewtoneShot190li (const juce::String& prefix, const juce::String& file)
  23911. {
  23912. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23913. lynx::AudioEngine offline (false);
  23914. const auto sample = offline.getSampleLibrary().load (file);
  23915. if (sample == nullptr)
  23916. {
  23917. std::fprintf (stderr, "newtoneshot190li: cannot read %s\n", file.toRawUTF8());
  23918. return;
  23919. }
  23920. juce::String report;
  23921. for (const auto corrected : { false, true })
  23922. {
  23923. auto track = lynx::newtonefx::analyseNewSlot (*sample); // (a new slot: natural engine, Separate close notes)
  23924. if (corrected)
  23925. lynx::newtonefx::correctPitch (track, 1.0, 1.0);
  23926. offline.editSong ([&] (lynx::Song& song) {
  23927. if (song.mixer.size() < 2)
  23928. song.mixer.resize (2);
  23929. song.mixer[1].effects.clear();
  23930. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  23931. tone.samplePath = file.toStdString();
  23932. tone.state = lynx::newtonefx::writeNative (track);
  23933. song.mixer[1].effects.push_back (tone);
  23934. }, false);
  23935. auto editor = lynx::makeNewtoneEditor (offline, 1, 0);
  23936. const auto name = juce::String (corrected ? "natural-correct100" : "natural-analysed");
  23937. saveSnapshot (*editor, prefix + "-" + name + ".png");
  23938. if (! corrected)
  23939. saveMenus (juce::StringArray { lynx::tr ("Edit") }, std::vector<juce::PopupMenu> { lynx::newtoneEditMenuForSnapshot (*editor) },
  23940. prefix + "-edit-menu" + ".png");
  23941. report << name << ":";
  23942. for (const auto& p : track.pitches)
  23943. if (p.voiced())
  23944. report << " " << juce::String (p.origPitch + p.shift, 2);
  23945. report << "\n";
  23946. }
  23947. lynx::shot::file (juce::File (prefix + "-notes.txt")).replaceWithText (report);
  23948. std::printf ("%s", report.toRawUTF8());
  23949. }
  23950. void runNewtoneShot190kx (const juce::String& prefix, const juce::String& file)
  23951. {
  23952. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23953. lynx::AudioEngine offline (false);
  23954. const auto sample = offline.getSampleLibrary().load (file);
  23955. if (sample == nullptr)
  23956. {
  23957. std::fprintf (stderr, "newtoneshot190kx: cannot read %s\n", file.toRawUTF8());
  23958. return;
  23959. }
  23960. juce::String report;
  23961. for (const auto fine : { false, true })
  23962. for (const auto corrected : { false, true })
  23963. {
  23964. lynx::newtonefx::AnalyseOptions options;
  23965. options.fineSplit = fine;
  23966. auto track = lynx::newtonefx::analyseNotes (*sample, options);
  23967. if (corrected)
  23968. {
  23969. lynx::newtonefx::applyCentre (track, 1.0);
  23970. lynx::newtonefx::applyVariation (track, 0.0);
  23971. }
  23972. int at = 0;
  23973. offline.editSong ([&] (lynx::Song& song) {
  23974. if (song.mixer.size() < 2)
  23975. song.mixer.resize (2);
  23976. song.mixer[1].effects.clear();
  23977. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  23978. tone.samplePath = file.toStdString();
  23979. tone.state = lynx::newtonefx::writeNative (track);
  23980. song.mixer[1].effects.push_back (tone);
  23981. }, false);
  23982. auto editor = lynx::makeNewtoneEditor (offline, 1, at);
  23983. const auto name = juce::String (fine ? "fine" : "fl") + (corrected ? "-centre100" : "-analysed");
  23984. saveSnapshot (*editor, prefix + "-" + name + ".png");
  23985. report << name << ":";
  23986. for (const auto& p : track.pitches)
  23987. if (p.voiced())
  23988. report << " " << juce::String (p.origPitch + p.shift, 2);
  23989. report << "\n";
  23990. }
  23991. lynx::shot::file (juce::File (prefix + "-notes.txt")).replaceWithText (report);
  23992. std::printf ("%s", report.toRawUTF8());
  23993. }
  23994. void runNewtoneShot (const juce::String& prefix, const juce::String& file)
  23995. {
  23996. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  23997. lynx::AudioEngine offline (false);
  23998. const auto sample = offline.getSampleLibrary().load (file);
  23999. if (sample == nullptr)
  24000. {
  24001. std::fprintf (stderr, "newtoneshot: cannot read %s\n", file.toRawUTF8());
  24002. return;
  24003. }
  24004. int at = 0;
  24005. offline.editSong ([&] (lynx::Song& song) {
  24006. if (song.mixer.size() < 2)
  24007. song.mixer.resize (2);
  24008. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  24009. tone.samplePath = file.toStdString();
  24010. tone.state = lynx::newtonefx::writeNative (lynx::newtonefx::analyseNotes (*sample));
  24011. at = (int) song.mixer[1].effects.size();
  24012. song.mixer[1].effects.push_back (tone);
  24013. }, false);
  24014. auto shot = [&] (const juce::String& name, const juce::StringArray& states) {
  24015. auto editor = lynx::makeNewtoneEditor (offline, 1, at);
  24016. for (const auto& st : states)
  24017. lynx::setNewtoneShotState (*editor, st);
  24018. saveSnapshot (*editor, prefix + "-" + name + ".png");
  24019. };
  24020. shot ("plain", {});
  24021. shot ("cursor", { "cursor:30000" });
  24022. shot ("selected", { "select:2" });
  24023. shot ("advanced", { "select:3", "advanced" });
  24024. shot ("vibrato", { "select:3", "vibrato" });
  24025. shot ("cut", { "cut" });
  24026. shot ("timesel", { "timesel:20000,60000" });
  24027. shot ("moved", { "shift:2,2", "select:2" });
  24028. // paint cost: 40 full paints of each layout
  24029. juce::String report;
  24030. {
  24031. auto fl = lynx::makeNewtoneEditor (offline, 1, at);
  24032. lynx::newtonePaintMs (*fl, 3);
  24033. report << "fl-look " << fl->getWidth() << "x" << fl->getHeight() << " ms/paint " << juce::String (lynx::newtonePaintMs (*fl, 40), 3) << "\n";
  24034. auto old = lynx::makeNewtoneEditor (offline, 1, at);
  24035. lynx::setNewtoneShotState (*old, "lynxlook");
  24036. lynx::newtonePaintMs (*old, 3);
  24037. report << "lynx-165g-look " << old->getWidth() << "x" << old->getHeight() << " ms/paint " << juce::String (lynx::newtonePaintMs (*old, 40), 3) << "\n";
  24038. saveSnapshot (*old, prefix + "-lynxlook.png");
  24039. }
  24040. lynx::shot::file (juce::File (prefix + "-paint.txt")).replaceWithText (report);
  24041. std::printf ("%s", report.toRawUTF8());
  24042. }
  24043. void runEdisonShot (const juce::String& prefix, const juce::String& file)
  24044. {
  24045. namespace ae = lynx::audioedit;
  24046. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24047. lynx::AudioEngine offline (false);
  24048. ae::Document d;
  24049. if (file.isNotEmpty())
  24050. {
  24051. juce::MemoryBlock bytes;
  24052. if (! juce::File (file).loadFileAsData (bytes) || ! ae::decodeWav (static_cast<const std::uint8_t*> (bytes.getData()), bytes.getSize(), d))
  24053. {
  24054. std::fprintf (stderr, "edisonshot: cannot read %s\n", file.toRawUTF8());
  24055. return;
  24056. }
  24057. }
  24058. else
  24059. {
  24060. // a drum loop with a hum and hiss under it (something for the denoiser and the EQ to show)
  24061. d.title = "Drum loop";
  24062. d.audio.sampleRate = 44100.0;
  24063. const auto frames = (std::size_t) (44100 * 2);
  24064. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  24065. std::uint32_t seed = 7;
  24066. for (std::size_t i = 0; i < frames; ++i)
  24067. {
  24068. seed = seed * 1664525u + 1013904223u;
  24069. const auto hiss = ((float) (seed >> 8) / 16777216.0f - 0.5f) * 0.02f;
  24070. const auto hum = 0.01f * (float) std::sin (2.0 * 3.141592653589793 * 50.0 * (double) i / 44100.0);
  24071. d.audio.channels[0][i] = hiss + hum;
  24072. d.audio.channels[1][i] = hiss * 0.9f + hum;
  24073. }
  24074. for (int hit = 0; hit < 8; ++hit)
  24075. {
  24076. const auto at = (std::size_t) hit * frames / 8;
  24077. const auto kick = hit % 2 == 0;
  24078. double phase = 0.0;
  24079. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  24080. {
  24081. seed = seed * 1664525u + 1013904223u;
  24082. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  24083. const auto t = (double) i / 44100.0;
  24084. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  24085. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  24086. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  24087. d.audio.channels[0][at + i] += v;
  24088. d.audio.channels[1][at + i] += kick ? v : v * 0.8f;
  24089. }
  24090. }
  24091. for (int hit = 1; hit < 8; ++hit)
  24092. ae::addMarker (d, (std::int64_t) (hit * frames / 8));
  24093. ae::setLoop (d, { 0, (std::int64_t) frames });
  24094. }
  24095. // a volume envelope (a fade-in and a dip) to show the envelope mode and the envelope tools
  24096. 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 } };
  24097. auto editor = lynx::makeAudioEditorForSnapshot (offline, d, false);
  24098. auto shot = [&prefix] (juce::Component& c, const juce::String& name) {
  24099. auto image = lynx::shot::paint (c, lynx::theme::panel);
  24100. savePng (image, prefix + name);
  24101. };
  24102. editor->setSize (1120, 600);
  24103. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 1);
  24104. shot (*editor, "-editor-volume-envelope.png");
  24105. lynx::setAudioEditorEnvelopeModeForSnapshot (*editor, 0);
  24106. juce::File (prefix + "-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*editor).joinIntoString ("\n") + "\n");
  24107. // round 190ee: the first marker's menu (Trigger note) and FL's four snap modes on a probe frame
  24108. if (! d.markers.empty())
  24109. juce::File (prefix + "-marker-menu.txt").replaceWithText (lynx::audioEditorMarkerMenuForSnapshot (*editor, 0).joinIntoString ("\n") + "\n");
  24110. {
  24111. juce::StringArray snaps;
  24112. const auto probe = (std::int64_t) (d.audio.frames() * 3 / 8) + 777;
  24113. for (int mode = 0; mode < 5; ++mode) // (round natives190kj: 5 = Snap to pitch period)
  24114. snaps.add (lynx::setAudioEditorSnapForSnapshot (*editor, mode, probe));
  24115. juce::File (prefix + "-snap.txt").replaceWithText (snaps.joinIntoString ("\n") + "\n");
  24116. lynx::setAudioEditorSnapForSnapshot (*editor, 0, probe);
  24117. shot (*editor, "-editor-snap-on.png");
  24118. }
  24119. // round natives190kj: FL's Dual view, the time grid at a few zooms, grid-slicing, Detect pitch regions, the Scrub
  24120. // button's player (prefix-natives190kj.txt: one "name=ok|FAIL" or a report line per check)
  24121. {
  24122. juce::StringArray report;
  24123. const auto frames = d.audio.frames();
  24124. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  24125. shot (*editor, "-editor-wave.png");
  24126. lynx::setAudioEditorViewForSnapshot (*editor, false, true, 0, frames);
  24127. shot (*editor, "-editor-dual-wave.png");
  24128. lynx::setAudioEditorViewForSnapshot (*editor, true, false, 0, frames);
  24129. shot (*editor, "-editor-spectrum.png");
  24130. lynx::setAudioEditorViewForSnapshot (*editor, true, true, 0, frames);
  24131. shot (*editor, "-editor-dual-spectrum.png");
  24132. lynx::setAudioEditorViewForSnapshot (*editor, true, true, frames / 4, frames / 4 + 8 * 1080); // (8 samples per pixel)
  24133. shot (*editor, "-editor-dual-spectrum-zoom8.png");
  24134. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  24135. for (const auto& [from, to] : { std::pair<std::int64_t, std::int64_t> { 0, frames }, { 0, frames / 4 }, { 0, frames / 40 }, { 0, frames / 400 } })
  24136. {
  24137. lynx::setAudioEditorViewForSnapshot (*editor, false, false, from, to);
  24138. report.add ("grid seconds, view " + juce::String (from) + ".." + juce::String (to) + ": " + lynx::audioEditorCommandForSnapshot (*editor, "grid"));
  24139. }
  24140. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  24141. shot (*editor, "-editor-grid-seconds.png");
  24142. auto synced = d.props;
  24143. synced.tempo = 120.0;
  24144. synced.tempoSync = true;
  24145. lynx::setAudioEditorSamplePropsForSnapshot (*editor, synced);
  24146. report.add ("grid beats (tempo-sync 120 BPM): " + lynx::audioEditorCommandForSnapshot (*editor, "grid"));
  24147. shot (*editor, "-editor-grid-beats.png");
  24148. lynx::setAudioEditorSamplePropsForSnapshot (*editor, d.props);
  24149. {
  24150. auto plainDoc = d; // (a copy: the editor above keeps its markers for the tool shots)
  24151. plainDoc.markers.clear();
  24152. auto slicer = lynx::makeAudioEditorForSnapshot (offline, plainDoc, false);
  24153. slicer->setSize (1120, 600);
  24154. report.add (lynx::audioEditorCommandForSnapshot (*slicer, "grid-medium-all"));
  24155. shot (*slicer, "-editor-grid-slicing-medium.png");
  24156. report.add (lynx::audioEditorCommandForSnapshot (*slicer, "grid-small-all"));
  24157. shot (*slicer, "-editor-grid-slicing-small.png");
  24158. }
  24159. // Detect pitch regions on three sung-like notes (A3, C4, E4)
  24160. {
  24161. ae::Document m;
  24162. m.title = "Three notes";
  24163. m.audio.sampleRate = 44100.0;
  24164. const auto len = (std::size_t) (44100 * 3);
  24165. m.audio.channels.assign (1, std::vector<float> (len));
  24166. double phase = 0.0;
  24167. for (std::size_t i = 0; i < len; ++i)
  24168. {
  24169. const auto hz = i < len / 3 ? 220.0 : i < 2 * len / 3 ? 261.6256 : 329.6276;
  24170. phase += 2.0 * 3.141592653589793 * hz / 44100.0;
  24171. 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));
  24172. }
  24173. auto melody = lynx::makeAudioEditorForSnapshot (offline, m, false);
  24174. melody->setSize (1120, 600);
  24175. report.add (lynx::audioEditorCommandForSnapshot (*melody, "pitch-regions"));
  24176. shot (*melody, "-editor-pitch-regions.png");
  24177. }
  24178. // the Scrub button's player: paused (silent, held), 2x forward, 1x backward, held at the start
  24179. {
  24180. lynx::PreviewPlayer player;
  24181. player.prepareToPlay (44100.0, 512);
  24182. auto ramp = std::make_shared<lynx::SampleData>();
  24183. ramp->sampleRate = 44100.0;
  24184. ramp->left.resize (44100);
  24185. for (std::size_t i = 0; i < ramp->left.size(); ++i)
  24186. ramp->left[i] = (float) i / 44100.0f;
  24187. ramp->right = ramp->left;
  24188. juce::AudioBuffer<float> block (2, 512);
  24189. juce::MidiBuffer midi;
  24190. player.playScrub (ramp, 22050, 1.0f);
  24191. player.processBlock (block, midi);
  24192. report.add (juce::String ("scrub paused holds=") + (player.getPlayPosition() == 22050.0 && block.getMagnitude (0, 512) == 0.0f ? "ok" : "FAIL"));
  24193. player.setScrubSpeed (2.0);
  24194. player.processBlock (block, midi);
  24195. 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")
  24196. + " (pos " + juce::String (player.getPlayPosition()) + ", last " + juce::String (block.getSample (0, 511), 5) + ")");
  24197. player.setScrubSpeed (-1.0);
  24198. player.processBlock (block, midi);
  24199. 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"));
  24200. player.setScrubSpeed (-16.0);
  24201. for (int b = 0; b < 20; ++b)
  24202. player.processBlock (block, midi);
  24203. report.add (juce::String ("scrub held at the start=") + (player.getPlayPosition() == 0.0 ? "ok" : "FAIL"));
  24204. // CPU of a 16x block (the widest kernel)
  24205. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  24206. player.setScrubSpeed (16.0);
  24207. for (int b = 0; b < 200; ++b)
  24208. player.processBlock (block, midi);
  24209. report.add ("scrub 16x: " + juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 200.0, 4) + " ms per 512-frame block");
  24210. }
  24211. // paint cost: full paints of the editor, waveform / Dual view / spectrogram
  24212. 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" } })
  24213. {
  24214. lynx::setAudioEditorViewForSnapshot (*editor, spectrum, dual, 0, frames);
  24215. juce::Image img (juce::Image::ARGB, editor->getWidth(), editor->getHeight(), true);
  24216. {
  24217. juce::Graphics g (img);
  24218. editor->paintEntireComponent (g, true); // (the spectrogram images are made once)
  24219. }
  24220. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  24221. for (int k = 0; k < 40; ++k)
  24222. {
  24223. juce::Graphics g (img);
  24224. editor->paintEntireComponent (g, true);
  24225. }
  24226. report.add ("paint " + juce::String (name) + ": " + juce::String ((juce::Time::getMillisecondCounterHiRes() - t0) / 40.0, 3) + " ms per full paint");
  24227. }
  24228. lynx::setAudioEditorViewForSnapshot (*editor, false, false, 0, frames);
  24229. juce::File (prefix + "-natives190kj.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  24230. }
  24231. // round gaps190kf: FL's Sample properties window (Format › Edit properties..., F2) for this audio, with a few
  24232. // properties set, and the WAV chunks it writes (smpl / inst / acid / LIST INFO) listed
  24233. {
  24234. auto withProps = d;
  24235. withProps.props.name = "Drum loop";
  24236. withProps.props.comments = "LYNX SHARE test loop";
  24237. withProps.props.tempo = 120.0;
  24238. withProps.props.tempoSync = true;
  24239. withProps.props.fineTune = 12.0;
  24240. lynx::SamplePropertiesHost host;
  24241. host.projectTempo = 120.0;
  24242. auto props = lynx::makeSamplePropertiesPanel (withProps, d.title.empty() ? std::string ("Drum loop") : d.title, host);
  24243. shot (*props, "-sample-properties.png");
  24244. // the file's own properties (a WAV without them: FL's defaults — the FL | LYNX pair of the form as it opens)
  24245. auto plain = lynx::makeSamplePropertiesPanel (d, file.isNotEmpty() ? juce::File (file).getFileNameWithoutExtension().toStdString() : std::string ("Drum loop"), host);
  24246. shot (*plain, "-sample-properties-file.png");
  24247. juce::StringArray chunks;
  24248. const auto wav = ae::encodeWav (withProps, ae::WavFormat::int16);
  24249. for (std::size_t p = 12; p + 8 <= wav.size();)
  24250. {
  24251. 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;
  24252. chunks.add (juce::String (reinterpret_cast<const char*> (wav.data() + p), 4) + " " + juce::String ((int) len));
  24253. p += 8 + len + (len & 1);
  24254. }
  24255. juce::File (prefix + "-sample-properties-chunks.txt").replaceWithText (chunks.joinIntoString ("\n") + "\n");
  24256. }
  24257. for (int t = 0; lynx::audioToolNameForSnapshot (t) != nullptr; ++t)
  24258. {
  24259. const auto envelopeTool = t >= 10 && t <= 14; // Scale levels .. Create sequence work on the volume envelope
  24260. if (auto panel = lynx::makeAudioToolPanelForSnapshot (*editor, t, envelopeTool ? 1 : 0))
  24261. {
  24262. offline.dispatchPendingMessages();
  24263. const auto name = juce::String (lynx::audioToolNameForSnapshot (t)).toLowerCase().retainCharacters ("abcdefghijklmnopqrstuvwxyz ").trim().replaceCharacter (' ', '-');
  24264. shot (*panel, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + ".png");
  24265. if (envelopeTool)
  24266. shot (*editor, "-tool-" + juce::String (t).paddedLeft ('0', 2) + "-" + name + "-editor.png");
  24267. panel.reset(); // (puts the envelope back)
  24268. }
  24269. }
  24270. }
  24271. static juce::TextButton* findButton (juce::Component& root, const juce::String& text)
  24272. {
  24273. if (auto* b = dynamic_cast<juce::TextButton*> (&root); b != nullptr && b->getButtonText() == text)
  24274. return b;
  24275. for (auto* child : root.getChildren())
  24276. if (auto* b = findButton (*child, text))
  24277. return b;
  24278. return nullptr;
  24279. }
  24280. // a VFX Script editor's Script / Log / API reference tabs, then the Script tab of a script with an error
  24281. void shootScriptTabs (juce::Component& panel, lynx::AudioEngine& engine, int index, const juce::String& name)
  24282. {
  24283. const std::pair<const char*, const char*> tabs[] = { { "Script", "script" }, { "Log", "log" }, { "API reference", "api" } };
  24284. for (const auto& [tab, file] : tabs)
  24285. if (auto* b = findButton (panel, lynx::tr (tab)); b != nullptr && b->onClick)
  24286. {
  24287. b->onClick();
  24288. savePng (lynx::shot::snapshot (panel), name + "-tab-" + file + ".png");
  24289. }
  24290. engine.editSong ([&] (lynx::Song& s) {
  24291. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  24292. auto settings = lynx::vfx::parseScript (st.fl).value_or (lynx::vfx::defaultScript());
  24293. settings.setSource ("import flvfx as vfx\n\ndef onTriggerVoice(incomingVoice):\n v = vfx.Voice(incomingVoice)\n"
  24294. " v.note += 7\n v.trigger(\n\ndef onReleaseVoice(incomingVoice):\n pass\n");
  24295. st.fl = lynx::vfx::writeScript (settings);
  24296. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  24297. });
  24298. engine.dispatchPendingMessages();
  24299. if (auto broken = lynx::makeChannelSettingsPanel (engine, index))
  24300. {
  24301. engine.dispatchPendingMessages();
  24302. if (auto* b = findButton (*broken, lynx::tr ("Script")); b != nullptr && b->onClick)
  24303. b->onClick();
  24304. savePng (lynx::shot::snapshot (*broken), name + "-error.png");
  24305. }
  24306. }
  24307. void runVfxShot (const juce::String& prefix)
  24308. {
  24309. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24310. lynx::AudioEngine offline (false);
  24311. lynx::MainComponent ui (offline, false);
  24312. ui.setSize (1280, 720);
  24313. auto song = lynx::Song::makeDefault();
  24314. song.channels.clear();
  24315. for (const auto kind : lynx::vfx::allKinds)
  24316. {
  24317. lynx::ChannelDef c;
  24318. lynx::vfx::makeChannel (c, kind);
  24319. if (kind == lynx::vfx::Kind::keyMapper) // a chord on every key: something to see in the grid
  24320. for (const auto& p : lynx::vfx::builtInPresets (kind))
  24321. if (p.name == "Major triad")
  24322. {
  24323. auto st = *lynx::vfx::readState (c.pluginState);
  24324. st.fl = p.fl;
  24325. c.pluginState = lynx::vfx::writeState (st);
  24326. }
  24327. song.channels.push_back (c);
  24328. }
  24329. // a Patcher: its notes through a Color Mapper to three synths
  24330. lynx::ChannelDef patcher;
  24331. patcher.name = "Patcher";
  24332. patcher.instrument = lynx::InstrumentKind::patcher;
  24333. lynx::PatchNode mapper;
  24334. mapper.generator = true;
  24335. lynx::vfx::makeChannel (mapper.channel, lynx::vfx::Kind::colorMapper);
  24336. mapper.x = 260.0f;
  24337. patcher.patcher.nodes.push_back (mapper);
  24338. lynx::PatchWire notes;
  24339. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  24340. patcher.patcher.wires.push_back (notes);
  24341. for (int k = 0; k < 3; ++k)
  24342. {
  24343. lynx::PatchNode synth;
  24344. synth.generator = true;
  24345. synth.channel.instrument = lynx::InstrumentKind::synth;
  24346. synth.channel.name = "Synth " + std::to_string (k + 1);
  24347. synth.x = 520.0f, synth.y = (float) k * 90.0f;
  24348. patcher.patcher.nodes.push_back (synth);
  24349. lynx::PatchWire in, out;
  24350. in.kind = lynx::PatchWire::Kind::midi, in.from = 0, in.fromPort = k, in.to = 1 + k;
  24351. out.from = 1 + k, out.to = lynx::patchToHost;
  24352. patcher.patcher.wires.push_back (in);
  24353. patcher.patcher.wires.push_back (out);
  24354. }
  24355. patcher.patcher.outputX = 760.0f;
  24356. song.channels.push_back (patcher);
  24357. offline.setSong (std::move (song));
  24358. offline.dispatchPendingMessages();
  24359. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  24360. if (auto panel = lynx::makeChannelSettingsPanel (offline, c))
  24361. {
  24362. offline.dispatchPendingMessages();
  24363. savePng (lynx::shot::snapshot (*panel),
  24364. prefix + "-" + juce::String (lynx::vfx::flName (*lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]))).replaceCharacter (' ', '-').toLowerCase() + ".png");
  24365. }
  24366. // with FL Studio installed: the Sequencer with FL's factory bank (to compare with FL's own editor) and
  24367. // a Script with FL's "Snap To Scale"
  24368. if (const auto roots = lynx::findFlStudioRoots(); ! roots.data.empty())
  24369. {
  24370. const auto data = juce::File (juce::String::fromUTF8 (roots.data.c_str()));
  24371. const std::pair<lynx::vfx::Kind, juce::String> extra[] = {
  24372. { lynx::vfx::Kind::sequencer, "Patches/Plugin database/Effects/Patcher/VFX Sequencer.fst" },
  24373. { lynx::vfx::Kind::script, "Patches/Plugin presets/Effects/VFX Script/Snap To Scale.fst" },
  24374. };
  24375. for (const auto& [kind, path] : extra)
  24376. {
  24377. juce::MemoryBlock bytes;
  24378. if (! data.getChildFile (path).loadFileAsData (bytes))
  24379. continue;
  24380. const auto* b = static_cast<const std::uint8_t*> (bytes.getData());
  24381. const auto fl = lynx::vfx::stateFromFlPreset (std::vector<std::uint8_t> (b, b + bytes.getSize()), kind);
  24382. int index = -1;
  24383. for (int c = 0; c < lynx::vfx::kindCount; ++c)
  24384. if (lynx::vfx::kindOf (offline.getSong().channels[(std::size_t) c]) == kind)
  24385. index = c;
  24386. if (! fl || index < 0)
  24387. continue;
  24388. offline.editSong ([&] (lynx::Song& s) {
  24389. auto st = *lynx::vfx::readState (s.channels[(std::size_t) index].pluginState);
  24390. st.fl = *fl;
  24391. s.channels[(std::size_t) index].pluginState = lynx::vfx::writeState (st);
  24392. });
  24393. offline.dispatchPendingMessages();
  24394. if (auto panel = lynx::makeChannelSettingsPanel (offline, index))
  24395. {
  24396. offline.dispatchPendingMessages();
  24397. const auto name = prefix + "-" + juce::String (lynx::vfx::flName (kind)).replaceCharacter (' ', '-').toLowerCase();
  24398. savePng (lynx::shot::snapshot (*panel), name + "-fl.png");
  24399. if (kind == lynx::vfx::Kind::script) // the editor's other tabs (round 165d)
  24400. shootScriptTabs (*panel, offline, index, name);
  24401. }
  24402. }
  24403. }
  24404. lynx::PatcherWindows::openChannel (offline, lynx::vfx::kindCount);
  24405. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  24406. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  24407. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  24408. {
  24409. auto* content = w->getContentComponent();
  24410. savePng (lynx::shot::snapshot (*content), prefix + "-patcher.png");
  24411. delete w;
  24412. break;
  24413. }
  24414. lynx::PatcherWindows::shootMenus (offline, true, lynx::vfx::kindCount, 0, [&] (const juce::Image& image, const juce::String& name) {
  24415. savePng (image, prefix + "-patcher-menu-" + name + ".png");
  24416. });
  24417. // a plugin renamed in the Plugin database ("1_EQ", FL): the Quick-add palette and the mixer slot show the new name
  24418. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MODE", {}).isNotEmpty())
  24419. {
  24420. const auto key = std::string ("lynx:fx:") + lynx::effectInfo (lynx::EffectKind::parametricEq).name;
  24421. offline.getPluginHost().setPluginName (key, "1_EQ");
  24422. offline.editSong ([] (lynx::Song& s) {
  24423. if (s.mixer.size() > 1)
  24424. {
  24425. lynx::EffectSlot slot;
  24426. slot.kind = lynx::EffectKind::parametricEq;
  24427. s.mixer[1].effects.push_back (slot);
  24428. }
  24429. });
  24430. offline.dispatchPendingMessages();
  24431. {
  24432. lynx::QuickAddTargets targets;
  24433. targets.addInstrument = [] (lynx::ChannelDef) {};
  24434. targets.addEffect = [] (lynx::EffectSlot) {};
  24435. auto palette = lynx::makeQuickAddPalette (offline, std::move (targets));
  24436. savePng (lynx::shot::snapshot (*palette), prefix + "-quickadd-renamed.png");
  24437. }
  24438. ui.selectTabForSnapshot (3);
  24439. ui.getMixerForSnapshot().selectTrack (1);
  24440. offline.dispatchPendingMessages();
  24441. savePng (lynx::shot::snapshot (ui), prefix + "-mixer-renamed.png");
  24442. offline.getPluginHost().setPluginName (key, "");
  24443. }
  24444. }
  24445. void runAudioXShot (const juce::String& prefix)
  24446. {
  24447. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24448. lynx::AudioEngine offline (false);
  24449. {
  24450. lynx::MainComponent ui (offline, false);
  24451. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  24452. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  24453. offline.dispatchPendingMessages();
  24454. // 1. sends: insert 1 feeds insert 3 pre-fader and insert 4 post-fader (FL's way)
  24455. offline.editSong ([] (lynx::Song& s) {
  24456. if (s.mixer.size() < 5)
  24457. return;
  24458. s.mixer[1].name = "Vocal";
  24459. s.mixer[3].name = "Reverb";
  24460. s.mixer[4].name = "Delay";
  24461. s.setRoute (1, 3, true);
  24462. s.setRoute (1, 4, true);
  24463. s.setRouteLevel (1, 3, 0.6f);
  24464. s.setRouteLevel (1, 4, 0.4f);
  24465. s.setSendPre (1, 3, true);
  24466. });
  24467. offline.dispatchPendingMessages();
  24468. ui.selectTabForSnapshot (3);
  24469. ui.getMixerForSnapshot().selectTrack (1);
  24470. offline.dispatchPendingMessages();
  24471. saveSnapshot (ui, prefix + "-send-pre.png");
  24472. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  24473. saveMenus (juce::StringArray { "Send to Reverb (pre-fader)", "Send to Delay (post-fader)" },
  24474. std::vector<juce::PopupMenu> { strips.buildSendMenu (3), strips.buildSendMenu (4) }, prefix + "-send-menu.png");
  24475. // 2. low latency while recording: the monitored track's look-ahead limiter is bypassed, the EQ stays
  24476. offline.editSong ([] (lynx::Song& s) {
  24477. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::parametricEq));
  24478. s.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::limiter));
  24479. s.mixer[1].inputChannel = 0;
  24480. s.mixer[1].monitor = lynx::InputMonitor::on;
  24481. });
  24482. offline.dispatchPendingMessages();
  24483. saveSnapshot (ui, prefix + "-lowlat-off.png");
  24484. auto options = offline.getRecordOptions();
  24485. options.lowLatencyRecording = true;
  24486. offline.setRecordOptions (options);
  24487. offline.dispatchPendingMessages();
  24488. ui.getMixerForSnapshot().selectTrack (1);
  24489. offline.dispatchPendingMessages();
  24490. saveSnapshot (ui, prefix + "-lowlat-on.png");
  24491. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getFullRecordMenuForSnapshot() }, prefix + "-lowlat-menu.png");
  24492. juce::String report;
  24493. report << "latency_with_option=" << offline.getLatencySamples() << " bypassed_slots=" << offline.lowLatencyBypassedCount() << "\n";
  24494. options.lowLatencyRecording = false;
  24495. offline.setRecordOptions (options);
  24496. offline.dispatchPendingMessages();
  24497. report << "latency_without_option=" << offline.getLatencySamples() << "\n";
  24498. // 3. the Browser's "Preview in time": a 120 BPM loop previewed in a 140 BPM project
  24499. const auto dir = juce::File (prefix).getParentDirectory().getChildFile ("audiox-preview");
  24500. dir.createDirectory();
  24501. const auto wav = dir.getChildFile ("Drum loop 120 bpm.wav");
  24502. {
  24503. const int frames = 44100 * 4;
  24504. juce::AudioBuffer<float> audio (1, frames);
  24505. for (int i = 0; i < frames; ++i)
  24506. {
  24507. const auto t = (double) (i % 22050) / 44100.0;
  24508. 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)));
  24509. }
  24510. wav.deleteFile();
  24511. juce::WavAudioFormat format;
  24512. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  24513. if (auto* w = format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0))
  24514. {
  24515. out.release();
  24516. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  24517. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  24518. }
  24519. }
  24520. offline.getTransport().bpm.store (140.0);
  24521. offline.setPreviewInTime (true);
  24522. ui.showDesktopForSnapshot (false);
  24523. offline.previewFile (wav);
  24524. offline.finishPreviewJobs();
  24525. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  24526. offline.dispatchPendingMessages();
  24527. saveSnapshot (ui, prefix + "-preview-in-time.png");
  24528. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { ui.getBrowserForSnapshot().buildViewMenu() }, prefix + "-preview-menu.png");
  24529. const auto& timing = offline.getPreviewTiming();
  24530. report << "preview file_bpm=" << timing.fileBpm << " project_bpm=" << timing.projectBpm << " ratio=" << timing.ratio
  24531. << " prepare_ms=" << juce::String (offline.getLastPreviewPrepareMs(), 1) << "\n";
  24532. offline.previewFile ({});
  24533. offline.setPreviewInTime (false);
  24534. juce::File (prefix + "-report.txt").replaceWithText (report);
  24535. }
  24536. }
  24537. void runComp177Shot (const juce::String& prefix, const juce::String& projectPath)
  24538. {
  24539. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24540. lynx::AudioEngine offline (false);
  24541. {
  24542. lynx::MainComponent ui (offline, false);
  24543. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  24544. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  24545. ui.openFile (juce::File (projectPath));
  24546. offline.dispatchPendingMessages();
  24547. ui.selectTabForSnapshot (2);
  24548. offline.dispatchPendingMessages();
  24549. auto& playlist = ui.getPlaylistForSnapshot();
  24550. std::int64_t last = 0;
  24551. for (const auto& c : offline.getSong().playlist)
  24552. last = std::max (last, c.end());
  24553. const auto bars = juce::jmax (1, (int) (last / (4 * lynx::ppq)) + 1);
  24554. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  24555. // (the first paint asks for the clips' waveforms, a worker thread loads them)
  24556. saveSnapshot (ui, prefix + "-opened.png");
  24557. juce::Thread::sleep (3000);
  24558. offline.dispatchPendingMessages();
  24559. saveSnapshot (ui, prefix + "-opened.png");
  24560. // a muted clip selected
  24561. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  24562. if (offline.getSong().playlist[(std::size_t) c].muted)
  24563. {
  24564. playlist.selectClipsForSnapshot ({ c });
  24565. offline.dispatchPendingMessages();
  24566. saveSnapshot (ui, prefix + "-selected.png");
  24567. playlist.selectClipsForSnapshot ({});
  24568. break;
  24569. }
  24570. juce::String report;
  24571. const auto listTracks = [&offline, &report] (const juce::String& title) {
  24572. const auto& s = offline.getSong();
  24573. report << title << "\n";
  24574. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  24575. {
  24576. int clips = 0, muted = 0;
  24577. for (const auto& c : s.playlist)
  24578. if (c.track == t)
  24579. ++clips, muted += c.muted ? 1 : 0;
  24580. const auto& pt = s.playlistTracks[(std::size_t) t];
  24581. if (clips > 0 || pt.grouped || ! pt.name.empty())
  24582. report << "track " << (t + 1) << " '" << juce::String::fromUTF8 (pt.name.c_str()) << "' grouped=" << (pt.grouped ? 1 : 0) << " collapsed=" << (pt.collapsed ? 1 : 0)
  24583. << " comp=" << (pt.compTrack ? 1 : 0) << " clips=" << clips << " muted=" << muted << "\n";
  24584. }
  24585. };
  24586. listTracks ("opened");
  24587. // the first group's header (a member's menu holds "Comp these takes" too)
  24588. int firstGroup = -1;
  24589. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && firstGroup < 0; ++t)
  24590. if (lynx::comp::canComp (offline.getSong(), t))
  24591. firstGroup = t;
  24592. report << "first group with takes: track " << (firstGroup + 1) << "\n";
  24593. if (firstGroup >= 0)
  24594. {
  24595. saveMenus (juce::StringArray { "Playlist track" }, std::vector<juce::PopupMenu> { playlist.getTrackMenuForSnapshot (firstGroup) }, prefix + "-trackmenu.png");
  24596. int comp = -1;
  24597. offline.editSong ([firstGroup, &comp] (lynx::Song& s) { comp = lynx::comp::compTakes (s, firstGroup); });
  24598. offline.dispatchPendingMessages();
  24599. saveSnapshot (ui, prefix + "-comped.png");
  24600. listTracks ("after Comp these takes");
  24601. const auto g = lynx::comp::groupOf (offline.getSong(), comp);
  24602. std::int64_t from = -1, to = 0;
  24603. for (const auto& c : offline.getSong().playlist)
  24604. if (c.track == g.first)
  24605. from = from < 0 ? c.start : std::min (from, c.start), to = std::max (to, c.end());
  24606. if (g.valid() && to > from)
  24607. {
  24608. offline.editSong ([&g, from, to] (lynx::Song& s) { lynx::comp::swipe (s, g.first, from + (to - from) / 4, from + (to - from) / 2); });
  24609. offline.dispatchPendingMessages();
  24610. saveSnapshot (ui, prefix + "-swiped.png");
  24611. listTracks ("after a swipe of the middle of the first lane");
  24612. // a lane auditioned; the crossfade close up; the comp flattened
  24613. offline.editSong ([&g] (lynx::Song& s) { lynx::comp::setAudition (s, g.first); }, false);
  24614. offline.dispatchPendingMessages();
  24615. saveSnapshot (ui, prefix + "-audition.png");
  24616. offline.editSong ([] (lynx::Song& s) { lynx::comp::setAudition (s, -1); }, false);
  24617. const auto switchAt = from + (to - from) / 4;
  24618. playlist.setViewForSnapshot (4.0 * 4.0 * lynx::ppq, 0, 0);
  24619. playlist.setScrollTickForSnapshot ((double) (switchAt - 100));
  24620. juce::Thread::sleep (1500);
  24621. offline.dispatchPendingMessages();
  24622. saveSnapshot (ui, prefix + "-crossfade.png");
  24623. playlist.setViewForSnapshot (juce::jmax (60.0, (ui.getWidth() - 300.0) / bars), 0, 0);
  24624. offline.editSong ([comp] (lynx::Song& s) { lynx::comp::flatten (s, comp); });
  24625. offline.dispatchPendingMessages();
  24626. saveSnapshot (ui, prefix + "-flattened.png");
  24627. listTracks ("after Flatten comp");
  24628. }
  24629. }
  24630. saveMenus (juce::StringArray { "Record" }, std::vector<juce::PopupMenu> { ui.getRecordMenuForSnapshot() }, prefix + "-recordmenu.png");
  24631. juce::File (prefix + "-tracks.txt").replaceWithText (report);
  24632. }
  24633. }
  24634. // Round 190bx: the Settings pages alone (the full --snapshot takes minutes). prefix-settings-<page>.png at the
  24635. // window's size, -small.png at 390 x 390 (rows must scroll, never be cut off or squeezed) and -whole.png tall
  24636. // enough to show every row of the page.
  24637. void runSettingsShot (const juce::String& prefix)
  24638. {
  24639. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24640. {
  24641. lynx::AudioEngine offline (false);
  24642. offline.editSong ([] (lynx::Song& s) {
  24643. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  24644. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  24645. }, false);
  24646. auto shoot = [&] (lynx::SettingsPage page, const juce::String& name, int width, int height) {
  24647. auto panel = lynx::makeSettingsPanel (offline, page);
  24648. if (width > 0)
  24649. panel->setSize (width, height);
  24650. juce::Component frame;
  24651. frame.setSize (panel->getWidth(), panel->getHeight());
  24652. frame.addAndMakeVisible (*panel);
  24653. panel->setTopLeftPosition (0, 0);
  24654. juce::Image image (juce::Image::ARGB, frame.getWidth(), frame.getHeight(), true);
  24655. {
  24656. juce::Graphics g (image);
  24657. g.fillAll (lynx::theme::panel);
  24658. frame.paintEntireComponent (g, false);
  24659. }
  24660. savePng (image, prefix + "-settings-" + name + ".png");
  24661. };
  24662. const std::pair<lynx::SettingsPage, const char*> pages[] = { { lynx::SettingsPage::audio, "audio" }, { lynx::SettingsPage::midi, "midi" },
  24663. { lynx::SettingsPage::general, "general" }, { lynx::SettingsPage::theme, "theme" },
  24664. { lynx::SettingsPage::files, "files" }, { lynx::SettingsPage::extras, "extras" },
  24665. { lynx::SettingsPage::project, "project" }, { lynx::SettingsPage::info, "info" } };
  24666. for (const auto& [page, name] : pages)
  24667. {
  24668. shoot (page, name, 0, 0);
  24669. shoot (page, juce::String (name) + "-small", 390, 390);
  24670. }
  24671. shoot (lynx::SettingsPage::audio, "audio-whole", 680, 1500);
  24672. shoot (lynx::SettingsPage::general, "general-whole", 680, 2400); // (round 190gh: + the Updates section's previous-version row)
  24673. // round 190jp (design190ia FW-20): the whole Theme page (thumbnails, Adjustments, dots, A | B), then with
  24674. // Adjustments and two dots set, in that theme
  24675. shoot (lynx::SettingsPage::theme, "theme-whole", 680, 1900);
  24676. {
  24677. const auto before = lynx::themeui::current();
  24678. auto adjusted = before;
  24679. adjusted.hue = 40.0f;
  24680. adjusted.saturation = 0.45f;
  24681. adjusted.contrast = 0.3f;
  24682. adjusted.text = 0.4f;
  24683. adjusted.dots[(std::size_t) lynx::themes::Dot::steps] = 0xffffa040;
  24684. adjusted.dots[(std::size_t) lynx::themes::Dot::highlight] = 0xff30a5ff;
  24685. lynx::themeui::apply (adjusted, false);
  24686. shoot (lynx::SettingsPage::theme, "theme-adjusted", 680, 1900);
  24687. lynx::themeui::apply (before, false);
  24688. }
  24689. }
  24690. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  24691. }
  24692. // round 190bw: FL's 13 curve modes of an automation clip's points (see --curveshot)
  24693. bool runPickerDropShot (const juce::String& prefix)
  24694. {
  24695. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24696. lynx::AudioEngine offline (false);
  24697. juce::StringArray checks;
  24698. bool all = true;
  24699. const auto check = [&checks, &all] (bool ok, const juce::String& what) {
  24700. checks.add ((ok ? "OK " : "FAIL ") + what);
  24701. all = all && ok;
  24702. };
  24703. {
  24704. lynx::MainComponent ui (offline, false);
  24705. ui.setSize (1600, 900);
  24706. offline.dispatchPendingMessages();
  24707. const auto bar = (std::int64_t) lynx::ppq * 4;
  24708. offline.editSong ([bar] (lynx::Song& s) {
  24709. s.patterns.resize (3);
  24710. const char* names[] = { "Pattern 1", "Pattern 2", "Pattern 3" };
  24711. for (int p = 0; p < 3; ++p)
  24712. {
  24713. auto& pattern = s.patterns[(std::size_t) p];
  24714. pattern.name = names[p];
  24715. pattern.notes.clear();
  24716. for (int n = 0; n < 4 * (p + 1); ++n)
  24717. {
  24718. lynx::Note note;
  24719. note.start = (std::int64_t) n * lynx::ppq / 2;
  24720. note.length = lynx::ppq / 4;
  24721. note.key = 60 + (n * 5 + p * 3) % 12;
  24722. pattern.notes.push_back (note);
  24723. }
  24724. }
  24725. s.patterns[1].lengthTicks = bar * 2; // (Pattern 2 is two bars long)
  24726. s.currentPattern = 0;
  24727. s.playlist.clear();
  24728. }, false);
  24729. offline.dispatchPendingMessages();
  24730. ui.selectTabForSnapshot (2);
  24731. offline.dispatchPendingMessages();
  24732. auto& playlist = ui.getPlaylistForSnapshot();
  24733. playlist.setViewForSnapshot (120.0, 0, 0);
  24734. offline.dispatchPendingMessages();
  24735. // the drag's description survives the trip
  24736. {
  24737. auto kind = lynx::ClipKind::audio;
  24738. std::vector<int> entries;
  24739. const auto text = lynx::PlaylistComponent::pickerDragDescription (lynx::ClipKind::pattern, { 2, 0 });
  24740. check (lynx::PlaylistComponent::pickerDrag (text, kind, entries) && kind == lynx::ClipKind::pattern && entries == std::vector<int> ({ 2, 0 }),
  24741. "drag description " + text);
  24742. }
  24743. const auto at = [&playlist] (int track, double ticks) {
  24744. return juce::Point<int> (juce::roundToInt (playlist.xOfTickForSnapshot (ticks)), playlist.trackRowForSnapshot (track).getCentreY());
  24745. };
  24746. const auto find = [&offline] (int track, int pattern) -> const lynx::Clip* {
  24747. for (const auto& c : offline.getSong().playlist)
  24748. if (c.track == track && c.kind == lynx::ClipKind::pattern && c.pattern == pattern)
  24749. return &c;
  24750. return nullptr;
  24751. };
  24752. // 1. Pattern 1 dropped on track 1 a little after bar 2's line: it starts on that line
  24753. playlist.dropFromPicker (lynx::ClipKind::pattern, { 0 }, at (0, (double) bar + lynx::ppq * 0.2), false);
  24754. offline.dispatchPendingMessages();
  24755. const auto* one = find (0, 0);
  24756. check (one != nullptr && one->start == bar && one->length == bar, "plain drop: Pattern 1 on track 1 at bar 2");
  24757. // 2. Pattern 2 + Pattern 3 (picked together) dropped on track 3 at bar 3: tracks 3 and 4, same time
  24758. playlist.dropFromPicker (lynx::ClipKind::pattern, { 1, 2 }, at (2, (double) bar * 2), false);
  24759. offline.dispatchPendingMessages();
  24760. const auto* two = find (2, 1);
  24761. const auto* three = find (3, 2);
  24762. check (two != nullptr && three != nullptr && two->start == bar * 2 && three->start == bar * 2,
  24763. "two picked patterns: Pattern 2 on track 3, Pattern 3 on track 4, both at bar 3");
  24764. check (offline.getSong().currentPattern == 2, "the current pattern is the last dropped one (Pattern 3)");
  24765. const auto selectedAre = [&playlist, &offline] (int track, std::size_t count) {
  24766. const auto& sel = playlist.getSelectedClips();
  24767. if (sel.size() != count)
  24768. return false;
  24769. for (const auto i : sel)
  24770. 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)
  24771. || (track >= 0 && offline.getSong().playlist[(std::size_t) i].track != track))
  24772. return false;
  24773. return true;
  24774. };
  24775. check (selectedAre (-1, 2), "the two dropped clips are the selection (FL), Pattern 1's clip is not");
  24776. saveSnapshot (ui, prefix + "-plain.png");
  24777. // 3. Shift: all three on track 6 from bar 1, one after the other
  24778. playlist.dropFromPicker (lynx::ClipKind::pattern, { 0, 1, 2 }, at (5, 0.0), true);
  24779. offline.dispatchPendingMessages();
  24780. const auto* a = find (5, 0);
  24781. const auto* b = find (5, 1);
  24782. const auto* c = find (5, 2);
  24783. check (a != nullptr && b != nullptr && c != nullptr && a->start == 0 && b->start == a->end() && c->start == b->end(),
  24784. "Shift drop: Pattern 1, 2, 3 one after the other on track 6");
  24785. check (offline.getSong().currentPattern == 2, "Shift keeps the current pattern");
  24786. check (selectedAre (5, 3), "the three chained clips are the selection");
  24787. saveSnapshot (ui, prefix + "-shift.png");
  24788. }
  24789. checks.add (all ? "ALL OK" : "FAILURES");
  24790. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  24791. return all;
  24792. }
  24793. bool runTrackModeShot (const juce::String& prefix)
  24794. {
  24795. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24796. lynx::AudioEngine offline (false);
  24797. bool all = true;
  24798. juce::String report;
  24799. {
  24800. lynx::MainComponent ui (offline, false);
  24801. ui.setSize (1600, 900);
  24802. offline.dispatchPendingMessages();
  24803. auto& playlist = ui.getPlaylistForSnapshot();
  24804. // the track's menu, Track mode and Audio track side by side; the Audio track entries as FL writes them
  24805. // ("-" in front = greyed, "v" = ticked)
  24806. const auto shoot = [&] (int track, const juce::String& name, const juce::StringArray& fl) {
  24807. const auto menu = playlist.getTrackMenuForSnapshot (track);
  24808. juce::StringArray names { "Track " + juce::String (track + 1) };
  24809. std::vector<juce::PopupMenu> menus { menu };
  24810. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  24811. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Track mode"), 'T'))
  24812. {
  24813. names.add (lynx::tr ("Track mode"));
  24814. menus.push_back (*it.getItem().subMenu);
  24815. }
  24816. if (menus.size() == 2)
  24817. for (juce::PopupMenu::MenuItemIterator it (menus[1]); it.next();)
  24818. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::theme::mnemonic (lynx::tr ("Audio track"), 'A'))
  24819. {
  24820. names.add (lynx::tr ("Audio track"));
  24821. menus.push_back (*it.getItem().subMenu);
  24822. }
  24823. juce::StringArray lynxList;
  24824. if (menus.size() == 3)
  24825. for (juce::PopupMenu::MenuItemIterator it (menus[2]); it.next();)
  24826. lynxList.add (it.getItem().isSeparator ? juce::String ("|")
  24827. : (it.getItem().isTicked ? "v " : "") + juce::String (it.getItem().isEnabled ? "" : "- ") + it.getItem().text);
  24828. saveMenus (names, menus, prefix + "-" + name + ".png");
  24829. const auto same = menus.size() == 3 && lynxList == fl;
  24830. all = all && same;
  24831. report << name << ": " << (same ? "SAME AS FL" : "DIFFERENT") << "\n LYNX: " << lynxList.joinIntoString (" / ")
  24832. << "\n FL: " << fl.joinIntoString (" / ") << "\n";
  24833. };
  24834. const auto flList = [] (int inserts, std::map<int, juce::String> named, std::set<int> greyed) {
  24835. juce::StringArray l { "New mixer track(s)", "|" };
  24836. for (int i = 1; i <= inserts; ++i)
  24837. l.add ((greyed.count (i) ? "- " : "") + juce::String (i) + ". " + (named.count (i) ? named[i] : "Insert " + juce::String (i)));
  24838. return l;
  24839. };
  24840. // q1-01: a fresh project, Track 1 unassigned
  24841. shoot (0, "fresh", flList (16, {}, {}));
  24842. // q1-02: Track 1 linked to insert 6, insert 7 renamed "Vox chain"; Track 2's menu
  24843. offline.editSong ([] (lynx::Song& s) {
  24844. lynx::trackmodes::assignAudioTracks (s, { 0 }, 6);
  24845. s.mixer[7].name = "Vox chain";
  24846. });
  24847. offline.dispatchPendingMessages();
  24848. shoot (1, "linked-renamed", flList (16, { { 7, "Vox chain" } }, { 6 }));
  24849. // q1-07: the rest of FL's session (live 190cu Q2): Track 3 → 7; Track 4 → New mixer track (17), insert 9
  24850. // renamed "Vox chain", Track 4 → 9; Track 5 "Lead" → 11, insert 12 "Vox chain", Track 5 → 12; Track 6 "Lead"
  24851. // (unassigned), insert 13 "Vox chain", Track 6 → 13. Track 7's menu
  24852. offline.editSong ([] (lynx::Song& s) {
  24853. namespace tm = lynx::trackmodes;
  24854. if (s.playlistTracks.size() < 8)
  24855. s.playlistTracks.resize (8);
  24856. tm::assignAudioTracks (s, { 2 }, 7);
  24857. tm::assignAudioTracks (s, { 3 }, tm::newMixerTrack);
  24858. s.mixer[9].name = "Vox chain";
  24859. tm::assignAudioTracks (s, { 3 }, 9);
  24860. s.playlistTracks[4].name = "Lead";
  24861. tm::assignAudioTracks (s, { 4 }, 11);
  24862. s.mixer[12].name = "Vox chain";
  24863. tm::assignAudioTracks (s, { 4 }, 12);
  24864. s.playlistTracks[5].name = "Lead";
  24865. s.mixer[13].name = "Vox chain";
  24866. tm::assignAudioTracks (s, { 5 }, 13);
  24867. });
  24868. offline.dispatchPendingMessages();
  24869. shoot (6, "full-state", flList (17, { { 7, "Vox chain" }, { 9, "Insert 17" }, { 12, "Lead" }, { 13, "Vox chain" } }, { 6, 7, 9, 12, 13 }));
  24870. }
  24871. report << (all ? "ALL SAME AS FL\n" : "FAILURES\n");
  24872. juce::File (prefix + "-report.txt").replaceWithText (report);
  24873. return all;
  24874. }
  24875. void runCurveShot (const juce::String& prefix)
  24876. {
  24877. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  24878. lynx::AudioEngine offline (false);
  24879. {
  24880. lynx::MainComponent ui (offline, false);
  24881. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  24882. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  24883. offline.dispatchPendingMessages();
  24884. // FL's menu order, one bar per mode, the levels going up and down; a tension where the mode needs one to show
  24885. static const int order[] = { lynx::flcurve::smooth, lynx::flcurve::hold, lynx::flcurve::singleCurve, lynx::flcurve::singleCurve2,
  24886. lynx::flcurve::singleCurve3, lynx::flcurve::doubleCurve, lynx::flcurve::doubleCurve2, lynx::flcurve::doubleCurve3,
  24887. lynx::flcurve::halfSine, lynx::flcurve::stairs, lynx::flcurve::smoothStairs, lynx::flcurve::pulse, lynx::flcurve::wave };
  24888. const auto bar = (std::int64_t) lynx::ppq * 4;
  24889. offline.editSong ([bar] (lynx::Song& song) {
  24890. song.mode = lynx::PlayMode::song;
  24891. lynx::Automation a;
  24892. a.name = "Curve modes";
  24893. a.target = { lynx::AutomationTargetKind::mixerVolume, 1 };
  24894. a.points.push_back ({ 0, 0.15f, 0.0f });
  24895. int k = 0;
  24896. for (const auto mode : order)
  24897. {
  24898. const auto stepped = mode == lynx::flcurve::stairs || mode == lynx::flcurve::smoothStairs || mode == lynx::flcurve::pulse || mode == lynx::flcurve::wave;
  24899. a.points.back().mode = (std::uint8_t) mode;
  24900. a.points.back().tension = mode == lynx::flcurve::smooth || mode == lynx::flcurve::hold ? 0.0f : stepped ? -0.72f : (k % 2 == 0 ? 0.55f : -0.55f);
  24901. ++k;
  24902. a.points.push_back ({ bar * k, k % 2 == 1 ? 0.85f : 0.15f, 0.0f });
  24903. }
  24904. song.automations.insert (song.automations.begin(), a);
  24905. for (auto& c : song.playlist)
  24906. if (c.kind == lynx::ClipKind::automation)
  24907. ++c.automation;
  24908. lynx::Clip clip;
  24909. clip.kind = lynx::ClipKind::automation;
  24910. clip.automation = 0;
  24911. clip.track = 3;
  24912. clip.length = bar * 13;
  24913. song.playlist.push_back (clip);
  24914. if (song.playlistTracks.size() < 4)
  24915. song.playlistTracks.resize (4);
  24916. song.playlistTracks[3].height = 150;
  24917. }, false);
  24918. offline.dispatchPendingMessages();
  24919. ui.selectTabForSnapshot (2);
  24920. offline.dispatchPendingMessages();
  24921. auto& playlist = ui.getPlaylistForSnapshot();
  24922. saveSnapshot (ui, prefix + "-playlist.png");
  24923. const auto clipIndex = (int) offline.getSong().playlist.size() - 1;
  24924. // the point menu of the point that ends the "Stairs" segment (point 10), and of the first point
  24925. saveMenus (juce::StringArray { "Automation point (ends a Stairs segment)", "First point" },
  24926. std::vector<juce::PopupMenu> { playlist.getAutomationPointMenuForSnapshot (clipIndex, 10), playlist.getAutomationPointMenuForSnapshot (clipIndex, 0) },
  24927. prefix + "-point-menu.png");
  24928. auto editor = lynx::makeAutomationEditor (offline, 0);
  24929. editor->setSize (1500, 420);
  24930. savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-editor.png");
  24931. editor.reset();
  24932. // the project itself, for --export-flp and a look at the same clip in FL
  24933. {
  24934. juce::String saveError;
  24935. lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-modes.lynx"), saveError);
  24936. }
  24937. // part 2: the Piano roll tools that gained FL's options (they preview on the pattern and put the notes back)
  24938. ui.selectTabForSnapshot (1);
  24939. offline.dispatchPendingMessages();
  24940. auto& roll = ui.getPianoRollForSnapshot();
  24941. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::flip, "-tool-flip.png" },
  24942. { lynx::NoteTool::limit, "-tool-limit.png" },
  24943. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  24944. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  24945. { lynx::NoteTool::lfo, "-tool-lfo.png" } };
  24946. // round 190ct: checks of the FL-live fixes, one line each in <prefix>-checks.txt (OK / FAIL)
  24947. juce::StringArray checks;
  24948. const auto check = [&checks] (bool ok, const juce::String& what) { checks.add ((ok ? "OK " : "FAIL ") + what); };
  24949. {
  24950. juce::String header;
  24951. const auto pointMenu = playlist.getAutomationPointMenuForSnapshot (clipIndex, 10); // (the iterator keeps a reference)
  24952. for (juce::PopupMenu::MenuItemIterator it (pointMenu); it.next();)
  24953. {
  24954. header = it.getItem().text;
  24955. break;
  24956. }
  24957. check (header == "Point 11/14", "point menu header \"" + header + "\" (FL: \"Point n/N\")");
  24958. }
  24959. for (const auto& [tool, name] : tools)
  24960. {
  24961. auto panel = lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot());
  24962. offline.dispatchPendingMessages();
  24963. savePng (panel->createComponentSnapshot (panel->getLocalBounds()), prefix + name);
  24964. if (tool == lynx::NoteTool::flip)
  24965. {
  24966. std::vector<juce::ToggleButton*> toggles;
  24967. for (auto* child : panel->getChildren())
  24968. if (auto* t = dynamic_cast<juce::ToggleButton*> (child))
  24969. toggles.push_back (t);
  24970. check (toggles.size() == 3 && toggles[0]->getToggleState() && toggles[1]->getToggleState() && ! toggles[2]->getToggleState(),
  24971. "flip opens with Flip horizontally on, Preserve start times on, Flip vertically off");
  24972. if (toggles.size() == 3)
  24973. {
  24974. toggles[2]->setToggleState (true, juce::sendNotificationSync);
  24975. check (! toggles[0]->getToggleState() && toggles[2]->getToggleState(), "flip: vertically turns horizontally off (radios)");
  24976. toggles[0]->setToggleState (true, juce::sendNotificationSync);
  24977. check (toggles[0]->getToggleState() && ! toggles[2]->getToggleState(), "flip: horizontally turns vertically off (radios)");
  24978. }
  24979. }
  24980. if (tool == lynx::NoteTool::limit)
  24981. {
  24982. auto* list = lynx::noteToolLongestChoiceForSnapshot (*panel);
  24983. juce::ComboBox* key = nullptr;
  24984. for (auto* child : panel->getChildren())
  24985. if (auto* box = dynamic_cast<juce::ComboBox*> (child); box != nullptr && box->getNumItems() == 12)
  24986. key = box;
  24987. check (list != nullptr && list->getNumItems() == 89, "limit list has (none) + 66 chords + 22 scales: "
  24988. + juce::String (list != nullptr ? list->getNumItems() : 0));
  24989. check (list != nullptr && key != nullptr && list->getY() == key->getY() && list->getX() > key->getRight(),
  24990. "limit: Key and the chord / scale list share one row");
  24991. if (list != nullptr)
  24992. saveMenus (juce::StringArray { "Limit: Key / scale list" }, std::vector<juce::PopupMenu> { *list->getRootMenu() },
  24993. prefix + "-tool-limit-list.png");
  24994. }
  24995. if (tool == lynx::NoteTool::lfo)
  24996. saveMenus (juce::StringArray { "LFO tool: right-click on a Period slider" },
  24997. std::vector<juce::PopupMenu> { lynx::noteToolPresetMenuForSnapshot (*panel) }, prefix + "-tool-lfo-steps.png");
  24998. }
  24999. juce::File (prefix + "-checks.txt").replaceWithText (checks.joinIntoString ("\n") + "\n");
  25000. }
  25001. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  25002. }
  25003. bool runEvPaneShot (const juce::String& prefix, const juce::String& projectPath)
  25004. {
  25005. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25006. lynx::AudioEngine offline (false);
  25007. juce::StringArray report;
  25008. bool ok = true;
  25009. {
  25010. lynx::MainComponent ui (offline, false);
  25011. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  25012. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  25013. if (projectPath.isNotEmpty())
  25014. ui.openFile (juce::File (projectPath));
  25015. offline.dispatchPendingMessages();
  25016. ui.selectTabForSnapshot (1); // the Piano Roll
  25017. offline.dispatchPendingMessages();
  25018. auto& roll = ui.getPianoRollForSnapshot();
  25019. roll.scrollToNotes();
  25020. const auto area = ui.getLocalArea (&roll, roll.getLocalBounds());
  25021. const auto file = lynx::platform::settingsFile ("piano-roll-event-pane.txt");
  25022. auto source = juce::Desktop::getInstance().getMainMouseSource();
  25023. const auto now = juce::Time::getCurrentTime();
  25024. auto event = [&] (juce::Point<int> p, juce::Point<int> down, juce::ModifierKeys mods, int clicks, bool dragged) {
  25025. 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);
  25026. };
  25027. auto barCentre = [&roll] { return roll.eventPaneBarArea().getCentre(); };
  25028. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier),
  25029. middle (juce::ModifierKeys::middleButtonModifier);
  25030. auto click = [&] (juce::ModifierKeys button, int clicks) {
  25031. const auto at = barCentre();
  25032. roll.mouseDown (event (at, at, button, clicks, false));
  25033. roll.mouseUp (event (at, at, {}, clicks, false));
  25034. offline.dispatchPendingMessages();
  25035. };
  25036. auto dragTo = [&] (int y) {
  25037. const auto at = barCentre();
  25038. roll.mouseDown (event (at, at, left, 1, false));
  25039. for (int step = 1; step <= 8; ++step) // (a few moves, as a hand does)
  25040. roll.mouseDrag (event ({ at.x, at.y + (y - at.y) * step / 8 }, at, left, 1, true));
  25041. roll.mouseUp (event ({ at.x, y }, at, {}, 1, true));
  25042. offline.dispatchPendingMessages();
  25043. };
  25044. auto state = [&] (const juce::String& name) {
  25045. const auto grid = roll.getHeight() - lynx::PianoRollComponent::headerHeight - roll.velocityHeight - lynx::evpane::barThickness;
  25046. const auto& st = lynx::PianoRollComponent::eventPaneState();
  25047. report.add (name + ": roll " + juce::String (roll.getHeight()) + " px, grid " + juce::String (juce::jmax (0, grid)) + " px, bar top "
  25048. + juce::String (roll.eventPaneBarTopForTests()) + ", event editor " + juce::String (roll.velocityHeight) + " px, aspect "
  25049. + juce::String (st.aspect, 4) + ", spare " + juce::String (st.spare, 4) + ", file \"" + file.loadFileAsString().trim().replace ("\n", " ") + "\"");
  25050. saveArea (ui, area, prefix + "-" + name + ".png");
  25051. };
  25052. auto expect = [&] (bool condition, const juce::String& what) {
  25053. report.add ((condition ? "PASS " : "FAIL ") + what);
  25054. ok = ok && condition;
  25055. };
  25056. state ("1-default");
  25057. const auto defaultLane = roll.velocityHeight;
  25058. expect (std::abs (lynx::PianoRollComponent::eventPaneState().aspect - 0.8f) < 1e-6f, "default place is FL's 0.8");
  25059. ui.setHintForSnapshot (roll.hintAt (barCentre()));
  25060. saveSnapshot (ui, prefix + "-2-hover-hint.png");
  25061. ui.setHintForSnapshot ({});
  25062. const auto travelTop = lynx::PianoRollComponent::headerHeight, travelBottom = roll.getHeight() - lynx::evpane::barThickness;
  25063. dragTo (travelTop + (travelBottom - travelTop) * 45 / 100);
  25064. state ("3-dragged-larger");
  25065. const auto largeLane = roll.velocityHeight;
  25066. expect (largeLane > defaultLane * 2, "drag up makes the event editor taller");
  25067. expect (lynx::evpane::fromText (file.loadFileAsString().toStdString()) == lynx::PianoRollComponent::eventPaneState(),
  25068. "the place is written to the settings file on release");
  25069. click (right, 1);
  25070. state ("4-right-click-alternate");
  25071. expect (roll.velocityHeight == 0, "right-click: the alternate size (FL's spare 1.0) folds the event editor away");
  25072. click (right, 1);
  25073. state ("5-right-click-back");
  25074. expect (roll.velocityHeight == largeLane, "right-click again: back to the dragged size");
  25075. roll.runAction ("pianoRoll.eventPaneAlternate");
  25076. offline.dispatchPendingMessages();
  25077. expect (roll.velocityHeight == 0, "Shift+Enter (pianoRoll.eventPaneAlternate) swaps too");
  25078. roll.runAction ("pianoRoll.eventPaneAlternate");
  25079. offline.dispatchPendingMessages();
  25080. dragTo (travelTop + 10);
  25081. state ("6-grid-folded");
  25082. expect (roll.eventPaneBarTopForTests() == travelTop, "a drag within 23 px of the top folds the note grid away");
  25083. click (middle, 1);
  25084. state ("7-middle-click-default");
  25085. expect (roll.velocityHeight == defaultLane, "middle-click: back to the default place");
  25086. // a taller window keeps the proportion (the place is a fraction of the travel)
  25087. dragTo (travelTop + (travelBottom - travelTop) * 60 / 100);
  25088. const auto before = lynx::PianoRollComponent::eventPaneState().aspect;
  25089. roll.setSize (roll.getWidth(), roll.getHeight() + 200);
  25090. offline.dispatchPendingMessages();
  25091. const auto newTravel = roll.getHeight() - lynx::evpane::barThickness - travelTop;
  25092. expect (std::abs (roll.eventPaneBarTopForTests() - (travelTop + juce::roundToInt (before * (float) newTravel))) <= 1,
  25093. "a taller window keeps the proportion");
  25094. roll.setSize (roll.getWidth(), roll.getHeight() - 200);
  25095. offline.dispatchPendingMessages();
  25096. click (middle, 1); // leave FL's default behind
  25097. }
  25098. report.add (ok ? "RESULT OK" : "RESULT FAIL");
  25099. juce::File (prefix + "-report.txt").replaceWithText (report.joinIntoString ("\n") + "\n");
  25100. return ok;
  25101. }
  25102. void runFeat166Shot (const juce::String& prefix, const juce::String& projectPath)
  25103. {
  25104. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25105. lynx::AudioEngine offline (false);
  25106. {
  25107. lynx::MainComponent ui (offline, false);
  25108. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  25109. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  25110. if (projectPath.isNotEmpty())
  25111. ui.openFile (juce::File (projectPath));
  25112. offline.dispatchPendingMessages();
  25113. ui.selectTabForSnapshot (1); // the Piano Roll, on the channel with the most notes
  25114. offline.dispatchPendingMessages();
  25115. // the scale the pattern's notes fit best (major / minor, any root)
  25116. const auto& song = offline.getSong();
  25117. const auto& notes = song.patterns[(std::size_t) song.currentPattern].notes;
  25118. int bestRoot = 0, bestScale = 1, bestHits = -1;
  25119. for (int sc = 1; sc < (int) lynx::notetools::scales().size(); ++sc)
  25120. {
  25121. const juce::String name (lynx::notetools::scales()[(std::size_t) sc].name);
  25122. if (name != "Major" && name != "Minor")
  25123. continue;
  25124. for (int root = 0; root < 12; ++root)
  25125. {
  25126. int hits = 0;
  25127. for (const auto& n : notes)
  25128. hits += lynx::notetools::inScale (n.key, root, sc) ? 1 : 0;
  25129. if (hits > bestHits)
  25130. bestHits = hits, bestRoot = root, bestScale = sc;
  25131. }
  25132. }
  25133. auto& roll = ui.getPianoRollForSnapshot();
  25134. roll.setScaleForSnapshot (bestRoot, bestScale);
  25135. roll.scrollToNotes();
  25136. offline.dispatchPendingMessages();
  25137. saveSnapshot (ui, prefix + "-pr-scale.png");
  25138. roll.setFoldToScale (true);
  25139. offline.dispatchPendingMessages();
  25140. saveSnapshot (ui, prefix + "-pr-folded.png");
  25141. roll.setFoldToScale (false);
  25142. // ghost channels: only the first other channel with notes stays a ghost
  25143. const auto selected = offline.getSelectedChannel();
  25144. int keep = -1;
  25145. for (const auto& n : notes)
  25146. if (n.channel != selected && keep < 0)
  25147. keep = n.channel;
  25148. offline.editSong ([keep] (lynx::Song& s) {
  25149. for (int c = 0; c < (int) s.channels.size(); ++c)
  25150. s.channels[(std::size_t) c].ghostHidden = c != keep;
  25151. }, false);
  25152. offline.dispatchPendingMessages();
  25153. saveSnapshot (ui, prefix + "-pr-ghost-one.png");
  25154. saveMenus (juce::StringArray { "Ghost channels" }, { roll.ghostChannelsMenu() }, prefix + "-ghostmenu.png");
  25155. offline.editSong ([] (lynx::Song& s) {
  25156. for (auto& c : s.channels)
  25157. c.ghostHidden = false;
  25158. }, false);
  25159. // the Mixer at 500 inserts
  25160. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  25161. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::insertTracks (s, (int) s.mixer.size(), lynx::mixerops::roomForInserts (s)); }, false);
  25162. const auto t1 = juce::Time::getMillisecondCounterHiRes();
  25163. offline.dispatchPendingMessages();
  25164. ui.selectTabForSnapshot (3);
  25165. offline.dispatchPendingMessages();
  25166. auto& mixer = ui.getMixerForSnapshot();
  25167. const auto t2 = juce::Time::getMillisecondCounterHiRes();
  25168. saveSnapshot (ui, prefix + "-mixer500-start.png");
  25169. const auto t3 = juce::Time::getMillisecondCounterHiRes();
  25170. mixer.selectTrack ((int) offline.getSong().mixer.size() - 1);
  25171. offline.dispatchPendingMessages();
  25172. saveSnapshot (ui, prefix + "-mixer500-end.png");
  25173. juce::File (prefix + "-mixer500.txt")
  25174. .replaceWithText ("inserts=" + juce::String ((int) offline.getSong().mixer.size() - 1) + "\nfill_ms=" + juce::String (t1 - t0, 2)
  25175. + "\nsnapshot_ms=" + juce::String (t3 - t2, 2) + "\n");
  25176. }
  25177. }
  25178. // Round 190ay, Freeze, end to end with the real engine, files and export (LYNX.exe --freezetest prefix [project]).
  25179. // The project (.lynx / .flp / .als; without one, a small demo song) is rendered live, every channel that can be
  25180. // frozen is frozen, and the same render is made again: the two mixes must null. Written to prefix-report.txt: the
  25181. // null residual, the process memory and the render time before / frozen / unfrozen, what a save holds, whether
  25182. // Unfreeze gives the channels back as they were, the out-of-date and missing-audio states. Shots: the Channel Rack
  25183. // (live, frozen, out of date), the channel menus, the Piano roll of a frozen channel. The frozen audio goes to
  25184. // prefix-data (never next to the project). True = every check passed.
  25185. bool runFreezeTest (const juce::String& prefix, const juce::String& projectPath, const juce::String& mode = {})
  25186. {
  25187. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25188. lynx::AudioEngine offline (false);
  25189. lynx::MainComponent ui (offline, false);
  25190. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  25191. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  25192. const auto write = [&prefix, &ui] (const char* name) {
  25193. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  25194. file.deleteFile();
  25195. juce::FileOutputStream out (file);
  25196. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  25197. };
  25198. juce::String report;
  25199. int failures = 0;
  25200. const auto check = [&] (bool ok, const juce::String& what) {
  25201. report << (ok ? "ok " : "FAIL ") << what << "\n";
  25202. failures += ok ? 0 : 1;
  25203. };
  25204. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  25205. if (projectPath.isNotEmpty())
  25206. {
  25207. ui.openFile (juce::File (projectPath));
  25208. offline.dispatchPendingMessages();
  25209. }
  25210. else
  25211. offline.editSong ([] (lynx::Song& s) {
  25212. s.channels.clear();
  25213. s.patterns.clear();
  25214. s.playlist.clear();
  25215. s.bpm = 120.0;
  25216. const char* names[] = { "Lead", "Bass", "Pad", "Kick" };
  25217. for (int c = 0; c < 4; ++c)
  25218. {
  25219. lynx::ChannelDef d;
  25220. d.name = names[c];
  25221. d.instrument = c == 3 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  25222. d.synth.release = 0.3f + 0.3f * (float) c;
  25223. d.synth.cutoff = 1500.0f + 900.0f * (float) c;
  25224. d.mixerTrack = c + 1;
  25225. s.channels.push_back (d);
  25226. }
  25227. for (int p = 0; p < 2; ++p)
  25228. {
  25229. auto& pattern = s.patterns.emplace_back();
  25230. pattern.name = p == 0 ? "Verse" : "Break";
  25231. pattern.lengthTicks = 4 * lynx::ppq * 4;
  25232. for (int c = 0; c < 4; ++c)
  25233. for (int step = 0; step < (p == 0 ? 8 : 2); ++step)
  25234. {
  25235. lynx::Note n;
  25236. n.channel = c;
  25237. n.start = (std::int64_t) step * lynx::ppq * (p == 0 ? 2 : 1) + (c == 2 ? lynx::ppq / 2 : 0);
  25238. n.length = c == 3 ? lynx::ppq / 4 : lynx::ppq;
  25239. n.key = c == 3 ? 36 : 48 + c * 7 + (step * 5) % 12;
  25240. pattern.notes.push_back (n);
  25241. }
  25242. pattern.sortNotes();
  25243. }
  25244. const int order[] = { 0, 0, 1, 0 };
  25245. for (int i = 0; i < 4; ++i)
  25246. {
  25247. lynx::Clip clip;
  25248. clip.pattern = order[i];
  25249. clip.start = (std::int64_t) i * 16 * lynx::ppq;
  25250. clip.length = 16 * lynx::ppq;
  25251. s.playlist.push_back (clip);
  25252. }
  25253. s.mode = lynx::PlayMode::song;
  25254. });
  25255. offline.dispatchPendingMessages();
  25256. // the case Freeze exists for, a heavy hosted plugin: LYNX_FREEZETEST_PLUGIN = a plugin file whose first
  25257. // instrument plays the demo song's Lead (tools/testplugin/lynx_test_heavy_vst3.cpp: memory, CPU, latency, a
  25258. // state, and with LYNX_TEST_HEAVY_LOG the instances alive)
  25259. int hostedChannel = -1;
  25260. const auto hostedLog = juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_HEAVY_LOG", {});
  25261. const auto hostedAlive = [&hostedLog] {
  25262. int alive = 0;
  25263. juce::StringArray lines;
  25264. juce::File (hostedLog).readLines (lines);
  25265. for (const auto& l : lines)
  25266. alive += l.startsWith ("create") ? 1 : l.startsWith ("destroy") ? -1 : 0;
  25267. return alive;
  25268. };
  25269. if (const auto pluginPath = juce::SystemStats::getEnvironmentVariable ("LYNX_FREEZETEST_PLUGIN", {}); pluginPath.isNotEmpty() && projectPath.isEmpty())
  25270. {
  25271. auto& host = offline.getPluginHost();
  25272. const auto added = host.addPluginFile (juce::File (pluginPath));
  25273. report << "hosted plugin file: " << pluginPath << " (" << added << " plugins)\n";
  25274. for (const auto& type : host.getKnownPlugins().getTypes())
  25275. if (type.isInstrument && juce::File (type.fileOrIdentifier).getFileName() == juce::File (pluginPath).getFileName())
  25276. {
  25277. offline.editSong ([&type] (lynx::Song& s) {
  25278. auto& c = s.channels[0];
  25279. c.instrument = lynx::InstrumentKind::plugin;
  25280. c.plugin.id = type.createIdentifierString().toStdString();
  25281. c.plugin.name = type.name.toStdString();
  25282. });
  25283. hostedChannel = 0;
  25284. break;
  25285. }
  25286. offline.dispatchPendingMessages();
  25287. auto* instance = dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (0).get());
  25288. check (hostedChannel == 0 && instance != nullptr, "the hosted plugin is loaded on channel 1");
  25289. report << "hosted plugin: " << juce::String::fromUTF8 (offline.getSong().channels[0].plugin.name.c_str())
  25290. << ", engine latency " << offline.getLatencySamples() << " frames, instances alive " << hostedAlive() << "\n";
  25291. }
  25292. const auto hostedLine = [&] (const char* stage) {
  25293. if (hostedChannel < 0)
  25294. return;
  25295. offline.freeRetiredRacks();
  25296. report << "hosted, " << stage << ": instance on the channel "
  25297. << (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr ? "yes" : "no")
  25298. << ", plugin instances alive in the process " << (hostedLog.isNotEmpty() ? juce::String (hostedAlive()) : juce::String ("(no log)")) << "\n";
  25299. };
  25300. const juce::File data (prefix + "-data");
  25301. data.deleteRecursively();
  25302. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "freezetest");
  25303. report << "project=" << (projectPath.isNotEmpty() ? projectPath : juce::String ("(demo song)")) << "\n"
  25304. << "frozen_audio_folder=" << offline.getFreezeFolder().getFullPathName() << "\n";
  25305. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  25306. struct Mix
  25307. {
  25308. juce::AudioBuffer<float> audio;
  25309. double renderSeconds = 0.0, audioSeconds = 0.0;
  25310. std::int64_t workingSet = 0, privateBytes = 0;
  25311. };
  25312. // the song as it stands, rendered by an export (its own engine: frozen channels play their audio there too)
  25313. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr, std::vector<int>* renderedLive = nullptr, int range = 0) {
  25314. Mix m;
  25315. offline.dispatchPendingMessages();
  25316. offline.freeRetiredRacks(); // (what the message loop does in the app: this mode runs without one)
  25317. m.workingSet = lynx::toolbar::PerformanceMeter::processMemoryBytes();
  25318. m.privateBytes = lynx::toolbar::PerformanceMeter::processPrivateBytes();
  25319. const juce::File file (prefix + "-" + name + ".wav");
  25320. lynx::ExportSettings settings;
  25321. settings.format = lynx::ExportSettings::Format::wav32Float;
  25322. settings.sampleRate = offline.getTransport().sampleRate.load();
  25323. settings.tailSeconds = 2.0;
  25324. juce::String error;
  25325. {
  25326. auto options = settings.toOptions();
  25327. options.hqAllPlugins = false; // the quality heard while playing: what a frozen channel's audio is made at
  25328. options.disableMaxPolyphony = false; // (and each channel's Max polyphony, as while playing)
  25329. if (range == 1)
  25330. options.range = lynx::exportopts::Range::selection;
  25331. if (range == 2)
  25332. {
  25333. options.range = lynx::exportopts::Range::pattern;
  25334. options.loops = 2;
  25335. }
  25336. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  25337. if (renderedLive != nullptr)
  25338. *renderedLive = job.channelsRenderedLive();
  25339. const auto started = juce::Time::getMillisecondCounterHiRes();
  25340. const auto ok = job.run ([] (double) { return true; }, error);
  25341. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  25342. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  25343. }
  25344. juce::WavAudioFormat wav;
  25345. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  25346. {
  25347. m.audio.setSize (2, (int) reader->lengthInSamples);
  25348. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  25349. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  25350. }
  25351. file.deleteFile();
  25352. return m;
  25353. };
  25354. // the worst sample difference, in dB below the first mix's peak
  25355. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  25356. float worst = 0.0f;
  25357. peak = 0.0f;
  25358. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  25359. for (int ch = 0; ch < 2; ++ch)
  25360. for (int i = 0; i < n; ++i)
  25361. {
  25362. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  25363. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  25364. }
  25365. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  25366. };
  25367. const auto line = [&] (const char* name, const Mix& m) {
  25368. report << name << ": working set " << megabytes (m.workingSet) << " MB, private " << megabytes (m.privateBytes) << " MB, render "
  25369. << juce::String (m.renderSeconds, 2) << " s for " << juce::String (m.audioSeconds, 2) << " s of audio ("
  25370. << juce::String (m.audioSeconds > 0.0 ? 100.0 * m.renderSeconds / m.audioSeconds : 0.0, 1) << " % of real time)\n";
  25371. };
  25372. if (mode == "measure")
  25373. {
  25374. // a process that only loaded this project and renders it: its memory with the project loaded, and after
  25375. int frozenCount = 0, hosted = 0;
  25376. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  25377. {
  25378. frozenCount += offline.getSong().channels[(std::size_t) c].freeze.on();
  25379. hosted += dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) != nullptr;
  25380. }
  25381. report << "channels " << (int) offline.getSong().channels.size() << ", frozen " << frozenCount << ", hosted plugin instances " << hosted << "\n";
  25382. const auto m = renderMix ("measure");
  25383. line ("loaded ", m);
  25384. report << "after the render: working set " << megabytes (lynx::toolbar::PerformanceMeter::processMemoryBytes()) << " MB, private "
  25385. << megabytes (lynx::toolbar::PerformanceMeter::processPrivateBytes()) << " MB\n";
  25386. flush();
  25387. return failures == 0;
  25388. }
  25389. // --- live ---
  25390. offline.capturePluginStates();
  25391. offline.editSong ([] (lynx::Song&) {}, false); // (whatever any edit settles — ids of new objects... — settled first)
  25392. const auto before = offline.getSong();
  25393. // (the project's working-time counter runs on while the test does: not part of what is compared)
  25394. const auto savedJson = [] (lynx::Song song) {
  25395. song.info.workSeconds = 0.0;
  25396. return lynx::ProjectFile::toJson (song, false);
  25397. };
  25398. const auto jsonBefore = savedJson (before);
  25399. std::vector<int> targets;
  25400. for (int c = 0; c < (int) before.channels.size(); ++c)
  25401. {
  25402. const auto* why = lynx::freeze::whyNot (before, c);
  25403. const auto plays = std::any_of (before.patterns.begin(), before.patterns.end(), [c] (const lynx::Pattern& p) {
  25404. return std::any_of (p.notes.begin(), p.notes.end(), [c] (const lynx::Note& n) { return n.channel == c; });
  25405. });
  25406. report << "channel " << (c + 1) << " '" << juce::String::fromUTF8 (before.channels[(std::size_t) c].name.c_str()) << "': "
  25407. << (why != nullptr ? juce::String ("not frozen (") + why + ")" : plays ? juce::String ("freeze") : juce::String ("no notes, left alone")) << "\n";
  25408. if (why == nullptr && plays)
  25409. {
  25410. targets.push_back (c);
  25411. // what could make a stem differ from the live channel, for the record
  25412. const auto& def = before.channels[(std::size_t) c];
  25413. int volPan = 0, params = 0, live = 0, lanes = 0, routes = 0;
  25414. for (const auto& a : before.automations)
  25415. if (a.target.index == c)
  25416. {
  25417. volPan += a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan;
  25418. params += a.target.kind == lynx::AutomationTargetKind::channelParam;
  25419. live += a.isLive() && (a.target.kind == lynx::AutomationTargetKind::channelVolume || a.target.kind == lynx::AutomationTargetKind::channelPan
  25420. || a.target.kind == lynx::AutomationTargetKind::channelParam);
  25421. }
  25422. for (const auto& p : before.patterns)
  25423. for (const auto& lane : p.events)
  25424. lanes += lane.target.index == c && (lane.target.kind == lynx::AutomationTargetKind::channelVolume
  25425. || lane.target.kind == lynx::AutomationTargetKind::channelPan
  25426. || lane.target.kind == lynx::AutomationTargetKind::channelParam);
  25427. for (const auto& m : before.modulators)
  25428. for (const auto& r : m.routes)
  25429. routes += r.target.index == c && (r.target.kind == lynx::AutomationTargetKind::channelVolume
  25430. || r.target.kind == lynx::AutomationTargetKind::channelPan
  25431. || r.target.kind == lynx::AutomationTargetKind::channelParam);
  25432. report << " instrument kind " << (int) def.instrument << ", insert " << def.mixerTrack << ", automation: volume/pan " << volPan
  25433. << ", parameters " << params << ", live links " << live << ", event lanes " << lanes << ", modulator routes " << routes << "\n";
  25434. }
  25435. }
  25436. check (! targets.empty(), "the project has channels to freeze (" + juce::String ((int) targets.size()) + ")");
  25437. if (targets.empty())
  25438. {
  25439. flush();
  25440. return false;
  25441. }
  25442. const auto first = targets.front();
  25443. offline.setSelectedChannel (first);
  25444. ui.selectTabForSnapshot (0);
  25445. write ("rack-live");
  25446. saveMenus (juce::StringArray { "Channel (live)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-live.png");
  25447. const auto live = renderMix ("live");
  25448. line ("live ", live);
  25449. hostedLine ("live");
  25450. const auto hostedState = hostedChannel >= 0 ? before.channels[(std::size_t) hostedChannel].plugin.state : std::string();
  25451. if (hostedChannel >= 0)
  25452. check (! hostedState.empty(), "the hosted plugin's state is in the project (" + juce::String ((int) hostedState.size()) + " characters)");
  25453. flush();
  25454. // --- frozen ---
  25455. const auto freezeStarted = juce::Time::getMillisecondCounterHiRes();
  25456. for (const auto c : targets)
  25457. {
  25458. const auto error = lynx::freezeChannelNow (offline, c);
  25459. check (error.isEmpty(), "freeze channel " + juce::String (c + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  25460. }
  25461. const auto freezeSeconds = (juce::Time::getMillisecondCounterHiRes() - freezeStarted) / 1000.0;
  25462. offline.dispatchPendingMessages();
  25463. std::int64_t stemBytes = 0;
  25464. int stemFiles = 0;
  25465. bool pluginsGone = true, allFrozen = true;
  25466. for (const auto c : targets)
  25467. {
  25468. const auto& ch = offline.getSong().channels[(std::size_t) c];
  25469. allFrozen = allFrozen && ch.freeze.on() && ! offline.frozenAudioMissing (c) && ! offline.freezeOutOfDate (c);
  25470. for (const auto& stem : ch.freeze.stems)
  25471. {
  25472. stemBytes += juce::File (juce::String::fromUTF8 (stem.path.c_str())).getSize();
  25473. ++stemFiles;
  25474. }
  25475. pluginsGone = pluginsGone && dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (c).get()) == nullptr;
  25476. auto thawed = ch;
  25477. thawed.freeze = {};
  25478. check (thawed == before.channels[(std::size_t) c], "channel " + juce::String (c + 1) + " keeps its instrument and settings as they were while frozen");
  25479. }
  25480. check (allFrozen, "every target is frozen, its audio on disk and up to date");
  25481. check (pluginsGone, "no hosted plugin instance is left on a frozen channel");
  25482. report << "freeze: " << juce::String (freezeSeconds, 2) << " s for " << (int) targets.size() << " channels, " << stemFiles << " files, "
  25483. << megabytes (stemBytes) << " MB on disk\n";
  25484. if (mode == "keep")
  25485. {
  25486. juce::String error;
  25487. check (lynx::ProjectFile::save (offline.getSong(), juce::File (prefix + "-frozen.lynx"), error), "the frozen project is saved" + (error.isEmpty() ? juce::String() : ": " + error));
  25488. flush();
  25489. return failures == 0;
  25490. }
  25491. const auto frozen = renderMix ("frozen");
  25492. line ("frozen ", frozen);
  25493. hostedLine ("frozen");
  25494. if (hostedChannel >= 0 && hostedLog.isNotEmpty())
  25495. check (hostedAlive() == 0, "while frozen no instance of the hosted plugin is alive in the process");
  25496. float peak = 0.0f;
  25497. const auto nullFrozen = residual (live, frozen, peak);
  25498. report << "null frozen vs live: " << juce::String (nullFrozen, 1) << " dB (peak " << juce::String (peak, 4) << ", "
  25499. << live.audio.getNumSamples() << " / " << frozen.audio.getNumSamples() << " samples)\n";
  25500. check (peak > 0.001f && nullFrozen < -90.0 && live.audio.getNumSamples() == frozen.audio.getNumSamples(), "the frozen mix nulls against the live mix (below -90 dB)");
  25501. ui.selectTabForSnapshot (0);
  25502. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  25503. write ("rack-frozen");
  25504. saveMenus (juce::StringArray { "Channel (frozen)" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (first) }, prefix + "-menu-frozen.png");
  25505. report << "hint frozen: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  25506. offline.setSelectedChannel (first);
  25507. ui.selectTabForSnapshot (1);
  25508. offline.setSelectedChannel (first);
  25509. offline.dispatchPendingMessages();
  25510. ui.setHintForSnapshot ({ lynx::tr ("{0} is frozen: Unfreeze to edit ([RMB] on the channel, Unfreeze)",
  25511. { juce::String::fromUTF8 (offline.getSong().channels[(std::size_t) first].name.c_str()) }), {} });
  25512. write ("pianoroll-frozen");
  25513. // --- exports that do not play the song's timeline once: a selection, one pattern twice ---
  25514. // (the frozen audio is the whole song from its start: those renders play the instruments, never a wrong part of it)
  25515. if (projectPath.isEmpty())
  25516. {
  25517. auto part = offline.getSong();
  25518. part.loopStart = 16 * lynx::ppq;
  25519. part.loopEnd = 40 * lynx::ppq;
  25520. const auto partLive = lynx::freeze::thawed (part);
  25521. for (int range = 1; range <= 2; ++range)
  25522. {
  25523. std::vector<int> renderedLive;
  25524. const auto a = renderMix (range == 1 ? "selection-live" : "pattern-live", &partLive, nullptr, range);
  25525. const auto b = renderMix (range == 1 ? "selection-frozen" : "pattern-frozen", &part, &renderedLive, range);
  25526. float partPeak = 0.0f;
  25527. const auto null = residual (a, b, partPeak);
  25528. report << (range == 1 ? "export of a selection (bars 5-10)" : "export of the current pattern, twice") << ", frozen vs live: " << juce::String (null, 1)
  25529. << " dB (peak " << juce::String (partPeak, 4) << ", " << juce::String (b.audioSeconds, 2) << " s), channels rendered live: " << (int) renderedLive.size() << "\n";
  25530. check (partPeak > 0.001f && null < -90.0 && a.audio.getNumSamples() == b.audio.getNumSamples(),
  25531. 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");
  25532. }
  25533. }
  25534. // --- what a save holds ---
  25535. {
  25536. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  25537. juce::String error;
  25538. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  25539. check (json.contains ("\"freeze\""), "the saved project holds the frozen state");
  25540. check (loaded.has_value() && loaded->channels.size() == offline.getSong().channels.size()
  25541. && loaded->channels[(std::size_t) first].freeze == offline.getSong().channels[(std::size_t) first].freeze,
  25542. "a frozen project loads frozen, with the same audio files");
  25543. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore,
  25544. "without the frozen state the saved project is byte for byte what it was before the freeze");
  25545. check (! jsonBefore.contains ("\"freeze\""), "a project with nothing frozen has no freeze field");
  25546. }
  25547. // --- out of date: the tempo, a note of the frozen channel; not another channel's notes ---
  25548. {
  25549. offline.editSong ([] (lynx::Song& s) { s.bpm += 4.0; });
  25550. check (offline.freezeOutOfDate (first), "a tempo change marks the freeze out of date");
  25551. ui.selectTabForSnapshot (0);
  25552. ui.setHintForSnapshot (ui.getRackForSnapshot().getChannelHintForSnapshot (first));
  25553. write ("rack-out-of-date");
  25554. report << "hint out of date: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  25555. offline.editSong ([] (lynx::Song& s) { s.bpm -= 4.0; });
  25556. check (! offline.freezeOutOfDate (first), "the tempo back: up to date again");
  25557. int pattern = -1;
  25558. for (int p = 0; p < (int) before.patterns.size() && pattern < 0; ++p)
  25559. for (const auto& n : before.patterns[(std::size_t) p].notes)
  25560. if (n.channel == first)
  25561. {
  25562. pattern = p;
  25563. break;
  25564. }
  25565. if (pattern >= 0)
  25566. {
  25567. offline.editSong ([pattern, first] (lynx::Song& s) {
  25568. lynx::Note n;
  25569. n.channel = first;
  25570. n.start = 0;
  25571. n.key = 71;
  25572. s.patterns[(std::size_t) pattern].notes.push_back (n);
  25573. s.patterns[(std::size_t) pattern].sortNotes();
  25574. });
  25575. check (offline.freezeOutOfDate (first), "a note edit on the frozen channel marks it out of date");
  25576. bool othersFresh = true;
  25577. for (const auto c : targets)
  25578. othersFresh = othersFresh && (c == first || ! offline.freezeOutOfDate (c));
  25579. check (othersFresh, "the other frozen channels stay up to date");
  25580. // an export of the project in that state: the out-of-date channel renders live (never the old audio),
  25581. // the others keep their frozen audio — the same mix as the edited project with nothing frozen
  25582. {
  25583. std::vector<int> renderedLive;
  25584. const auto stale = renderMix ("stale", nullptr, &renderedLive);
  25585. const auto edited = lynx::freeze::thawed (offline.getSong());
  25586. const auto reference = renderMix ("stale-reference", &edited);
  25587. float stalePeak = 0.0f;
  25588. const auto nullStale = residual (reference, stale, stalePeak);
  25589. const auto nullOld = residual (frozen, stale, stalePeak);
  25590. report << "export with channel " << (first + 1) << " out of date: " << juce::String (nullStale, 1) << " dB vs the edited project live, "
  25591. << juce::String (nullOld, 1) << " dB vs the old frozen mix; channels rendered live: " << (int) renderedLive.size() << "\n";
  25592. check (renderedLive == std::vector<int> { first }, "an export renders the out-of-date frozen channel live, and only that one");
  25593. check (nullStale < -90.0 && nullOld > -60.0, "an export of an out-of-date freeze holds the edited notes, not the old audio");
  25594. }
  25595. offline.editSong ([&before] (lynx::Song& s) { s.patterns = before.patterns; });
  25596. check (! offline.freezeOutOfDate (first), "the notes back: up to date again");
  25597. }
  25598. }
  25599. // --- the audio gone: the instrument plays, never silence ---
  25600. {
  25601. const auto stems = offline.getSong().channels[(std::size_t) first].freeze.stems;
  25602. std::vector<std::pair<juce::File, juce::File>> moved;
  25603. for (const auto& stem : stems)
  25604. {
  25605. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  25606. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  25607. if (file.moveFileTo (away))
  25608. moved.emplace_back (file, away);
  25609. }
  25610. offline.editSong ([] (lynx::Song&) {}, false);
  25611. check (offline.frozenAudioMissing (first), "frozen audio that is not on disk is noticed");
  25612. report << "hint audio missing: " << ui.getRackForSnapshot().getChannelHintForSnapshot (first).text << "\n";
  25613. const auto fallback = renderMix ("missing");
  25614. const auto nullMissing = residual (live, fallback, peak);
  25615. report << "null with the first channel's audio missing vs live: " << juce::String (nullMissing, 1) << " dB\n";
  25616. check (nullMissing < -90.0, "with its audio missing the channel plays its instrument");
  25617. for (const auto& [file, away] : moved)
  25618. away.moveFileTo (file);
  25619. offline.editSong ([] (lynx::Song&) {}, false);
  25620. check (! offline.frozenAudioMissing (first), "the audio back: frozen again");
  25621. // the frozen mix did not null and the first channel is not (alone) why: which one is, each thawed in turn
  25622. if (nullFrozen >= -90.0 && nullMissing >= -90.0)
  25623. for (const auto c : targets)
  25624. {
  25625. if (c == first)
  25626. continue;
  25627. std::vector<std::pair<juce::File, juce::File>> aside;
  25628. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  25629. {
  25630. const juce::File file (juce::String::fromUTF8 (stem.path.c_str()));
  25631. const auto away = file.getSiblingFile (file.getFileName() + ".away");
  25632. if (file.moveFileTo (away))
  25633. aside.emplace_back (file, away);
  25634. }
  25635. offline.editSong ([] (lynx::Song&) {}, false);
  25636. const auto one = renderMix ("thawed");
  25637. report << "null with channel " << (c + 1) << " thawed vs live: " << juce::String (residual (live, one, peak), 1) << " dB\n";
  25638. for (const auto& [file, away] : aside)
  25639. away.moveFileTo (file);
  25640. offline.editSong ([] (lynx::Song&) {}, false);
  25641. }
  25642. }
  25643. // --- unfrozen ---
  25644. std::vector<juce::File> stemPaths;
  25645. for (const auto c : targets)
  25646. for (const auto& stem : offline.getSong().channels[(std::size_t) c].freeze.stems)
  25647. stemPaths.emplace_back (juce::String::fromUTF8 (stem.path.c_str()));
  25648. for (const auto c : targets)
  25649. lynx::unfreezeChannel (offline, c);
  25650. offline.dispatchPendingMessages();
  25651. check (offline.getSong().channels == before.channels, "Unfreeze gives every channel back exactly as it was (instrument, plugin state, settings)");
  25652. {
  25653. const auto jsonAfter = savedJson (offline.getSong());
  25654. check (jsonAfter == jsonBefore, "the unfrozen project saves byte for byte as before the freeze");
  25655. if (jsonAfter != jsonBefore)
  25656. {
  25657. juce::File (prefix + "-before.json").replaceWithText (jsonBefore);
  25658. juce::File (prefix + "-after.json").replaceWithText (jsonAfter);
  25659. }
  25660. }
  25661. int left = 0;
  25662. for (const auto& f : stemPaths)
  25663. left += f.existsAsFile() ? 1 : 0;
  25664. check (left == 0, "Unfreeze deletes the frozen audio (" + juce::String (left) + " of " + juce::String ((int) stemPaths.size()) + " files left)");
  25665. if (hostedChannel >= 0)
  25666. {
  25667. // the new instance (it starts with another tuning than the first one had) took the saved state
  25668. offline.capturePluginStates();
  25669. check (dynamic_cast<lynx::PluginInstrument*> (offline.getChannelInstrument (hostedChannel).get()) != nullptr, "Unfreeze loads the hosted plugin again");
  25670. check (offline.getSong().channels[(std::size_t) hostedChannel].plugin.state == hostedState,
  25671. "the hosted plugin's state, read back from the new instance, is the state it had before the freeze");
  25672. }
  25673. const auto unfrozen = renderMix ("unfrozen");
  25674. line ("unfrozen ", unfrozen);
  25675. hostedLine ("unfrozen");
  25676. const auto nullUnfrozen = residual (live, unfrozen, peak);
  25677. report << "null unfrozen vs live: " << juce::String (nullUnfrozen, 1) << " dB\n";
  25678. check (nullUnfrozen < -90.0, "the unfrozen mix nulls against the live mix");
  25679. ui.selectTabForSnapshot (0);
  25680. flush();
  25681. data.deleteRecursively();
  25682. return failures == 0;
  25683. }
  25684. // Round 190ff, the Clip-launch workflow's track commands end to end with the real engine, files and export
  25685. // (LYNX --trackfreezetest prefix). A demo song of three tracks (Lead through a delay and a reverb whose mix is
  25686. // automated, Bass through a delay, Drums on a bare insert; each insert's fader, pan and EQ set) is rendered live; then
  25687. // Freeze Track on every track (the instrument with its volume and pan through its insert's effects), the same render
  25688. // again (must null), the effects and instruments unloaded, the render time (the CPU while frozen), what a save holds;
  25689. // Flatten (Bounce Track in Place on a frozen track) with its undo; Bounce Track in Place of a live track; Bounce to New
  25690. // Track of a track's clips against that track's device output; Consolidate of pattern clips; Unfreeze. Written to
  25691. // prefix-report.txt; shots of the grid, the column menus, the Detail View's frozen devices and the Playlist's clip
  25692. // menu. True = every check passed.
  25693. bool runTrackFreezeTest (const juce::String& prefix)
  25694. {
  25695. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  25696. lynx::AudioEngine offline (false);
  25697. lynx::MainComponent ui (offline, false);
  25698. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  25699. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  25700. const auto write = [&prefix, &ui] (const char* name) {
  25701. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  25702. file.deleteFile();
  25703. juce::FileOutputStream out (file);
  25704. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  25705. };
  25706. juce::String report;
  25707. int failures = 0;
  25708. const auto check = [&] (bool ok, const juce::String& what) {
  25709. report << (ok ? "ok " : "FAIL ") << what << "\n";
  25710. failures += ok ? 0 : 1;
  25711. };
  25712. const auto flush = [&] { juce::File (prefix + "-report.txt").replaceWithText (report + "failures=" + juce::String (failures) + "\n"); };
  25713. const juce::File data (prefix + "-data");
  25714. data.deleteRecursively();
  25715. offline.setRecordingTarget (data.getChildFile ("Audio").getChildFile ("Recorded"), "trackfreezetest");
  25716. ui.setVisible (true);
  25717. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  25718. ui.setClipLaunchWorkflow (true);
  25719. offline.editSong ([] (lynx::Song& s) {
  25720. s.channels.clear();
  25721. s.patterns.clear();
  25722. s.playlist.clear();
  25723. s.automations.clear();
  25724. s.bpm = 120.0;
  25725. s.mode = lynx::PlayMode::song;
  25726. const char* names[] = { "Lead", "Bass", "Drums" };
  25727. for (int c = 0; c < 3; ++c)
  25728. {
  25729. lynx::ChannelDef d;
  25730. d.name = names[c];
  25731. d.instrument = c == 2 ? lynx::InstrumentKind::kick : lynx::InstrumentKind::synth;
  25732. d.synth.release = c == 0 ? 0.6f : 0.2f;
  25733. d.synth.cutoff = c == 0 ? 2400.0f : 900.0f;
  25734. d.volume = c == 0 ? 0.65f : 0.78f;
  25735. d.pan = c == 0 ? 0.25f : 0.0f;
  25736. d.mixerTrack = c + 1;
  25737. s.channels.push_back (d);
  25738. }
  25739. if (s.mixer.size() < 5)
  25740. s.mixer.resize (5);
  25741. s.mixer[1].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay), lynx::makeEffectSlot (lynx::EffectKind::reverb) };
  25742. s.mixer[2].effects = { lynx::makeEffectSlot (lynx::EffectKind::delay) };
  25743. s.mixer[3].effects.clear();
  25744. for (int t = 1; t <= 3; ++t)
  25745. {
  25746. s.mixer[(std::size_t) t].name = names[t - 1];
  25747. s.mixer[(std::size_t) t].volume = 0.7f;
  25748. s.mixer[(std::size_t) t].pan = t == 1 ? -0.3f : 0.1f;
  25749. s.mixer[(std::size_t) t].eq.gainDb[1] = 3.0f;
  25750. }
  25751. for (int p = 0; p < 3; ++p)
  25752. {
  25753. auto& pattern = s.patterns.emplace_back();
  25754. pattern.name = names[p];
  25755. pattern.lengthTicks = 4 * lynx::ppq * 2;
  25756. for (int step = 0; step < 8; ++step)
  25757. {
  25758. lynx::Note n;
  25759. n.channel = p;
  25760. n.start = (std::int64_t) step * lynx::ppq;
  25761. n.length = p == 2 ? lynx::ppq / 4 : lynx::ppq / 2;
  25762. n.key = p == 2 ? 36 : (p == 0 ? 60 : 36) + (step * 5) % 12;
  25763. pattern.notes.push_back (n);
  25764. }
  25765. }
  25766. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 4));
  25767. for (int t = 0; t < 3; ++t)
  25768. {
  25769. s.playlistTracks[(std::size_t) t].name = names[t];
  25770. for (int k = 0; k < 3; ++k)
  25771. {
  25772. if (t == 0 && k == 1)
  25773. continue; // (a gap in the Lead: its tail rings into it)
  25774. lynx::Clip clip;
  25775. clip.pattern = t;
  25776. clip.track = t;
  25777. clip.start = (std::int64_t) k * 8 * lynx::ppq;
  25778. clip.length = 8 * lynx::ppq;
  25779. s.playlist.push_back (clip);
  25780. }
  25781. }
  25782. // the Lead's reverb mix rises over the song (automation the freeze takes into its audio)
  25783. lynx::Automation a;
  25784. a.name = "Lead reverb mix";
  25785. a.target = { lynx::AutomationTargetKind::effectMix, 1, 1, 0 };
  25786. a.points = { { 0, 0.2f }, { 24 * lynx::ppq, 0.9f } };
  25787. s.automations.push_back (a);
  25788. lynx::Clip lane;
  25789. lane.kind = lynx::ClipKind::automation;
  25790. lane.automation = 0;
  25791. lane.track = 3;
  25792. lane.length = 24 * lynx::ppq;
  25793. s.playlist.push_back (lane);
  25794. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& x, const lynx::Clip& y) { return x.start < y.start; });
  25795. });
  25796. offline.dispatchPendingMessages();
  25797. const auto megabytes = [] (std::int64_t bytes) { return juce::String ((double) bytes / 1048576.0, 1); };
  25798. struct Mix
  25799. {
  25800. juce::AudioBuffer<float> audio;
  25801. double renderSeconds = 0.0, audioSeconds = 0.0;
  25802. };
  25803. const auto renderMix = [&] (const char* name, const lynx::Song* other = nullptr) {
  25804. Mix m;
  25805. offline.dispatchPendingMessages();
  25806. offline.freeRetiredRacks();
  25807. const juce::File file (prefix + "-" + name + ".wav");
  25808. lynx::ExportSettings settings;
  25809. settings.format = lynx::ExportSettings::Format::wav32Float;
  25810. settings.sampleRate = offline.getTransport().sampleRate.load();
  25811. settings.tailSeconds = 2.0;
  25812. juce::String error;
  25813. auto options = settings.toOptions();
  25814. options.hqAllPlugins = false;
  25815. options.disableMaxPolyphony = false;
  25816. {
  25817. lynx::ExportJob job (other != nullptr ? *other : offline.getSong(), options, file);
  25818. const auto started = juce::Time::getMillisecondCounterHiRes();
  25819. const auto ok = job.run ([] (double) { return true; }, error);
  25820. m.renderSeconds = (juce::Time::getMillisecondCounterHiRes() - started) / 1000.0;
  25821. check (ok, juce::String ("render ") + name + (ok ? juce::String() : ": " + error));
  25822. }
  25823. juce::WavAudioFormat wav;
  25824. if (std::unique_ptr<juce::AudioFormatReader> reader { wav.createReaderFor (file.createInputStream().release(), true) })
  25825. {
  25826. m.audio.setSize (2, (int) reader->lengthInSamples);
  25827. reader->read (&m.audio, 0, (int) reader->lengthInSamples, 0, true, true);
  25828. m.audioSeconds = (double) reader->lengthInSamples / reader->sampleRate;
  25829. }
  25830. if (juce::SystemStats::getEnvironmentVariable ("LYNX_TRACKFREEZE_KEEP", {}).isEmpty()) // (kept: to look at a residual)
  25831. file.deleteFile();
  25832. return m;
  25833. };
  25834. const auto residual = [] (const Mix& a, const Mix& b, float& peak) {
  25835. float worst = 0.0f;
  25836. peak = 0.0f;
  25837. const auto n = juce::jmin (a.audio.getNumSamples(), b.audio.getNumSamples());
  25838. for (int ch = 0; ch < 2; ++ch)
  25839. for (int i = 0; i < n; ++i)
  25840. {
  25841. worst = juce::jmax (worst, std::abs (a.audio.getSample (ch, i) - b.audio.getSample (ch, i)));
  25842. peak = juce::jmax (peak, std::abs (a.audio.getSample (ch, i)));
  25843. }
  25844. return worst <= 0.0f ? -200.0 : 20.0 * std::log10 ((double) worst / (double) juce::jmax (peak, 1.0e-12f));
  25845. };
  25846. const auto nullLine = [&] (const char* what, const Mix& a, const Mix& b, double limit) {
  25847. float peak = 0.0f;
  25848. const auto r = residual (a, b, peak);
  25849. report << what << ": " << juce::String (r, 1) << " dB (peak " << juce::String (peak, 4) << ", " << a.audio.getNumSamples() << " / "
  25850. << b.audio.getNumSamples() << " samples)\n";
  25851. check (peak > 0.001f && r < limit && a.audio.getNumSamples() == b.audio.getNumSamples(), juce::String (what) + " below " + juce::String (limit, 0) + " dB");
  25852. return r;
  25853. };
  25854. const auto savedJson = [] (lynx::Song song) {
  25855. song.info.workSeconds = 0.0;
  25856. return lynx::ProjectFile::toJson (song, false);
  25857. };
  25858. // --- live ---
  25859. offline.capturePluginStates();
  25860. offline.editSong ([] (lynx::Song&) {}, false);
  25861. const auto before = offline.getSong();
  25862. const auto jsonBefore = savedJson (before);
  25863. auto* grid = ui.getClipGridForSnapshot();
  25864. check (grid != nullptr, "the Clip-launch workflow's grid is there");
  25865. if (grid == nullptr)
  25866. {
  25867. flush();
  25868. return false;
  25869. }
  25870. ui.setClipGridView (lynx::PlaylistArea::GridView::beside);
  25871. write ("live");
  25872. saveMenus (juce::StringArray { "Track title (live)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-live.png");
  25873. int leadClip = -1;
  25874. for (int i = 0; i < (int) before.playlist.size() && leadClip < 0; ++i)
  25875. if (before.playlist[(std::size_t) i].track == 0 && before.playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  25876. leadClip = i;
  25877. ui.getPlaylistForSnapshot().selectForSnapshot ({ leadClip });
  25878. saveMenus (juce::StringArray { "Playlist clip (Clip-launch workflow)" }, std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().getClipMenuForSnapshot (leadClip) },
  25879. prefix + "-menu-clip.png");
  25880. const auto live = renderMix ("live");
  25881. report << "live: render " << juce::String (live.renderSeconds, 2) << " s for " << juce::String (live.audioSeconds, 2) << " s of audio\n";
  25882. // --- Freeze Track on every track ---
  25883. std::vector<int> channels;
  25884. for (int t = 0; t < 3; ++t)
  25885. {
  25886. const auto c = lynx::detailchain::forTrack (before, t).channel;
  25887. check (c == t, "track " + juce::String (t + 1) + " shows channel " + juce::String (t + 1));
  25888. const auto* why = lynx::freeze::whyNotTrack (before, c);
  25889. check (why == nullptr, "track " + juce::String (t + 1) + " can be frozen" + (why != nullptr ? juce::String (": ") + why : juce::String()));
  25890. const auto error = lynx::freezeTrackNow (offline, c);
  25891. check (error.isEmpty(), "Freeze Track " + juce::String (t + 1) + (error.isEmpty() ? juce::String() : ": " + error));
  25892. channels.push_back (c);
  25893. }
  25894. offline.dispatchPendingMessages();
  25895. offline.freeRetiredRacks();
  25896. int loadedEffects = 0;
  25897. for (int t = 1; t <= 3; ++t)
  25898. for (int slot = 0; slot < (int) offline.getSong().mixer[(std::size_t) t].effects.size(); ++slot)
  25899. loadedEffects += offline.getEffect (t, slot) != nullptr ? 1 : 0;
  25900. check (loadedEffects == 0, "no effect of a frozen track is loaded (" + juce::String (loadedEffects) + " left)");
  25901. bool fresh = true;
  25902. for (const auto c : channels)
  25903. {
  25904. const auto& f = offline.getSong().channels[(std::size_t) c].freeze;
  25905. fresh = fresh && f.on() && f.insert == c + 1 && lynx::freeze::trackFreezeHolds (offline.getSong(), c) && ! offline.freezeOutOfDate (c)
  25906. && ! offline.frozenAudioMissing (c);
  25907. }
  25908. check (fresh, "every track is frozen with its insert, its audio on disk and up to date");
  25909. check (offline.getSong().mixer == before.mixer, "the project keeps every effect as it was (Unfreeze brings them back)");
  25910. const auto frozenSong = offline.getSong();
  25911. const auto frozen = renderMix ("frozen");
  25912. report << "frozen: render " << juce::String (frozen.renderSeconds, 2) << " s (" << juce::String (100.0 * frozen.renderSeconds / juce::jmax (0.001, live.renderSeconds), 0)
  25913. << " % of the live render's time)\n";
  25914. nullLine ("frozen vs live", live, frozen, -90.0);
  25915. write ("frozen");
  25916. saveMenus (juce::StringArray { "Track title (frozen)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*grid, 0) }, prefix + "-menu-track-frozen.png");
  25917. if (auto* detail = ui.getDetailViewForSnapshot())
  25918. {
  25919. detail->showSelection (0, 0);
  25920. detail->setPage (lynx::DetailView::Page::devices);
  25921. write ("detail-frozen");
  25922. }
  25923. // the insert's fader is live: moved, the frozen and the live song change alike
  25924. {
  25925. auto liveLouder = before, frozenLouder = frozenSong;
  25926. liveLouder.mixer[1].volume = frozenLouder.mixer[1].volume = 0.8f;
  25927. nullLine ("frozen vs live, the Lead's fader moved afterwards", renderMix ("live-louder", &liveLouder), renderMix ("frozen-louder", &frozenLouder), -90.0);
  25928. }
  25929. // --- what a save holds ---
  25930. {
  25931. const auto json = lynx::ProjectFile::toJson (offline.getSong(), false);
  25932. juce::String error;
  25933. const auto loaded = lynx::ProjectFile::fromJson (json, error);
  25934. check (json.contains ("\"trackFreeze\"") && ! json.contains ("\"freeze\""), "a track freeze is saved under its own key (older versions play it live)");
  25935. check (loaded.has_value() && loaded->channels.size() == frozenSong.channels.size() && loaded->channels[0].freeze == frozenSong.channels[0].freeze,
  25936. "a track-frozen project loads frozen, with its insert and audio files");
  25937. check (savedJson (lynx::freeze::thawed (offline.getSong())) == jsonBefore, "without the frozen state the project saves as before the freeze");
  25938. }
  25939. // --- an edit of a frozen device's insert routing: the freeze stops holding, the track plays live ---
  25940. {
  25941. offline.editSong ([] (lynx::Song& s) { s.channels[1].mixerTrack = 1; }); // (the Bass into the Lead's insert)
  25942. check (! lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && offline.freezeOutOfDate (0), "another channel routed into a frozen insert: out of date, plays live");
  25943. offline.undo();
  25944. offline.dispatchPendingMessages();
  25945. check (lynx::freeze::trackFreezeHolds (offline.getSong(), 0) && ! offline.freezeOutOfDate (0), "undo: frozen again");
  25946. }
  25947. // --- Flatten: Bounce Track in Place on the frozen Lead, and its undo ---
  25948. {
  25949. const auto error = lynx::flattenChannelNow (offline, 0);
  25950. check (error.isEmpty(), "Bounce Track in Place of the frozen Lead (Flatten)" + (error.isEmpty() ? juce::String() : ": " + error));
  25951. const auto& song = offline.getSong();
  25952. check (song.channels[0].instrument == lynx::InstrumentKind::audioClip && song.mixer[1].effects.empty() && song.mixer[1].volume == before.mixer[1].volume
  25953. && song.channels[0].name == "Lead (Bounce)",
  25954. "the Lead is audio now (\"Lead (Bounce)\"), its insert's effects removed, its fader kept");
  25955. int audioClips = 0;
  25956. for (const auto& c : song.playlist)
  25957. audioClips += c.kind == lynx::ClipKind::audio && c.channel == 0;
  25958. report << "flattened Lead: " << audioClips << " audio clips\n";
  25959. write ("flattened");
  25960. // over the song (the flattened clips end where the arrangement ends, as a frozen track plays; an export's
  25961. // ring-out after the song's end is not in them)
  25962. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  25963. auto flatMix = renderMix ("flattened");
  25964. auto reference = live;
  25965. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  25966. flatMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  25967. nullLine ("flattened (Lead) + frozen (others) vs live, over the song", reference, flatMix, -90.0);
  25968. offline.undo();
  25969. offline.dispatchPendingMessages();
  25970. check (savedJson (offline.getSong()) == savedJson (frozenSong), "undo of the Flatten: the frozen project exactly as before");
  25971. }
  25972. // --- Unfreeze every track ---
  25973. for (const auto c : channels)
  25974. lynx::unfreezeChannel (offline, c);
  25975. offline.dispatchPendingMessages();
  25976. check (savedJson (offline.getSong()) == jsonBefore, "Unfreeze: the project saves byte for byte as before the freeze");
  25977. nullLine ("unfrozen vs live", live, renderMix ("unfrozen"), -90.0);
  25978. // --- Bounce Track in Place of a live track (render and flatten in one step, one undo) ---
  25979. {
  25980. const auto error = lynx::freezeTrackNow (offline, 1, true);
  25981. check (error.isEmpty(), "Bounce Track in Place of the live Bass" + (error.isEmpty() ? juce::String() : ": " + error));
  25982. check (offline.getSong().channels[1].instrument == lynx::InstrumentKind::audioClip && ! offline.getSong().channels[1].freeze.on(),
  25983. "the Bass is audio, not frozen");
  25984. auto bouncedMix = renderMix ("bounced");
  25985. auto reference = live;
  25986. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  25987. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  25988. bouncedMix.audio.setSize (2, reference.audio.getNumSamples(), true);
  25989. nullLine ("Bass bounced in place vs live, over the song", reference, bouncedMix, -90.0);
  25990. offline.undo();
  25991. offline.dispatchPendingMessages();
  25992. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce Track in Place: the project as before");
  25993. }
  25994. // --- Bounce to New Track: the Lead's clips onto a new track (the clips muted, the new track with the Lead's mixer) ---
  25995. {
  25996. std::vector<int> leadClips;
  25997. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  25998. if (offline.getSong().playlist[(std::size_t) i].track == 0 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  25999. leadClips.push_back (i);
  26000. const auto channelsBefore = offline.getSong().channels.size();
  26001. const auto error = lynx::bounceToNewTrack (offline, leadClips, true);
  26002. check (error.isEmpty(), "Bounce to New Track of the Lead's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  26003. const auto& song = offline.getSong();
  26004. check (song.channels.size() == channelsBefore + 1 && song.channels.back().instrument == lynx::InstrumentKind::audioClip
  26005. && song.channels.back().mixerTrack > 3 && song.mixer[(std::size_t) song.channels.back().mixerTrack].volume == before.mixer[1].volume,
  26006. "a new audio channel holds the bounce, on an insert with the Lead's mixer");
  26007. // the song's span (the bounce stops at the last clip's end, the live render rings on after it)
  26008. auto bounced = renderMix ("bounced-new-track");
  26009. auto reference = live;
  26010. const auto span = (int) std::llround (before.secondsForTicks (24 * lynx::ppq) * offline.getTransport().sampleRate.load());
  26011. reference.audio.setSize (2, juce::jmin (span, reference.audio.getNumSamples()), true);
  26012. bounced.audio.setSize (2, reference.audio.getNumSamples(), true);
  26013. nullLine ("Bounce to New Track (Lead's clips muted) vs live, over the song", reference, bounced, -90.0);
  26014. write ("bounced-new-track");
  26015. offline.undo();
  26016. offline.dispatchPendingMessages();
  26017. check (savedJson (offline.getSong()) == jsonBefore, "undo of Bounce to New Track: the project as before");
  26018. }
  26019. // --- Consolidate: the Bass's three pattern clips become one ---
  26020. {
  26021. std::vector<int> bassClips;
  26022. for (int i = 0; i < (int) offline.getSong().playlist.size(); ++i)
  26023. if (offline.getSong().playlist[(std::size_t) i].track == 1 && offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::pattern)
  26024. bassClips.push_back (i);
  26025. const auto error = lynx::consolidateClips (offline, bassClips, true);
  26026. check (error.isEmpty(), "Consolidate of the Bass's clips" + (error.isEmpty() ? juce::String() : ": " + error));
  26027. int left = 0;
  26028. for (const auto& c : offline.getSong().playlist)
  26029. left += c.track == 1 && c.kind == lynx::ClipKind::pattern;
  26030. check (left == 1, "one clip on the Bass track (" + juce::String (left) + ")");
  26031. nullLine ("consolidated vs live", live, renderMix ("consolidated"), -90.0);
  26032. offline.undo();
  26033. offline.dispatchPendingMessages();
  26034. check (savedJson (offline.getSong()) == jsonBefore, "undo of Consolidate: the project as before");
  26035. }
  26036. report << "frozen audio folder: " << offline.getFreezeFolder().getFullPathName() << "\n";
  26037. flush();
  26038. data.deleteRecursively();
  26039. (void) megabytes;
  26040. return failures == 0;
  26041. }
  26042. // --paintbench (round 190ge): the paint cost of every main view, off screen. Each view is shown maximised in a
  26043. // LYNX_SNAPSHOT_SIZE window (default 1920x1080) and drawn whole into a picture `frames` times (after a repaint of
  26044. // all of it, so no cached picture is reused: the cost of a frame after an edit), then `frames` times without the
  26045. // repaint (what a view's own caches leave of a frame). The report gives the median and the 90th percentile of
  26046. // the message thread's CPU per frame.
  26047. void runPaintBench (const juce::File& project, const juce::File& report)
  26048. {
  26049. // LYNX_PROFILE_MAIN=<file> (round 190gr): the message thread sampled while it paints (Windows; one view at a time
  26050. // with LYNX_PAINTBENCH_VIEWS)
  26051. const auto profile = juce::SystemStats::getEnvironmentVariable ("LYNX_PROFILE_MAIN", {});
  26052. if (profile.isNotEmpty())
  26053. lynx::crashguard::startMainProfiler (profile.toStdString(), 1000, 2);
  26054. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26055. lynx::AudioEngine offline (false);
  26056. lynx::MainComponent ui (offline, false);
  26057. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  26058. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  26059. juce::String text;
  26060. text << "project: " << project.getFullPathName() << "\nLYNX " << getApplicationVersion() << ", " << juce::SystemStats::getCpuModel()
  26061. << ", window " << ui.getWidth() << "x" << ui.getHeight() << "\n";
  26062. if (project.existsAsFile())
  26063. {
  26064. // (round perfgate190id) the time to open it headless, and the memory after
  26065. const auto open0 = juce::Time::getMillisecondCounterHiRes();
  26066. const auto cpu0 = lynx::threadCpuSeconds();
  26067. ui.openFile (project);
  26068. offline.dispatchPendingMessages();
  26069. text << "open: " << juce::String (juce::Time::getMillisecondCounterHiRes() - open0, 1) << " ms wall, "
  26070. << juce::String (1000.0 * (lynx::threadCpuSeconds() - cpu0), 1) << " ms message thread CPU, working set "
  26071. << juce::String ((double) lynx::toolbar::PerformanceMeter::processMemoryBytes() / 1048576.0, 0) << " MB\n";
  26072. }
  26073. const auto& song = offline.getSong();
  26074. text << "channels " << (int) song.channels.size() << ", patterns " << (int) song.patterns.size() << ", playlist clips " << (int) song.playlist.size()
  26075. << ", inserts " << (int) song.mixer.size() << "\n";
  26076. // the playhead a third into the song (song mode) so the views draw it as when playing
  26077. offline.getTransport().songMode = true;
  26078. offline.getTransport().positionTicks.store ((double) song.songLength() / 3.0);
  26079. const auto frames = juce::jlimit (3, 500, juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_FRAMES", "40").getIntValue());
  26080. juce::Image image (juce::Image::ARGB, ui.getWidth(), ui.getHeight(), true);
  26081. {
  26082. // (round 190gr) which renderer draws the frames: the software one (Linux), Direct2D (Windows), Core Graphics
  26083. juce::Graphics g (image);
  26084. auto& context = g.getInternalContext();
  26085. text << "renderer: " << (dynamic_cast<juce::LowLevelGraphicsSoftwareRenderer*> (&context) != nullptr ? "software" : typeid (context).name())
  26086. << ", paint caches " << (lynx::ui::paintCache() ? "on" : "off (LYNX_PAINT_CACHE=0)") << ", paint savings "
  26087. << (lynx::ui::paintSavings() ? "on" : "off (LYNX_PAINT_SAVINGS=0)") << "\n";
  26088. }
  26089. // LYNX_PAINTBENCH_VIEWS="mixer,channel rack" (round 190gr): only those views
  26090. const auto onlyViews = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_VIEWS", {}), ",", "");
  26091. const auto wanted = [&onlyViews] (const juce::String& name) { return onlyViews.isEmpty() || onlyViews.contains (name); };
  26092. // the picture's pixels as one number: the same before and after a change = the same drawing
  26093. auto pixelHash = [&image] {
  26094. const juce::Image::BitmapData data (image, juce::Image::BitmapData::readOnly);
  26095. std::uint64_t h = 1469598103934665603ull;
  26096. for (int y = 0; y < data.height; ++y)
  26097. for (int x = 0; x < data.width; ++x)
  26098. h = (h ^ data.getPixelColour (x, y).getARGB()) * 1099511628211ull;
  26099. return juce::String::toHexString ((juce::int64) h);
  26100. };
  26101. // mode 0: whole frames after a repaint of everything; 1: whole frames, the views' own caches kept; 2: a 14-pixel
  26102. // column of the whole height at 40 places (what a moving playhead repaints each frame)
  26103. // (rollup step 9: the instructions the message thread retires per frame, Linux, where the CPU counter can be read:
  26104. // the performance gate's stable paint measure, scripts/perf_gate.py "paint_instr")
  26105. const lynx::platform::ThreadInstructions instructions;
  26106. auto measure = [&] (const juce::String& name, int mode) {
  26107. offline.dispatchPendingMessages();
  26108. std::vector<double> ms, wall;
  26109. std::vector<long long> instr;
  26110. juce::String hash;
  26111. for (int f = -3; f < frames; ++f) // (3 frames to warm the caches up)
  26112. {
  26113. if (mode == 0)
  26114. ui.repaint();
  26115. const auto column = juce::Rectangle<int> ((juce::jmax (0, f) * 97) % juce::jmax (1, ui.getWidth() - 14), 0, 14, ui.getHeight());
  26116. const auto t0 = lynx::threadCpuSeconds();
  26117. const auto w0 = juce::Time::getMillisecondCounterHiRes();
  26118. const auto i0 = instructions.now();
  26119. {
  26120. juce::Graphics g (image);
  26121. if (mode == 2)
  26122. g.reduceClipRegion (column);
  26123. ui.paintEntireComponent (g, true);
  26124. }
  26125. if (const auto i1 = instructions.now(); f >= 0 && i0 >= 0 && i1 >= i0)
  26126. instr.push_back (i1 - i0);
  26127. if (f >= 0)
  26128. {
  26129. ms.push_back (1000.0 * (lynx::threadCpuSeconds() - t0));
  26130. wall.push_back (juce::Time::getMillisecondCounterHiRes() - w0); // (round 190gr: Direct2D's work ends with the frame)
  26131. }
  26132. if (f == 0 && mode == 0)
  26133. {
  26134. hash = pixelHash();
  26135. // LYNX_PAINTBENCH_PNG=<prefix> (round 190gr): the whole frame as <prefix>-<view>.png, to compare pixels
  26136. if (const auto png = juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_PNG", {}); png.isNotEmpty())
  26137. {
  26138. const juce::File file (png + "-" + name.replaceCharacter (' ', '-') + ".png");
  26139. file.deleteFile();
  26140. juce::FileOutputStream out (file);
  26141. juce::PNGImageFormat().writeImageToStream (image, out);
  26142. }
  26143. }
  26144. }
  26145. std::sort (ms.begin(), ms.end());
  26146. std::sort (wall.begin(), wall.end());
  26147. text << name << (mode == 0 ? ", whole frame" : mode == 1 ? ", cached frame" : ", playhead column") << ": median "
  26148. << juce::String (ms[ms.size() / 2], 3) << " ms, p90 " << juce::String (ms[(ms.size() * 9) / 10], 3) << " ms, wall median "
  26149. << juce::String (wall[wall.size() / 2], 3) << " ms"
  26150. << (hash.isNotEmpty() ? ", pixels " + hash : juce::String());
  26151. if (instr.size() == ms.size())
  26152. {
  26153. std::sort (instr.begin(), instr.end());
  26154. text << ", instructions median " << juce::String ((juce::int64) instr[instr.size() / 2]);
  26155. }
  26156. text << "\n";
  26157. report.replaceWithText (text);
  26158. };
  26159. auto measureAll = [&] (const juce::String& name) {
  26160. if (! wanted (name))
  26161. return;
  26162. measure (name, 0);
  26163. measure (name, 1);
  26164. measure (name, 2);
  26165. // the columns' pixels too (painted over the whole frame: culling must not change a pixel)
  26166. ui.repaint();
  26167. {
  26168. juce::Graphics g (image);
  26169. ui.paintEntireComponent (g, true);
  26170. for (int x = 3; x < ui.getWidth() - 14; x += 211)
  26171. {
  26172. juce::Graphics::ScopedSaveState state (g);
  26173. g.reduceClipRegion (x, 0, 14, ui.getHeight());
  26174. ui.paintEntireComponent (g, true);
  26175. }
  26176. }
  26177. text << name << ", columns over the whole frame: pixels " << pixelHash() << "\n";
  26178. };
  26179. const char* views[] { "channel rack", "piano roll", "playlist", "mixer" };
  26180. for (int v = 0; v < 4; ++v)
  26181. {
  26182. ui.selectTabForSnapshot (v);
  26183. measureAll (views[v]);
  26184. }
  26185. ui.showDesktopForSnapshot (false);
  26186. measureAll ("desktop");
  26187. ui.selectTabForSnapshot (2);
  26188. ui.setClipLaunchWorkflow (true);
  26189. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  26190. measureAll ("clip grid");
  26191. ui.setClipGridView (lynx::PlaylistArea::GridView::song); // (round 190jn: the Clip-launch layout's Arrangement)
  26192. measureAll ("clip arrangement");
  26193. // (and with View > Tall Arrangement lanes: LYNX's 38 px rows in Live's look, the classic look's row height)
  26194. lynx::playlistTallLiveLanes() = true;
  26195. ui.getPlaylistForSnapshot().liveLanesChanged();
  26196. measureAll ("clip arrangement, tall lanes");
  26197. lynx::playlistTallLiveLanes() = false;
  26198. ui.getPlaylistForSnapshot().liveLanesChanged();
  26199. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  26200. ui.setClipLaunchWorkflow (false);
  26201. // LYNX_PAINTBENCH_SIMPLE=1 (round 190jc): the same project's Playlist in the Simple layout too
  26202. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PAINTBENCH_SIMPLE", {}) == "1")
  26203. {
  26204. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  26205. offline.dispatchPendingMessages();
  26206. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  26207. simple->hideChooser();
  26208. ui.selectTabForSnapshot (2);
  26209. measureAll ("simple playlist");
  26210. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  26211. }
  26212. text << "result=OK\n";
  26213. report.replaceWithText (text);
  26214. if (profile.isNotEmpty())
  26215. lynx::crashguard::stopMainProfiler();
  26216. }
  26217. // Round 190iv: the toolbar per layout style (see --toolbarshot190iv above)
  26218. void runToolbarShot190iv (const juce::String& prefix, const juce::String& projectPath)
  26219. {
  26220. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26221. lynx::ui::motion::enabled() = false; // (hover states drawn at once, no fade)
  26222. lynx::AudioEngine offline (false);
  26223. lynx::MainComponent ui (offline, false);
  26224. ui.setSize (1920, 1080);
  26225. juce::String report;
  26226. const auto write = [&prefix] (const juce::Image& image, const juce::String& name) {
  26227. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  26228. file.deleteFile();
  26229. juce::FileOutputStream out (file);
  26230. juce::PNGImageFormat().writeImageToStream (image, out);
  26231. };
  26232. const auto bar = [&ui] { return ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 90)); };
  26233. const auto describe = [&ui, &report] (const juce::String& title) {
  26234. report << "== " << title << " (" << ui.getWidth() << "x" << ui.getHeight() << ")\n";
  26235. for (const auto* name : { "play", "stop", "record", "metronome", "tap", "tempo", "signature", "quantisation", "key", "link", "browser",
  26236. "backToArrangement", "position", "overdub", "capture", "sessionRecord", "punch", "draw", "computerKeys",
  26237. "keyMap", "midiMap", "cpu", "more", "sessionView", "arrangementView", "status", "finish" })
  26238. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible() && c->getParentComponent() == &ui)
  26239. report << " " << name << " " << c->getBounds().toString() << "\n";
  26240. };
  26241. const std::pair<int, int> sizes[] { { 1920, 1080 }, { 1366, 768 }, { 1280, 800 } };
  26242. // a song with a few tracks for the Simple layout (voice, instrument, drums), as --simpleshot makes them
  26243. offline.editSong ([] (lynx::Song& s) {
  26244. namespace st = lynx::simpletracks;
  26245. st::Request q;
  26246. q.kind = st::Kind::voice;
  26247. q.name = "Lead vocal";
  26248. st::addTrack (s, q);
  26249. q = {};
  26250. q.kind = st::Kind::instrument;
  26251. q.name = "Keys";
  26252. lynx::ChannelDef keys;
  26253. keys.instrument = lynx::InstrumentKind::synth;
  26254. q.channel = keys;
  26255. st::addTrack (s, q);
  26256. q = {};
  26257. q.kind = st::Kind::drums;
  26258. q.name = "Drums";
  26259. st::addTrack (s, q);
  26260. s.bpm = 120.0;
  26261. }, false);
  26262. offline.dispatchPendingMessages();
  26263. // 1. Pattern: FL's toolbar (it must stay as it was: compare with the base build's)
  26264. ui.selectTabForSnapshot (2);
  26265. for (const auto& [w, h] : sizes)
  26266. {
  26267. ui.setSize (w, h);
  26268. write (lynx::shot::snapshot (ui, bar()), "pattern-bar-" + juce::String (w));
  26269. }
  26270. ui.setSize (1920, 1080);
  26271. // 2. Simple
  26272. ui.setLayoutStyle (lynx::layoutstyle::Style::simple, false);
  26273. offline.dispatchPendingMessages();
  26274. for (const auto& [w, h] : sizes)
  26275. {
  26276. ui.setSize (w, h);
  26277. offline.dispatchPendingMessages();
  26278. write (lynx::shot::snapshot (ui), "simple-" + juce::String (w));
  26279. write (lynx::shot::snapshot (ui, bar()), "simple-bar-" + juce::String (w));
  26280. describe ("simple " + juce::String (w));
  26281. }
  26282. ui.setSize (1920, 1080);
  26283. auto* play = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("play"));
  26284. auto* stop = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("stop"));
  26285. auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record"));
  26286. const auto capsuleArea = [&] {
  26287. juce::Rectangle<int> r;
  26288. for (const auto* name : { "play", "stop", "record", "position", "metronome", "tempo", "signature", "key" })
  26289. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible())
  26290. r = r.isEmpty() ? c->getBounds() : r.getUnion (c->getBounds());
  26291. return r.expanded (8, 10);
  26292. };
  26293. if (play != nullptr && stop != nullptr && rec != nullptr)
  26294. {
  26295. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-idle");
  26296. play->setState (juce::Button::buttonOver);
  26297. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-hover");
  26298. play->setState (juce::Button::buttonDown);
  26299. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-pressed");
  26300. play->setState (juce::Button::buttonNormal);
  26301. play->setToggleState (true, juce::dontSendNotification);
  26302. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-playing");
  26303. rec->setToggleState (true, juce::dontSendNotification);
  26304. write (lynx::shot::snapshot (ui, capsuleArea()), "simple-transport-recording");
  26305. play->setToggleState (false, juce::dontSendNotification);
  26306. rec->setToggleState (false, juce::dontSendNotification);
  26307. }
  26308. if (auto* status = ui.toolbarPartForSnapshot ("status"))
  26309. {
  26310. using S = lynx::toolbarlayout::SaveState;
  26311. int n = 0;
  26312. for (const auto state : { S::fresh, S::unsaved, S::backedUp, S::saved })
  26313. {
  26314. ui.setSaveStatusForSnapshot (state);
  26315. auto r = status->getBounds();
  26316. if (auto* finish = ui.toolbarPartForSnapshot ("finish"); finish != nullptr && finish->isVisible())
  26317. r = r.getUnion (finish->getBounds());
  26318. write (lynx::shot::snapshot (ui, r.expanded (8, 10)), "simple-status-" + juce::String (n++));
  26319. }
  26320. }
  26321. {
  26322. auto more = ui.makeToolbarMoreMenuForSnapshot();
  26323. saveMenus (juce::StringArray { "More" }, std::vector<juce::PopupMenu> { more }, prefix + "-simple-more-menu.png");
  26324. }
  26325. // 3. Clip-launch: Live's control bar (the Live demo set when given, else an empty grid)
  26326. if (projectPath.isNotEmpty())
  26327. {
  26328. ui.openFile (juce::File (projectPath));
  26329. offline.dispatchPendingMessages();
  26330. }
  26331. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch, false);
  26332. offline.dispatchPendingMessages();
  26333. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  26334. for (const auto& [w, h] : sizes)
  26335. {
  26336. ui.setSize (w, h);
  26337. offline.dispatchPendingMessages();
  26338. write (lynx::shot::snapshot (ui), "live-" + juce::String (w));
  26339. write (lynx::shot::snapshot (ui, bar()), "live-bar-" + juce::String (w));
  26340. describe ("clip-launch " + juce::String (w));
  26341. }
  26342. ui.setSize (1920, 1080);
  26343. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  26344. write (lynx::shot::snapshot (ui), "live-arrangement-1920");
  26345. ui.setClipGridView (lynx::PlaylistArea::GridView::beside);
  26346. write (lynx::shot::snapshot (ui), "live-both-1920");
  26347. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  26348. // every control-bar button idle / hover / pressed / lit, all at once per picture
  26349. std::vector<juce::Button*> buttons;
  26350. for (const auto* name : { "play", "stop", "record", "metronome", "tap", "browser", "backToArrangement", "overdub", "capture", "sessionRecord", "punch",
  26351. "draw", "computerKeys", "keyMap", "midiMap", "more", "sessionView", "arrangementView" })
  26352. if (auto* b = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot (name)); b != nullptr && b->isVisible())
  26353. buttons.push_back (b);
  26354. std::vector<bool> lit;
  26355. for (auto* b : buttons)
  26356. lit.push_back (b->getToggleState());
  26357. const auto controlBar = ui.getLocalBounds().withTrimmedTop (lynx::toolbarlayout::livebar::menuRow).withHeight (lynx::toolbarlayout::livebar::band);
  26358. write (lynx::shot::snapshot (ui, controlBar), "live-states-idle");
  26359. for (const auto& [state, name] : { std::pair<juce::Button::ButtonState, const char*> { juce::Button::buttonOver, "hover" }, { juce::Button::buttonDown, "pressed" } })
  26360. {
  26361. for (auto* b : buttons)
  26362. b->setState (state);
  26363. write (lynx::shot::snapshot (ui, controlBar), juce::String ("live-states-") + name);
  26364. }
  26365. for (auto* b : buttons)
  26366. {
  26367. b->setState (juce::Button::buttonNormal);
  26368. b->setToggleState (true, juce::dontSendNotification);
  26369. }
  26370. write (lynx::shot::snapshot (ui, controlBar), "live-states-lit");
  26371. for (std::size_t k = 0; k < buttons.size(); ++k)
  26372. buttons[k]->setToggleState (lit[k], juce::dontSendNotification);
  26373. {
  26374. auto more = ui.makeToolbarMoreMenuForSnapshot();
  26375. saveMenus (juce::StringArray { "More" }, std::vector<juce::PopupMenu> { more }, prefix + "-live-more-menu.png");
  26376. }
  26377. // the Session button row kept as an option
  26378. ui.setSessionButtonRowShown (true);
  26379. write (lynx::shot::snapshot (ui), "live-buttonrow-1920");
  26380. ui.setSessionButtonRowShown (false);
  26381. // 4. back to Pattern: FL's toolbar again, as it was
  26382. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern, false);
  26383. offline.dispatchPendingMessages();
  26384. for (const auto& [w, h] : sizes)
  26385. {
  26386. ui.setSize (w, h);
  26387. write (lynx::shot::snapshot (ui, bar()), "pattern-after-bar-" + juce::String (w));
  26388. }
  26389. juce::File (prefix + "-report.txt").replaceWithText (report);
  26390. lynx::ui::motion::enabled() = true;
  26391. }
  26392. void runGridShot (const juce::String& prefix, const juce::String& projectPath = {})
  26393. {
  26394. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26395. lynx::AudioEngine offline (false);
  26396. lynx::MainComponent ui (offline, false);
  26397. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  26398. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  26399. const auto write = [&prefix, &ui] (const char* name) {
  26400. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  26401. file.deleteFile();
  26402. juce::FileOutputStream out (file);
  26403. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  26404. };
  26405. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  26406. if (projectPath.isNotEmpty())
  26407. {
  26408. ui.openFile (juce::File (projectPath));
  26409. offline.dispatchPendingMessages();
  26410. ui.setClipLaunchWorkflow (true);
  26411. offline.dispatchPendingMessages();
  26412. write ("file-both");
  26413. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  26414. write ("file-grid");
  26415. const auto& song = offline.getSong();
  26416. juce::String info;
  26417. info << "grid " << (song.clipGrid ? "yes" : "no") << ", clips " << (song.clipGrid ? (int) song.clipGrid->clips.size() : 0)
  26418. << ", scenes " << (song.clipGrid ? (int) song.clipGrid->scenes.size() : 0) << ", playlist clips " << (int) song.playlist.size() << "\n";
  26419. // round qafix190kq (QA-2): the grid's columns (take lanes have none) and the Session mixer's strips follow them
  26420. if (auto* grid = ui.getClipGridForSnapshot())
  26421. {
  26422. const auto columns = lynx::clipGridColumnTracks (*grid);
  26423. int lanes = 0, laneColumns = 0;
  26424. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  26425. lanes += lynx::comp::isTakeLane (song, t) ? 1 : 0;
  26426. juce::StringArray names;
  26427. for (const auto t : columns)
  26428. {
  26429. laneColumns += lynx::comp::isTakeLane (song, t) ? 1 : 0;
  26430. names.add (t < (int) song.playlistTracks.size() ? juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str()) : "(empty)");
  26431. }
  26432. info << "playlist tracks " << (int) song.playlistTracks.size() << ", take lanes " << lanes << ", grid columns " << (int) columns.size()
  26433. << ", lane columns " << laneColumns << "\ncolumns: " << names.joinIntoString (" | ") << "\n";
  26434. // the lanes' flag survives a save and an open (ProjectFile "playlistTakeLanes")
  26435. juce::String error;
  26436. auto same = false;
  26437. if (const auto back = lynx::ProjectFile::fromJson (lynx::ProjectFile::toJson (song), error); back && back->playlistTracks.size() == song.playlistTracks.size())
  26438. {
  26439. same = true;
  26440. for (std::size_t t = 0; t < song.playlistTracks.size(); ++t)
  26441. same = same && back->playlistTracks[t].takeLane == song.playlistTracks[t].takeLane;
  26442. }
  26443. info << "take lanes after save + open: " << (same ? "same" : "DIFFERENT") << "\n";
  26444. }
  26445. juce::File (prefix + "-file.txt").replaceWithText (info);
  26446. ui.setClipLaunchWorkflow (false);
  26447. return;
  26448. }
  26449. write ("pattern"); // Pattern workflow: nothing of the grid exists yet
  26450. const auto madeBefore = lynx::launcher::Runtime::instances.load();
  26451. offline.editSong ([] (lynx::Song& s) {
  26452. while (s.patterns.size() < 6)
  26453. s.patterns.emplace_back();
  26454. for (int p = 0; p < 6; ++p)
  26455. {
  26456. auto& pattern = s.patterns[(std::size_t) p];
  26457. const char* names[] { "Drums A", "Drums B", "Bass", "Chords", "Lead", "Pad" };
  26458. pattern.name = names[p];
  26459. pattern.lengthTicks = 4 * lynx::ppq;
  26460. }
  26461. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  26462. const char* tracks[] { "Drums", "Bass", "Chords", "Lead", "Vocals", "FX" };
  26463. for (int t = 0; t < 6; ++t)
  26464. s.playlistTracks[(std::size_t) t].name = tracks[t];
  26465. 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 } };
  26466. for (const auto& c : placed)
  26467. {
  26468. lynx::Clip clip;
  26469. clip.pattern = c[2];
  26470. clip.length = 4 * lynx::ppq;
  26471. lynx::launcher::setClip (s, c[0], c[1], clip);
  26472. }
  26473. auto& grid = lynx::launcher::ensureGrid (s);
  26474. const char* scenes[] { "Intro", "Verse", "Drop", "Break" };
  26475. grid.scenes.resize (6);
  26476. for (int r = 0; r < 4; ++r)
  26477. grid.scenes[(std::size_t) r].name = scenes[r];
  26478. }, false);
  26479. offline.dispatchPendingMessages();
  26480. write ("pattern-edited"); // the same song as -pattern-after: the workflow must leave no trace
  26481. ui.setClipLaunchWorkflow (true);
  26482. offline.dispatchPendingMessages();
  26483. if (auto* runtime = offline.launcherStateForSnapshot())
  26484. {
  26485. runtime->tracks[0].playing.store (2);
  26486. runtime->tracks[0].progress.store (0.4f);
  26487. runtime->tracks[0].taken.store (true);
  26488. runtime->tracks[1].playing.store (2);
  26489. runtime->tracks[1].progress.store (0.4f);
  26490. runtime->tracks[1].taken.store (true);
  26491. runtime->tracks[2].pending.store (2);
  26492. runtime->tracks[3].taken.store (true);
  26493. }
  26494. write ("both");
  26495. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  26496. write ("grid");
  26497. // round 190bv: recording into slots and the Groove Pool. Two tracks armed (round record buttons in their empty
  26498. // slots, their arm buttons lit), one of them recording and one waiting for its start; then a clip through a
  26499. // groove with the pool shown, and the slot menus
  26500. if (auto* gridView = ui.getClipGridForSnapshot())
  26501. {
  26502. offline.setGridTrackArmed (4, true);
  26503. offline.setGridTrackArmed (5, true, false);
  26504. offline.dispatchPendingMessages();
  26505. write ("rec-armed");
  26506. if (auto* runtime = offline.launcherStateForSnapshot())
  26507. {
  26508. runtime->tracks[4].recording.store (1);
  26509. runtime->tracks[4].recordFrom.store (0.0); // (round 190cy: one beat recorded, the counter reads 0.1.0)
  26510. runtime->clockNow.store ((double) lynx::ppq);
  26511. runtime->tracks[5].recordPending.store (1);
  26512. }
  26513. write ("rec-recording");
  26514. if (auto* runtime = offline.launcherStateForSnapshot())
  26515. {
  26516. runtime->tracks[4].recording.store (-1);
  26517. runtime->tracks[5].recordPending.store (-1);
  26518. }
  26519. offline.editSong ([] (lynx::Song& s) {
  26520. const auto& bank = lynx::groove::factoryBank();
  26521. std::uint32_t first = 0;
  26522. for (const auto index : { std::size_t (9), std::size_t (20), std::size_t (27) })
  26523. if (index < bank.size())
  26524. {
  26525. const auto id = lynx::groove::add (s.grooves, bank[index].groove);
  26526. first = first == 0 ? id : first;
  26527. }
  26528. lynx::groove::setClipGroove (s, 0, 0, first);
  26529. }, false);
  26530. offline.dispatchPendingMessages();
  26531. lynx::setClipGridGroovePoolShown (*gridView, true);
  26532. write ("groove-pool");
  26533. saveMenus ({ "Clip slot", "Groove", "Empty slot" },
  26534. { lynx::clipGridSlotMenu (*gridView, 0, 0), [&] {
  26535. juce::PopupMenu found;
  26536. const auto menu = lynx::clipGridSlotMenu (*gridView, 0, 0);
  26537. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  26538. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Groove"))
  26539. found = *it.getItem().subMenu;
  26540. return found;
  26541. }(), lynx::clipGridSlotMenu (*gridView, 4, 1) },
  26542. prefix + "-rec-menus.png");
  26543. lynx::setClipGridGroovePoolShown (*gridView, false);
  26544. // round 190cy: a second record button pressed while recording: the first take ("Vocals 1") plays on, the
  26545. // clicked slot records "Vocals 2" with its counter at 2.0.2 (as Live 12.4.16, live check 190cw shot 03b)
  26546. {
  26547. const auto name = offline.slotRecordingName (4);
  26548. offline.editSong ([&name] (lynx::Song& s) { lynx::session::placeRecordedPattern (s, 4, 0, {}, 8 * lynx::ppq, name); }, false);
  26549. offline.dispatchPendingMessages();
  26550. if (auto* runtime = offline.launcherStateForSnapshot())
  26551. {
  26552. runtime->tracks[4].playing.store (0);
  26553. runtime->tracks[4].progress.store (0.3f);
  26554. runtime->tracks[4].recording.store (1);
  26555. runtime->tracks[4].recordFrom.store (0.0);
  26556. runtime->clockNow.store (8.0 * lynx::ppq + 2.0 * lynx::ppq / 4.0);
  26557. }
  26558. write ("rec-second");
  26559. if (auto* runtime = offline.launcherStateForSnapshot())
  26560. {
  26561. runtime->tracks[4].playing.store (-1);
  26562. runtime->tracks[4].recording.store (-1);
  26563. }
  26564. offline.editSong ([] (lynx::Song& s) {
  26565. if (lynx::session::cut (s, 4, 0) && ! s.patterns.empty())
  26566. s.patterns.pop_back();
  26567. }, false);
  26568. offline.dispatchPendingMessages();
  26569. }
  26570. offline.setGridTrackArmed (4, false);
  26571. offline.setGridTrackArmed (5, false);
  26572. offline.dispatchPendingMessages();
  26573. }
  26574. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  26575. write ("song");
  26576. ui.setClipLaunchWorkflow (false);
  26577. write ("pattern-after");
  26578. juce::File (prefix + "-counts.txt").replaceWithText ("runtimes before " + juce::String (madeBefore) + ", after " + juce::String (lynx::launcher::Runtime::instances.load()) + "\n");
  26579. }
  26580. // Round 190bu: the Simple workflow's track dock (ui/SimpleDock.h), off-screen
  26581. void runSimpleFxShot (const juce::String& prefix)
  26582. {
  26583. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26584. lynx::AudioEngine offline (false);
  26585. lynx::MainComponent ui (offline, false);
  26586. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  26587. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  26588. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  26589. const auto file = juce::File (prefix + "-" + name + ".png");
  26590. file.deleteFile();
  26591. juce::FileOutputStream out (file);
  26592. juce::PNGImageFormat().writeImageToStream (image, out);
  26593. };
  26594. juce::String report;
  26595. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  26596. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  26597. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  26598. ui.selectTabForSnapshot (2);
  26599. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  26600. offline.dispatchPendingMessages();
  26601. auto* simple = ui.getSimpleWorkflowForSnapshot();
  26602. if (simple == nullptr)
  26603. {
  26604. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  26605. return;
  26606. }
  26607. simple->hideChooser();
  26608. // three tracks: a voice, keys with a few chords, a drum kit
  26609. int keysInsert = -1;
  26610. offline.editSong ([&keysInsert] (lynx::Song& s) {
  26611. namespace st = lynx::simpletracks;
  26612. st::Request q;
  26613. q.kind = st::Kind::voice;
  26614. q.name = "Lead vocal";
  26615. st::addTrack (s, q);
  26616. q = {};
  26617. q.kind = st::Kind::instrument;
  26618. q.name = "Keys";
  26619. lynx::ChannelDef keys;
  26620. keys.instrument = lynx::InstrumentKind::synth;
  26621. q.channel = keys;
  26622. lynx::Pattern chords;
  26623. for (int i = 0; i < 4; ++i)
  26624. for (int k : { 60, 64, 67 })
  26625. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  26626. q.pattern = chords;
  26627. keysInsert = st::addTrack (s, q).insert;
  26628. q = {};
  26629. q.kind = st::Kind::drums;
  26630. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  26631. {
  26632. lynx::ChannelDef c;
  26633. c.instrument = kind;
  26634. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  26635. q.kit.push_back (c);
  26636. }
  26637. lynx::Pattern beat;
  26638. for (int step = 0; step < 16; step += 2)
  26639. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 2, 60 });
  26640. q.pattern = beat;
  26641. st::addTrack (s, q);
  26642. });
  26643. offline.dispatchPendingMessages();
  26644. simple->hideChooser();
  26645. auto& playlist = ui.getPlaylistForSnapshot();
  26646. // the tracks' places in the Playlist
  26647. int voiceTrack = -1, keysTrack = -1, drumsTrack = -1;
  26648. {
  26649. const auto& song = offline.getSong();
  26650. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  26651. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  26652. {
  26653. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  26654. voiceTrack = t;
  26655. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  26656. keysTrack = t;
  26657. else if (*kind == lynx::simpletracks::Kind::drums && drumsTrack < 0)
  26658. drumsTrack = t;
  26659. }
  26660. }
  26661. check ("three Simple tracks (voice, keys, drums)", voiceTrack >= 0 && keysTrack >= 0 && drumsTrack >= 0);
  26662. playlist.selectTrack (keysTrack);
  26663. offline.dispatchPendingMessages();
  26664. auto* dock = simple->dockForSnapshot();
  26665. if (dock == nullptr)
  26666. {
  26667. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  26668. return;
  26669. }
  26670. // the whole window and the dock alone, at 1x and 2x
  26671. const auto shots = [&] (const juce::String& name) {
  26672. offline.dispatchPendingMessages();
  26673. for (float scale : { 1.0f, 2.0f })
  26674. {
  26675. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  26676. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  26677. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  26678. }
  26679. };
  26680. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  26681. juce::StringArray names { title };
  26682. std::vector<juce::PopupMenu> menus { menu };
  26683. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  26684. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  26685. {
  26686. names.add (subTitle);
  26687. menus.push_back (*it.getItem().subMenu);
  26688. }
  26689. saveMenus (names, menus, prefix + "-" + name + ".png");
  26690. };
  26691. // --- the Instrument tab ---------------------------------------------------------------------------------------
  26692. check ("the dock shows the selected track", dock->shownTrack() == keysTrack && dock->isVisible() && dock->getParentComponent() != nullptr);
  26693. check ("an instrument track opens on its sound", dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::instrument);
  26694. const auto channel = dock->channelForCheck();
  26695. line ("sound at first: " + dock->soundNameForCheck() + ", rows in its category: " + juce::String (dock->soundRowsForCheck()));
  26696. shots ("instrument");
  26697. // a click on a row of another category: the track plays that sound, its own settings stay
  26698. const auto before = offline.getSong().channels[(std::size_t) channel];
  26699. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::pad);
  26700. offline.dispatchPendingMessages();
  26701. const auto padRows = dock->soundRowsForCheck();
  26702. dock->clickSoundForCheck (juce::jmin (2, padRows - 1));
  26703. offline.dispatchPendingMessages();
  26704. {
  26705. const auto& now = offline.getSong().channels[(std::size_t) channel];
  26706. const auto found = lynx::soundlib::find (lynx::soundlib::builtIn(), now);
  26707. check ("a click on a sound puts it on the track's channel (" + dock->soundNameForCheck() + ")",
  26708. padRows > 0 && found >= 0 && lynx::soundlib::builtIn()[(std::size_t) found].category == lynx::soundlib::Category::pad
  26709. && ! lynx::soundlib::sameSound (before, now));
  26710. check ("the channel keeps its name, level and insert", now.name == before.name && now.volume == before.volume && now.mixerTrack == before.mixerTrack);
  26711. double seconds = 0.0;
  26712. const auto heard = offline.auditionSound (now, { 60, 64, 67 }, &seconds);
  26713. check ("the sound's audition renders (" + juce::String (seconds, 2) + " s)", heard && seconds > 1.0);
  26714. }
  26715. shots ("instrument-pad");
  26716. const auto picked = dock->soundNameForCheck();
  26717. dock->stepSoundForCheck (1);
  26718. offline.dispatchPendingMessages();
  26719. const auto stepped = dock->soundNameForCheck();
  26720. dock->stepSoundForCheck (-1);
  26721. offline.dispatchPendingMessages();
  26722. check ("the arrows step through the category (" + picked + " -> " + stepped + " -> back)", stepped != picked && dock->soundNameForCheck() == picked);
  26723. check ("one undo step per sound", offline.canUndo());
  26724. // the user's SoundFont files (an index made here: no file is read)
  26725. {
  26726. std::vector<lynx::sf::IndexedFont> fonts (2);
  26727. fonts[0].path = "/home/me/SoundFonts/Concert Band.sf2";
  26728. fonts[0].name = "Concert Band";
  26729. int program = 0;
  26730. for (const char* name : { "Grand Piano", "Bright Piano", "Electric Piano", "Harpsichord", "Clavinet", "Celesta", "Music Box", "Vibraphone" })
  26731. fonts[0].presets.push_back ({ name, 0, program++ });
  26732. 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 } })
  26733. fonts[0].presets.push_back ({ name, 0, p });
  26734. fonts[0].presets.push_back ({ "Standard Kit", 128, 0 });
  26735. fonts[1].path = "/home/me/SoundFonts/Old Upright.sf2";
  26736. fonts[1].name = "Old Upright";
  26737. fonts[1].presets.push_back ({ "Old Upright", 0, 0 });
  26738. fonts[1].presets.push_back ({ "Old Upright Soft", 0, 1 });
  26739. dock->setFontsForSnapshot (fonts);
  26740. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::keys);
  26741. offline.dispatchPendingMessages();
  26742. check ("My SoundFonts lists the presets of the user's files by category (Keys: " + juce::String (dock->soundRowsForCheck()) + " of 17)", dock->soundRowsForCheck() == 7);
  26743. dock->clickSoundForCheck (0);
  26744. offline.dispatchPendingMessages();
  26745. const auto& now = offline.getSong().channels[(std::size_t) channel];
  26746. check ("a SoundFont preset becomes the track's sound (" + dock->soundNameForCheck() + ")",
  26747. now.instrument == lynx::InstrumentKind::soundfont && juce::String (now.samplePath).endsWith (".sf2"));
  26748. shots ("instrument-soundfonts");
  26749. }
  26750. // --- the Effects tab ------------------------------------------------------------------------------------------
  26751. playlist.selectTrack (voiceTrack);
  26752. offline.dispatchPendingMessages();
  26753. const auto insert = dock->insertForCheck();
  26754. check ("an audio track has no Instrument tab and opens on its effects",
  26755. dock->shownTrack() == voiceTrack && ! dock->hasInstrumentTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::effects && insert > 0);
  26756. check ("no effects yet: no cards", dock->cardCountForCheck() == 0);
  26757. shots ("effects-empty");
  26758. menuShot (dock->addMenuForSnapshot(), lynx::tr ("Add an effect"), {}, "menu-add");
  26759. // + adds one-knob effects at the end of the chain
  26760. dock->addOneKnobForCheck (lynx::goals::brighter);
  26761. dock->addOneKnobForCheck (lynx::goals::room);
  26762. dock->addOneKnobForCheck (lynx::goals::level);
  26763. offline.dispatchPendingMessages();
  26764. const auto slotsText = [&offline] (int t) {
  26765. juce::String text;
  26766. const auto rows = lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) t].effects); // (the Mixer's slot of each)
  26767. std::size_t at = 0;
  26768. for (const auto& fx : offline.getSong().mixer[(std::size_t) t].effects)
  26769. text << "[slot " << rows[at++] + 1 << " " << lynx::effectInfo (fx.kind).name
  26770. << (lynx::goals::active (fx) ? " = " + juce::String (lynx::goals::name (fx.goal)) + " " + juce::String (juce::roundToInt (fx.goalAmount * 100.0f)) + "%" : juce::String())
  26771. << (fx.enabled ? "" : " off") << "] ";
  26772. return text.trimEnd();
  26773. };
  26774. line ("after + x3: " + slotsText (insert));
  26775. check ("three cards, three one-knob effects", dock->cardCountForCheck() == 3 && dock->oneKnobCardsForCheck() == 3);
  26776. // the knob writes the effect's own parameters
  26777. const auto roomBefore = offline.getSong().mixer[(std::size_t) insert].effects[1];
  26778. dock->turnKnobForCheck (1, 0.8f);
  26779. offline.dispatchPendingMessages();
  26780. {
  26781. const auto& room = offline.getSong().mixer[(std::size_t) insert].effects[1];
  26782. 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));
  26783. }
  26784. // ‹ › reorder, × removes
  26785. dock->moveCardForCheck (2, -1);
  26786. offline.dispatchPendingMessages();
  26787. line ("Level moved left: " + slotsText (insert));
  26788. {
  26789. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  26790. check ("the card moved one place earlier", fx.size() == 3 && fx[1].goal == lynx::goals::level && fx[2].goal == lynx::goals::room);
  26791. }
  26792. dock->removeCardForCheck (0);
  26793. offline.dispatchPendingMessages();
  26794. line ("Brighter removed: " + slotsText (insert));
  26795. check ("the card is gone", dock->cardCountForCheck() == 2 && offline.getSong().mixer[(std::size_t) insert].effects.size() == 2);
  26796. // a hand edit in the full editor: the slot is an ordinary effect again (its card shows Mix)
  26797. offline.editSong ([insert] (lynx::Song& s) {
  26798. auto& slot = s.mixer[(std::size_t) insert].effects[0];
  26799. const auto moved = (std::size_t) lynx::goals::mapping (slot.goal, slot.goalAmount).back().param;
  26800. slot.params[moved] = slot.params[moved] > 0.5f ? 0.2f : 0.9f;
  26801. });
  26802. offline.dispatchPendingMessages();
  26803. check ("a parameter moved by hand makes the card an ordinary effect", dock->cardCountForCheck() == 2 && dock->oneKnobCardsForCheck() == 1);
  26804. dock->turnKnobForCheck (0, 0.5f); // (its knob is the slot's Mix now)
  26805. offline.dispatchPendingMessages();
  26806. 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);
  26807. // a preset replaces the chain; Blend is the chain's dry/wet
  26808. if (const auto* preset = lynx::chains::find ("Clear Voice"))
  26809. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  26810. offline.dispatchPendingMessages();
  26811. line ("preset Clear Voice: " + slotsText (insert));
  26812. 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)
  26813. && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size());
  26814. shots ("effects-preset");
  26815. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("Voice"), "menu-preset");
  26816. dock->setBlendForCheck (0.7f);
  26817. dock->addOneKnobForCheck (lynx::goals::echo);
  26818. offline.dispatchPendingMessages();
  26819. check ("Blend 70 % is the insert's chain blend; the preset shows as edited",
  26820. std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.7f) < 1.0e-6f && ! lynx::chains::unchanged (offline.getSong(), insert));
  26821. shots ("effects-edited");
  26822. // a user preset: saved to a file, loaded on another track (its slots and Blend; that track's level stays)
  26823. const auto mine = offline.getSong().mixer[(std::size_t) insert];
  26824. const auto saved = lynx::SimpleDock::saveUserPreset (offline, insert, "My voice");
  26825. const auto file = lynx::SimpleDock::userPresetFolder().getChildFile ("My voice.lynxtrack");
  26826. check ("the preset is saved as " + file.getFileName(), saved && file.existsAsFile() && offline.getSong().mixer[(std::size_t) insert].chainPreset == "My voice");
  26827. offline.editSong ([keysInsert] (lynx::Song& s) { s.mixer[(std::size_t) keysInsert].volume = 0.42f; });
  26828. const auto loaded = keysInsert > 0 && lynx::SimpleDock::loadUserPreset (offline, keysInsert, file);
  26829. offline.dispatchPendingMessages();
  26830. {
  26831. const auto& other = offline.getSong().mixer[(std::size_t) keysInsert];
  26832. auto same = loaded && other.effects.size() == mine.effects.size() && std::abs (other.chainBlend - mine.chainBlend) < 1.0e-6f && other.chainPreset == "My voice";
  26833. for (std::size_t i = 0; same && i < mine.effects.size(); ++i)
  26834. same = other.effects[i].kind == mine.effects[i].kind && other.effects[i].goal == mine.effects[i].goal
  26835. && 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]);
  26836. check ("loaded on the Keys track: the same slots and Blend", same);
  26837. check ("the Keys track keeps its level", std::abs (other.volume - 0.42f) < 1.0e-6f);
  26838. line ("Keys after load: " + slotsText (keysInsert));
  26839. }
  26840. menuShot (dock->presetMenuForSnapshot(), lynx::tr ("Preset"), lynx::tr ("My presets"), "menu-preset-mine");
  26841. file.deleteFile();
  26842. // the drums: effects only (a kit has no single sound to pick)
  26843. playlist.selectTrack (drumsTrack);
  26844. offline.dispatchPendingMessages();
  26845. check ("the Drums track shows its insert's effects, no Instrument tab", dock->shownTrack() == drumsTrack && ! dock->hasInstrumentTabForCheck() && dock->insertForCheck() > 0);
  26846. if (const auto* preset = lynx::chains::find ("Smash Room"))
  26847. offline.editSongStructural ([t = dock->insertForCheck(), preset] (lynx::Song& s) { lynx::chains::apply (s, t, *preset); });
  26848. shots ("effects-drums");
  26849. // the project file keeps all of it
  26850. {
  26851. juce::String error;
  26852. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  26853. const auto back = lynx::ProjectFile::fromJson (json, error);
  26854. auto same = back && back->mixer.size() == offline.getSong().mixer.size();
  26855. for (std::size_t t = 0; same && t < back->mixer.size(); ++t)
  26856. {
  26857. const auto& a = offline.getSong().mixer[t];
  26858. const auto& b = back->mixer[t];
  26859. same = a.effects.size() == b.effects.size() && std::abs (a.chainBlend - b.chainBlend) < 1.0e-6f && a.chainPreset == b.chainPreset;
  26860. for (std::size_t i = 0; same && i < a.effects.size(); ++i)
  26861. 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
  26862. && std::abs (a.effects[i].goalAmount - b.effects[i].goalAmount) < 1.0e-6f;
  26863. }
  26864. check ("saved and loaded as a project: the same chains, knobs, Blend and preset names", same);
  26865. }
  26866. // --- the same plugins in the same slots in FL's layout --------------------------------------------------------
  26867. const auto simpleSong = offline.getSong();
  26868. const auto inSimple = slotsText (insert);
  26869. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  26870. offline.dispatchPendingMessages();
  26871. check ("Pattern workflow: the dock is gone", dock->getParentComponent() == nullptr);
  26872. ui.selectTabForSnapshot (3);
  26873. ui.getMixerForSnapshot().selectTrack (insert);
  26874. offline.dispatchPendingMessages();
  26875. for (float scale : { 1.0f, 2.0f })
  26876. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), juce::String ("pattern-mixer") + (scale > 1.0f ? "@2x" : ""));
  26877. line ("Simple layout: " + inSimple);
  26878. line ("Pattern layout: " + slotsText (insert));
  26879. check ("the same effects in the same Mixer slots in the Pattern workflow", offline.getSong().mixer == simpleSong.mixer && offline.getSong().channels == simpleSong.channels);
  26880. // an effect added in the Mixer's way shows as a card when the Simple workflow comes back
  26881. offline.editSongStructural ([insert] (lynx::Song& s) { lynx::mixerops::insertEffectAtRow (s, insert, lynx::makeEffectSlot (lynx::EffectKind::chorus), 7); });
  26882. ui.selectTabForSnapshot (2);
  26883. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  26884. offline.dispatchPendingMessages();
  26885. simple->hideChooser();
  26886. playlist.selectTrack (voiceTrack);
  26887. offline.dispatchPendingMessages();
  26888. check ("back in Simple: the dock shows the insert as it is now, the Mixer's new effect too",
  26889. dock->getParentComponent() != nullptr && dock->cardCountForCheck() == (int) offline.getSong().mixer[(std::size_t) insert].effects.size()
  26890. && lynx::mixerops::effectRows (offline.getSong().mixer[(std::size_t) insert].effects).back() == 7);
  26891. line ("Simple again: " + slotsText (insert));
  26892. shots ("effects-back");
  26893. // hidden with its key, shown again by "+FX"
  26894. simple->toggleDock();
  26895. offline.dispatchPendingMessages();
  26896. check ("Ctrl+Alt+L hides the dock", ! simple->isDockShowing() && ! lynx::SimpleDock::shownSetting);
  26897. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "dock-hidden");
  26898. simple->showEffectsOfInsert (keysInsert);
  26899. offline.dispatchPendingMessages();
  26900. check ("+FX on a track header shows the dock on that track's effects",
  26901. simple->isDockShowing() && dock->shownTrack() == keysTrack && dock->getTab() == lynx::SimpleDock::Tab::effects && dock->insertForCheck() == keysInsert);
  26902. simple->cycleDockTab();
  26903. check ("Shift+Tab goes to the Instrument tab", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  26904. line ("Simple workflow objects: " + juce::String (madeBefore) + " before, " + juce::String (lynx::SimpleWorkflow::instances.load()) + " after");
  26905. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  26906. juce::File (prefix + "-report.txt").replaceWithText (report);
  26907. }
  26908. // --simpleclosetest (round 190fc, 0.1.27 RC blocker B1): every close in the Simple layout crashed (the Simple workflow
  26909. // was destroyed after the Workspace and its destructor called into it). Off-screen, no window: the main window in the
  26910. // Simple layout with everything of it open — Welcome, the first-song tour's card, Start from, a demo song, each dock
  26911. // tab (the Editor tab docks the Piano roll), Finish, Lyrics, the chooser — then destroyed as the app's shutdown does.
  26912. // A second main window goes Simple -> Pattern -> Simple and closes too. Checks: no Simple workflow outlives its main
  26913. // window's destructor body, none is left at all. (Under ASan on Linux the old order is a heap-use-after-free.)
  26914. bool runDonateShot (const juce::String& prefix)
  26915. {
  26916. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  26917. juce::String report;
  26918. bool ok = true;
  26919. const auto line = [&report, &prefix] (const juce::String& text) {
  26920. report << text << "\n";
  26921. juce::File (prefix + "-report.txt").replaceWithText (report); // (written as it goes)
  26922. };
  26923. const auto check = [&line, &ok] (const juce::String& what, bool good) {
  26924. line ((good ? "ok " : "FAIL ") + what);
  26925. ok = ok && good;
  26926. };
  26927. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  26928. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  26929. file.deleteFile();
  26930. juce::FileOutputStream out (file);
  26931. juce::PNGImageFormat().writeImageToStream (image, out);
  26932. };
  26933. // a window as the --snapshot route saves one (off the desktop, on the theme's panel colour), at 1x and 2x
  26934. const auto saveAlert = [&] (juce::AlertWindow& w, const juce::String& name) {
  26935. if (w.isOnDesktop())
  26936. w.removeFromDesktop();
  26937. w.setOpaque (true);
  26938. juce::Component frame;
  26939. frame.setSize (w.getWidth(), w.getHeight());
  26940. frame.setOpaque (true);
  26941. frame.addAndMakeVisible (w);
  26942. w.setTopLeftPosition (0, 0);
  26943. writeImage (lynx::shot::paint (frame, lynx::theme::panel), name);
  26944. writeImage (frame.createComponentSnapshot (frame.getLocalBounds(), true, 2.0f), name + "@2x");
  26945. frame.removeChildComponent (&w);
  26946. };
  26947. const auto buttonTexts = [] (juce::AlertWindow& w) {
  26948. if (auto* d = dynamic_cast<lynx::ui::dialog::Dialog*> (&w)) // (round 190jp: LYNX's dialog, its own buttons)
  26949. return d->dialogButtonTexts();
  26950. juce::StringArray texts;
  26951. for (int b = 0; b < w.getNumButtons(); ++b)
  26952. if (auto* button = w.getButton (b))
  26953. texts.add (button->getButtonText());
  26954. return texts;
  26955. };
  26956. check ("the donation page is one constant, on Ko-fi", juce::String (lynx::links::donate).startsWith ("https://ko-fi"));
  26957. line ("donate URL: " + juce::String (lynx::links::donate));
  26958. const auto stateFile = lynx::PluginHost::settingsFolder().getChildFile ("support-note.txt");
  26959. const auto hadState = stateFile.existsAsFile();
  26960. const auto oldState = stateFile.loadFileAsString();
  26961. line ("state file: " + stateFile.getFullPathName() + (hadState ? " (exists; put back at the end)" : ""));
  26962. {
  26963. lynx::AudioEngine offline (false);
  26964. lynx::MainComponent ui (offline, false);
  26965. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  26966. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  26967. ui.setVisible (true);
  26968. const auto settle = [&] {
  26969. for (int k = 0; k < 3; ++k)
  26970. offline.dispatchPendingMessages();
  26971. };
  26972. // --- Help › Support LYNX SHARE..., right above About, in the three layouts ----------------------------------
  26973. for (auto [style, name] : { std::pair { lynx::layoutstyle::Style::pattern, "pattern" }, { lynx::layoutstyle::Style::clipLaunch, "cliplaunch" },
  26974. { lynx::layoutstyle::Style::simple, "simple" } })
  26975. {
  26976. ui.setLayoutStyle (style);
  26977. settle();
  26978. const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
  26979. juce::StringArray items;
  26980. for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
  26981. if (! it.getItem().isSeparator)
  26982. items.add (it.getItem().text);
  26983. const auto support = items.indexOf (lynx::tr ("Support LYNX SHARE..."));
  26984. const auto about = items.indexOf (lynx::tr ("About LYNX SHARE"));
  26985. check (juce::String ("Help has Support LYNX SHARE... right above About LYNX SHARE (") + name + " layout)",
  26986. support >= 0 && about == support + 1);
  26987. saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help-" + name + ".png");
  26988. }
  26989. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  26990. settle();
  26991. // --- the Support window -------------------------------------------------------------------------------------
  26992. {
  26993. auto w = lynx::support::makeSupportWindow();
  26994. const auto texts = buttonTexts (*w);
  26995. check ("Support window: Donate on Ko-fi, Close", texts == juce::StringArray { lynx::tr ("Donate on Ko-fi"), lynx::tr ("Close") });
  26996. check ("Support window: Donate on Ko-fi points at the constant",
  26997. dynamic_cast<lynx::ui::dialog::Dialog*> (w.get()) != nullptr
  26998. && static_cast<lynx::ui::dialog::Dialog*> (w.get())->dialogButton (0)->getTooltip() == juce::String (lynx::links::donate));
  26999. check ("Support window title", w->getName() == lynx::tr ("Support LYNX SHARE"));
  27000. saveAlert (*w, "support");
  27001. }
  27002. // --- the About window ---------------------------------------------------------------------------------------
  27003. {
  27004. auto w = lynx::MainComponent::makeAboutWindow();
  27005. const auto texts = buttonTexts (*w);
  27006. check ("About window: Support LYNX SHARE (result 2) and OK", texts == juce::StringArray { lynx::tr ("Support LYNX SHARE"), lynx::tr ("OK") });
  27007. saveAlert (*w, "about");
  27008. }
  27009. // --- Settings › General › Show the support note -------------------------------------------------------------
  27010. {
  27011. auto page = lynx::makeGeneralPage (offline, {}, false);
  27012. bool found = false;
  27013. std::function<void (juce::Component&)> walk = [&] (juce::Component& c) {
  27014. if (auto* t = dynamic_cast<juce::ToggleButton*> (&c); t != nullptr && t->getButtonText() == lynx::tr ("Show the support note"))
  27015. found = t->getToggleState();
  27016. for (auto* child : c.getChildren())
  27017. walk (*child);
  27018. };
  27019. walk (*page);
  27020. check ("Settings > General: \"Show the support note\", ticked by default", found);
  27021. }
  27022. // --- the start-up note's rules, end to end on the saved state ----------------------------------------------
  27023. lynx::supportnote::Moment moment; // (the main window here is off-screen: the moment is set by hand)
  27024. lynx::support::StartupNote note (ui, [&moment] { return moment; }, [] { return 0; });
  27025. const auto state = [] { return lynx::support::loadState(); };
  27026. const auto setState = [] (int launches, int next, bool show) { lynx::support::saveState ({ launches, next, show }); };
  27027. stateFile.deleteFile();
  27028. for (int k = 0; k < 15; ++k)
  27029. note.begin (true);
  27030. note.pollForSnapshot();
  27031. check ("test mode / CI runs: 15 starts, nothing counted, no file, no card", ! stateFile.existsAsFile() && ! note.isCardShowing());
  27032. check ("a first start's defaults: next at start 10, shown", state() == lynx::supportnote::State { 0, 10, true });
  27033. for (int k = 1; k <= 9; ++k)
  27034. {
  27035. note.begin (false);
  27036. note.pollForSnapshot();
  27037. }
  27038. check ("starts 1 to 9: counted, no card", state().launches == 9 && ! note.isCardShowing());
  27039. moment.playing = true;
  27040. note.begin (false); // the 10th start
  27041. note.pollForSnapshot();
  27042. check ("10th start while playing: the card waits", state().launches == 10 && ! note.isCardShowing());
  27043. moment = {};
  27044. moment.dialogOpen = true;
  27045. note.pollForSnapshot();
  27046. check ("... and while a dialog is open", ! note.isCardShowing());
  27047. moment = {};
  27048. note.pollForSnapshot();
  27049. check ("10th start, a quiet moment: the card shows", note.isCardShowing());
  27050. check ("shown: left without an answer it comes back 30 starts later", state().nextAt == 40);
  27051. if (auto* card = note.cardForSnapshot())
  27052. {
  27053. const auto b = card->getBounds();
  27054. check ("the card sits in the bottom-right corner", b.getRight() <= ui.getWidth() - 8 && b.getRight() >= ui.getWidth() - 40
  27055. && b.getBottom() <= ui.getHeight() - 4 && b.getBottom() >= ui.getHeight() - 40);
  27056. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), "note-in-window");
  27057. writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), "note@2x");
  27058. // the corner of the window around the card, at 2x
  27059. writeImage (ui.createComponentSnapshot (b.expanded (220, 120).getIntersection (ui.getLocalBounds()), true, 2.0f), "note-corner@2x");
  27060. }
  27061. moment.playing = true;
  27062. note.pollForSnapshot();
  27063. check ("playback starts: the card steps aside", ! note.isCardShowing());
  27064. moment = {};
  27065. // Not now: again after 30 more starts
  27066. setState (10, 10, true);
  27067. note.begin (false); // start 11
  27068. note.pollForSnapshot();
  27069. if (auto* card = note.cardForSnapshot(); card != nullptr && card->buttonForSnapshot (lynx::supportnote::Choice::notNow) != nullptr)
  27070. card->buttonForSnapshot (lynx::supportnote::Choice::notNow)->onClick();
  27071. note.closeCard(); // (the click closes it on the next message turn)
  27072. check ("Not now: next at start 41", state() == lynx::supportnote::State { 11, 41, true });
  27073. for (int k = 12; k <= 40; ++k)
  27074. {
  27075. note.begin (false);
  27076. note.pollForSnapshot();
  27077. if (note.isCardShowing())
  27078. break;
  27079. }
  27080. check ("Not now: starts 12 to 40 without the card", ! note.isCardShowing() && state().launches == 40);
  27081. note.begin (false);
  27082. note.pollForSnapshot();
  27083. check ("Not now: the card again at start 41", note.isCardShowing());
  27084. // Don't show again: never, and Settings shows the box unticked
  27085. if (auto* card = note.cardForSnapshot())
  27086. card->buttonForSnapshot (lynx::supportnote::Choice::never)->onClick();
  27087. note.closeCard();
  27088. check ("Don't show again: off", ! state().show && ! lynx::support::noteEnabled());
  27089. for (int k = 0; k < 200; ++k)
  27090. {
  27091. note.begin (false);
  27092. note.pollForSnapshot();
  27093. }
  27094. check ("Don't show again: 200 more starts, never", ! note.isCardShowing());
  27095. // Support: opens the Support window (on the next message turn) and the note doesn't come back
  27096. setState (20, 10, true);
  27097. note.begin (false);
  27098. note.pollForSnapshot();
  27099. if (auto* card = note.cardForSnapshot())
  27100. card->buttonForSnapshot (lynx::supportnote::Choice::support)->onClick();
  27101. note.closeCard();
  27102. check ("Support: the note has done its job", ! state().show);
  27103. // Settings off: never; on again: counts from now
  27104. setState (5, 10, true);
  27105. lynx::support::setNoteEnabled (false);
  27106. for (int k = 0; k < 100; ++k)
  27107. {
  27108. note.begin (false);
  27109. note.pollForSnapshot();
  27110. }
  27111. check ("Settings off: 100 starts, never", ! note.isCardShowing() && state().launches == 105);
  27112. lynx::support::setNoteEnabled (true);
  27113. check ("Settings on again: next 30 starts later", state() == lynx::supportnote::State { 105, 135, true });
  27114. note.closeCard();
  27115. }
  27116. stateFile.deleteFile();
  27117. if (hadState)
  27118. stateFile.replaceWithText (oldState);
  27119. line (ok ? "result=OK" : "result=FAILED");
  27120. return ok;
  27121. }
  27122. bool runSimpleCloseTest (const juce::String& reportPath)
  27123. {
  27124. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27125. juce::String report;
  27126. bool ok = true;
  27127. const auto line = [&report, &reportPath] (const juce::String& text) {
  27128. report << text << "\n";
  27129. juce::File (reportPath).replaceWithText (report); // (written as it goes: a crash still leaves the last step)
  27130. };
  27131. const auto check = [&line, &ok] (const juce::String& what, bool good) {
  27132. line ((good ? "ok " : "FAIL ") + what);
  27133. ok = ok && good;
  27134. };
  27135. const auto aliveBefore = lynx::SimpleWorkflow::alive.load();
  27136. {
  27137. lynx::AudioEngine offline (false);
  27138. {
  27139. lynx::MainComponent ui (offline, false);
  27140. ui.setSize (1600, 900);
  27141. ui.setVisible (true); // (no window: the docked editor and the tour only need their parents visible)
  27142. const auto settle = [&] {
  27143. for (int k = 0; k < 3; ++k)
  27144. offline.dispatchPendingMessages();
  27145. };
  27146. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  27147. settle();
  27148. auto* simple = ui.getSimpleWorkflowForSnapshot();
  27149. check ("the Simple workflow is up", simple != nullptr);
  27150. if (simple != nullptr)
  27151. {
  27152. const auto empty = lynx::builtInTemplateIndex ("Empty");
  27153. offline.setSong (empty >= 0 ? lynx::makeNewProject (empty) : lynx::makeNewProject());
  27154. settle();
  27155. simple->showWelcome();
  27156. settle();
  27157. auto* tour = simple->tourForSnapshot();
  27158. check ("Welcome screen shown", tour != nullptr && tour->isWelcomeShowing());
  27159. simple->startOrContinueTour();
  27160. settle();
  27161. simple->doTourStep (lynx::tour::beat);
  27162. settle();
  27163. check ("the tour runs with its card up", simple->tourRunning() && tour != nullptr && tour->cardForSnapshot() != nullptr);
  27164. // a demo song from Start from (the panel stays up over the Playlist)
  27165. if (auto* start = simple->startFromForSnapshot(); start != nullptr && lynx::demos::count > 1)
  27166. {
  27167. offline.setSong (lynx::demos::make (1));
  27168. settle();
  27169. check ("a demo song opened, Start from up", simple->isStartFromShowing() && ! offline.getSong().playlist.empty());
  27170. }
  27171. // the dock on a track, every tab (the Editor tab docks the Piano roll)
  27172. if (auto* dock = simple->dockForSnapshot())
  27173. {
  27174. simple->trackSelected ([] (const lynx::Song& song) { // the first Instrument track (the dock's Keyboard and Editor tabs are for it)
  27175. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  27176. if (lynx::simpletracks::kindOf (song, t) == lynx::simpletracks::Kind::instrument)
  27177. return t;
  27178. return 0;
  27179. } (offline.getSong()));
  27180. for (auto tab : { lynx::SimpleDock::Tab::instrument, lynx::SimpleDock::Tab::keyboard, lynx::SimpleDock::Tab::editor,
  27181. lynx::SimpleDock::Tab::effects, lynx::SimpleDock::Tab::editor })
  27182. {
  27183. dock->setTab (tab);
  27184. settle();
  27185. }
  27186. check ("the dock shows", simple->isDockShowing());
  27187. line ("dock tab at the close: " + juce::String ((int) dock->getTab()) + " (2 = Editor, the docked Piano roll)");
  27188. }
  27189. ui.toggleLyrics(); // (Lyrics, then Finish: they share the dock on the right)
  27190. settle();
  27191. simple->showFinish();
  27192. settle();
  27193. check ("Finish open", simple->isFinishShowing());
  27194. simple->showChooser();
  27195. settle();
  27196. line ("Simple workflow objects alive before the close: " + juce::String (lynx::SimpleWorkflow::alive.load() - aliveBefore));
  27197. }
  27198. } // (the main window goes as at shutdown)
  27199. check ("no Simple workflow outlived its main window's destructor body (it reaches the Workspace)",
  27200. lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore);
  27201. check ("none left after the close", lynx::SimpleWorkflow::alive.load() == aliveBefore);
  27202. // Simple, then Pattern, then Simple again, and closed
  27203. {
  27204. lynx::MainComponent ui (offline, false);
  27205. ui.setSize (1600, 900);
  27206. ui.setVisible (true);
  27207. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  27208. offline.dispatchPendingMessages();
  27209. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  27210. offline.dispatchPendingMessages();
  27211. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  27212. offline.dispatchPendingMessages();
  27213. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  27214. simple->showWelcome();
  27215. offline.dispatchPendingMessages();
  27216. }
  27217. check ("Simple -> Pattern -> Simple, closed: none outlived the destructor body", lynx::MainComponent::simpleWorkflowAliveAfterTeardown == aliveBefore
  27218. && lynx::SimpleWorkflow::alive.load() == aliveBefore);
  27219. }
  27220. line (ok ? "result=OK" : "result=FAILED");
  27221. return ok;
  27222. }
  27223. void runTour190dvShot (const juce::String& prefix)
  27224. {
  27225. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27226. lynx::AudioEngine offline (false);
  27227. lynx::MainComponent ui (offline, false);
  27228. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  27229. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  27230. ui.setVisible (true); // (no window: the docked editor and the ring's targets only need their parents visible)
  27231. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  27232. const auto file = juce::File (prefix + "-" + name + ".png");
  27233. file.deleteFile();
  27234. juce::FileOutputStream out (file);
  27235. juce::PNGImageFormat().writeImageToStream (image, out);
  27236. };
  27237. juce::String report;
  27238. // (written as it goes: a run that stops halfway still leaves its checks)
  27239. const auto line = [&report, &prefix] (const juce::String& text) {
  27240. report << text << "\n";
  27241. juce::File (prefix + "-report.txt").replaceWithText (report);
  27242. };
  27243. const auto check = [&line] (const juce::String& what, bool ok) { line ((ok ? "OK " : "ERROR ") + what); };
  27244. ui.selectTabForSnapshot (2);
  27245. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  27246. offline.dispatchPendingMessages();
  27247. auto* simple = ui.getSimpleWorkflowForSnapshot();
  27248. auto* tour = simple != nullptr ? simple->tourForSnapshot() : nullptr;
  27249. if (tour == nullptr)
  27250. {
  27251. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow / tour\n");
  27252. return;
  27253. }
  27254. check ("no Welcome screen by itself in a --snapshot route (not a real first start)", ! tour->isWelcomeShowing());
  27255. const auto settle = [&] {
  27256. for (int k = 0; k < 3; ++k)
  27257. offline.dispatchPendingMessages();
  27258. };
  27259. const auto window = [&] (const juce::String& name, bool twoX = false) {
  27260. settle();
  27261. tour->ringForSnapshot(); // (the ring follows the layout: resolved now, as its timer would)
  27262. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name);
  27263. if (twoX)
  27264. if (auto* card = tour->cardForSnapshot(); card != nullptr && card->getParentComponent() != nullptr)
  27265. writeImage (card->createComponentSnapshot (card->getLocalBounds(), true, 2.0f), name + "-card@2x");
  27266. };
  27267. const auto stepIs = [&] (int step, const juce::String& target) {
  27268. settle();
  27269. const auto ring = tour->ringForSnapshot();
  27270. const auto id = tour->targetIdForSnapshot();
  27271. line ("step " + juce::String (tour->step() + 1) + " (" + lynx::tour::stepId (tour->step()) + "): ring on " + (id.isEmpty() ? juce::String ("-") : id) + " "
  27272. + ring.toString());
  27273. check (juce::String ("the card shows step ") + lynx::tour::stepId (step), tour->isRunning() && tour->step() == step);
  27274. if (target.isNotEmpty())
  27275. check ("the ring is on " + target, id == target && ! ring.isEmpty());
  27276. };
  27277. // --- the Welcome screen (on a new, empty project: the built-in "Empty" template, as File › New can give) -------------
  27278. const auto emptyProject = [] {
  27279. const auto index = lynx::builtInTemplateIndex ("Empty");
  27280. return index >= 0 ? lynx::makeNewProject (index) : lynx::makeNewProject();
  27281. };
  27282. offline.setSong (emptyProject());
  27283. settle();
  27284. check ("the new project is empty for the Simple workflow (it opens on the chooser)", lynx::simpletracks::isEmptySong (offline.getSong()));
  27285. simple->showWelcome();
  27286. settle();
  27287. check ("Help › Welcome screen shows it", tour->isWelcomeShowing());
  27288. window ("welcome");
  27289. if (auto* w = tour->welcomeForSnapshot())
  27290. writeImage (w->createComponentSnapshot (w->getLocalBounds(), true, 2.0f), "welcome@2x");
  27291. tour->clickForSnapshot ("welcome.tour");
  27292. settle();
  27293. check ("Make my first song: the Welcome screen closes, the tour starts, the chooser comes up for the beat",
  27294. ! tour->isWelcomeShowing() && tour->isRunning() && simple->isChooserShowing());
  27295. // --- step 1: the beat ---------------------------------------------------------------------------------------------
  27296. stepIs (lynx::tour::beat, "simple.tile.drums");
  27297. window ("step1-beat", true);
  27298. simple->showStarterPageForSnapshot();
  27299. stepIs (lynx::tour::beat, "simple.starters");
  27300. window ("step1-beat-starters");
  27301. tour->clickForSnapshot ("do");
  27302. settle();
  27303. check ("Do it for me added a starter beat", lynx::tour::hasBeat (offline.getSong()));
  27304. // --- step 2: the key ----------------------------------------------------------------------------------------------
  27305. stepIs (lynx::tour::key, "toolbar.key");
  27306. window ("step2-key", true);
  27307. tour->clickForSnapshot ("do");
  27308. settle();
  27309. check ("Do it for me set A minor", lynx::projectkey::get (offline.getSong()).has_value());
  27310. // --- step 3: an instrument (Add track opens the chooser: the ring moves to its tile) ------------------------------
  27311. stepIs (lynx::tour::instrument, "simple.addTrack");
  27312. window ("step3-instrument", true);
  27313. simple->showChooser();
  27314. stepIs (lynx::tour::instrument, "simple.tile.instrument");
  27315. window ("step3-instrument-chooser");
  27316. tour->clickForSnapshot ("do");
  27317. settle();
  27318. check ("Do it for me added an Instrument track (the chooser closed)", lynx::tour::firstInstrumentTrack (offline.getSong()) >= 0 && ! simple->isChooserShowing());
  27319. // --- step 4: chords -----------------------------------------------------------------------------------------------
  27320. stepIs (lynx::tour::chords, "keyboard.chordPad");
  27321. window ("step4-chords", true);
  27322. tour->clickForSnapshot ("do");
  27323. settle();
  27324. check ("Do it for me wrote four chords (12 notes) on the instrument's pattern", [&] {
  27325. const auto& song = offline.getSong();
  27326. const auto p = lynx::simpletracks::patternOf (song, lynx::tour::firstInstrumentTrack (song));
  27327. return p >= 0 && song.patterns[(std::size_t) p].notes.size() == 12;
  27328. }());
  27329. // --- step 5: a voice or a loop (no "Do it for me": a loop is dropped as a user would) ------------------------------
  27330. stepIs (lynx::tour::loop, "simple.dropLane"); // (round 190jc, SG-18: it rang "+ Add track")
  27331. window ("step5-loop", true);
  27332. {
  27333. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190dv-loops");
  27334. dir.deleteRecursively();
  27335. dir.createDirectory();
  27336. const auto wav = dir.getChildFile ("Warm Keys 120 Am.wav");
  27337. const int frames = 192000;
  27338. juce::AudioBuffer<float> audio (1, frames);
  27339. for (int i = 0; i < frames; ++i)
  27340. {
  27341. const auto t = (double) i / 48000.0;
  27342. double v = 0.0;
  27343. for (const auto key : { 57, 60, 64 })
  27344. v += std::sin (2.0 * juce::MathConstants<double>::pi * 440.0 * std::pow (2.0, (key - 69) / 12.0) * t);
  27345. audio.setSample (0, i, (float) (0.1 * v * (1.0 - std::exp (-std::fmod (t, 0.5) * 60.0))));
  27346. }
  27347. {
  27348. juce::WavAudioFormat format;
  27349. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  27350. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  27351. {
  27352. out.release();
  27353. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  27354. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  27355. }
  27356. }
  27357. simple->dropFiles ({ wav.getFullPathName() }, 0);
  27358. settle();
  27359. check ("a dropped loop (A minor in its name) follows the key", [&] {
  27360. for (const auto& c : offline.getSong().playlist)
  27361. if (c.kind == lynx::ClipKind::audio)
  27362. return c.followKey;
  27363. return false;
  27364. }());
  27365. }
  27366. // --- step 6: a one-knob effect --------------------------------------------------------------------------------------
  27367. stepIs (lynx::tour::effect, "simple.dock.addEffect");
  27368. window ("step6-effect", true);
  27369. tour->clickForSnapshot ("do");
  27370. settle();
  27371. check ("Do it for me put Room on the instrument track", lynx::tour::hasOneKnob (offline.getSong()));
  27372. // --- step 7: Finish -----------------------------------------------------------------------------------------------
  27373. stepIs (lynx::tour::finish, "simple.finish");
  27374. window ("step7-finish", true);
  27375. tour->clickForSnapshot ("do");
  27376. settle();
  27377. check ("Do it for me opened Finish and chose Balanced", simple->isFinishShowing() && lynx::looks::present (offline.getSong()));
  27378. // --- the end card, Back / Next, close -------------------------------------------------------------------------------
  27379. settle();
  27380. check ("the end card", tour->isRunning() && tour->step() == lynx::tour::stepCount);
  27381. window ("end", true);
  27382. tour->clickForSnapshot ("back");
  27383. settle();
  27384. check ("Back: the Finish step again, shown done (the tour waits for Next)", tour->step() == lynx::tour::finish
  27385. && tour->machineForCheck().shownDone (offline.getSong()));
  27386. window ("back-done", true);
  27387. tour->clickForSnapshot ("next");
  27388. settle();
  27389. check ("Next: the end card again", tour->step() == lynx::tour::stepCount);
  27390. check ("all seven steps done by the song", tour->machineForCheck().state().completed == 0x7fu);
  27391. tour->clickForSnapshot ("close");
  27392. settle();
  27393. check ("closing the end card ends the tour (not continued from Help)", ! tour->isRunning() && ! tour->canContinue()
  27394. && tour->machineForCheck().state().done);
  27395. line ("-- paused tour");
  27396. // --- a paused tour, the Help menu and the chooser's button ---------------------------------------------------------
  27397. offline.setSong (emptyProject());
  27398. settle();
  27399. tour->machineForCheck() = lynx::tour::Machine {};
  27400. simple->startOrContinueTour();
  27401. settle();
  27402. line ("-- do beat");
  27403. simple->doTourStep (lynx::tour::beat);
  27404. settle();
  27405. check ("a new tour on an empty project: the beat done moves it to the key", tour->step() == lynx::tour::key);
  27406. tour->clickForSnapshot ("close");
  27407. settle();
  27408. check ("closing the card pauses the tour (Help continues it)", ! tour->isRunning() && tour->canContinue());
  27409. line ("-- help menu");
  27410. {
  27411. const auto help = ui.getMenuForSnapshot (ui.getMenuNamesForSnapshot().indexOf (lynx::tr ("Help")));
  27412. bool continueItem = false, welcomeItem = false;
  27413. for (juce::PopupMenu::MenuItemIterator it (help); it.next();)
  27414. {
  27415. continueItem = continueItem || it.getItem().text.startsWith (lynx::tr ("Continue the first-song tour (step {0} of {1})", { "2", "7" }));
  27416. welcomeItem = welcomeItem || it.getItem().text == lynx::tr ("Welcome screen...");
  27417. }
  27418. check ("Help: Continue the first-song tour (step 2 of 7) and Welcome screen...", continueItem && welcomeItem);
  27419. saveMenus ({ lynx::tr ("Help") }, { help }, prefix + "-menu-help.png");
  27420. }
  27421. simple->startOrContinueTour();
  27422. settle();
  27423. check ("Help › Continue: back on the key step", tour->isRunning() && tour->step() == lynx::tour::key);
  27424. tour->clickForSnapshot ("skip");
  27425. settle();
  27426. check ("Skip tour ends it", ! tour->isRunning() && ! tour->canContinue());
  27427. offline.setSong (emptyProject());
  27428. settle();
  27429. simple->showChooser();
  27430. window ("chooser");
  27431. line ("-- start from");
  27432. // --- Start from: the three demo songs; a demo opened in Simple -------------------------------------------------------
  27433. if (auto* start = simple->startFromForSnapshot())
  27434. {
  27435. settle();
  27436. writeImage (start->createComponentSnapshot (start->getLocalBounds(), true, 1.0f), "startfrom");
  27437. const auto list = lynx::startfrom::entries();
  27438. int demos = 0;
  27439. for (const auto& e : list)
  27440. demos += e.kind == lynx::startfrom::Entry::Kind::demo && e.playable ? 1 : 0;
  27441. check ("Start from lists three playable demo songs first", demos == 3 && list.size() >= 3 && list[1].demo == 1 && list[2].demo == 2);
  27442. for (int d = 1; d < 3 && d < (int) list.size(); ++d)
  27443. 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");
  27444. simple->hideStartFrom();
  27445. }
  27446. line ("-- demos");
  27447. for (int d = 1; d < lynx::demos::count; ++d)
  27448. {
  27449. offline.setSong (lynx::demos::make (d));
  27450. settle();
  27451. simple->hideChooser();
  27452. window (juce::String ("demo-") + (d == 1 ? "hiphop" : "pop"));
  27453. // the committed file is the generated song
  27454. const auto file = juce::File::getCurrentWorkingDirectory().getChildFile ("resources/demos").getChildFile (lynx::demos::fileName (d));
  27455. juce::String error;
  27456. const auto loaded = lynx::ProjectFile::load (file, error);
  27457. check ("resources/demos/" + juce::String (lynx::demos::fileName (d)) + " loads and is the generated song",
  27458. loaded.has_value() && lynx::ProjectFile::toJson (*loaded, false) == lynx::ProjectFile::toJson (lynx::demos::make (d), false));
  27459. }
  27460. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  27461. juce::File (prefix + "-report.txt").replaceWithText (report);
  27462. }
  27463. // --patterns190ea (round 190ea): FL keeps at least one pattern; the engine now does too (AudioEngine::publishSong,
  27464. // Song::keepOnePattern). Before, a Song without a pattern crashed the docked Piano roll's listener.
  27465. bool runPatterns190ea (const juce::String& reportPath)
  27466. {
  27467. namespace st = lynx::simpletracks;
  27468. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27469. lynx::AudioEngine offline (false);
  27470. lynx::MainComponent ui (offline, false);
  27471. ui.setSize (1600, 900);
  27472. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  27473. juce::String report;
  27474. bool ok = true;
  27475. const auto check = [&report, &ok] (const juce::String& what, bool good) {
  27476. report << (good ? "OK " : "ERROR ") << what << "\n";
  27477. ok = ok && good;
  27478. };
  27479. const auto save = [&report, &reportPath] { juce::File (reportPath).replaceWithText (report); };
  27480. const auto settle = [&] { offline.dispatchPendingMessages(); ui.getPianoRollForSnapshot().repaint(); };
  27481. const auto onePattern = [&offline] {
  27482. const auto& s = offline.getSong();
  27483. return s.patterns.size() >= 1 && s.currentPattern >= 0 && s.currentPattern < (int) s.patterns.size();
  27484. };
  27485. // the hand-built songs the engine can be given: none of them has a pattern
  27486. const auto bare = [] {
  27487. lynx::Song s;
  27488. s.mixer = lynx::Song::defaultMixer();
  27489. return s;
  27490. };
  27491. // every way to reach "no pattern" in the current layout
  27492. const auto paths = [&] (const juce::String& where) {
  27493. offline.setSong (bare());
  27494. settle();
  27495. check (where + ": a song without a pattern opens with one empty \"Pattern 1\"",
  27496. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].name == "Pattern 1"
  27497. && offline.getSong().patterns[0].notes.empty());
  27498. offline.editSong ([] (lynx::Song& s) { s.patterns.clear(); });
  27499. settle();
  27500. check (where + ": an edit that clears every pattern leaves one", onePattern());
  27501. offline.editSong ([] (lynx::Song& s) {
  27502. s.patterns.resize (2);
  27503. s.patterns[1].notes.push_back ({});
  27504. s.currentPattern = 1;
  27505. });
  27506. settle();
  27507. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  27508. offline.editSong ([] (lynx::Song& s) { s.removePattern (s.currentPattern); });
  27509. settle();
  27510. check (where + ": deleting the last pattern leaves an empty \"Pattern 1\" (FL's invariant)",
  27511. onePattern() && offline.getSong().patterns.size() == 1 && offline.getSong().patterns[0].notes.empty());
  27512. for (int k = 0; k < 6; ++k)
  27513. {
  27514. offline.undo();
  27515. settle();
  27516. }
  27517. check (where + ": undo back over those steps keeps a pattern", onePattern());
  27518. for (int k = 0; k < 6; ++k)
  27519. {
  27520. offline.redo();
  27521. settle();
  27522. }
  27523. check (where + ": redo keeps a pattern", onePattern());
  27524. offline.applyRemote (bare());
  27525. settle();
  27526. check (where + ": a live session's remote song without a pattern gets one", onePattern());
  27527. offline.editSong ([] (lynx::Song& s) { s.currentPattern = 99; });
  27528. settle();
  27529. check (where + ": a current pattern out of range is put back in range", onePattern() && offline.getSong().currentPattern == 0);
  27530. };
  27531. // the Simple layout with the Piano roll docked in the Editor tab (round 190dv's crash)
  27532. ui.selectTabForSnapshot (2);
  27533. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  27534. settle();
  27535. auto* simple = ui.getSimpleWorkflowForSnapshot();
  27536. check ("the Simple workflow is up", simple != nullptr);
  27537. if (simple == nullptr)
  27538. {
  27539. save();
  27540. return false;
  27541. }
  27542. simple->hideChooser();
  27543. st::Request q;
  27544. q.kind = st::Kind::instrument;
  27545. q.name = "Keys";
  27546. lynx::ChannelDef synth;
  27547. synth.instrument = lynx::InstrumentKind::synth;
  27548. q.channel = synth;
  27549. q.emptyBars = 4;
  27550. st::Result r;
  27551. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  27552. settle();
  27553. ui.getPlaylistForSnapshot().selectTrack (r.track);
  27554. simple->trackSelected (r.track);
  27555. settle();
  27556. auto* dock = simple->dockForSnapshot();
  27557. check ("the instrument track's dock has the Editor tab", dock != nullptr && dock->hasPlayTabsForCheck());
  27558. if (dock != nullptr)
  27559. dock->setTab (lynx::SimpleDock::Tab::editor);
  27560. settle();
  27561. check ("the Piano roll is docked in the Editor tab", dock != nullptr && dock->isEditorDocked() && dock->isParentOf (&ui.getPianoRollForSnapshot()));
  27562. paths ("Simple, Editor tab");
  27563. // the Pattern layout with the Piano roll panel, then the Clip-launch layout
  27564. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  27565. settle();
  27566. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::pianoRoll });
  27567. settle();
  27568. paths ("Pattern layout, Piano roll");
  27569. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  27570. settle();
  27571. paths ("Clip-launch layout");
  27572. report << (ok ? "RESULT OK\n" : "RESULT FAILED\n");
  27573. save();
  27574. return ok;
  27575. }
  27576. // round 190fo: the Simple layout's Sampler track (16 pads) and a folder of stems and MIDI files, off-screen at 1x and
  27577. // 2x, with a text report of the checks (.lynx round trip, kits, typing keys, the folder import)
  27578. void runReabl190foShot (const juce::String& prefix)
  27579. {
  27580. namespace st = lynx::simpletracks;
  27581. namespace sp = lynx::simplepads;
  27582. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27583. lynx::AudioEngine offline (false);
  27584. lynx::MainComponent ui (offline, false);
  27585. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  27586. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  27587. ui.setVisible (true);
  27588. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  27589. const auto file = juce::File (prefix + "-" + name + ".png");
  27590. file.deleteFile();
  27591. juce::FileOutputStream out (file);
  27592. juce::PNGImageFormat().writeImageToStream (image, out);
  27593. };
  27594. juce::String report;
  27595. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  27596. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  27597. ui.selectTabForSnapshot (2);
  27598. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  27599. offline.dispatchPendingMessages();
  27600. auto* simple = ui.getSimpleWorkflowForSnapshot();
  27601. if (simple == nullptr)
  27602. {
  27603. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  27604. return;
  27605. }
  27606. const auto whole = [&] (const juce::String& name) {
  27607. offline.dispatchPendingMessages();
  27608. for (float scale : { 1.0f, 2.0f })
  27609. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
  27610. };
  27611. // the chooser: the Sampler tile (16 pads, "On keys..." for one sample over the keys) and Import's "Folder..."
  27612. simple->showChooser();
  27613. whole ("chooser");
  27614. simple->hideChooser();
  27615. // --- test sounds -------------------------------------------------------------------------------------------------
  27616. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190fo");
  27617. dir.deleteRecursively();
  27618. dir.createDirectory();
  27619. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  27620. juce::AudioBuffer<float> audio (1, frames);
  27621. for (int i = 0; i < frames; ++i)
  27622. audio.setSample (0, i, f (i));
  27623. wav.getParentDirectory().createDirectory();
  27624. juce::WavAudioFormat format;
  27625. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  27626. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  27627. {
  27628. out.release();
  27629. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  27630. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  27631. }
  27632. return wav;
  27633. };
  27634. juce::Random rnd (190);
  27635. const auto pi = juce::MathConstants<double>::pi;
  27636. const auto kick = writeWav (dir.getChildFile ("pads/Kick.wav"), 24000, [pi] (int i) {
  27637. const auto t = i / 48000.0;
  27638. 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));
  27639. });
  27640. 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)); });
  27641. 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)); });
  27642. const auto chord = writeWav (dir.getChildFile ("pads/Chord stab.wav"), 48000, [pi] (int i) {
  27643. const auto t = i / 48000.0;
  27644. double v = 0.0;
  27645. for (int k : { 57, 60, 64 })
  27646. v += std::sin (2.0 * pi * 440.0 * std::pow (2.0, (k - 69) / 12.0) * t);
  27647. return (float) (0.2 * v * std::exp (-t * 2.5));
  27648. });
  27649. const auto vox = writeWav (dir.getChildFile ("pads/Vox hey.wav"), 30000, [pi] (int i) {
  27650. const auto t = i / 48000.0;
  27651. 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));
  27652. });
  27653. // --- the Sampler track ---------------------------------------------------------------------------------------------
  27654. check ("the Sampler tile's track was added", simple->addPads());
  27655. offline.dispatchPendingMessages();
  27656. const auto& song0 = offline.getSong();
  27657. int track = -1;
  27658. for (int t = 0; t < (int) song0.playlistTracks.size() && track < 0; ++t)
  27659. if (st::kindOf (song0, t) == st::Kind::pads)
  27660. track = t;
  27661. check ("a Sampler track with 16 pads", track >= 0 && [&] {
  27662. const auto c = sp::padChannels (song0, track);
  27663. return std::all_of (c.begin(), c.end(), [] (int i) { return i >= 0; });
  27664. }());
  27665. auto* dock = simple->dockForSnapshot();
  27666. if (dock == nullptr || track < 0)
  27667. {
  27668. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock / track\n");
  27669. return;
  27670. }
  27671. simple->trackSelected (track);
  27672. offline.dispatchPendingMessages();
  27673. check ("the dock opens on the Pads tab", dock->hasPadsTabForCheck() && dock->getTab() == lynx::SimpleDock::Tab::pads);
  27674. const auto shots = [&] (const juce::String& name) {
  27675. offline.dispatchPendingMessages();
  27676. for (float scale : { 1.0f, 2.0f })
  27677. {
  27678. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  27679. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  27680. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  27681. }
  27682. };
  27683. shots ("pads-empty");
  27684. const juce::File files[] { kick, snare, hat, hat, chord, vox };
  27685. for (int p = 0; p < 6; ++p)
  27686. dock->padsLoadForCheck (p, files[p]);
  27687. offline.dispatchPendingMessages();
  27688. check ("six pads hold a sound", [&] {
  27689. int n = 0;
  27690. for (int p = 0; p < sp::padCount; ++p)
  27691. n += sp::hasSample (offline.getSong(), track, p) ? 1 : 0;
  27692. return n == 6;
  27693. }());
  27694. // pad 3 = the open hat: one-shot, group 1 with pad 2 (closed hat), a colour; pad 4 = the chord, looped and darker
  27695. dock->padsSelectForCheck (2);
  27696. dock->padsModeForCheck (1);
  27697. dock->padsSelectForCheck (3);
  27698. dock->padsModeForCheck (1);
  27699. offline.editSong ([track] (lynx::Song& s) {
  27700. for (int p : { 2, 3 })
  27701. if (const auto c = sp::padChannel (s, track, p); c >= 0)
  27702. {
  27703. s.channels[(std::size_t) c].simplePad.group = 1;
  27704. s.channels[(std::size_t) c].simplePad.colour = 2;
  27705. sp::apply (s.channels[(std::size_t) c], 4800);
  27706. }
  27707. });
  27708. dock->padsSelectForCheck (4);
  27709. dock->padsModeForCheck (2);
  27710. dock->padsKnobForCheck (2, 0.3f); // tone: a low-pass
  27711. dock->padsKnobForCheck (1, 0.35f); // release
  27712. dock->padsRegionForCheck (0.05f, 0.7f);
  27713. dock->padsNormalizeForCheck();
  27714. dock->padsUpdateForCheck();
  27715. {
  27716. const auto& s = offline.getSong();
  27717. const auto& c = s.channels[(std::size_t) sp::padChannel (s, track, 4)];
  27718. line ("pad 5: mode " + juce::String ((int) c.simplePad.mode) + " tone " + juce::String (c.simplePad.tone, 2) + " cutoff " + juce::String (c.sampler.cutoff, 0)
  27719. + " release " + juce::String (c.sampler.release, 3) + " region " + juce::String (c.sampler.regionStart, 2) + "-" + juce::String (c.sampler.regionEnd, 2)
  27720. + " gain " + juce::String (c.sampler.gainDb, 2) + " dB zones " + juce::String ((int) c.zones.size()));
  27721. 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
  27722. && c.sampler.filterType == 0 && c.sampler.cutoff < 5000.0f && c.sampler.gainDb > 0.5f);
  27723. const auto& h = s.channels[(std::size_t) sp::padChannel (s, track, 3)];
  27724. 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);
  27725. }
  27726. shots ("pads");
  27727. dock->padsHitForCheck (0);
  27728. dock->lightPad (2);
  27729. shots ("pads-hit");
  27730. // the typing keys: V plays pad 1, M pad 4, 7 pad 16; Z is not a pad key
  27731. check ("typing keys reach the pads", simple->padChannelForKey ('V') == sp::padChannel (offline.getSong(), track, 0)
  27732. && simple->padChannelForKey ('m') == sp::padChannel (offline.getSong(), track, 3)
  27733. && simple->padChannelForKey ('7') == sp::padChannel (offline.getSong(), track, 15)
  27734. && simple->padChannelForKey ('Z') == -1);
  27735. // drag pad 6 (vox) onto the empty pad 9: it moves; Alt-drag pad 1 onto pad 10: a copy
  27736. dock->padsDragForCheck (5, 8, false);
  27737. dock->padsDragForCheck (0, 9, true);
  27738. check ("a pad moved and a pad copied", ! sp::hasSample (offline.getSong(), track, 5) && sp::hasSample (offline.getSong(), track, 8)
  27739. && sp::hasSample (offline.getSong(), track, 9) && sp::hasSample (offline.getSong(), track, 0));
  27740. dock->padsSelectForCheck (4);
  27741. shots ("pads-moved");
  27742. saveMenus ({ "Pad menu", "Colour", "Copy a value to every pad" }, [&] {
  27743. const auto top = dock->padMenuForSnapshot (4);
  27744. std::vector<juce::PopupMenu> menus { top };
  27745. for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
  27746. if (it.getItem().subMenu != nullptr)
  27747. menus.push_back (*it.getItem().subMenu);
  27748. return menus;
  27749. }(), prefix + "-menu-pad.png");
  27750. // kits: saved, the pads cleared, opened again
  27751. const auto kitFile = lynx::platform::documentsFolder().getChildFile ("LYNX/Sampler kits/Test kit 190fo.lynxkit");
  27752. kitFile.deleteFile();
  27753. check ("the pads saved as a kit", dock->saveKitForCheck ("Test kit 190fo") && kitFile.existsAsFile());
  27754. saveMenus ({ "Kit", "My kits" }, [&] {
  27755. const auto top = dock->kitMenuForSnapshot();
  27756. std::vector<juce::PopupMenu> menus { top };
  27757. for (juce::PopupMenu::MenuItemIterator it (top); it.next();)
  27758. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("My kits"))
  27759. menus.push_back (*it.getItem().subMenu);
  27760. return menus;
  27761. }(), prefix + "-menu-kit.png");
  27762. const auto before = offline.getSong().channels;
  27763. offline.editSong ([track] (lynx::Song& s) {
  27764. for (int p = 0; p < sp::padCount; ++p)
  27765. sp::clearPad (s, track, p);
  27766. });
  27767. check ("the kit opens the same pads again", dock->openKitForCheck (kitFile) && [&] {
  27768. const auto& now = offline.getSong().channels;
  27769. for (int p = 0; p < sp::padCount; ++p)
  27770. {
  27771. const auto c = sp::padChannel (offline.getSong(), track, p);
  27772. 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
  27773. || 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)
  27774. return false;
  27775. }
  27776. return true;
  27777. }());
  27778. {
  27779. const auto renamed = kitFile.getSiblingFile ("Renamed kit 190fo.lynxkit");
  27780. renamed.deleteFile();
  27781. check ("a kit renamed (and a one-letter name refused)", ! lynx::SimpleDock::renameKitForCheck (kitFile, "x")
  27782. && lynx::SimpleDock::renameKitForCheck (kitFile, "Renamed kit 190fo") && renamed.existsAsFile()
  27783. && ! kitFile.exists());
  27784. renamed.deleteFile();
  27785. }
  27786. kitFile.deleteFile();
  27787. // a beat on the pads (the track's pattern) and the .lynx round trip
  27788. offline.editSong ([track] (lynx::Song& s) {
  27789. const auto pattern = [&] {
  27790. for (const auto& c : s.playlist)
  27791. if (c.track == track && c.kind == lynx::ClipKind::pattern)
  27792. return c.pattern;
  27793. return -1;
  27794. }();
  27795. if (pattern < 0)
  27796. return;
  27797. for (int step = 0; step < 16; ++step)
  27798. {
  27799. const int pad = step % 4 == 0 ? 0 : step % 8 == 4 ? 1 : 2;
  27800. lynx::Note n;
  27801. n.channel = sp::padChannel (s, track, pad);
  27802. n.key = sp::padKey;
  27803. n.start = (std::int64_t) step * lynx::ticksPerStep;
  27804. n.length = lynx::ticksPerStep;
  27805. s.patterns[(std::size_t) pattern].notes.push_back (n);
  27806. }
  27807. });
  27808. {
  27809. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  27810. juce::String error;
  27811. const auto back = lynx::ProjectFile::fromJson (json, error);
  27812. bool same = back.has_value() && back->channels.size() == offline.getSong().channels.size() && st::kindOf (*back, track) == st::Kind::pads;
  27813. for (std::size_t c = 0; same && c < back->channels.size(); ++c)
  27814. {
  27815. const auto& a = back->channels[c];
  27816. const auto& b = offline.getSong().channels[c];
  27817. same = a.simplePad == b.simplePad && a.zones == b.zones && a.cutGroup == b.cutGroup && a.cutBy == b.cutBy && a.samplePath == b.samplePath
  27818. && a.sampler.regionStart == b.sampler.regionStart && a.sampler.release == b.sampler.release && a.sampler.cutoff == b.sampler.cutoff;
  27819. }
  27820. check ("pads, their modes, groups and loops survive .lynx", same);
  27821. lynx::Song plain = lynx::Song::makeDefault();
  27822. check ("a project without pads writes no pad field", ! lynx::ProjectFile::toJson (plain).contains ("simplePad"));
  27823. }
  27824. ui.getPlaylistForSnapshot().selectTrack (track);
  27825. // --- a folder of stems and MIDI files (the other app's "download stems" naming) --------------------------------------
  27826. const auto stems = dir.getChildFile ("My song stems");
  27827. writeWav (stems.getChildFile ("01_Drums.wav"), 96000, [&rnd] (int i) { return (i % 24000) < 2000 ? (rnd.nextFloat() - 0.5f) * 0.8f : 0.0f; });
  27828. writeWav (stems.getChildFile ("02_Bass.wav"), 96000, [pi] (int i) { return (float) (0.3 * std::sin (2.0 * pi * 55.0 * i / 48000.0)); });
  27829. 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)); });
  27830. {
  27831. juce::MidiMessageSequence seq;
  27832. for (int k = 0; k < 8; ++k)
  27833. {
  27834. seq.addEvent (juce::MidiMessage::noteOn (1, 36 + (k % 4) * 3, (juce::uint8) 100), k * 480.0);
  27835. seq.addEvent (juce::MidiMessage::noteOff (1, 36 + (k % 4) * 3), k * 480.0 + 400.0);
  27836. }
  27837. seq.updateMatchedPairs();
  27838. juce::MidiFile midi;
  27839. midi.setTicksPerQuarterNote (960);
  27840. midi.addTrack (seq);
  27841. for (const auto& name : { "02_Bass.mid", "03_Keys.mid" })
  27842. {
  27843. juce::FileOutputStream out (stems.getChildFile (name));
  27844. midi.writeTo (out);
  27845. }
  27846. }
  27847. const auto tracksBefore = [&] {
  27848. int n = 0;
  27849. for (int t = 0; t < (int) offline.getSong().playlistTracks.size(); ++t)
  27850. n += st::kindOf (offline.getSong(), t).has_value() ? 1 : 0;
  27851. return n;
  27852. }();
  27853. simple->addFilesForCheck ({ stems });
  27854. offline.dispatchPendingMessages();
  27855. {
  27856. const auto& s = offline.getSong();
  27857. juce::StringArray names;
  27858. int muted = 0, count = 0;
  27859. for (int t = 0; t < (int) s.playlistTracks.size(); ++t)
  27860. if (st::kindOf (s, t).has_value())
  27861. {
  27862. ++count;
  27863. if (count > tracksBefore)
  27864. {
  27865. names.add (juce::String::fromUTF8 (s.playlistTracks[(std::size_t) t].name.c_str()) + (s.playlistTracks[(std::size_t) t].muted ? " (muted)" : ""));
  27866. muted += s.playlistTracks[(std::size_t) t].muted ? 1 : 0;
  27867. }
  27868. }
  27869. line ("folder tracks: " + names.joinIntoString (", "));
  27870. check ("the folder gave 5 tracks in number order, named without numbers, the Bass notes muted (its stem plays)",
  27871. names == juce::StringArray { "Drums", "Bass", "Lead Vox", "Bass 2 (muted)", "Keys" } && muted == 1);
  27872. bool atZero = true;
  27873. for (const auto& c : s.playlist)
  27874. if (c.track >= 0 && st::kindOf (s, c.track) == st::Kind::audio)
  27875. atZero = atZero && c.start == 0;
  27876. check ("every stem starts at the song's start", atZero);
  27877. }
  27878. simple->hideChooser();
  27879. whole ("folder-import");
  27880. dir.deleteRecursively();
  27881. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  27882. juce::File (prefix + "-report.txt").replaceWithText (report);
  27883. }
  27884. void runSimple190dsShot (const juce::String& prefix)
  27885. {
  27886. namespace st = lynx::simpletracks;
  27887. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  27888. lynx::AudioEngine offline (false);
  27889. lynx::MainComponent ui (offline, false);
  27890. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  27891. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  27892. ui.setVisible (true); // (no window: the docked editor only needs its parents visible)
  27893. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  27894. const auto file = juce::File (prefix + "-" + name + ".png");
  27895. file.deleteFile();
  27896. juce::FileOutputStream out (file);
  27897. juce::PNGImageFormat().writeImageToStream (image, out);
  27898. };
  27899. juce::String report;
  27900. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  27901. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  27902. ui.selectTabForSnapshot (2);
  27903. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  27904. offline.dispatchPendingMessages();
  27905. auto* simple = ui.getSimpleWorkflowForSnapshot();
  27906. if (simple == nullptr)
  27907. {
  27908. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  27909. return;
  27910. }
  27911. simple->hideChooser();
  27912. auto& playlist = ui.getPlaylistForSnapshot();
  27913. // --- three loops: two with their key in the name, one only in its sound ---------------------------------------
  27914. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190ds-loops");
  27915. dir.deleteRecursively();
  27916. dir.createDirectory();
  27917. // a chord loop (two bars at 120 BPM, 48 kHz): each chord's notes with six harmonics, a soft attack per beat
  27918. const auto writeLoop = [&dir] (const juce::String& name, std::vector<std::vector<int>> chords) {
  27919. const int frames = 192000;
  27920. juce::AudioBuffer<float> audio (1, frames);
  27921. audio.clear();
  27922. for (int i = 0; i < frames; ++i)
  27923. {
  27924. const auto& chord = chords[(std::size_t) (i / (frames / (int) chords.size()))];
  27925. const auto t = (double) i / 48000.0;
  27926. const auto beat = std::fmod (t, 0.5);
  27927. double v = 0.0;
  27928. for (const auto key : chord)
  27929. {
  27930. const auto f = 440.0 * std::pow (2.0, (key - 69) / 12.0);
  27931. for (int h = 1; h <= 6; ++h)
  27932. v += std::sin (2.0 * juce::MathConstants<double>::pi * f * h * t) / (h * h);
  27933. }
  27934. audio.setSample (0, i, (float) (0.08 * v * (1.0 - std::exp (-beat * 60.0)) * (0.6 + 0.4 * std::exp (-beat * 3.0))));
  27935. }
  27936. const auto wav = dir.getChildFile (name);
  27937. juce::WavAudioFormat format;
  27938. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  27939. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  27940. {
  27941. out.release();
  27942. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  27943. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  27944. }
  27945. return wav.getFullPathName();
  27946. };
  27947. const auto gMinor = writeLoop ("Night Pad 120 Gm.wav", { { 55, 58, 62 }, { 51, 55, 58 }, { 53, 57, 60 }, { 55, 58, 62 } });
  27948. const auto dMinor = writeLoop ("Pluck_120_D_minor.wav", { { 50, 53, 57 }, { 46, 50, 53 }, { 48, 52, 55 }, { 50, 53, 57 } });
  27949. 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 } });
  27950. lynx::SimpleWorkflow::answerForSnapshot = 1; // "Set the project key to G minor?" — yes
  27951. simple->dropFiles ({ gMinor, dMinor, eMinor }, 0);
  27952. lynx::SimpleWorkflow::answerForSnapshot = -1;
  27953. offline.dispatchPendingMessages();
  27954. simple->hideChooser();
  27955. line ("question: " + simple->lastKeyQuestionForCheck());
  27956. check ("the first keyed loop offered its key (G minor)", simple->lastKeyQuestionForCheck().contains ("G minor"));
  27957. {
  27958. const auto& song = offline.getSong();
  27959. const auto key = lynx::projectkey::get (song);
  27960. check ("the project key is G minor", key && key->root == 7 && lynx::projectkey::isMinor (*key));
  27961. std::vector<int> clips;
  27962. for (int i = 0; i < (int) song.playlist.size(); ++i)
  27963. if (song.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  27964. clips.push_back (i);
  27965. check ("three loop clips", clips.size() == 3);
  27966. const int expect[] { 0, 5, 3 }; // G minor, D minor (F -> Bb: +5), E minor detected (G -> Bb: +3)
  27967. const int roots[] { 7, 2, 4 };
  27968. const int sources[] { 1, 1, 2 };
  27969. for (std::size_t k = 0; k < clips.size() && k < 3; ++k)
  27970. {
  27971. const auto& c = song.playlist[(std::size_t) clips[k]];
  27972. const auto& sampler = song.channels[(std::size_t) c.channel].sampler;
  27973. line ("loop " + juce::String ((int) k + 1) + ": key " + juce::String (sampler.loopKeyRoot) + (sampler.loopKeyMinor ? "m" : "") + " source "
  27974. + juce::String ((int) sampler.loopKeySource) + " follow " + juce::String (c.followKey ? 1 : 0) + " shift " + juce::String ((int) c.keyShift)
  27975. + " pitch " + juce::String (c.pitch));
  27976. check ("loop " + juce::String ((int) k + 1) + " key, source and move", sampler.loopKeyRoot == roots[k] && sampler.loopKeyMinor
  27977. && sampler.loopKeySource == sources[k] && c.followKey
  27978. && c.keyShift == expect[k] && std::abs (c.pitch - (float) expect[k]) < 1.0e-4f);
  27979. }
  27980. }
  27981. // the key changes: every following loop moves with it (one undo step)
  27982. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, lynx::projectkey::Key { 9, lynx::projectkey::commonFirst()[1] }); });
  27983. offline.dispatchPendingMessages();
  27984. {
  27985. const auto& song = offline.getSong();
  27986. std::vector<int> shifts;
  27987. for (const auto& c : song.playlist)
  27988. if (c.kind == lynx::ClipKind::audio)
  27989. shifts.push_back (c.keyShift);
  27990. line ("after A minor: " + juce::String (shifts.size() > 2 ? shifts[0] : 99) + " " + juce::String (shifts.size() > 2 ? shifts[1] : 99) + " "
  27991. + juce::String (shifts.size() > 2 ? shifts[2] : 99));
  27992. check ("A minor: the loops move by +2, -5, +5", shifts == std::vector<int> { 2, -5, 5 });
  27993. }
  27994. // the loop tracks in the dock: the switch and what it does
  27995. int loopTrack = -1;
  27996. for (const auto& c : offline.getSong().playlist)
  27997. if (c.kind == lynx::ClipKind::audio && loopTrack < 0)
  27998. loopTrack = c.track;
  27999. playlist.selectTrack (loopTrack);
  28000. offline.dispatchPendingMessages();
  28001. auto* dock = simple->dockForSnapshot();
  28002. if (dock == nullptr)
  28003. {
  28004. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  28005. return;
  28006. }
  28007. simple->trackSelected (loopTrack);
  28008. offline.dispatchPendingMessages();
  28009. const auto shots = [&] (const juce::String& name) {
  28010. offline.dispatchPendingMessages();
  28011. for (float scale : { 1.0f, 2.0f })
  28012. {
  28013. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  28014. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  28015. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  28016. }
  28017. };
  28018. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  28019. juce::StringArray names { title };
  28020. std::vector<juce::PopupMenu> menus { menu };
  28021. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  28022. if (it.getItem().subMenu != nullptr && it.getItem().text.startsWith (subTitle))
  28023. {
  28024. names.add (subTitle);
  28025. menus.push_back (*it.getItem().subMenu);
  28026. }
  28027. saveMenus (names, menus, prefix + "-" + name + ".png");
  28028. };
  28029. check ("the dock shows the follow switch for the loop track", dock->followShownForCheck());
  28030. shots ("follow-on");
  28031. {
  28032. int clip = -1;
  28033. for (int i = 0; i < (int) offline.getSong().playlist.size() && clip < 0; ++i)
  28034. if (offline.getSong().playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  28035. clip = i;
  28036. const auto menu = playlist.getClipMenuForSnapshot (clip);
  28037. bool follow = false, keyItem = false;
  28038. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  28039. {
  28040. follow = follow || (it.getItem().text.startsWith (lynx::tr ("Follow the project key")) && it.getItem().isTicked);
  28041. keyItem = keyItem || it.getItem().text.startsWith (lynx::tr ("Loop key"));
  28042. }
  28043. check ("the clip menu has Follow the project key (ticked) and Loop key", follow && keyItem);
  28044. menuShot (menu, lynx::tr ("Audio clip"), lynx::tr ("Loop key"), "menu-clip-key");
  28045. }
  28046. dock->clickFollowForCheck(); // off: back to its own key
  28047. offline.dispatchPendingMessages();
  28048. {
  28049. float pitch = 99.0f;
  28050. bool following = true;
  28051. for (const auto& c : offline.getSong().playlist)
  28052. if (c.kind == lynx::ClipKind::audio && c.track == loopTrack)
  28053. pitch = c.pitch, following = c.followKey;
  28054. check ("switched off: the loop plays in its own key (pitch 0)", ! following && std::abs (pitch) < 1.0e-6f);
  28055. }
  28056. shots ("follow-off");
  28057. dock->clickFollowForCheck();
  28058. offline.dispatchPendingMessages();
  28059. // --- an instrument track from the tile: a pattern to write into, the Editor tab ------------------------------
  28060. {
  28061. st::Request q;
  28062. q.kind = st::Kind::instrument;
  28063. q.name = "Keys";
  28064. lynx::ChannelDef synth;
  28065. synth.instrument = lynx::InstrumentKind::synth;
  28066. q.channel = synth;
  28067. q.emptyBars = 4;
  28068. st::Result r;
  28069. offline.editSong ([&] (lynx::Song& s) { r = st::addTrack (s, q); });
  28070. offline.dispatchPendingMessages();
  28071. check ("the new Instrument track has an empty 4-bar pattern on it", r.ok() && r.pattern >= 0
  28072. && st::patternOf (offline.getSong(), r.track) == r.pattern
  28073. && offline.getSong().patterns[(std::size_t) r.pattern].notes.empty());
  28074. // a few notes, as the first clicks would write them (A minor: A C E, then G B D)
  28075. offline.editSong ([r] (lynx::Song& s) {
  28076. auto& p = s.patterns[(std::size_t) r.pattern];
  28077. const int keys[] { 57, 60, 64, 67, 71, 74, 69, 72 };
  28078. for (int i = 0; i < 8; ++i)
  28079. {
  28080. lynx::Note n;
  28081. n.channel = r.channels.front();
  28082. n.key = keys[i];
  28083. n.start = (std::int64_t) (i / 3) * lynx::ppq * 2 + (i % 3 == 0 ? 0 : 0);
  28084. n.length = lynx::ppq * 2;
  28085. n.velocity = 0.8f;
  28086. p.notes.push_back (n);
  28087. }
  28088. p.sortNotes();
  28089. });
  28090. offline.dispatchPendingMessages();
  28091. playlist.selectTrack (r.track);
  28092. simple->trackSelected (r.track);
  28093. offline.dispatchPendingMessages();
  28094. check ("the instrument track has the Keyboard and Editor tabs", dock->hasPlayTabsForCheck());
  28095. dock->setTab (lynx::SimpleDock::Tab::editor);
  28096. offline.dispatchPendingMessages();
  28097. check ("the Piano roll is docked in the Editor tab", dock->isEditorDocked());
  28098. check ("on the track's pattern", offline.getSong().currentPattern == r.pattern);
  28099. ui.getPianoRollForSnapshot().scrollToNotes(); // (done asynchronously when it docks)
  28100. shots ("editor");
  28101. dock->clickFoldForCheck (true); // "Only notes in key"
  28102. check ("Only notes in key folds the rows to A minor", ui.getPianoRollForSnapshot().isFoldedToScale());
  28103. ui.getPianoRollForSnapshot().scrollToNotes();
  28104. shots ("editor-in-key");
  28105. dock->clickFoldForCheck (false);
  28106. // --- the keyboard's modes ------------------------------------------------------------------------------
  28107. auto& keyboard = lynx::scalekeys::current();
  28108. const auto saved = keyboard;
  28109. keyboard = {};
  28110. keyboard.lockToKey = true;
  28111. dock->setTab (lynx::SimpleDock::Tab::keyboard);
  28112. if (auto* panel = dock->keyboardPanelForSnapshot())
  28113. {
  28114. lynx::refreshKeyboardPanel (*panel);
  28115. shots ("keys-locked");
  28116. keyboard.lockToKey = false;
  28117. keyboard.mode = lynx::scalekeys::Mode::scaleKeys;
  28118. lynx::refreshKeyboardPanel (*panel);
  28119. shots ("scale-keys");
  28120. keyboard.mode = lynx::scalekeys::Mode::chordPad;
  28121. keyboard.complexity = lynx::scalekeys::Complexity::seventh;
  28122. keyboard.strumMs = 40;
  28123. lynx::refreshKeyboardPanel (*panel);
  28124. shots ("chord-pad");
  28125. }
  28126. check ("the Keyboard tab shows the keyboard panel", dock->keyboardPanelForSnapshot() != nullptr);
  28127. // the same panel as the Touch keyboard window, each mode with a key / pad held
  28128. for (const auto& [mode, name, pressed] : { std::tuple { lynx::scalekeys::Mode::scaleKeys, juce::String ("window-scale-keys"), 4 },
  28129. std::tuple { lynx::scalekeys::Mode::chordPad, juce::String ("window-chord-pad"), 3 } })
  28130. {
  28131. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, mode, pressed, [ch = r.channels.front()] { return ch; });
  28132. panel->setSize (1100, 260);
  28133. for (float scale : { 1.0f, 2.0f })
  28134. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), name + (scale > 1.0f ? "@2x" : ""));
  28135. if (mode == lynx::scalekeys::Mode::chordPad)
  28136. menuShot (lynx::chordPadMenuForSnapshot (*panel, 3), lynx::tr ("Edit chord"), lynx::tr ("Chord type"), "menu-chord-edit");
  28137. }
  28138. // the Chord pad on an FL Studio Mobile chord set (the default set's shape: C Dm Em F G Am B° C)
  28139. {
  28140. 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})");
  28141. check ("an FLM chord set reads as 8 chords (B diminished)", set.size() == 8 && set[6].quality == 3);
  28142. offline.editSong ([set] (lynx::Song& s) { s.keyboardChords = set; });
  28143. keyboard.projectChords = true;
  28144. keyboard.complexity = lynx::scalekeys::Complexity::triad;
  28145. auto panel = lynx::makeKeyboardPanelForSnapshot (offline, lynx::scalekeys::Mode::chordPad, 5, [ch = r.channels.front()] { return ch; });
  28146. panel->setSize (1100, 260);
  28147. for (float scale : { 1.0f, 2.0f })
  28148. writeImage (panel->createComponentSnapshot (panel->getLocalBounds(), true, scale), juce::String ("window-chord-set") + (scale > 1.0f ? "@2x" : ""));
  28149. }
  28150. // the typing keys in each mode (A minor; Z = the root)
  28151. {
  28152. const auto& song = offline.getSong();
  28153. lynx::scalekeys::Settings s;
  28154. s.mode = lynx::scalekeys::Mode::scaleKeys;
  28155. juce::String z;
  28156. for (const int typed : { 60, 62, 64, 65, 67, 69, 71, 72, 61 })
  28157. {
  28158. const auto n = lynx::scalekeys::typedNotes (song, s, typed, 60);
  28159. z << (n.empty() ? juce::String ("-") : juce::String (n.front())) << " ";
  28160. }
  28161. line ("Scale keys, typing C D E F G A B C C#: " + z);
  28162. check ("Scale keys: the white typing keys play A minor from A", z.trim() == "69 71 72 74 76 77 79 81 -");
  28163. s.mode = lynx::scalekeys::Mode::chordPad;
  28164. s.projectChords = false;
  28165. const auto pad = lynx::scalekeys::typedNotes (song, s, 60, 60);
  28166. check ("Chord pad: Z plays A minor (A C E)", pad == std::vector<int> { 69, 72, 76 });
  28167. }
  28168. keyboard = saved;
  28169. }
  28170. // --- the project round trip --------------------------------------------------------------------------------
  28171. {
  28172. const auto json = lynx::ProjectFile::toJson (offline.getSong());
  28173. juce::String error;
  28174. const auto back = lynx::ProjectFile::fromJson (json, error);
  28175. bool same = back.has_value() && back->keyboardChords == offline.getSong().keyboardChords && back->playlist.size() == offline.getSong().playlist.size();
  28176. for (std::size_t i = 0; same && i < back->playlist.size(); ++i)
  28177. same = back->playlist[i].followKey == offline.getSong().playlist[i].followKey && back->playlist[i].keyShift == offline.getSong().playlist[i].keyShift
  28178. && back->playlist[i].pitch == offline.getSong().playlist[i].pitch;
  28179. for (std::size_t c = 0; same && c < back->channels.size(); ++c)
  28180. same = back->channels[c].sampler.loopKeyRoot == offline.getSong().channels[c].sampler.loopKeyRoot
  28181. && back->channels[c].sampler.loopKeySource == offline.getSong().channels[c].sampler.loopKeySource;
  28182. check ("follow, key moves, loop keys and the chord set survive .lynx", same);
  28183. }
  28184. dir.deleteRecursively();
  28185. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  28186. juce::File (prefix + "-report.txt").replaceWithText (report);
  28187. }
  28188. void runSimple190dgShot (const juce::String& prefix)
  28189. {
  28190. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28191. lynx::AudioEngine offline (false);
  28192. lynx::MainComponent ui (offline, false);
  28193. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  28194. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  28195. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  28196. const auto file = juce::File (prefix + "-" + name + ".png");
  28197. file.deleteFile();
  28198. juce::FileOutputStream out (file);
  28199. juce::PNGImageFormat().writeImageToStream (image, out);
  28200. };
  28201. juce::String report;
  28202. const auto line = [&report] (const juce::String& text) { report << text << "\n"; };
  28203. const auto check = [&report] (const juce::String& what, bool ok) { report << (ok ? "OK " : "ERROR ") << what << "\n"; };
  28204. ui.selectTabForSnapshot (2);
  28205. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  28206. offline.dispatchPendingMessages();
  28207. auto* simple = ui.getSimpleWorkflowForSnapshot();
  28208. if (simple == nullptr)
  28209. {
  28210. juce::File (prefix + "-report.txt").replaceWithText ("ERROR no Simple workflow\n");
  28211. return;
  28212. }
  28213. simple->hideChooser();
  28214. offline.editSong ([] (lynx::Song& s) {
  28215. namespace st = lynx::simpletracks;
  28216. st::Request q;
  28217. q.kind = st::Kind::voice;
  28218. q.name = "Lead vocal";
  28219. st::addTrack (s, q);
  28220. q = {};
  28221. q.kind = st::Kind::instrument;
  28222. q.name = "Keys";
  28223. lynx::ChannelDef keys;
  28224. keys.instrument = lynx::InstrumentKind::synth;
  28225. q.channel = keys;
  28226. st::addTrack (s, q);
  28227. });
  28228. offline.dispatchPendingMessages();
  28229. simple->hideChooser();
  28230. auto& playlist = ui.getPlaylistForSnapshot();
  28231. int voiceTrack = -1, keysTrack = -1;
  28232. {
  28233. const auto& song = offline.getSong();
  28234. for (int t = 0; t < (int) song.playlistTracks.size(); ++t)
  28235. if (const auto kind = lynx::simpletracks::kindOf (song, t))
  28236. {
  28237. if (*kind == lynx::simpletracks::Kind::audio && voiceTrack < 0)
  28238. voiceTrack = t;
  28239. else if (*kind == lynx::simpletracks::Kind::instrument && keysTrack < 0)
  28240. keysTrack = t;
  28241. }
  28242. }
  28243. check ("two Simple tracks (voice, keys)", voiceTrack >= 0 && keysTrack >= 0);
  28244. playlist.selectTrack (voiceTrack);
  28245. offline.dispatchPendingMessages();
  28246. auto* dock = simple->dockForSnapshot();
  28247. if (dock == nullptr)
  28248. {
  28249. juce::File (prefix + "-report.txt").replaceWithText (report + "ERROR no dock\n");
  28250. return;
  28251. }
  28252. const auto shots = [&] (const juce::String& name) {
  28253. offline.dispatchPendingMessages();
  28254. for (float scale : { 1.0f, 2.0f })
  28255. {
  28256. const auto suffix = scale > 1.0f ? juce::String ("@2x") : juce::String();
  28257. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, scale), name + suffix);
  28258. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + suffix);
  28259. }
  28260. };
  28261. const auto menuShot = [&] (const juce::PopupMenu& menu, const juce::String& title, const juce::String& subTitle, const juce::String& name) {
  28262. juce::StringArray names { title };
  28263. std::vector<juce::PopupMenu> menus { menu };
  28264. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  28265. if (it.getItem().subMenu != nullptr && it.getItem().text == subTitle)
  28266. {
  28267. names.add (subTitle);
  28268. menus.push_back (*it.getItem().subMenu);
  28269. }
  28270. saveMenus (names, menus, prefix + "-" + name + ".png");
  28271. };
  28272. const auto insert = dock->insertForCheck();
  28273. // --- every one-knob effect as a card, each at a knob position of its own -------------------------------------
  28274. const float at[] { 0.0f, 0.55f, 0.40f, 0.70f, 0.30f, 0.60f, 0.45f, 0.35f, 0.80f };
  28275. for (int id = 1; id <= lynx::goals::count; ++id)
  28276. dock->addOneKnobForCheck (id);
  28277. offline.dispatchPendingMessages();
  28278. for (int id = 1; id <= lynx::goals::count; ++id)
  28279. dock->turnKnobForCheck (id - 1, at[id]);
  28280. offline.dispatchPendingMessages();
  28281. check ("eight one-knob cards on the insert", dock->cardCountForCheck() == 8 && dock->oneKnobCardsForCheck() == 8);
  28282. {
  28283. const auto& fx = offline.getSong().mixer[(std::size_t) insert].effects;
  28284. bool turned = fx.size() == 8;
  28285. for (std::size_t i = 0; turned && i < fx.size(); ++i)
  28286. turned = lynx::goals::active (fx[i]) && std::abs (fx[i].goalAmount - at[i + 1]) < 1.0e-6f;
  28287. check ("each knob wrote its effect's parameters", turned);
  28288. }
  28289. shots ("effects-all");
  28290. offline.dispatchPendingMessages();
  28291. for (int card = 0; card < dock->cardCountForCheck(); ++card)
  28292. {
  28293. const auto area = dock->cardBoundsForSnapshot (card);
  28294. const auto name = juce::String (lynx::goals::name (card + 1)).toLowerCase();
  28295. check ("card " + juce::String (card + 1) + " (" + name + ") is on screen", ! area.isEmpty() && dock->getLocalBounds().contains (area));
  28296. for (float scale : { 1.0f, 2.0f })
  28297. writeImage (dock->createComponentSnapshot (area.expanded (4), true, scale), "card-" + name + (scale > 1.0f ? "@2x" : ""));
  28298. }
  28299. // --- a chain preset with Blend --------------------------------------------------------------------------------
  28300. if (const auto* preset = lynx::chains::find ("Canyon"))
  28301. offline.editSongStructural ([insert, preset] (lynx::Song& s) { lynx::chains::apply (s, insert, *preset); });
  28302. offline.dispatchPendingMessages();
  28303. dock->setBlendForCheck (0.6f);
  28304. offline.dispatchPendingMessages();
  28305. check ("preset Canyon with Blend 60 % (shown as edited)", offline.getSong().mixer[(std::size_t) insert].chainPreset == "Canyon"
  28306. && std::abs (offline.getSong().mixer[(std::size_t) insert].chainBlend - 0.6f) < 1.0e-6f
  28307. && ! lynx::chains::unchanged (offline.getSong(), insert));
  28308. shots ("effects-preset-blend");
  28309. // favourites: the track's preset starred; the menu lists it first
  28310. const auto favFile = lynx::SimpleDock::favouritesFile();
  28311. const auto hadFavourites = favFile.existsAsFile();
  28312. const auto oldFavourites = favFile.loadFileAsString();
  28313. lynx::SimpleDock::setFavouritePreset ("Canyon", true);
  28314. lynx::SimpleDock::setFavouritePreset ("Clear Voice", true);
  28315. lynx::SimpleDock::setFavouritePreset ("Canyon", true); // (twice: once in the list)
  28316. check ("two favourites kept, in order", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Canyon", "Clear Voice" });
  28317. {
  28318. bool first = false, toggle = false;
  28319. const auto menu = dock->presetMenuForSnapshot();
  28320. juce::PopupMenu::MenuItemIterator it (menu);
  28321. if (it.next())
  28322. first = it.getItem().subMenu != nullptr && it.getItem().text.contains (lynx::tr ("Favourites"));
  28323. for (juce::PopupMenu::MenuItemIterator all (menu); all.next();)
  28324. toggle = toggle || all.getItem().text == lynx::tr ("Remove \"{0}\" from favourites", { "Canyon" });
  28325. check ("the Preset menu starts with the favourites and offers to unstar the track's preset", first && toggle);
  28326. menuShot (menu, lynx::tr ("Preset"), juce::String::fromUTF8 ("\xe2\x98\x85 ") + lynx::tr ("Favourites"), "menu-preset-favourites");
  28327. }
  28328. lynx::SimpleDock::setFavouritePreset ("Canyon", false);
  28329. check ("unstarred", lynx::SimpleDock::favouritePresets() == juce::StringArray { "Clear Voice" });
  28330. if (hadFavourites)
  28331. favFile.replaceWithText (oldFavourites);
  28332. else
  28333. favFile.deleteFile();
  28334. // --- the sound picker: a search, and the installed plugins -----------------------------------------------------
  28335. playlist.selectTrack (keysTrack);
  28336. offline.dispatchPendingMessages();
  28337. check ("the Keys track opens on its sound", dock->getTab() == lynx::SimpleDock::Tab::instrument);
  28338. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::bass);
  28339. dock->setSearchForSnapshot ("sub");
  28340. offline.dispatchPendingMessages();
  28341. line ("search \"sub\" in Bass: " + juce::String (dock->soundRowsForCheck()) + " rows");
  28342. check ("a search narrows the category", dock->soundRowsForCheck() > 0 && dock->soundRowsForCheck() < (int) lynx::soundlib::filter (lynx::soundlib::builtIn(), lynx::soundlib::Category::bass).size());
  28343. shots ("picker-search");
  28344. dock->setSearchForSnapshot ({});
  28345. // a made-up list of installed plugins (nothing is scanned or loaded)
  28346. dock->setPluginsForSnapshot ({ { "VST3-demo-1", "Analog Mono", "Example Audio", "VST3", "Instrument|Synth" },
  28347. { "VST3-demo-2", "Grand Upright", "Example Audio", "VST3", "Instrument|Piano" },
  28348. { "VST3-demo-3", "Beat Kit 808", "Sample Lab", "VST3", "Instrument|Drum" },
  28349. { "CLAP-demo-4", "Orchestra Strings", "Sample Lab", "CLAP", "Instrument|Sampler" },
  28350. { "VST3-demo-5", "Wave Table One", "Example Audio", "VST3", "Instrument|Synth" },
  28351. { "VST-demo-6", "Sub Bass Machine", "Low End", "VST", "Synth" },
  28352. { "VST3-demo-7", "Sample Player", "Sample Lab", "VST3", "Instrument|Sampler" } });
  28353. dock->showCategoryForSnapshot ((int) lynx::soundlib::Category::synths);
  28354. offline.dispatchPendingMessages();
  28355. check ("My plugins: the generic synths and samplers in their own category (" + juce::String (dock->soundRowsForCheck()) + " of 7)", dock->soundRowsForCheck() == 3);
  28356. shots ("picker-plugins");
  28357. line (report.contains ("ERROR ") ? "RESULT ERROR" : "RESULT OK");
  28358. juce::File (prefix + "-report.txt").replaceWithText (report);
  28359. }
  28360. // LYNX --simple190jcshot prefix (round 190jc, design190ia slices 5, 14, 15, 22, 24 + Large controls): the Simple
  28361. // layout's tracks (only real rows, the round "+", M S, type icons, the track-colour volume and clips; muted, soloed,
  28362. // selected), the drop lane idle and lit, the dock (close X, icon tabs, a lone tab, the sound picker, the keyboard's
  28363. // keycaps and octave capsule, effect cards), the pads in all 8 colours (label contrast measured), the chooser,
  28364. // starter beats, Finish, the tour card beside its ring with the beacon (Animations on / off), and Large controls;
  28365. // windows at 1x and 2x, and a text report of the checks
  28366. void runSimple190jcShot (const juce::String& prefix)
  28367. {
  28368. namespace st = lynx::simpletracks;
  28369. namespace sp = lynx::simplepads;
  28370. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28371. lynx::AudioEngine offline (false);
  28372. lynx::MainComponent ui (offline, false);
  28373. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  28374. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  28375. ui.setVisible (true);
  28376. const auto writeImage = [&prefix] (const juce::Image& image, const juce::String& name) {
  28377. const auto file = juce::File (prefix + "-" + name + ".png");
  28378. file.deleteFile();
  28379. juce::FileOutputStream out (file);
  28380. juce::PNGImageFormat().writeImageToStream (image, out);
  28381. };
  28382. juce::String report;
  28383. const auto line = [&report, &prefix] (const juce::String& text) {
  28384. report << text << "\n";
  28385. juce::File (prefix + "-report.txt").replaceWithText (report);
  28386. };
  28387. const auto check = [&line] (const juce::String& what, bool ok) { line ((ok ? "OK " : "ERROR ") + what); };
  28388. const auto settle = [&] {
  28389. for (int k = 0; k < 3; ++k)
  28390. offline.dispatchPendingMessages();
  28391. };
  28392. const auto whole = [&] (const juce::String& name, bool twoX = true) {
  28393. settle();
  28394. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 1.0f), name);
  28395. if (twoX)
  28396. writeImage (ui.createComponentSnapshot (ui.getLocalBounds(), true, 2.0f), name + "@2x");
  28397. };
  28398. ui.selectTabForSnapshot (2);
  28399. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  28400. settle();
  28401. auto* simple = ui.getSimpleWorkflowForSnapshot();
  28402. auto& playlist = ui.getPlaylistForSnapshot();
  28403. if (simple == nullptr)
  28404. {
  28405. line ("ERROR no Simple workflow");
  28406. return;
  28407. }
  28408. // an empty project: the drop lane alone, the round "+"
  28409. offline.setSong ([] {
  28410. lynx::Song s;
  28411. s.mixer = lynx::Song::defaultMixer();
  28412. return s;
  28413. }());
  28414. settle();
  28415. simple->hideChooser();
  28416. whole ("empty");
  28417. check ("an empty song shows one row (the drop lane), with the round +", st::rowsShown (offline.getSong(), 500) == 1 && ! playlist.simpleAddButtonForSnapshot().isEmpty());
  28418. // --- sounds ------------------------------------------------------------------------------------------------------
  28419. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190jc");
  28420. dir.deleteRecursively();
  28421. dir.createDirectory();
  28422. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  28423. wav.getParentDirectory().createDirectory();
  28424. juce::AudioBuffer<float> audio (1, frames);
  28425. for (int i = 0; i < frames; ++i)
  28426. audio.setSample (0, i, f (i));
  28427. juce::WavAudioFormat format;
  28428. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  28429. if (auto* w = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  28430. {
  28431. out.release();
  28432. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  28433. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  28434. }
  28435. return wav;
  28436. };
  28437. const auto pi = juce::MathConstants<double>::pi;
  28438. juce::Random rnd (190);
  28439. const auto loop = writeWav (dir.getChildFile ("Vocal chop 100.wav"), 230400, [pi] (int i) {
  28440. const auto t = i / 48000.0, inBeat = std::fmod (t, 0.6);
  28441. 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)));
  28442. });
  28443. std::vector<juce::File> padSounds;
  28444. const char* padNames[] { "Kick", "Snare", "Hat", "Clap", "Chord stab", "Vox hey", "Perc", "Bass hit" };
  28445. for (int k = 0; k < 8; ++k)
  28446. padSounds.push_back (writeWav (dir.getChildFile (juce::String ("pads/") + padNames[k] + ".wav"), 12000 + 3000 * k, [&rnd, k] (int i) {
  28447. return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.6f * std::exp (-i / (600.0f + 500.0f * (float) k)));
  28448. }));
  28449. // --- tracks: a voice with a loop, keys with chords, drums, a bass take, a Sampler track --------------------------------
  28450. int vocal = -1, keys = -1, drums = -1, bass = -1;
  28451. offline.editSong ([&] (lynx::Song& s) {
  28452. st::Request q;
  28453. q.kind = st::Kind::audio;
  28454. q.name = "Vocal chop";
  28455. q.audioFile = loop.getFullPathName().toStdString();
  28456. q.audioLength = 8 * lynx::ppq;
  28457. q.audioBeats = 8.0f;
  28458. vocal = st::addTrack (s, q).track;
  28459. q = {};
  28460. q.kind = st::Kind::instrument;
  28461. q.name = "Keys";
  28462. lynx::ChannelDef synth;
  28463. synth.instrument = lynx::InstrumentKind::synth;
  28464. q.channel = synth;
  28465. lynx::Pattern chords;
  28466. for (int i = 0; i < 4; ++i)
  28467. for (int k : { 60, 64, 67 })
  28468. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  28469. q.pattern = chords;
  28470. const auto r = st::addTrack (s, q);
  28471. keys = r.track;
  28472. q = {};
  28473. q.kind = st::Kind::drums;
  28474. q.name = "Drums";
  28475. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  28476. {
  28477. lynx::ChannelDef c;
  28478. c.instrument = kind;
  28479. q.kit.push_back (c);
  28480. }
  28481. lynx::Pattern beat;
  28482. for (int step = 0; step < 16; step += 2)
  28483. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 2, 60 });
  28484. for (int step : { 0, 8 })
  28485. beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, 0, 60 });
  28486. q.pattern = beat;
  28487. q.fillBars = 4;
  28488. const auto d = st::addTrack (s, q);
  28489. drums = d.track;
  28490. q = {};
  28491. q.kind = st::Kind::bass;
  28492. q.name = "Bass";
  28493. bass = st::addTrack (s, q).track;
  28494. if (r.insert > 0)
  28495. {
  28496. s.mixer[(std::size_t) r.insert].volume = 0.55f;
  28497. s.mixer[(std::size_t) r.insert].pan = -0.4f;
  28498. s.mixer[(std::size_t) r.insert].solo = true;
  28499. }
  28500. if (d.insert > 0)
  28501. s.mixer[(std::size_t) d.insert].muted = true;
  28502. });
  28503. settle();
  28504. check ("the Sampler tile's track was added", simple->addPads());
  28505. settle();
  28506. const auto& song = offline.getSong();
  28507. int pads = -1;
  28508. for (int t = 0; t < (int) song.playlistTracks.size() && pads < 0; ++t)
  28509. if (st::kindOf (song, t) == st::Kind::pads)
  28510. pads = t;
  28511. lynx::ui::WaveformCache::getInstance()->find (loop.getFullPathName(), [&offline, &loop] { return offline.getSampleLibrary().load (loop.getFullPathName()); });
  28512. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  28513. simple->hideChooser();
  28514. playlist.selectTrack (keys);
  28515. settle();
  28516. const auto rows = st::rowsShown (song, 500);
  28517. line ("tracks: vocal " + juce::String (vocal) + " keys " + juce::String (keys) + " drums " + juce::String (drums) + " bass " + juce::String (bass)
  28518. + " pads " + juce::String (pads) + "; rows shown " + juce::String (rows));
  28519. check ("five tracks + the drop lane are the rows shown (no placeholder rows)", rows == 6);
  28520. whole ("tracks");
  28521. {
  28522. // the Simple Playlist's whole paint (its rows only, no placeholder rows): CPU ms per frame
  28523. juce::Image img (juce::Image::ARGB, juce::jmax (1, playlist.getWidth()), juce::jmax (1, playlist.getHeight()), true);
  28524. std::vector<double> ms;
  28525. for (int f = -3; f < 40; ++f)
  28526. {
  28527. const auto t0 = lynx::threadCpuSeconds();
  28528. {
  28529. juce::Graphics g (img);
  28530. playlist.paintEntireComponent (g, true);
  28531. }
  28532. if (f >= 0)
  28533. ms.push_back (1000.0 * (lynx::threadCpuSeconds() - t0));
  28534. }
  28535. std::sort (ms.begin(), ms.end());
  28536. line ("simple playlist " + juce::String (playlist.getWidth()) + "x" + juce::String (playlist.getHeight()) + " whole paint: median "
  28537. + juce::String (ms[ms.size() / 2], 3) + " ms, p90 " + juce::String (ms[ms.size() * 9 / 10], 3) + " ms");
  28538. }
  28539. playlist.setDropLaneHotForSnapshot (true);
  28540. whole ("droplane-hot", false);
  28541. playlist.setDropLaneHotForSnapshot (false);
  28542. // --- the dock ------------------------------------------------------------------------------------------------------
  28543. auto* dock = simple->dockForSnapshot();
  28544. if (dock == nullptr)
  28545. {
  28546. line ("ERROR no dock");
  28547. return;
  28548. }
  28549. const auto dockShots = [&] (const juce::String& name) {
  28550. settle();
  28551. for (float scale : { 1.0f, 2.0f })
  28552. writeImage (dock->createComponentSnapshot (dock->getLocalBounds(), true, scale), "dock-" + name + (scale > 1.0f ? "@2x" : ""));
  28553. };
  28554. simple->trackSelected (keys);
  28555. dock->setTab (lynx::SimpleDock::Tab::instrument);
  28556. dockShots ("instrument");
  28557. whole ("window-dock-instrument", false);
  28558. dock->showKeyboard();
  28559. dockShots ("keyboard");
  28560. simple->trackSelected (vocal);
  28561. settle();
  28562. check ("an audio track's dock has one tab (drawn as a title)", dock->getTab() == lynx::SimpleDock::Tab::effects);
  28563. dockShots ("audio-lone-tab");
  28564. simple->showEffectsOfInsert (st::insertOf (offline.getSong(), keys));
  28565. dock->addOneKnobForCheck (1);
  28566. dock->addOneKnobForCheck (2);
  28567. dockShots ("effects");
  28568. // --- pads: 8 sounds in the 8 colours --------------------------------------------------------------------------------
  28569. if (pads >= 0)
  28570. {
  28571. simple->trackSelected (pads);
  28572. settle();
  28573. for (int p = 0; p < 8; ++p)
  28574. dock->padsLoadForCheck (p, padSounds[(std::size_t) p]);
  28575. offline.editSong ([pads] (lynx::Song& s) {
  28576. for (int p = 0; p < 8; ++p)
  28577. if (const auto c = sp::padChannel (s, pads, p); c >= 0)
  28578. s.channels[(std::size_t) c].simplePad.colour = (std::uint8_t) (p + 1);
  28579. });
  28580. dock->padsSelectForCheck (4);
  28581. dock->padsUpdateForCheck();
  28582. dockShots ("pads");
  28583. dock->padsHitForCheck (2);
  28584. dockShots ("pads-hit");
  28585. whole ("window-pads", false);
  28586. // the labels' contrast on the 8 colours, unlit and lit (the same colours the page draws)
  28587. static const juce::uint32 palette[] { 0xffe5383b, 0xffe8833a, 0xffe2c044, 0xff5fbf6a, 0xff3fb6b0, 0xff4f8ee0, 0xff9a6fe0, 0xffe06aa8 };
  28588. float worst = 99.0f;
  28589. for (auto argb : palette)
  28590. for (bool lit : { false, true })
  28591. {
  28592. const auto fill = juce::Colour (argb).withMultipliedBrightness (lit ? 1.0f : 0.55f).withMultipliedSaturation (lit ? 1.0f : 0.8f);
  28593. const auto ratio = lynx::ui::simplelook::contrast (lynx::ui::simplelook::inkOn (fill), fill);
  28594. worst = juce::jmin (worst, ratio);
  28595. line ("pad " + juce::String::toHexString ((int) argb).substring (2) + (lit ? " lit " : " unlit") + ": label " + juce::String (ratio, 2) + ":1");
  28596. }
  28597. check ("pad labels >= 4.5:1 on all 8 colours, lit and unlit (worst " + juce::String (worst, 2) + ":1)", worst >= 4.5f);
  28598. }
  28599. // --- chooser, starters, Finish ---------------------------------------------------------------------------------------
  28600. simple->showChooser();
  28601. whole ("chooser");
  28602. simple->showStarterPageForSnapshot();
  28603. whole ("starters");
  28604. simple->hideChooser();
  28605. simple->showFinish();
  28606. whole ("finish");
  28607. simple->hideFinish();
  28608. // --- the tour: the card beside its ring, the beacon with Animations on and off -----------------------------------------
  28609. if (auto* tour = simple->tourForSnapshot())
  28610. {
  28611. simple->showWelcome();
  28612. settle();
  28613. tour->clickForSnapshot ("welcome.tour");
  28614. settle();
  28615. const auto ring = tour->ringForSnapshot();
  28616. const auto card = tour->cardBoundsForSnapshot();
  28617. const auto distance = juce::jmax (0, juce::jmax (card.getY() - ring.getBottom(), ring.getY() - card.getBottom()))
  28618. + juce::jmax (0, juce::jmax (card.getX() - ring.getRight(), ring.getX() - card.getRight()));
  28619. line ("tour step 1: ring " + ring.toString() + " card " + card.toString() + " gap " + juce::String (distance) + " px");
  28620. check ("the card sits beside its ring (<= 24 px)", ! ring.isEmpty() && distance <= 24 && ! card.intersects (ring));
  28621. check ("the beacon pulses after a step change (Animations on)", tour->pulsingForCheck());
  28622. tour->setPulseForSnapshot (0.5f);
  28623. whole ("tour-pulse-on", false);
  28624. lynx::ui::motion::enabled() = false;
  28625. tour->clickForSnapshot ("next");
  28626. settle();
  28627. check ("no pulse timer with Animations off", ! tour->pulsingForCheck());
  28628. tour->setPulseForSnapshot (0.0f);
  28629. whole ("tour-pulse-off", false);
  28630. lynx::ui::motion::enabled() = true;
  28631. tour->clickForSnapshot ("skip");
  28632. settle();
  28633. }
  28634. // --- Large controls ---------------------------------------------------------------------------------------------------
  28635. ui.setSimpleLargeControls (true);
  28636. simple->hideChooser();
  28637. playlist.selectTrack (keys);
  28638. settle();
  28639. whole ("large-tracks", false);
  28640. if (pads >= 0)
  28641. {
  28642. simple->trackSelected (pads);
  28643. dockShots ("large-pads");
  28644. }
  28645. ui.setSimpleLargeControls (false);
  28646. line ("done");
  28647. }
  28648. void runSimpleShot (const juce::String& prefix)
  28649. {
  28650. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28651. lynx::AudioEngine offline (false);
  28652. lynx::MainComponent ui (offline, false);
  28653. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  28654. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  28655. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  28656. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  28657. file.deleteFile();
  28658. juce::FileOutputStream out (file);
  28659. juce::PNGImageFormat().writeImageToStream (image, out);
  28660. };
  28661. const auto write = [&ui, &writeImage] (const char* name) { writeImage (lynx::shot::snapshot (ui), name); };
  28662. // View › Layout style, with its submenu, as it is with `style` chosen
  28663. const auto viewMenu = [&ui] {
  28664. const auto names = ui.getMenuNamesForSnapshot();
  28665. const auto view = names.indexOf (lynx::tr ("View"));
  28666. return ui.getMenuForSnapshot (juce::jmax (0, view));
  28667. };
  28668. const auto saveStyleMenus = [&] (const juce::String& suffix) {
  28669. const auto view = viewMenu();
  28670. juce::StringArray names { lynx::tr ("View") };
  28671. std::vector<juce::PopupMenu> menus { view };
  28672. for (juce::PopupMenu::MenuItemIterator it (view); it.next();)
  28673. if (it.getItem().subMenu != nullptr && it.getItem().text == lynx::tr ("Layout style"))
  28674. {
  28675. names.add (lynx::tr ("Layout style"));
  28676. menus.push_back (*it.getItem().subMenu);
  28677. }
  28678. saveMenus (names, menus, prefix + "-menu-" + suffix + ".png");
  28679. };
  28680. // Settings › General with `style` selected, and its style list
  28681. const auto saveSettings = [&] (lynx::layoutstyle::Style style, const char* name) {
  28682. lynx::SettingsHooks hooks;
  28683. hooks.getGeneral = [style] {
  28684. lynx::GeneralOptions o;
  28685. o.language = lynx::i18n::current();
  28686. o.layoutStyle = (int) style;
  28687. return o;
  28688. };
  28689. auto page = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general, false, hooks);
  28690. const auto image = lynx::shot::paint (*page, lynx::theme::panel, -1, juce::jmin (page->getHeight(), 420));
  28691. writeImage (image, name);
  28692. std::function<juce::ComboBox* (juce::Component&)> find = [&find] (juce::Component& c) -> juce::ComboBox* {
  28693. if (c.getComponentID() == "layoutStyle")
  28694. return dynamic_cast<juce::ComboBox*> (&c);
  28695. for (auto* child : c.getChildren())
  28696. if (auto* box = find (*child))
  28697. return box;
  28698. return nullptr;
  28699. };
  28700. if (auto* box = find (*page); box != nullptr && box->getRootMenu() != nullptr)
  28701. saveMenus (juce::StringArray { lynx::tr ("Layout style") }, std::vector<juce::PopupMenu> { *box->getRootMenu() },
  28702. prefix + "-" + name + "-list.png");
  28703. };
  28704. const auto madeBefore = lynx::SimpleWorkflow::instances.load();
  28705. ui.selectTabForSnapshot (2); // the Playlist panel, maximized (as --gridshot)
  28706. write ("pattern");
  28707. saveStyleMenus ("pattern");
  28708. saveSettings (lynx::layoutstyle::Style::pattern, "settings-pattern");
  28709. const auto madePattern = lynx::SimpleWorkflow::instances.load();
  28710. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  28711. saveStyleMenus ("cliplaunch");
  28712. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  28713. offline.dispatchPendingMessages();
  28714. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  28715. simple->showChooser(); // (an empty project opens on it by itself; the offline project may hold the default song)
  28716. write ("simple"); // the New track chooser (slice S3)
  28717. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  28718. {
  28719. simple->showStarterPageForSnapshot();
  28720. write ("simple-starter");
  28721. simple->hideChooser();
  28722. write ("simple-closed");
  28723. // round 190p: a loop keeps time. Two files with the same 4.8 s of audio dropped on the empty Simple timeline:
  28724. // "Guitar loop 100.wav" (2 bars at 100 BPM) lasts 2 bars at the project's tempo, "Guitar take.wav" plays at
  28725. // its own speed. Both are undone again, so the shots after this one are as they were.
  28726. {
  28727. const auto folder = juce::File (prefix + "-loops");
  28728. folder.createDirectory();
  28729. juce::StringArray files;
  28730. for (const auto* name : { "Guitar loop 100.wav", "Guitar take.wav" })
  28731. {
  28732. const auto file = folder.getChildFile (name);
  28733. file.deleteFile();
  28734. const auto rate = 44100.0;
  28735. const auto frames = (int) (4.8 * rate);
  28736. juce::AudioBuffer<float> audio (1, frames);
  28737. for (int i = 0; i < frames; ++i)
  28738. {
  28739. const auto t = (double) i / rate, inBeat = std::fmod (t, 0.6); // a plucked note on every beat at 100 BPM
  28740. audio.setSample (0, i, (float) (0.7 * std::exp (-inBeat * 7.0) * std::sin (juce::MathConstants<double>::twoPi * 196.0 * t)));
  28741. }
  28742. if (auto out = file.createOutputStream())
  28743. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0)))
  28744. {
  28745. out.release();
  28746. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  28747. }
  28748. files.add (file.getFullPathName());
  28749. }
  28750. simple->dropFiles (files, 0);
  28751. offline.dispatchPendingMessages();
  28752. // the clips' waveforms are analysed in the background and drawn once ready (a live window repaints by
  28753. // itself; one off-screen paint came too early and showed empty clips)
  28754. for (const auto& path : files)
  28755. lynx::ui::WaveformCache::getInstance()->find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  28756. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  28757. offline.dispatchPendingMessages();
  28758. write ("simple-loop");
  28759. const auto& song = offline.getSong();
  28760. juce::String report;
  28761. for (const auto& clip : song.playlist)
  28762. if (clip.kind == lynx::ClipKind::audio)
  28763. report << song.channels[(std::size_t) clip.channel].name << ": " << juce::String ((double) clip.length / lynx::ppq, 3) << " beats, stretch "
  28764. << juce::String (song.channels[(std::size_t) clip.channel].sampler.stretchBeats, 2) << "\n";
  28765. juce::File (prefix + "-loop.txt").replaceWithText ("tempo " + juce::String (song.bpm, 1) + "\n" + report);
  28766. for (int i = 0; i < files.size() && offline.canUndo(); ++i) // (one undo step per dropped file)
  28767. offline.undo();
  28768. offline.dispatchPendingMessages();
  28769. simple->hideChooser();
  28770. }
  28771. // round 190t, slice A: one click on a starter beat adds it, placed for four bars (undone again)
  28772. {
  28773. const auto clipsBefore = offline.getSong().playlist.size();
  28774. const auto tempoBefore = offline.getSong().bpm;
  28775. simple->clickStarterForSnapshot (1);
  28776. offline.dispatchPendingMessages();
  28777. write ("simple-starter-added");
  28778. const auto& song = offline.getSong();
  28779. juce::String report ("tempo " + juce::String (tempoBefore, 1) + " -> " + juce::String (song.bpm, 1) + "\n");
  28780. for (auto i = clipsBefore; i < song.playlist.size(); ++i)
  28781. report << "clip at beat " << juce::String ((double) song.playlist[i].start / lynx::ppq, 2) << ", " << juce::String ((double) song.playlist[i].length / lynx::ppq, 2)
  28782. << " beats, pattern " << song.playlist[i].pattern << ", track " << song.playlist[i].track << "\n";
  28783. juce::File (prefix + "-starter.txt").replaceWithText (report);
  28784. if (song.playlist.size() > clipsBefore && offline.canUndo())
  28785. offline.undo();
  28786. offline.dispatchPendingMessages();
  28787. simple->hideChooser();
  28788. }
  28789. // slice S4: the Simple headers with a few tracks (voice, instrument, drums, an audio file), some levels moved
  28790. offline.editSong ([] (lynx::Song& s) {
  28791. namespace st = lynx::simpletracks;
  28792. st::Request q;
  28793. q.kind = st::Kind::voice;
  28794. q.name = "Lead vocal";
  28795. st::addTrack (s, q);
  28796. q = {};
  28797. q.kind = st::Kind::instrument;
  28798. q.name = "Keys";
  28799. lynx::ChannelDef keys;
  28800. keys.instrument = lynx::InstrumentKind::synth;
  28801. q.channel = keys;
  28802. lynx::Pattern chords;
  28803. for (int i = 0; i < 4; ++i)
  28804. for (int k : { 60, 64, 67 })
  28805. chords.notes.push_back (lynx::Note { (std::int64_t) i * 4 * lynx::ppq, 4 * lynx::ppq - lynx::ppq / 4, 0, k });
  28806. q.pattern = chords;
  28807. const auto r = st::addTrack (s, q);
  28808. q = {};
  28809. q.kind = st::Kind::drums;
  28810. for (auto kind : { lynx::InstrumentKind::kick, lynx::InstrumentKind::snare, lynx::InstrumentKind::hat })
  28811. {
  28812. lynx::ChannelDef c;
  28813. c.instrument = kind;
  28814. c.name = kind == lynx::InstrumentKind::kick ? "Kick" : kind == lynx::InstrumentKind::snare ? "Snare" : "Hat";
  28815. q.kit.push_back (c);
  28816. }
  28817. lynx::Pattern beat;
  28818. const auto hit = [&beat] (int step, int row) { beat.notes.push_back (lynx::Note { (std::int64_t) step * lynx::ticksPerStep, lynx::ticksPerStep, row, 60 }); };
  28819. for (int step = 0; step < 16; step += 2)
  28820. hit (step, 2); // hats on the 8ths, kick on 1 and 3, snare on 2 and 4
  28821. for (int step : { 0, 8 })
  28822. hit (step, 0);
  28823. for (int step : { 4, 12 })
  28824. hit (step, 1);
  28825. q.pattern = beat;
  28826. q.bpm = 96.0;
  28827. st::addTrack (s, q);
  28828. if (r.insert > 0)
  28829. {
  28830. s.mixer[(std::size_t) r.insert].volume = 0.55f;
  28831. s.mixer[(std::size_t) r.insert].pan = -0.4f;
  28832. s.mixer[(std::size_t) r.insert].solo = true;
  28833. }
  28834. });
  28835. offline.dispatchPendingMessages();
  28836. ui.getPlaylistForSnapshot().selectTrack (1);
  28837. write ("simple-tracks");
  28838. // round 190t, slice E: the backup status beside the title tools, in each of its states
  28839. {
  28840. const auto now = juce::Time::currentTimeMillis();
  28841. juce::String states;
  28842. int n = 0;
  28843. for (const auto& text : { lynx::MainComponent::simpleSaveStatusText (true, false, 0, now), lynx::MainComponent::simpleSaveStatusText (true, false, now - 5000, now),
  28844. lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now), lynx::MainComponent::simpleSaveStatusText (false, true, 0, now),
  28845. lynx::MainComponent::simpleSaveStatusText (false, false, 0, now) })
  28846. {
  28847. simple->setStatusForSnapshot (text);
  28848. offline.dispatchPendingMessages();
  28849. states << n << ": " << text << "\n";
  28850. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withTop (juce::jmin (ui.getHeight() - 1, 70)).withHeight (juce::jmin (ui.getHeight(), 44))),
  28851. ("status-" + juce::String (n++)).toRawUTF8());
  28852. }
  28853. juce::File (prefix + "-status.txt").replaceWithText (states);
  28854. simple->setStatusForSnapshot (lynx::MainComponent::simpleSaveStatusText (true, true, now - 125000, now));
  28855. offline.dispatchPendingMessages();
  28856. write ("simple-status");
  28857. }
  28858. // slice S8: the Finish dock, empty, then with a look on the Master (Balanced, Normal, a little Tone)
  28859. simple->showFinish();
  28860. offline.dispatchPendingMessages();
  28861. write ("simple-finish-empty");
  28862. offline.editSongStructural ([] (lynx::Song& s) { lynx::looks::apply (s, lynx::MasterLookSettings { lynx::looks::balanced, 0.5f, { 1.5f, 0.0f, 1.0f }, -3.0f }); });
  28863. offline.dispatchPendingMessages();
  28864. simple->showFinish();
  28865. write ("simple-finish");
  28866. simple->hideFinish();
  28867. }
  28868. saveStyleMenus ("simple");
  28869. saveSettings (lynx::layoutstyle::Style::simple, "settings-simple");
  28870. // round 184a S11: the Key panel (no key, then an A minor riff and its guesses) and its menu
  28871. const auto toolbarShot = [&] (const char* name) {
  28872. writeImage (lynx::shot::snapshot (ui, ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 80))), name);
  28873. };
  28874. toolbarShot ("key-none");
  28875. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-empty.png");
  28876. offline.editSong ([] (lynx::Song& s) {
  28877. if (s.channels.empty())
  28878. s.channels.resize (1);
  28879. if (s.patterns.empty())
  28880. s.patterns.emplace_back();
  28881. int t = 0;
  28882. for (int k : { 57, 60, 64, 67, 69, 67, 64, 60, 57, 59, 60, 62, 64, 62, 60, 59, 57, 57, 64, 45 })
  28883. {
  28884. lynx::Note n;
  28885. n.channel = 0;
  28886. n.key = k;
  28887. n.start = t * lynx::ppq / 2;
  28888. n.length = k == 57 || k == 45 ? lynx::ppq : lynx::ppq / 2;
  28889. s.patterns[0].notes.push_back (n);
  28890. ++t;
  28891. }
  28892. });
  28893. offline.dispatchPendingMessages();
  28894. saveMenus (juce::StringArray { lynx::tr ("Key") }, std::vector<juce::PopupMenu> { ui.getKeyMenuForSnapshot() }, prefix + "-key-menu-guess.png");
  28895. const auto guesses = lynx::keyguess::guess (offline.getSong(), 3);
  28896. if (! guesses.empty())
  28897. offline.editSong ([k = guesses[0].key] (lynx::Song& s) { lynx::projectkey::set (s, k); });
  28898. offline.dispatchPendingMessages();
  28899. toolbarShot ("key-set");
  28900. write ("simple-key");
  28901. juce::String keyCounts;
  28902. for (const auto& g : guesses)
  28903. keyCounts << "guess " << lynx::projectkey::name (g.key) << " " << g.notesInScale << "/" << g.notes << " score " << g.score << "\n";
  28904. offline.editSong ([] (lynx::Song& s) { lynx::projectkey::set (s, std::nullopt); });
  28905. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  28906. offline.dispatchPendingMessages();
  28907. toolbarShot ("key-pattern-toolbar");
  28908. write ("pattern-after");
  28909. // round 184a S17: the setup wizard with its Workflow choice — a first start (Pattern selected), then reopened in Simple
  28910. for (int style : { 0, 2 })
  28911. {
  28912. auto wizard = lynx::makeSetupWizardContent (offline, {}, {}, style, {});
  28913. auto image = lynx::shot::paint (*wizard);
  28914. writeImage (image, style == 0 ? "wizard-pattern" : "wizard-simple");
  28915. }
  28916. juce::File (prefix + "-counts.txt").replaceWithText ("simple workflows before " + juce::String (madeBefore) + ", in pattern workflow "
  28917. + juce::String (madePattern) + ", after " + juce::String (lynx::SimpleWorkflow::instances.load())
  28918. + "\nstyle after " + lynx::layoutstyle::id (ui.getLayoutStyle()) + "\n" + keyCounts);
  28919. }
  28920. void runLiveRackShot190hr (const juce::String& prefix)
  28921. {
  28922. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  28923. lynx::AudioEngine offline (false);
  28924. lynx::MainComponent ui (offline, false);
  28925. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  28926. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  28927. const auto write = [&prefix, &ui, &offline] (const char* name) {
  28928. offline.dispatchPendingMessages();
  28929. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  28930. file.deleteFile();
  28931. juce::FileOutputStream out (file);
  28932. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  28933. };
  28934. const auto writeView = [&prefix] (juce::Component& c, const char* name) {
  28935. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  28936. file.deleteFile();
  28937. juce::FileOutputStream out (file);
  28938. juce::PNGImageFormat().writeImageToStream (lynx::shot::paint (c, lynx::theme::panel), out);
  28939. };
  28940. juce::String checks;
  28941. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  28942. const auto itemEnabled = [] (const juce::PopupMenu& menu, const juce::String& start) {
  28943. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  28944. if (it.getItem().text.startsWith (start))
  28945. return it.getItem().isEnabled ? 1 : 0;
  28946. return -1;
  28947. };
  28948. ui.setVisible (true);
  28949. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  28950. ui.setClipLaunchWorkflow (true);
  28951. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  28952. offline.editSong ([] (lynx::Song& s) {
  28953. if (s.channels.size() < 1)
  28954. s.channels.resize (1);
  28955. s.channels[0].name = "Lead";
  28956. s.channels[0].instrument = lynx::InstrumentKind::synth;
  28957. s.channels[0].mixerTrack = 2;
  28958. if (s.mixer.size() < 4)
  28959. s.mixer.resize (4);
  28960. s.mixer[2].name = "Lead";
  28961. s.mixer[2].effects.clear();
  28962. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::delay })
  28963. s.mixer[2].effects.push_back (lynx::makeEffectSlot (kind));
  28964. while (s.patterns.size() < 1)
  28965. s.patterns.emplace_back();
  28966. lynx::Note note;
  28967. note.channel = 0;
  28968. note.key = 60;
  28969. s.patterns[0].notes = { note };
  28970. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  28971. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  28972. s.playlistTracks[1].name = "Lead";
  28973. lynx::Clip clip;
  28974. clip.pattern = 0;
  28975. clip.length = 4 * lynx::ppq;
  28976. lynx::launcher::setClip (s, 1, 0, clip);
  28977. }, false);
  28978. offline.dispatchPendingMessages();
  28979. auto* detail = ui.getDetailViewForSnapshot();
  28980. if (detail == nullptr)
  28981. {
  28982. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  28983. return;
  28984. }
  28985. detail->showSelection (1, 0);
  28986. detail->setPage (lynx::DetailView::Page::devices);
  28987. detail->selectCardForCheck (0); // the instrument
  28988. write ("01-devices");
  28989. auto menu = detail->cardMenuForSnapshot (0);
  28990. saveMenus (juce::StringArray { "Instrument" }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-instrument-menu.png");
  28991. check ("instrument menu: Group on, Ungroup off", itemEnabled (menu, lynx::tr ("Group")) == 1 && itemEnabled (menu, lynx::tr ("Ungroup")) == 0);
  28992. // Ctrl+G: the synth into an Instrument Rack (the card becomes the rack's)
  28993. check ("Ctrl+G groups the instrument into an Instrument Rack", detail->groupCardForCheck (0, false));
  28994. const auto& grouped = offline.getSong().channels[0];
  28995. check ("the channel keeps its insert and the rack holds the synth",
  28996. grouped.mixerTrack == 2 && lynx::rack::isRack (grouped) && lynx::rack::rackOf (grouped.patcher)->kind == lynx::RackDoc::Kind::instrument
  28997. && lynx::rack::devices (*lynx::rack::rackOf (grouped.patcher), 0).size() == 1);
  28998. detail->selectCardForCheck (0);
  28999. write ("03-grouped");
  29000. menu = detail->cardMenuForSnapshot (0);
  29001. saveMenus (juce::StringArray { "Instrument Rack" }, std::vector<juce::PopupMenu> { menu }, prefix + "-04-rack-menu.png");
  29002. check ("rack menu: Ungroup on, Save as Live rack preset", itemEnabled (menu, lynx::tr ("Ungroup")) == 1
  29003. && itemEnabled (menu, lynx::tr ("Save as Live rack preset (.adg)...")) == 1);
  29004. check ("Ctrl+Shift+G ungroups it", detail->groupCardForCheck (0, true) && offline.getSong().channels[0].instrument == lynx::InstrumentKind::synth);
  29005. write ("05-ungrouped");
  29006. // a rack's view: Live's Save Preset button at the foot of the strip, the drop area
  29007. offline.editSong ([] (lynx::Song& s) {
  29008. auto rack = lynx::rack::makeRackSlot (lynx::RackDoc::Kind::audioEffect);
  29009. lynx::rack::rackOf (rack.patcher)->showDevices = true;
  29010. s.mixer[3].effects = { rack };
  29011. }, false);
  29012. offline.dispatchPendingMessages();
  29013. {
  29014. auto view = lynx::RackWindows::makeSlotView (offline, 3, 0, true);
  29015. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  29016. writeView (*view, "06-rack-empty");
  29017. lynx::PatchNode fx;
  29018. fx.effect = lynx::makeEffectSlot (lynx::EffectKind::delay);
  29019. const juce::Point<int> inDevices { view->getWidth() - 30, view->getHeight() / 2 };
  29020. check ("an effect dropped on the chain goes in", view->dropNodeForCheck (fx, inDevices));
  29021. lynx::PatchNode synth;
  29022. synth.generator = true;
  29023. synth.channel.instrument = lynx::InstrumentKind::synth;
  29024. check ("an instrument dropped on an Audio Effect Rack is refused", ! view->dropNodeForCheck (synth, inDevices));
  29025. const auto* r = lynx::rack::rackOf (offline.getSong().mixer[3].effects[0].patcher);
  29026. check ("the chain holds one device", r != nullptr && lynx::rack::devices (*r, 0).size() == 1);
  29027. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  29028. writeView (*view, "07-rack-after-drop");
  29029. // the rack as a Live preset and back
  29030. const auto out = lynx::exportLiveRackPreset (offline.getSong().mixer[3].effects[0].patcher, "Shot Rack");
  29031. check ("Save as .adg writes Live's preset form", out.xml.find ("<GroupDevicePreset>") != std::string::npos
  29032. && out.xml.find ("<AudioEffectBranchPreset ") != std::string::npos);
  29033. const auto back = lynx::importLiveDevicePreset (out.bytes);
  29034. check ("the .adg reads back as the rack", back.has_value() && lynx::rack::isRack (back->slot)
  29035. && lynx::rack::rackOf (back->slot.patcher)->chains.size() == 1);
  29036. }
  29037. // Live's own .adg (Core Library, read-only): before round 190hr it opened without chains
  29038. const juce::File live ("C:/ProgramData/Ableton/Live 12 Trial/Resources/Core Library/Racks/Audio Effect Racks/Distortion/Smokey Water.adg");
  29039. const juce::File liveWsl ("/mnt/c/ProgramData/Ableton/Live 12 Trial/Resources/Core Library/Racks/Audio Effect Racks/Distortion/Smokey Water.adg");
  29040. const auto adg = live.existsAsFile() ? live : liveWsl;
  29041. if (adg.existsAsFile())
  29042. {
  29043. juce::MemoryBlock data;
  29044. adg.loadFileAsData (data);
  29045. const auto* bytes = static_cast<const std::uint8_t*> (data.getData());
  29046. auto p = lynx::importLiveDevicePreset (std::vector<std::uint8_t> (bytes, bytes + data.getSize()));
  29047. check ("Live's Smokey Water.adg opens with its chain and devices", p.has_value() && lynx::rack::isRack (p->slot)
  29048. && ! lynx::rack::rackOf (p->slot.patcher)->chains.empty()
  29049. && lynx::rack::devices (*lynx::rack::rackOf (p->slot.patcher), 0).size() >= 3);
  29050. if (p)
  29051. {
  29052. lynx::rack::rackOf (p->slot.patcher)->showDevices = true;
  29053. lynx::rack::rackOf (p->slot.patcher)->showChains = true;
  29054. offline.editSong ([slot = p->slot] (lynx::Song& s) { s.mixer[3].effects = { slot }; }, false);
  29055. offline.dispatchPendingMessages();
  29056. auto view = lynx::RackWindows::makeSlotView (offline, 3, 0, true);
  29057. view->setSize (std::max (520, view->preferredWidth (228)), 228);
  29058. writeView (*view, "08-live-adg-smokey-water");
  29059. }
  29060. }
  29061. else
  29062. checks << "skip Live's Core Library is not on this machine\n";
  29063. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  29064. }
  29065. void runHelixShot190ja (const juce::String& prefix, const juce::String& preset)
  29066. {
  29067. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29068. lynx::AudioEngine offline (false);
  29069. lynx::MainComponent ui (offline, false);
  29070. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  29071. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29072. juce::String checks;
  29073. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  29074. const auto write = [&prefix, &ui, &offline] (const char* name) {
  29075. offline.dispatchPendingMessages();
  29076. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29077. file.deleteFile();
  29078. juce::FileOutputStream out (file);
  29079. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  29080. };
  29081. // the Helix channel: Helix's defaults, or a Live Wavetable preset's values through the .als import's own mapping
  29082. lynx::ChannelDef helix;
  29083. helix.instrument = lynx::InstrumentKind::helix;
  29084. helix.name = "Helix";
  29085. if (preset.isNotEmpty())
  29086. {
  29087. juce::MemoryBlock raw;
  29088. juce::File (preset).loadFileAsData (raw);
  29089. juce::MemoryInputStream in (raw, false);
  29090. juce::GZIPDecompressorInputStream gz (&in, false, juce::GZIPDecompressorInputStream::gzipFormat);
  29091. const auto text = juce::File (preset).getFileExtension() == ".adv" ? gz.readEntireStreamAsString() : juce::String();
  29092. lynx::xml::Document doc;
  29093. lynx::alsdev::Notes notes;
  29094. const auto parsed = doc.parse (text.toStdString());
  29095. auto device = parsed ? doc.root().child ("InstrumentVector") : lynx::xml::Element();
  29096. check ("preset read: " + preset, parsed && (bool) device && lynx::alsdev::wavetableToHelix (device, helix, notes));
  29097. helix.name = juce::File (preset).getFileNameWithoutExtension().toStdString();
  29098. }
  29099. ui.setVisible (true);
  29100. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  29101. ui.setClipLaunchWorkflow (true);
  29102. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  29103. offline.editSong ([&helix] (lynx::Song& s) {
  29104. if (s.channels.empty())
  29105. s.channels.resize (1);
  29106. helix.mixerTrack = s.channels[0].mixerTrack;
  29107. s.channels[0] = helix;
  29108. while (s.patterns.empty())
  29109. s.patterns.emplace_back();
  29110. lynx::Note note;
  29111. note.channel = 0;
  29112. note.key = 60;
  29113. s.patterns[0].name = "Chords";
  29114. s.patterns[0].notes = { note };
  29115. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  29116. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  29117. s.playlistTracks[0].name = helix.name;
  29118. lynx::Clip clip;
  29119. clip.pattern = 0;
  29120. clip.length = 4 * lynx::ppq;
  29121. lynx::launcher::setClip (s, 0, 0, clip);
  29122. }, false);
  29123. offline.dispatchPendingMessages();
  29124. auto* detail = ui.getDetailViewForSnapshot();
  29125. check ("detail view", detail != nullptr);
  29126. if (detail != nullptr)
  29127. {
  29128. detail->showSelection (0, 0);
  29129. detail->setPage (lynx::DetailView::Page::devices);
  29130. offline.dispatchPendingMessages();
  29131. write ("01-device");
  29132. struct View
  29133. {
  29134. const char* name;
  29135. int modTab, source, osc;
  29136. };
  29137. 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 },
  29138. View { "06-lfo1", 0, 3, 0 }, View { "07-osc2", 0, 0, 1 } })
  29139. {
  29140. check (juce::String ("Helix card shown for ") + v.name, lynx::helixcards::showView (*detail, v.modTab, v.source, v.osc) > 0);
  29141. write (v.name);
  29142. }
  29143. lynx::helixcards::showView (*detail, 0, 0, 0);
  29144. }
  29145. // the Pattern layout: the channel window's page alone
  29146. {
  29147. auto page = lynx::makeHelixEditor (offline, [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; }, 0);
  29148. const auto file = lynx::shot::file (juce::File (prefix + "-10-window.png"));
  29149. file.deleteFile();
  29150. juce::FileOutputStream out (file);
  29151. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*page), out);
  29152. check ("channel window page", page->getWidth() > 0);
  29153. }
  29154. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  29155. }
  29156. void runHelixShot190oc (const juce::String& prefix)
  29157. {
  29158. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29159. lynx::AudioEngine offline (false);
  29160. juce::String checks;
  29161. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  29162. const auto& bank = lynx::banks::bankOf (lynx::InstrumentKind::helix);
  29163. const auto load = [&] (const juce::String& name) {
  29164. int index = -1;
  29165. for (int b = 0; b < (int) bank.size(); ++b)
  29166. if (juce::String (bank[(std::size_t) b].name) == name)
  29167. index = b;
  29168. check ("preset " + name, index >= 0);
  29169. offline.editSong ([index] (lynx::Song& s) {
  29170. if (s.channels.empty())
  29171. s.channels.resize (1);
  29172. lynx::ChannelDef c;
  29173. c.instrument = lynx::InstrumentKind::helix;
  29174. c.name = "Helix";
  29175. c.mixerTrack = s.channels[0].mixerTrack;
  29176. if (auto loaded = lynx::banks::withPreset (c, std::max (index, 0)))
  29177. c = *loaded;
  29178. s.channels[0] = c;
  29179. }, false);
  29180. offline.dispatchPendingMessages();
  29181. };
  29182. const auto locate = [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; };
  29183. const auto save = [&prefix, &offline] (juce::Component& c, const char* name) {
  29184. offline.dispatchPendingMessages();
  29185. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29186. file.deleteFile();
  29187. juce::FileOutputStream out (file);
  29188. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  29189. };
  29190. const auto paintCost = [&checks] (juce::Component& c, const char* what) {
  29191. double best = 1.0e9;
  29192. for (int run = 0; run < 3; ++run)
  29193. {
  29194. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  29195. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  29196. for (int f = 0; f < 30; ++f)
  29197. {
  29198. juce::Graphics g (image);
  29199. c.paintEntireComponent (g, false);
  29200. }
  29201. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 30.0);
  29202. }
  29203. checks << "paint " << what << " " << juce::String (best, 3) << " ms per frame (" << c.getWidth() << " x " << c.getHeight() << ")\n";
  29204. };
  29205. // each part of a window alone (the strip, the device), its paint cost
  29206. const auto parts = [&checks] (juce::Component& page) {
  29207. for (int i = 0; i < page.getNumChildComponents(); ++i)
  29208. {
  29209. auto* child = page.getChildComponent (i);
  29210. juce::Image image (juce::Image::ARGB, std::max (1, child->getWidth()), std::max (1, child->getHeight()), true);
  29211. double best = 1.0e9;
  29212. for (int run = 0; run < 3; ++run)
  29213. {
  29214. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  29215. for (int f = 0; f < 10; ++f)
  29216. {
  29217. juce::Graphics g (image);
  29218. child->paintEntireComponent (g, false);
  29219. }
  29220. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 10.0);
  29221. }
  29222. checks << " part " << juce::String (best, 3) << " ms " << typeid (*child).name() << " " << child->getBounds().toString() << "\n";
  29223. }
  29224. };
  29225. // the channel window (Pattern layout, LYNX's look): Helix+'s strip with round 4's row
  29226. load ("Grain Swarm");
  29227. {
  29228. auto page = lynx::makeHelixEditor (offline, locate, 0);
  29229. check ("window page holds the six strip rows", page->getHeight() >= lynx::helixDeviceHeight + 16 + 446);
  29230. save (*page, "01-window-grain-swarm");
  29231. paintCost (*page, "window (Grain Swarm)");
  29232. }
  29233. load ("Spectral Ensemble");
  29234. {
  29235. auto page = lynx::makeHelixEditor (offline, locate, 0);
  29236. save (*page, "02-window-spectral-ensemble");
  29237. paintCost (*page, "window (Spectral Ensemble)");
  29238. parts (*page);
  29239. }
  29240. load ("Frozen Choir");
  29241. {
  29242. auto page = lynx::makeHelixEditor (offline, locate, 0);
  29243. save (*page, "03-window-frozen-choir");
  29244. }
  29245. load ("Triple Stack");
  29246. {
  29247. auto page = lynx::makeHelixEditor (offline, locate, 0);
  29248. save (*page, "04-window-triple");
  29249. paintCost (*page, "window (Triple Stack)");
  29250. parts (*page);
  29251. }
  29252. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  29253. }
  29254. void runHelixShot190mt (const juce::String& prefix)
  29255. {
  29256. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29257. lynx::AudioEngine offline (false);
  29258. juce::String checks;
  29259. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  29260. const auto& bank = lynx::banks::bankOf (lynx::InstrumentKind::helix);
  29261. const auto load = [&] (const juce::String& name) {
  29262. int index = -1;
  29263. for (int b = 0; b < (int) bank.size(); ++b)
  29264. if (juce::String (bank[(std::size_t) b].name) == name)
  29265. index = b;
  29266. check ("preset " + name, index >= 0);
  29267. offline.editSong ([index] (lynx::Song& s) {
  29268. if (s.channels.empty())
  29269. s.channels.resize (1);
  29270. lynx::ChannelDef c;
  29271. c.instrument = lynx::InstrumentKind::helix;
  29272. c.name = "Helix";
  29273. c.mixerTrack = s.channels[0].mixerTrack;
  29274. if (auto loaded = lynx::banks::withPreset (c, std::max (index, 0)))
  29275. c = *loaded;
  29276. s.channels[0] = c;
  29277. }, false);
  29278. offline.dispatchPendingMessages();
  29279. };
  29280. const auto locate = [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; };
  29281. const auto save = [&prefix, &offline] (juce::Component& c, const char* name) {
  29282. offline.dispatchPendingMessages();
  29283. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29284. file.deleteFile();
  29285. juce::FileOutputStream out (file);
  29286. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  29287. };
  29288. const auto paintCost = [&checks] (juce::Component& c, const char* what) {
  29289. double best = 1.0e9;
  29290. for (int run = 0; run < 3; ++run)
  29291. {
  29292. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  29293. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  29294. for (int f = 0; f < 30; ++f)
  29295. {
  29296. juce::Graphics g (image);
  29297. c.paintEntireComponent (g, false);
  29298. }
  29299. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 30.0);
  29300. }
  29301. checks << "paint " << what << " " << juce::String (best, 3) << " ms per frame (" << c.getWidth() << " x " << c.getHeight() << ")\n";
  29302. };
  29303. // the channel window (Pattern layout, LYNX's look): Helix+'s strip with round 3's row
  29304. load ("Grain Cloud");
  29305. {
  29306. auto page = lynx::makeHelixEditor (offline, locate, 0);
  29307. check ("window page holds the five strip rows", page->getHeight() >= lynx::helixDeviceHeight + 16 + 370);
  29308. save (*page, "01-window-granular");
  29309. paintCost (*page, "window (Grain Cloud)");
  29310. check ("Matrix tab", lynx::helixcards::showView (*page, 1, 0, 0) == 1);
  29311. save (*page, "04-matrix-granular");
  29312. }
  29313. load ("Frozen Choir");
  29314. {
  29315. auto page = lynx::makeHelixEditor (offline, locate, 0);
  29316. save (*page, "02-window-spectral");
  29317. }
  29318. load ("Spectral Glass");
  29319. {
  29320. auto page = lynx::makeHelixEditor (offline, locate, 0);
  29321. save (*page, "03-window-glass");
  29322. }
  29323. // the same preset as 190ml's first picture (the side by side)
  29324. load ("Triple Stack");
  29325. {
  29326. auto page = lynx::makeHelixEditor (offline, locate, 0);
  29327. save (*page, "05-window-triple");
  29328. paintCost (*page, "window (Triple Stack)");
  29329. for (int i = 0; i < page->getNumChildComponents(); ++i) // (each part alone)
  29330. {
  29331. auto* child = page->getChildComponent (i);
  29332. juce::Image image (juce::Image::ARGB, std::max (1, child->getWidth()), std::max (1, child->getHeight()), true);
  29333. double best = 1.0e9;
  29334. for (int run = 0; run < 3; ++run)
  29335. {
  29336. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  29337. for (int f = 0; f < 10; ++f)
  29338. {
  29339. juce::Graphics g (image);
  29340. child->paintEntireComponent (g, false);
  29341. }
  29342. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 10.0);
  29343. }
  29344. checks << " part " << juce::String (best, 3) << " ms " << typeid (*child).name() << " " << child->getBounds().toString() << "\n";
  29345. }
  29346. }
  29347. // the Clip-launch layout's Device View card (Live's look) with its Helix+ panel (Granular / Spectral discs)
  29348. load ("Frozen Choir");
  29349. {
  29350. lynx::MainComponent ui (offline, false);
  29351. ui.setSize (2560, 1080);
  29352. ui.setVisible (true);
  29353. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  29354. ui.setClipLaunchWorkflow (true);
  29355. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  29356. offline.editSong ([] (lynx::Song& s) {
  29357. while (s.patterns.empty())
  29358. s.patterns.emplace_back();
  29359. lynx::Note note;
  29360. note.channel = 0;
  29361. note.key = 60;
  29362. s.patterns[0].name = "Choir";
  29363. s.patterns[0].notes = { note };
  29364. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  29365. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  29366. s.playlistTracks[0].name = "Helix";
  29367. lynx::Clip clip;
  29368. clip.pattern = 0;
  29369. clip.length = 4 * lynx::ppq;
  29370. lynx::launcher::setClip (s, 0, 0, clip);
  29371. }, false);
  29372. offline.dispatchPendingMessages();
  29373. auto* detail = ui.getDetailViewForSnapshot();
  29374. check ("detail view", detail != nullptr);
  29375. if (detail != nullptr)
  29376. {
  29377. detail->showSelection (0, 0);
  29378. detail->setPage (lynx::DetailView::Page::devices);
  29379. offline.dispatchPendingMessages();
  29380. check ("card's Helix+ panel", lynx::helixcards::showPlusInCard (*detail, true) == 1);
  29381. offline.dispatchPendingMessages();
  29382. save (ui, "06-card-plus");
  29383. checks << "detail " << detail->getScreenBounds().translated (-ui.getScreenX(), -ui.getScreenY()).toString() << "\n";
  29384. lynx::helixcards::showPlusInCard (*detail, false);
  29385. }
  29386. }
  29387. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  29388. }
  29389. void runHelixShot190ml (const juce::String& prefix)
  29390. {
  29391. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29392. lynx::AudioEngine offline (false);
  29393. juce::String checks;
  29394. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  29395. const auto& bank = lynx::banks::bankOf (lynx::InstrumentKind::helix);
  29396. const auto load = [&] (const juce::String& name) {
  29397. int index = -1;
  29398. for (int b = 0; b < (int) bank.size(); ++b)
  29399. if (juce::String (bank[(std::size_t) b].name) == name)
  29400. index = b;
  29401. check ("preset " + name, index >= 0);
  29402. offline.editSong ([index] (lynx::Song& s) {
  29403. if (s.channels.empty())
  29404. s.channels.resize (1);
  29405. lynx::ChannelDef c;
  29406. c.instrument = lynx::InstrumentKind::helix;
  29407. c.name = "Helix";
  29408. c.mixerTrack = s.channels[0].mixerTrack;
  29409. if (auto loaded = lynx::banks::withPreset (c, std::max (index, 0)))
  29410. c = *loaded;
  29411. s.channels[0] = c;
  29412. }, false);
  29413. offline.dispatchPendingMessages();
  29414. };
  29415. const auto locate = [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; };
  29416. const auto save = [&prefix, &offline] (juce::Component& c, const char* name) {
  29417. offline.dispatchPendingMessages();
  29418. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29419. file.deleteFile();
  29420. juce::FileOutputStream out (file);
  29421. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  29422. };
  29423. const auto paintCost = [&checks] (juce::Component& c, const char* what) {
  29424. double best = 1.0e9;
  29425. for (int run = 0; run < 3; ++run)
  29426. {
  29427. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  29428. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  29429. for (int f = 0; f < 30; ++f)
  29430. {
  29431. juce::Graphics g (image);
  29432. c.paintEntireComponent (g, false);
  29433. }
  29434. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 30.0);
  29435. }
  29436. checks << "paint " << what << " " << juce::String (best, 3) << " ms per frame (" << c.getWidth() << " x " << c.getHeight() << ")\n";
  29437. };
  29438. // the channel window (Pattern layout, LYNX's look): Helix+'s strip with Helix+ 2's two rows
  29439. load ("Triple Stack");
  29440. {
  29441. auto page = lynx::makeHelixEditor (offline, locate, 0);
  29442. check ("window page holds the four strip rows", page->getHeight() >= lynx::helixDeviceHeight + 16 + 300);
  29443. save (*page, "01-window");
  29444. paintCost (*page, "window");
  29445. // (the slowest parts: each child of the page and of its children, alone)
  29446. std::vector<std::pair<double, juce::String>> parts;
  29447. std::function<void (juce::Component&, int)> walk = [&] (juce::Component& c, int depth) {
  29448. for (auto* child : c.getChildren())
  29449. {
  29450. if (child->getWidth() <= 0 || child->getHeight() <= 0)
  29451. continue;
  29452. juce::Image image (juce::Image::ARGB, child->getWidth(), child->getHeight(), true);
  29453. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  29454. for (int f = 0; f < 10; ++f)
  29455. {
  29456. juce::Graphics g (image);
  29457. child->paintEntireComponent (g, false);
  29458. }
  29459. parts.push_back ({ (juce::Time::getMillisecondCounterHiRes() - t0) / 10.0,
  29460. juce::String (depth) + " " + typeid (*child).name() + " " + child->getBounds().toString() });
  29461. if (depth < 2)
  29462. walk (*child, depth + 1);
  29463. }
  29464. };
  29465. walk (*page, 0);
  29466. for (int i = 0; i < page->getNumChildComponents(); ++i) // (the page with one child hidden)
  29467. {
  29468. auto* child = page->getChildComponent (i);
  29469. child->setVisible (false);
  29470. paintCost (*page, (juce::String ("window without child ") + juce::String (i)).toRawUTF8());
  29471. child->setVisible (true);
  29472. }
  29473. paintCost (*page, "window again");
  29474. std::sort (parts.begin(), parts.end(), [] (const auto& x, const auto& y) { return x.first > y.first; });
  29475. for (std::size_t i = 0; i < parts.size() && i < 12; ++i)
  29476. checks << " part " << juce::String (parts[i].first, 3) << " ms " << parts[i].second << "\n";
  29477. check ("Macros tab", lynx::helixcards::showView (*page, 4, 0, 0) == 1);
  29478. save (*page, "02-matrix-macros");
  29479. }
  29480. load ("Vowel Sync");
  29481. {
  29482. auto page = lynx::makeHelixEditor (offline, locate, 0);
  29483. save (*page, "03-window-sample");
  29484. }
  29485. // the table editor on a formula preset's table
  29486. load ("Formula Bell");
  29487. {
  29488. auto editor = lynx::helixcards::makeTableEditor (offline, locate, 0, 0, 0, 20);
  29489. save (*editor, "04-table-draw");
  29490. paintCost (*editor, "table editor (draw)");
  29491. auto harmonics = lynx::helixcards::makeTableEditor (offline, locate, 0, 0, 1, 20);
  29492. save (*harmonics, "05-table-harmonics");
  29493. }
  29494. // the Clip-launch layout's Device View card (Live's look), without and with its Helix+ panel
  29495. load ("Triple Stack");
  29496. {
  29497. lynx::MainComponent ui (offline, false);
  29498. ui.setSize (2560, 1080); // (wide: the card with its panel whole)
  29499. ui.setVisible (true);
  29500. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  29501. ui.setClipLaunchWorkflow (true);
  29502. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  29503. offline.editSong ([] (lynx::Song& s) {
  29504. while (s.patterns.empty())
  29505. s.patterns.emplace_back();
  29506. lynx::Note note;
  29507. note.channel = 0;
  29508. note.key = 60;
  29509. s.patterns[0].name = "Lead";
  29510. s.patterns[0].notes = { note };
  29511. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  29512. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  29513. s.playlistTracks[0].name = "Helix";
  29514. lynx::Clip clip;
  29515. clip.pattern = 0;
  29516. clip.length = 4 * lynx::ppq;
  29517. lynx::launcher::setClip (s, 0, 0, clip);
  29518. }, false);
  29519. offline.dispatchPendingMessages();
  29520. auto* detail = ui.getDetailViewForSnapshot();
  29521. check ("detail view", detail != nullptr);
  29522. if (detail != nullptr)
  29523. {
  29524. detail->showSelection (0, 0);
  29525. detail->setPage (lynx::DetailView::Page::devices);
  29526. offline.dispatchPendingMessages();
  29527. lynx::helixcards::showPlusInCard (*detail, false);
  29528. save (ui, "06-card");
  29529. check ("card's Helix+ panel", lynx::helixcards::showPlusInCard (*detail, true) == 1);
  29530. offline.dispatchPendingMessages();
  29531. save (ui, "07-card-plus");
  29532. // (where the Device View sits in the picture, for the crops)
  29533. checks << "detail " << detail->getScreenBounds().translated (-ui.getScreenX(), -ui.getScreenY()).toString() << "\n";
  29534. lynx::helixcards::showPlusInCard (*detail, false);
  29535. }
  29536. }
  29537. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  29538. }
  29539. void runHelixShot190mi (const juce::String& prefix, const juce::String& presetName)
  29540. {
  29541. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29542. lynx::AudioEngine offline (false);
  29543. juce::String checks;
  29544. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  29545. const auto& bank = lynx::banks::bankOf (lynx::InstrumentKind::helix);
  29546. int index = -1;
  29547. for (int b = 0; b < (int) bank.size(); ++b)
  29548. if (juce::String (bank[(std::size_t) b].name) == presetName)
  29549. index = b;
  29550. check ("preset " + presetName, index >= 0);
  29551. offline.editSong ([index] (lynx::Song& s) {
  29552. if (s.channels.empty())
  29553. s.channels.resize (1);
  29554. lynx::ChannelDef c;
  29555. c.instrument = lynx::InstrumentKind::helix;
  29556. c.mixerTrack = s.channels[0].mixerTrack;
  29557. if (auto loaded = lynx::banks::withPreset (c, std::max (index, 0)))
  29558. c = *loaded;
  29559. s.channels[0] = c;
  29560. }, false);
  29561. offline.dispatchPendingMessages();
  29562. auto page = lynx::makeHelixEditor (offline, [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; }, 0);
  29563. const auto write = [&prefix, &page, &offline] (const char* name) {
  29564. offline.dispatchPendingMessages();
  29565. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29566. file.deleteFile();
  29567. juce::FileOutputStream out (file);
  29568. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*page), out);
  29569. };
  29570. check ("window page", page->getWidth() > 0 && page->getHeight() > lynx::helixDeviceHeight + 100);
  29571. check ("Helix panel inside", lynx::helixcards::showView (*page, 0, 0, 0) == 1);
  29572. write ("01-window");
  29573. lynx::helixcards::showView (*page, 0, 3, 0);
  29574. write ("02-lfo1-drawn");
  29575. lynx::helixcards::showView (*page, 1, 0, 0);
  29576. write ("03-matrix");
  29577. // the window's paint cost (device + strip, the Mod Sources page): 60 whole frames off screen, the best of 3 runs
  29578. lynx::helixcards::showView (*page, 0, 0, 0);
  29579. double best = 1.0e9;
  29580. for (int run = 0; run < 3; ++run)
  29581. {
  29582. juce::Image image (juce::Image::ARGB, page->getWidth(), page->getHeight(), true);
  29583. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  29584. for (int f = 0; f < 60; ++f)
  29585. {
  29586. juce::Graphics g (image);
  29587. page->paintEntireComponent (g, false);
  29588. }
  29589. best = std::min (best, (juce::Time::getMillisecondCounterHiRes() - t0) / 60.0);
  29590. }
  29591. checks << "paint " << juce::String (best, 3) << " ms per frame (" << page->getWidth() << " x " << page->getHeight() << ")\n";
  29592. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  29593. }
  29594. void runLiveShot190ce (const juce::String& prefix)
  29595. {
  29596. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29597. lynx::AudioEngine offline (false);
  29598. lynx::MainComponent ui (offline, false);
  29599. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  29600. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  29601. const auto write = [&prefix, &ui, &offline] (const char* name) {
  29602. offline.dispatchPendingMessages();
  29603. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29604. file.deleteFile();
  29605. juce::FileOutputStream out (file);
  29606. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  29607. };
  29608. juce::String checks;
  29609. const auto check = [&checks] (const char* what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  29610. // a small library of its own (empty files: only names are shown)
  29611. const auto lib = juce::File (prefix + "-library");
  29612. lib.deleteRecursively();
  29613. for (const auto* path : { "Drums/Kicks/Kick Hard.wav", "Drums/Kicks/Kick Soft.wav", "Drums/Snare Tight.wav", "Drums/Hat Closed.wav",
  29614. "Loops/Break 120.wav", "Loops/Shaker 98.wav", "Textures/Vinyl Noise.wav", "Textures/Rain.wav" })
  29615. lib.getChildFile (path).create();
  29616. auto& browser = ui.getBrowserForSnapshot();
  29617. auto& store = lynx::BrowserComponent::collectionStore();
  29618. store = {};
  29619. const auto item = [&lib] (const char* path) { return lib.getChildFile (path).getFullPathName().toStdString(); };
  29620. ui.setVisible (true);
  29621. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  29622. ui.setClipLaunchWorkflow (true);
  29623. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  29624. offline.editSong ([] (lynx::Song& s) {
  29625. if (s.channels.size() < 2)
  29626. s.channels.resize (2);
  29627. s.channels[0].name = "Bass synth";
  29628. s.channels[0].mixerTrack = 2;
  29629. s.channels[1].mixerTrack = 3;
  29630. if (s.mixer.size() < 4)
  29631. s.mixer.resize (4);
  29632. s.mixer[2].name = "Bass";
  29633. s.mixer[2].effects.clear();
  29634. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  29635. {
  29636. lynx::EffectSlot fx;
  29637. fx.kind = kind;
  29638. const auto& info = lynx::effectInfo (kind);
  29639. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  29640. fx.params[k] = info.params[k].defaultValue;
  29641. s.mixer[2].effects.push_back (fx);
  29642. }
  29643. s.mixer[2].effects[1].enabled = false; // the compressor: off, at half mix
  29644. s.mixer[2].effects[1].mix = 0.5f;
  29645. while (s.patterns.size() < 2)
  29646. s.patterns.emplace_back();
  29647. s.patterns[0].name = "Bass line";
  29648. lynx::Note note;
  29649. note.channel = 0;
  29650. note.key = 36;
  29651. s.patterns[0].notes = { note };
  29652. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  29653. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  29654. s.playlistTracks[1].name = "Bass";
  29655. lynx::Clip clip;
  29656. clip.pattern = 0;
  29657. clip.length = 4 * lynx::ppq;
  29658. lynx::launcher::setClip (s, 1, 0, clip);
  29659. }, false);
  29660. offline.dispatchPendingMessages();
  29661. auto* detail = ui.getDetailViewForSnapshot();
  29662. if (detail == nullptr)
  29663. {
  29664. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  29665. return;
  29666. }
  29667. detail->showSelection (1, 0);
  29668. detail->setPage (lynx::DetailView::Page::devices);
  29669. detail->selectCardForCheck (2); // the compressor (card 0 is the instrument)
  29670. write ("01-devices"); // the cards' title buttons: hot-swap, save, fold
  29671. saveMenus (juce::StringArray { "Device (effect card)" }, std::vector<juce::PopupMenu> { detail->cardMenuForSnapshot (2) }, prefix + "-02-device-menu.png");
  29672. // hot-swap on for the compressor: the Browser's bar, the Plugin database's effects, the card's button lit
  29673. const auto compressor = lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1);
  29674. browser.beginHotSwap (compressor);
  29675. write ("03-hotswap-effect");
  29676. check ("hot-swap links the compressor", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  29677. // a swap through the Browser itself (the row of LYNX's Reverb, then Enter): the slot keeps its place, its off
  29678. // state and its Mix; the link moves to the new device
  29679. {
  29680. browser.showPluginDatabase ("LYNX SHARE", 0); // (the folder of LYNX's own effects, opened as a click would)
  29681. browser.selectRowForSnapshot (lynx::tr (lynx::effectInfo (lynx::EffectKind::reverb).name));
  29682. write ("03a-hotswap-row"); // the candidate's row selected
  29683. check ("swap: Enter on the Reverb row is taken by hot-swap", browser.hotSwapLoadSelected());
  29684. offline.dispatchPendingMessages();
  29685. const auto& slot = offline.getSong().mixer[2].effects[1];
  29686. // (round 190cy: the device comes in with its own on / off state, on, as in Live 12.4.16; the Mix stays)
  29687. 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);
  29688. check ("swap: three effects as before", offline.getSong().mixer[2].effects.size() == 3);
  29689. check ("swap: the Browser is linked to the new device", browser.isHotSwapping() && browser.hotSwapTarget() == lynx::hotswap::targetOfEffect (offline.getSong(), 2, 1)
  29690. && ! (browser.hotSwapTarget() == compressor));
  29691. write ("03b-hotswap-swapped");
  29692. offline.undo();
  29693. offline.dispatchPendingMessages();
  29694. const auto& back = offline.getSong().mixer[2].effects[1];
  29695. check ("undo: the compressor is back with its instance", back.kind == lynx::EffectKind::compressor && back.instance.id == compressor.instance);
  29696. check ("undo: the Browser is still linked to it", browser.isHotSwapping() && browser.hotSwapTarget() == compressor);
  29697. }
  29698. // round 190cy (Live 12.4.16 live check 190cw shot 02a): hot-swap starts on the device's current preset. The
  29699. // compressor got its settings from a saved preset of LYNX's ("Glue bus", in this run's own settings folder)
  29700. {
  29701. browser.endHotSwap();
  29702. const auto folder = lynx::pluginheader::userFolder (lynx::EffectKind::compressor);
  29703. folder.createDirectory();
  29704. const auto& fx = offline.getSong().mixer[2].effects[1];
  29705. for (const auto* name : { "Glue bus", "Gentle", "Parallel smash" })
  29706. folder.getChildFile (juce::String (name) + ".lynxpreset").replaceWithText (lynx::presets::toText (lynx::EffectKind::compressor, name, fx.params));
  29707. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects[1].presetName = "Glue bus"; }, false);
  29708. offline.dispatchPendingMessages();
  29709. browser.beginHotSwap (compressor);
  29710. write ("03c-hotswap-current-preset");
  29711. check ("hot-swap starts on the current preset", browser.getSelectedFile() == folder.getChildFile ("Glue bus.lynxpreset"));
  29712. // a preset of the same effect swapped in comes in on (the compressor was off)
  29713. browser.selectRowForSnapshot ("Gentle.lynxpreset");
  29714. check ("swap: the preset row is taken by hot-swap", browser.hotSwapLoadSelected());
  29715. offline.dispatchPendingMessages();
  29716. const auto& now = offline.getSong().mixer[2].effects[1];
  29717. check ("swap: the preset's settings, the device on", now.kind == lynx::EffectKind::compressor && now.presetName == "Gentle" && now.enabled);
  29718. write ("03d-hotswap-preset-swapped");
  29719. offline.undo();
  29720. offline.dispatchPendingMessages();
  29721. check ("undo: the compressor off again", ! offline.getSong().mixer[2].effects[1].enabled);
  29722. browser.endHotSwap();
  29723. check ("hot-swap ended: the preset list goes", ! browser.isHotSwapping());
  29724. browser.beginHotSwap (compressor);
  29725. }
  29726. // linked to the instrument instead
  29727. const auto bass = lynx::hotswap::targetOfChannel (offline.getSong(), 0);
  29728. browser.beginHotSwap (bass);
  29729. detail->selectCardForCheck (0);
  29730. write ("04-hotswap-instrument");
  29731. check ("re-link to the instrument", browser.hotSwapTarget() == bass);
  29732. browser.endHotSwap();
  29733. check ("hot-swap ended", ! browser.isHotSwapping());
  29734. write ("05-hotswap-ended"); // the Browser as it was before
  29735. // the device is deleted while linked: the mode ends by itself
  29736. browser.beginHotSwap (lynx::hotswap::targetOfEffect (offline.getSong(), 2, 2));
  29737. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.pop_back(); });
  29738. offline.dispatchPendingMessages();
  29739. check ("deleting the linked device ends hot-swap", ! browser.isHotSwapping());
  29740. offline.undo();
  29741. offline.dispatchPendingMessages();
  29742. // Duplicate (Ctrl+D) of the EQ
  29743. check ("duplicate", detail->duplicateCardForCheck (1));
  29744. offline.dispatchPendingMessages();
  29745. check ("duplicate: four effects, EQ twice", offline.getSong().mixer[2].effects.size() == 4 && offline.getSong().mixer[2].effects[1].kind == lynx::EffectKind::eq
  29746. && offline.getSong().mixer[2].effects[0].instance.id != offline.getSong().mixer[2].effects[1].instance.id);
  29747. write ("06-duplicated");
  29748. // --- collections ---
  29749. browser.showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  29750. ui.waitForBrowserForSnapshot();
  29751. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 0, true);
  29752. browser.setInCollection (item ("Drums/Snare Tight.wav"), 0, true);
  29753. browser.setInCollection (item ("Loops"), 0, true);
  29754. browser.setTab (lynx::BrowserComponent::starredTab);
  29755. write ("07-starred-only"); // only Starred shown: the tab as it always was
  29756. browser.setInCollection (item ("Drums/Kicks/Kick Hard.wav"), 4, true); // also Blue
  29757. browser.setInCollection (item ("Loops/Break 120.wav"), 4, true);
  29758. browser.setInCollection (item ("Textures/Vinyl Noise.wav"), 3, true);
  29759. browser.setInCollection (item ("Textures/Rain.wav"), 3, true);
  29760. browser.setInCollection (item ("Drums/Hat Closed.wav"), 1, true);
  29761. store.rename (3, "Textures");
  29762. browser.setCollectionShown (1, true);
  29763. browser.setCollectionShown (3, true);
  29764. browser.setCollectionShown (4, true);
  29765. write ("08-collections"); // a heading per collection shown
  29766. check ("collections: four shown", store.shown().size() == 4);
  29767. check ("collections: an item in two", store.mask (item ("Drums/Kicks/Kick Hard.wav")) == 0b10001);
  29768. // round 190cy: the Clip-launch workflow's row menu lists the collections flat, as Live's item menu (shot 05);
  29769. // the Pattern workflow keeps the "Collections" sub-menu
  29770. browser.setLiveItemMenus (false);
  29771. saveMenus (juce::StringArray { "Collections (Pattern workflow: a row's sub-menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  29772. prefix + "-09-collections-menu.png");
  29773. browser.setLiveItemMenus (true);
  29774. saveMenus (juce::StringArray { "Collections (Clip-launch workflow: a row's menu)" }, std::vector<juce::PopupMenu> { browser.collectionsMenuForSnapshot (item ("Drums/Kicks/Kick Hard.wav")) },
  29775. prefix + "-09b-collections-flat.png");
  29776. // the key of a hidden collection (6, Purple) labels the row and the collection appears
  29777. check ("hidden collection: not shown before", ! store.isShown (5));
  29778. browser.setInCollection (item ("Textures/Rain.wav"), 5, true);
  29779. check ("hidden collection: its key shows it", store.isShown (5) && store.has (item ("Textures/Rain.wav"), 5));
  29780. write ("08b-hidden-collection-shown");
  29781. saveMenus (juce::StringArray { "Browser options" }, std::vector<juce::PopupMenu> { browser.buildViewMenu() }, prefix + "-10-browser-options.png");
  29782. browser.setTab (lynx::BrowserComponent::allTab);
  29783. write ("11-all-tab-chips"); // the colour chips on the rows of the ALL tab
  29784. browser.setSearchForSnapshot ("textures");
  29785. ui.waitForBrowserForSnapshot();
  29786. write ("12-search-collection-name"); // found by the collection's name
  29787. browser.setSearchForSnapshot ({});
  29788. // the file round trip
  29789. {
  29790. const auto text = store.toText();
  29791. check ("collections: text round trip", lynx::collections::Store::fromText (text) == store);
  29792. }
  29793. store = {};
  29794. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  29795. lib.deleteRecursively();
  29796. }
  29797. void runLinkShot190gl (const juce::String& prefix)
  29798. {
  29799. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29800. lynx::AudioEngine offline (false);
  29801. lynx::MainComponent ui (offline, false);
  29802. ui.setSize (1600, 900);
  29803. ui.setVisible (true);
  29804. juce::String checks;
  29805. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  29806. const auto writeImage = [&prefix] (const juce::Image& image, const char* name) {
  29807. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29808. file.deleteFile();
  29809. juce::FileOutputStream out (file);
  29810. juce::PNGImageFormat().writeImageToStream (image, out);
  29811. };
  29812. const auto toolbarShot = [&] (const char* name) {
  29813. ui.tickLinkForSnapshot();
  29814. writeImage (lynx::shot::snapshot (ui, ui.getToolbarBoundsForSnapshot()), name);
  29815. };
  29816. auto& link = offline.getLink();
  29817. auto& transport = offline.getTransport();
  29818. link.deviceStarted (44100.0);
  29819. // the audio callbacks the offline engine has none of: Link's per-block step, in real time
  29820. const auto pump = [&] (double seconds, std::function<bool()> until = {}) {
  29821. const auto end = juce::Time::getMillisecondCounterHiRes() + seconds * 1000.0;
  29822. while (juce::Time::getMillisecondCounterHiRes() < end)
  29823. {
  29824. const auto start = link.beginBlock (transport, 256, 0.0);
  29825. if (start >= 0)
  29826. transport.playing.store (true);
  29827. if (transport.playing.load())
  29828. transport.positionTicks.store (transport.positionTicks.load() + 256 * transport.ticksPerSample());
  29829. juce::Thread::sleep (6);
  29830. if (until && until())
  29831. return true;
  29832. }
  29833. return ! until || until();
  29834. };
  29835. auto peer = lynx::AbletonLink::makeTestPeer (97.0); // the other app in the session (it was there first)
  29836. juce::Thread::sleep (1500); // (a session that started at the same moment as LYNX's could take either tempo)
  29837. using lynx::toolbarlayout::Group;
  29838. // FL's Pattern layout: no Link toggle on a new install
  29839. check ("Pattern layout: the Link toggle is hidden by default", ! ui.getToolbarLayoutForSnapshot().isShown (Group::link));
  29840. toolbarShot ("toolbar-fl-default");
  29841. // shown by hand (Settings › Ableton Link › Show Link Toggle): "Link", off
  29842. auto layout = ui.getToolbarLayoutForSnapshot();
  29843. layout.setShown (Group::link, true);
  29844. ui.setToolbarLayoutForSnapshot (layout);
  29845. toolbarShot ("toolbar-fl-link-off");
  29846. check ("off: the toggle says Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: Link"));
  29847. // on: the session the other peer runs (its tempo, 97 BPM, wins over the project's)
  29848. link.setEnabled (true, offline.getSong().bpm);
  29849. // (a new peer is counted at once; its session's tempo is taken after Link measured it, a moment later)
  29850. const auto joined = pump (8.0, [&] { return link.peers() > 0 && link.startProgress() >= 0.0 && std::abs (link.sessionTempo() - 97.0) < 1e-3; });
  29851. check ("Link on: one peer found", joined && link.peers() == 1);
  29852. 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);
  29853. toolbarShot ("toolbar-fl-link-on");
  29854. check ("on with one peer: the toggle says 1 Link", ui.getLinkToggleForSnapshot().text() == lynx::trc ("@Ableton Link: {0} Link").replace ("{0}", "1"));
  29855. check ("stopped with a peer: the position display shows the session's progress", link.startProgress() >= 0.0);
  29856. // the Clip-launch layout: the toggle is shown by default (the reference DAW's "Show Link Toggle": Show)
  29857. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  29858. ui.setClipLaunchWorkflow (true);
  29859. check ("Clip-launch layout: the Link toggle is shown by default", ui.getToolbarLayoutForSnapshot().isShown (Group::link));
  29860. pump (0.4);
  29861. toolbarShot ("toolbar-cliplaunch-1link");
  29862. writeImage (lynx::shot::snapshot (ui), "window-cliplaunch");
  29863. // Play: it waits for the session's phase (the play button lit, the progress bar running), then starts
  29864. transport.playing.store (true);
  29865. pump (0.05);
  29866. const auto waited = offline.isLinkWaiting();
  29867. check ("Play with a peer waits for the session's phase", waited);
  29868. toolbarShot ("toolbar-cliplaunch-waiting");
  29869. const auto started = pump (4.0, [&] { return transport.playing.load() && ! offline.isLinkWaiting(); });
  29870. check ("then playback starts on the session's phase", started);
  29871. pump (0.5);
  29872. toolbarShot ("toolbar-cliplaunch-playing");
  29873. check ("playing: no progress bar", link.startProgress() < 0.0);
  29874. // the toggle's drop-down and the Options menu
  29875. saveMenus (juce::StringArray { lynx::trc ("@Ableton Link: Link") }, std::vector<juce::PopupMenu> { ui.getLinkToggleForSnapshot().makeMenu() },
  29876. prefix + "-menu-link.png");
  29877. {
  29878. const auto names = ui.getMenuNamesForSnapshot();
  29879. for (int m = 0; m < names.size(); ++m)
  29880. if (names[m] == lynx::tr ("Options"))
  29881. saveMenus (juce::StringArray { names[m] }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (m) }, prefix + "-menu-options.png");
  29882. }
  29883. // Settings › Ableton Link
  29884. {
  29885. lynx::SettingsHooks hooks;
  29886. hooks.linkToggleShown = [] { return true; };
  29887. auto panel = lynx::makeSettingsPanel (offline, lynx::SettingsPage::link, false, hooks);
  29888. panel->setSize (680, 620);
  29889. writeImage (lynx::shot::snapshot (*panel), "settings-link");
  29890. }
  29891. // off: the project's own tempo comes back on the display
  29892. transport.playing.store (false);
  29893. pump (0.1);
  29894. link.setEnabled (false, offline.getSong().bpm);
  29895. pump (0.1);
  29896. toolbarShot ("toolbar-cliplaunch-link-off");
  29897. check ("off: the tempo display shows the project's tempo again", std::abs (offline.shownTempo() - offline.getSong().bpm) < 1e-9);
  29898. const auto stats = link.stats();
  29899. checks << "audio-thread cost of the Link step: mean " << juce::String (stats.meanUs, 2) << " us, max " << juce::String (stats.maxUs, 1)
  29900. << " us over " << (juce::int64) stats.blocks << " blocks\n";
  29901. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  29902. }
  29903. // LYNX --communityshot190hp <prefix> (round 190hp): the three community slices off-screen, with checks in
  29904. // prefix-checks.txt — B9 the MIDI Map Mode's "In every project (LYNX)" (the row menu, the Mapping Browser with the
  29905. // global rows, a new project still playing on the mapped CC, Settings' list), B16 the Mixer menu's Mix snapshots
  29906. // (take, recall, Compare A/B, the .lynx round trip), B18 the audio clip menu's "Split at silence..." (the dialog and
  29907. // the Playlist before / after).
  29908. void runCommunityShot190hp (const juce::String& prefix)
  29909. {
  29910. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  29911. lynx::AudioEngine offline (false);
  29912. lynx::MainComponent ui (offline, false);
  29913. ui.setSize (1600, 900);
  29914. const auto write = [&prefix] (juce::Component& c, const char* name) {
  29915. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  29916. file.deleteFile();
  29917. juce::FileOutputStream out (file);
  29918. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  29919. };
  29920. juce::String checks;
  29921. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  29922. const auto plain = [] (juce::String t) { return t.upToFirstOccurrenceOf ("\t", false, false).removeCharacters ("&"); };
  29923. const auto find = [&plain] (const juce::PopupMenu& menu, const juce::String& text) -> const juce::PopupMenu::Item* {
  29924. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  29925. if (plain (it.getItem().text) == plain (text))
  29926. return &it.getItem();
  29927. return nullptr;
  29928. };
  29929. const auto click = [&find] (const juce::PopupMenu& menu, const juce::String& text) {
  29930. const auto* item = find (menu, text);
  29931. if (item == nullptr || ! item->isEnabled || item->action == nullptr)
  29932. return false;
  29933. item->action();
  29934. return true;
  29935. };
  29936. using namespace lynx::remotemap;
  29937. ui.setVisible (true);
  29938. // ---- B9: the MIDI Map Mode's mappings for every project ---------------------------------------------------------
  29939. ui.setClipLaunchWorkflow (true);
  29940. offline.editSong ([] (lynx::Song& s) {
  29941. auto& grid = lynx::launcher::ensureGrid (s);
  29942. grid.scenes.resize (4);
  29943. assignMidi (s, Target::of (lynx::RemoteAction::play), { 0, 118, -1 });
  29944. assignMidi (s, Target::of (lynx::RemoteAction::stop), { 0, 117, -1 });
  29945. assignMidi (s, Target::sceneLaunch (0), { 0, lynx::linkNoteBase + 44, -1 });
  29946. assignMidi (s, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, -1 });
  29947. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }), { 0, 7, -1 });
  29948. }, false);
  29949. offline.dispatchPendingMessages();
  29950. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist, lynx::workspace::Panel::browser });
  29951. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  29952. ui.setMapMode (Mode::midi);
  29953. auto* list = ui.mappingBrowserForSnapshot();
  29954. if (list == nullptr)
  29955. {
  29956. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no Mapping Browser\n");
  29957. return;
  29958. }
  29959. list->setMode (Mode::midi);
  29960. ui.resized();
  29961. const auto rowOf = [&] (const Target& t) {
  29962. const auto rows = list->rowsShown();
  29963. for (int r = 0; r < (int) rows.size(); ++r)
  29964. if (rows[(std::size_t) r].target == t)
  29965. return r;
  29966. return -1;
  29967. };
  29968. const auto everyProject = lynx::tr ("In every project (LYNX)");
  29969. {
  29970. const auto slotMenu = list->rowMenu (rowOf (Target::slot (0, 0)));
  29971. const auto* item = find (slotMenu, everyProject);
  29972. check ("row menu: a clip slot cannot be for every project (greyed)", item != nullptr && ! item->isEnabled);
  29973. const auto playRow = rowOf (Target::of (lynx::RemoteAction::play));
  29974. list->selectRow (playRow);
  29975. const auto playMenu = list->rowMenu (playRow);
  29976. const auto* p = find (playMenu, everyProject);
  29977. check ("row menu: Play can, unticked", p != nullptr && p->isEnabled && ! p->isTicked);
  29978. saveMenus (juce::StringArray { "Row" }, std::vector<juce::PopupMenu> { playMenu }, prefix + "-b9-01-row-menu.png");
  29979. check ("Play goes to every project", click (playMenu, everyProject) && offline.getMidiPrefs().globalMappings.size() == 1);
  29980. }
  29981. check ("Stop goes too", click (list->rowMenu (rowOf (Target::of (lynx::RemoteAction::stop))), everyProject));
  29982. check ("the Master volume link goes too (FL's global links)",
  29983. click (list->rowMenu (rowOf (Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }))), everyProject)
  29984. && offline.getMidiPrefs().globalLinks.size() == 1 && offline.getSong().midiLinks.empty());
  29985. list->setMode (Mode::midi);
  29986. const auto shown = list->rowsShown();
  29987. check ("Mapping Browser: 2 project rows, then 3 global ones (" + juce::String ((int) shown.size()) + ")",
  29988. shown.size() == 5 && ! shown[0].global && ! shown[1].global && shown[2].global && shown[4].global);
  29989. {
  29990. const auto* ticked = find (list->rowMenu (2), everyProject);
  29991. check ("a global row's item is ticked", ticked != nullptr && ticked->isTicked);
  29992. }
  29993. write (*list, "b9-02-mapping-browser-global");
  29994. // a new project: the global mappings are there and act (CC 118 plays, CC 117 stops)
  29995. offline.setSong (lynx::Song::makeDefault());
  29996. offline.dispatchPendingMessages();
  29997. list->setMode (Mode::midi);
  29998. const auto fresh = list->rowsShown();
  29999. check ("new project: the 3 global rows (" + juce::String ((int) fresh.size()) + ")", fresh.size() == 3 && fresh[0].global);
  30000. write (*list, "b9-03-new-project-browser");
  30001. ui.setMapMode (Mode::off);
  30002. offline.injectControllerForTest (118, 0, 127);
  30003. offline.dispatchPendingMessages();
  30004. check ("new project: CC 118 plays", offline.getTransport().playing.load());
  30005. offline.injectControllerForTest (118, 0, 0);
  30006. offline.injectControllerForTest (117, 0, 127);
  30007. offline.dispatchPendingMessages();
  30008. check ("new project: CC 117 stops", ! offline.getTransport().playing.load());
  30009. offline.injectControllerForTest (7, 0, 0);
  30010. offline.dispatchPendingMessages();
  30011. check ("new project: CC 7 moves the Master", offline.currentTargetValue ({ lynx::AutomationTargetKind::mixerVolume, 0, 0, 0 }) < 0.01f);
  30012. // the Pattern layout: they act there too, and Settings › MIDI lists them
  30013. ui.setClipLaunchWorkflow (false);
  30014. offline.injectControllerForTest (117, 0, 0);
  30015. offline.injectControllerForTest (118, 0, 127);
  30016. offline.dispatchPendingMessages();
  30017. check ("Pattern layout: CC 118 plays", offline.getTransport().playing.load());
  30018. offline.stop();
  30019. // back into one project, then cleared (the settings of this test engine are never written)
  30020. ui.setClipLaunchWorkflow (true);
  30021. ui.setMapMode (Mode::midi);
  30022. list->setMode (Mode::midi);
  30023. check ("back into this project", click (list->rowMenu (rowOf (Target::of (lynx::RemoteAction::play))), everyProject)
  30024. && offline.getMidiPrefs().globalMappings.size() == 1 && offline.getSong().remoteMappings.size() == 1);
  30025. ui.setMapMode (Mode::off);
  30026. ui.setClipLaunchWorkflow (false);
  30027. // ---- B16: Mix snapshots ----------------------------------------------------------------------------------------
  30028. offline.setSong (lynx::Song::makeDefault());
  30029. offline.dispatchPendingMessages();
  30030. offline.editSong ([] (lynx::Song& s) {
  30031. const char* names[] { "Master", "Drums", "Bass", "Keys", "Vox", "Reverb" };
  30032. for (int i = 1; i < 6 && i < (int) s.mixer.size(); ++i)
  30033. s.mixer[(std::size_t) i].name = names[i];
  30034. s.mixer[1].volume = 0.7f;
  30035. s.mixer[4].pan = -0.3f;
  30036. s.setRoute (4, 5, true, 0.5f);
  30037. });
  30038. juce::PopupMenu mixerMenu;
  30039. lynx::mixeroptions::addItems (mixerMenu, offline, false);
  30040. const auto* snaps = find (mixerMenu, lynx::tr ("Mix snapshots (LYNX)"));
  30041. check ("Mixer menu: Mix snapshots (LYNX)", snaps != nullptr && snaps->subMenu != nullptr);
  30042. check ("Take snapshot", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Take snapshot")) && offline.getSong().mixSnapshots.size() == 1);
  30043. offline.editSong ([] (lynx::Song& s) {
  30044. s.mixer[1].volume = 0.4f;
  30045. s.mixer[4].pan = 0.6f;
  30046. s.mixer[3].muted = true;
  30047. s.setRoute (4, 5, false);
  30048. });
  30049. check ("Take snapshot again", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Take snapshot")) && offline.getSong().mixSnapshots.size() == 2);
  30050. {
  30051. const auto menu = lynx::mixeroptions::snapshotsMenu (offline);
  30052. const auto* first = find (menu, juce::String ("Snapshot 1 (B)"));
  30053. check ("snapshot 1 listed as B", first != nullptr && first->subMenu != nullptr && ! first->isTicked);
  30054. const auto* second = find (menu, juce::String ("Snapshot 2 (A)"));
  30055. check ("snapshot 2 ticked: the mix is it", second != nullptr && second->isTicked);
  30056. saveMenus (juce::StringArray { "Mixer", "Mix snapshots (LYNX)", "Snapshot 1" },
  30057. std::vector<juce::PopupMenu> { mixerMenu, menu, first != nullptr ? *first->subMenu : juce::PopupMenu() }, prefix + "-b16-01-menus.png");
  30058. check ("Recall snapshot 1", first != nullptr && click (*first->subMenu, lynx::tr ("Recall")));
  30059. }
  30060. const auto& m = offline.getSong().mixer;
  30061. check ("recalled: fader, pan, mute, send", m[1].volume == 0.7f && m[4].pan == -0.3f && ! m[3].muted && offline.getSong().routes (4, 5));
  30062. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::mixer });
  30063. ui.resized();
  30064. offline.dispatchPendingMessages();
  30065. write (ui, "b16-02-mixer-recalled");
  30066. check ("Compare A/B", click (lynx::mixeroptions::snapshotsMenu (offline), lynx::tr ("Compare A/B: back to \"{0}\"", { "Snapshot 2" }))
  30067. && m[1].volume == 0.4f && m[3].muted);
  30068. offline.undo();
  30069. check ("one undo step: back to snapshot 1", m[1].volume == 0.7f);
  30070. {
  30071. const auto file = juce::File (prefix + "-b16-snapshots.lynx");
  30072. juce::String error;
  30073. const auto saved = lynx::ProjectFile::save (offline.getSong(), file, error);
  30074. const auto back = lynx::ProjectFile::load (file, error);
  30075. check ("saved and loaded: the snapshots and A/B", saved && back && back->mixSnapshots == offline.getSong().mixSnapshots
  30076. && back->mixSnapshotCurrent == offline.getSong().mixSnapshotCurrent
  30077. && back->mixSnapshotPrevious == offline.getSong().mixSnapshotPrevious);
  30078. file.deleteFile();
  30079. }
  30080. // ---- B18: Split at silence -------------------------------------------------------------------------------------
  30081. {
  30082. // a "vocal take": 0.5 s silence, three phrases with pauses of 0.6 s and 0.15 s, quiet hiss in the gaps
  30083. const double rate = 44100.0;
  30084. juce::AudioBuffer<float> buffer (1, (int) (rate * 4.0));
  30085. buffer.clear();
  30086. juce::Random noise (190);
  30087. for (int i = 0; i < buffer.getNumSamples(); ++i)
  30088. {
  30089. const auto t = i / rate;
  30090. const auto phrase = (t >= 0.5 && t < 1.4) || (t >= 2.0 && t < 2.6) || (t >= 2.75 && t < 3.3);
  30091. 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)))
  30092. : (noise.nextFloat() - 0.5f) * 0.0004f);
  30093. }
  30094. const auto wav = juce::File (prefix + "-b18-take.wav");
  30095. wav.deleteFile();
  30096. juce::WavAudioFormat format;
  30097. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (format.createWriterFor (wav.createOutputStream().release(), rate, 1, 16, {}, 0)))
  30098. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  30099. auto song = lynx::Song::makeDefault();
  30100. song.channels.push_back ({});
  30101. song.channels.back().name = "Vocal take";
  30102. song.channels.back().instrument = lynx::InstrumentKind::audioClip;
  30103. song.channels.back().samplePath = wav.getFullPathName().toStdString();
  30104. lynx::Clip c;
  30105. c.kind = lynx::ClipKind::audio;
  30106. c.channel = (int) song.channels.size() - 1;
  30107. c.track = 1;
  30108. c.start = 4 * lynx::ppq;
  30109. c.length = (std::int64_t) std::llround (4.0 * song.bpm / 60.0 * lynx::ppq); // (the whole file at the song tempo)
  30110. song.playlist.push_back (c);
  30111. offline.setSong (std::move (song));
  30112. offline.dispatchPendingMessages();
  30113. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  30114. ui.resized();
  30115. auto& playlist = ui.getPlaylistForSnapshot();
  30116. const auto index = (int) offline.getSong().playlist.size() - 1;
  30117. const auto menu = playlist.getClipMenuForSnapshot (index);
  30118. const auto* item = find (menu, lynx::tr ("Split at silence..."));
  30119. const auto* splitHere = find (menu, lynx::tr ("Split here"));
  30120. check ("clip menu: Split at silence... in LYNX extras, enabled", item != nullptr && item->isEnabled && splitHere != nullptr);
  30121. savePng (columnMenuImage (menu), prefix + "-b18-01-clip-menu.png");
  30122. {
  30123. auto dialog = playlist.makeSplitSilenceDialogForSnapshot (index);
  30124. write (*dialog, "b18-02-dialog");
  30125. }
  30126. offline.dispatchPendingMessages();
  30127. write (ui, "b18-03-playlist-before");
  30128. juce::String why;
  30129. const auto made = playlist.splitClipsAtSilence ({ index }, lynx::PlaylistComponent::splitSilenceOptions(), &why);
  30130. offline.dispatchPendingMessages();
  30131. const auto& clips = offline.getSong().playlist;
  30132. std::vector<const lynx::Clip*> audio;
  30133. for (const auto& x : clips)
  30134. if (x.kind == lynx::ClipKind::audio)
  30135. audio.push_back (&x);
  30136. std::sort (audio.begin(), audio.end(), [] (const lynx::Clip* a, const lynx::Clip* b) { return a->start < b->start; });
  30137. const auto secondsAt = [&] (std::int64_t ticks) { return (double) (ticks - 4 * lynx::ppq) / lynx::ppq * 60.0 / offline.getSong().bpm; };
  30138. check ("split into 2 clips (the 0.15 s pause stays inside): " + juce::String (made) + ", " + why, made == 2 && audio.size() == 2);
  30139. if (audio.size() == 2)
  30140. check ("the clips start at the phrases less the pre-roll, end after them: " + juce::String (secondsAt (audio[0]->start), 3) + "-"
  30141. + juce::String (secondsAt (audio[0]->end()), 3) + ", " + juce::String (secondsAt (audio[1]->start), 3) + "-" + juce::String (secondsAt (audio[1]->end()), 3),
  30142. std::abs (secondsAt (audio[0]->start) - 0.49) < 0.02 && std::abs (secondsAt (audio[0]->end()) - 1.45) < 0.02
  30143. && std::abs (secondsAt (audio[1]->start) - 1.99) < 0.02 && std::abs (secondsAt (audio[1]->end()) - 3.35) < 0.02
  30144. && audio[1]->offset - audio[0]->offset == audio[1]->start - audio[0]->start);
  30145. write (ui, "b18-04-playlist-after");
  30146. offline.undo();
  30147. check ("one undo step", offline.getSong().playlist.size() == clips.size() && std::count_if (offline.getSong().playlist.begin(), offline.getSong().playlist.end(),
  30148. [] (const lynx::Clip& x) { return x.kind == lynx::ClipKind::audio; }) == 1);
  30149. lynx::stripsilence::Options loud;
  30150. loud.thresholdDb = -1.0f;
  30151. check ("all below the threshold: nothing split", playlist.splitClipsAtSilence ({ index }, loud, &why) == 0);
  30152. wav.deleteFile();
  30153. }
  30154. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  30155. }
  30156. void runMapShot190ef (const juce::String& prefix)
  30157. {
  30158. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30159. lynx::AudioEngine offline (false);
  30160. lynx::MainComponent ui (offline, false);
  30161. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  30162. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30163. const auto write = [&prefix] (juce::Component& c, const char* name) {
  30164. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  30165. file.deleteFile();
  30166. juce::FileOutputStream out (file);
  30167. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  30168. };
  30169. juce::String checks;
  30170. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  30171. using namespace lynx::remotemap;
  30172. ui.setVisible (true);
  30173. // the Pattern layout first: Ctrl+M stays FL's metronome there and no map mode starts
  30174. {
  30175. const auto before = offline.getTransport().metronome.load();
  30176. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  30177. check ("Pattern layout: Ctrl+M is the metronome, no map mode", ui.getMapMode() == Mode::off && offline.getTransport().metronome.load() != before);
  30178. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  30179. ui.setMapMode (Mode::midi);
  30180. check ("Pattern layout: setMapMode stays off", ui.getMapMode() == Mode::off);
  30181. }
  30182. ui.setClipLaunchWorkflow (true);
  30183. offline.editSong ([] (lynx::Song& s) {
  30184. if (s.mixer.size() < 6)
  30185. s.mixer.resize (6);
  30186. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Reverb" };
  30187. for (int i = 1; i < 6; ++i)
  30188. s.mixer[(std::size_t) i].name = inserts[i];
  30189. const int channels = (int) s.channels.size();
  30190. s.channels.resize ((std::size_t) channels + 3);
  30191. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  30192. for (int k = 0; k < 3; ++k)
  30193. {
  30194. auto& ch = s.channels[(std::size_t) (channels + k)];
  30195. ch.name = names[k];
  30196. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  30197. ch.mixerTrack = k + 1;
  30198. }
  30199. s.mixer[2].effects.clear();
  30200. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor })
  30201. {
  30202. lynx::EffectSlot fx;
  30203. fx.kind = kind;
  30204. const auto& info = lynx::effectInfo (kind);
  30205. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  30206. fx.params[k] = info.params[k].defaultValue;
  30207. s.mixer[2].effects.push_back (fx);
  30208. }
  30209. while (s.patterns.size() < 3)
  30210. s.patterns.emplace_back();
  30211. const char* patterns[] { "Beat", "Bassline", "Chords" };
  30212. for (int p = 0; p < 3; ++p)
  30213. {
  30214. auto& pattern = s.patterns[(std::size_t) p];
  30215. pattern.name = patterns[p];
  30216. lynx::Note n;
  30217. n.channel = channels + p;
  30218. n.key = 48 + p * 5;
  30219. pattern.notes = { n };
  30220. pattern.lengthTicks = 4 * lynx::ppq;
  30221. }
  30222. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  30223. const char* tracks[] { "Drums", "Bass", "Keys", "Vox" };
  30224. for (int t = 0; t < 4; ++t)
  30225. s.playlistTracks[(std::size_t) t].name = tracks[t];
  30226. for (int t = 0; t < 3; ++t)
  30227. for (int r = 0; r < 3; ++r)
  30228. {
  30229. lynx::Clip clip;
  30230. clip.pattern = t;
  30231. clip.length = 4 * lynx::ppq;
  30232. lynx::launcher::setClip (s, t, r, clip);
  30233. }
  30234. auto& grid = lynx::launcher::ensureGrid (s);
  30235. const char* scenes[] { "Intro", "Verse", "Drop" };
  30236. grid.scenes.resize (4);
  30237. for (int r = 0; r < 3; ++r)
  30238. grid.scenes[(std::size_t) r].name = scenes[r];
  30239. // some mappings, as the lesson's pictures show them (pads on slots and scenes, knobs on volume and pan)
  30240. assignMidi (s, Target::slot (0, 0), { 0, lynx::linkNoteBase + 36, -1 });
  30241. assignMidi (s, Target::slot (1, 0), { 0, lynx::linkNoteBase + 37, -1 });
  30242. assignMidi (s, Target::sceneLaunch (1), { 0, lynx::linkNoteBase + 44, -1 });
  30243. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }), { 0, 17, -1 });
  30244. assignMidi (s, Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }), { 0, 16, -1 });
  30245. assignMidi (s, Target::of (lynx::RemoteAction::play), { 0, 118, -1 });
  30246. setRange (s, rows (s, Mode::midi)[0], 0.0f, 0.85f);
  30247. assignKey (s, Target::slot (0, 1), 'A');
  30248. assignKey (s, Target::slot (1, 1), 'S');
  30249. assignKey (s, Target::sceneLaunch (2), '3');
  30250. assignKey (s, Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 }), 'V');
  30251. }, false);
  30252. offline.dispatchPendingMessages();
  30253. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist, lynx::workspace::Panel::browser }); // (no floating Channel Rack over the grid)
  30254. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  30255. offline.dispatchPendingMessages();
  30256. ui.resized();
  30257. if (auto* detail = ui.getDetailViewForSnapshot())
  30258. {
  30259. detail->showSelection (1, 0);
  30260. detail->setPage (lynx::DetailView::Page::devices);
  30261. }
  30262. ui.resized();
  30263. offline.dispatchPendingMessages();
  30264. write (ui, "00-clip-launch-before");
  30265. // Ctrl+M in the Clip-launch layout: MIDI Map Mode (the metronome stays as it was)
  30266. const auto metronome = offline.getTransport().metronome.load();
  30267. ui.keyPressed (juce::KeyPress ('M', juce::ModifierKeys::ctrlModifier, 0));
  30268. check ("Clip-launch layout: Ctrl+M starts MIDI Map Mode", ui.getMapMode() == Mode::midi && offline.getTransport().metronome.load() == metronome);
  30269. auto* overlay = ui.mapOverlayForSnapshot();
  30270. auto* list = ui.mappingBrowserForSnapshot();
  30271. if (overlay == nullptr || list == nullptr)
  30272. {
  30273. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no overlay\n");
  30274. return;
  30275. }
  30276. overlay->refresh();
  30277. const auto& spots = overlay->spots();
  30278. 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; }); };
  30279. const auto params = [&] (lynx::AutomationTargetKind k) {
  30280. 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; });
  30281. };
  30282. check ("overlay: clip slots (" + juce::String (count (lynx::RemoteAction::clipSlot)) + ")", count (lynx::RemoteAction::clipSlot) >= 12);
  30283. check ("overlay: scene launch buttons (" + juce::String (count (lynx::RemoteAction::sceneLaunch)) + ")", count (lynx::RemoteAction::sceneLaunch) >= 4);
  30284. check ("overlay: track stop buttons", count (lynx::RemoteAction::trackStop) >= 4);
  30285. check ("overlay: Stop all clips, Session Record", count (lynx::RemoteAction::stopAllClips) == 1 && count (lynx::RemoteAction::sessionRecord) == 1);
  30286. check ("overlay: transport play / stop / record / metronome", count (lynx::RemoteAction::play) == 1 && count (lynx::RemoteAction::stop) == 1
  30287. && count (lynx::RemoteAction::record) == 1 && count (lynx::RemoteAction::metronome) == 1);
  30288. check ("overlay: tempo", params (lynx::AutomationTargetKind::tempo) == 1);
  30289. check ("overlay: mixer volume / pan (" + juce::String (params (lynx::AutomationTargetKind::mixerVolume)) + " / " + juce::String (params (lynx::AutomationTargetKind::mixerPan)) + ")",
  30290. params (lynx::AutomationTargetKind::mixerVolume) >= 3 && params (lynx::AutomationTargetKind::mixerPan) >= 3);
  30291. check ("overlay: device knobs (" + juce::String (params (lynx::AutomationTargetKind::effectParam)) + ")", params (lynx::AutomationTargetKind::effectParam) >= 2);
  30292. // a click on Keys' first slot selects it; a MIDI control assigns it (as the engine's catch would)
  30293. for (const auto& spot : spots)
  30294. if (spot.target == Target::slot (2, 0))
  30295. {
  30296. auto source = juce::Desktop::getInstance().getMainMouseSource();
  30297. const auto now = juce::Time::getCurrentTime();
  30298. const auto at = spot.area.getCentre().toFloat();
  30299. overlay->mouseDown (juce::MouseEvent (source, at, juce::ModifierKeys (juce::ModifierKeys::leftButtonModifier), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
  30300. overlay, overlay, now, at, now, 1, false));
  30301. break;
  30302. }
  30303. if (spots.empty())
  30304. {
  30305. juce::File (prefix + "-checks.txt").replaceWithText (checks + "FAIL no spots\n");
  30306. return;
  30307. }
  30308. check ("a click selects the slot", overlay->selection() == std::optional<Target> (Target::slot (2, 0)));
  30309. check ("the overlay takes clicks only on elements", overlay->hitTest (spots.front().area.getCentreX(), spots.front().area.getCentreY()) && ! overlay->hitTest (2, ui.getHeight() - 2));
  30310. check ("a pad assigns it", overlay->assignMidi ({ 0, lynx::linkNoteBase + 38, -1 }) && midiOf (offline.getSong(), Target::slot (2, 0)).number == lynx::linkNoteBase + 38);
  30311. check ("the same pad again on track 0 is refused", ! (overlay->select (Target::slot (0, 2)), overlay->assignMidi ({ 0, lynx::linkNoteBase + 36, -1 })));
  30312. overlay->select (Target::slot (2, 0));
  30313. list->setMode (Mode::midi);
  30314. list->selectRow (0);
  30315. ui.resized();
  30316. overlay->refresh();
  30317. write (ui, "01-midi-map-mode");
  30318. check ("Mapping Browser rows (MIDI): " + juce::String ((int) list->rowsShown().size()), list->rowsShown().size() == 7);
  30319. write (*list, "02-mapping-browser-midi");
  30320. saveMenus (juce::StringArray { "Row" }, std::vector<juce::PopupMenu> { list->rowMenu (0) }, prefix + "-03-row-menu.png");
  30321. // Ctrl+K: Key Map Mode; a key assigns the selected element
  30322. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  30323. check ("Ctrl+K switches to Key Map Mode", ui.getMapMode() == Mode::key && offline.getMapMode() == Mode::key);
  30324. overlay->select (Target::sceneLaunch (0));
  30325. ui.keyPressed (juce::KeyPress ('1', {}, '1'));
  30326. check ("a key assigns the selected scene", keyOf (offline.getSong(), Target::sceneLaunch (0)).key == '1');
  30327. overlay->select (Target::sceneLaunch (1));
  30328. ui.keyPressed (juce::KeyPress ('A', {}, 'a'));
  30329. check ("a key already on a slot is refused for a scene", ! keyOf (offline.getSong(), Target::sceneLaunch (1)).found);
  30330. overlay->refresh();
  30331. write (ui, "04-key-map-mode");
  30332. write (*list, "05-mapping-browser-key");
  30333. {
  30334. // round 190em: Min / Max in the parameter's unit, Path "<track> | Mixer", Name "Track Volume" / "Slot n"
  30335. const lynx::remotemap::Target volume = Target::parameter ({ lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 });
  30336. const auto [path, name] = lynx::mapmode::describe (offline, volume);
  30337. check ("browser: volume row Path / Name = " + path + " / " + name, path == "Bass | Mixer" && name == "Track Volume");
  30338. check ("browser: volume Min / Max = " + lynx::mapmode::rangeText (offline, volume, 0.0f) + " / " + lynx::mapmode::rangeText (offline, volume, 1.0f),
  30339. lynx::mapmode::rangeText (offline, volume, 0.0f) == juce::String::fromUTF8 ("\xe2\x88\x92\xe2\x88\x9e dB")
  30340. && lynx::mapmode::rangeText (offline, volume, 1.0f).endsWith (" dB"));
  30341. const lynx::remotemap::Target pan = Target::parameter ({ lynx::AutomationTargetKind::mixerPan, 1, 0, 0 });
  30342. check ("browser: pan Min / Max = " + lynx::mapmode::rangeText (offline, pan, 0.25f) + " / " + lynx::mapmode::rangeText (offline, pan, 0.5f),
  30343. lynx::mapmode::rangeText (offline, pan, 0.25f) == "50L" && lynx::mapmode::rangeText (offline, pan, 0.5f) == "C"
  30344. && lynx::mapmode::rangeText (offline, pan, 1.0f) == "100R");
  30345. const auto typed = lynx::mapmode::rangeValueOf (offline, volume, "0 dB");
  30346. check ("browser: typing 0 dB", typed.has_value() && std::abs (lynx::mapmode::rangeText (offline, volume, *typed).getDoubleValue()) < 0.15);
  30347. check ("browser: typing 50L", lynx::mapmode::rangeValueOf (offline, pan, "50L") == std::optional<float> (0.25f));
  30348. check ("browser: Key column = " + lynx::mapmode::listKeyText ('V') + ", " + lynx::mapmode::listKeyText ('3'),
  30349. lynx::mapmode::listKeyText ('V') == "Key v" && lynx::mapmode::listKeyText ('3') == "Key 3");
  30350. check ("browser: slot row Name = " + lynx::mapmode::describe (offline, Target::slot (0, 2)).second,
  30351. lynx::mapmode::describe (offline, Target::slot (0, 2)) == std::pair<juce::String, juce::String> ("Drums", "Slot 3"));
  30352. }
  30353. // off again: the key mapping on a parameter toggles it between Min and Max
  30354. ui.keyPressed (juce::KeyPress ('K', juce::ModifierKeys::ctrlModifier, 0));
  30355. check ("Ctrl+K again ends it", ui.getMapMode() == Mode::off && ! overlay->isVisible() && ! list->isVisible());
  30356. const lynx::AutomationTarget keysVolume { lynx::AutomationTargetKind::mixerVolume, 2, 0, 0 };
  30357. // (round 190em, Live 12.4.16: the first press goes to Min, then Max, then Min)
  30358. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  30359. check ("the mapped key V moves Bass's volume to Min first", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  30360. ui.keyStateChanged (false); // (V is not down any more: its release)
  30361. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  30362. check ("again: to Max", std::abs (offline.currentTargetValue (keysVolume) - 1.0f) < 0.01f);
  30363. ui.keyStateChanged (false);
  30364. ui.keyPressed (juce::KeyPress ('V', {}, 'v'));
  30365. check ("again: to Min", std::abs (offline.currentTargetValue (keysVolume)) < 0.01f);
  30366. ui.keyStateChanged (false);
  30367. // the title bar switches
  30368. ui.setMapMode (Mode::midi);
  30369. write (ui, "06-switches-midi-on");
  30370. ui.setMapMode (Mode::off);
  30371. ui.setClipLaunchWorkflow (false);
  30372. check ("leaving the Clip-launch layout ends the map mode", ui.getMapMode() == Mode::off);
  30373. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  30374. }
  30375. void runSceneShot190ef (const juce::String& prefix)
  30376. {
  30377. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30378. lynx::AudioEngine offline (false);
  30379. lynx::MainComponent ui (offline, false);
  30380. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  30381. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30382. const auto write = [&prefix] (juce::Component& c, const char* name) {
  30383. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  30384. file.deleteFile();
  30385. juce::FileOutputStream out (file);
  30386. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  30387. };
  30388. juce::String checks;
  30389. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  30390. ui.setVisible (true);
  30391. lynx::DetailView::shownSetting = false;
  30392. ui.setClipLaunchWorkflow (true);
  30393. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  30394. offline.editSong ([] (lynx::Song& s) {
  30395. const int channels = (int) s.channels.size();
  30396. s.channels.resize ((std::size_t) channels + 3);
  30397. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  30398. for (int k = 0; k < 3; ++k)
  30399. {
  30400. auto& ch = s.channels[(std::size_t) (channels + k)];
  30401. ch.name = names[k];
  30402. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  30403. }
  30404. while (s.patterns.size() < 3)
  30405. s.patterns.emplace_back();
  30406. const char* patterns[] { "Beat", "Bassline", "Chords" };
  30407. for (int p = 0; p < 3; ++p)
  30408. {
  30409. auto& pattern = s.patterns[(std::size_t) p];
  30410. pattern.name = patterns[p];
  30411. lynx::Note n;
  30412. n.channel = channels + p;
  30413. n.key = 48 + p * 5;
  30414. pattern.notes = { n };
  30415. pattern.lengthTicks = 4 * lynx::ppq;
  30416. }
  30417. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  30418. const char* tracks[] { "Drums", "Bass", "Keys" };
  30419. const std::uint32_t colours[] { 0xFFE0533Bu, 0xFF3B8BE0u, 0xFF46C27Au };
  30420. for (int t = 0; t < 3; ++t)
  30421. {
  30422. s.playlistTracks[(std::size_t) t].name = tracks[t];
  30423. s.playlistTracks[(std::size_t) t].colour = colours[t];
  30424. }
  30425. for (int t = 0; t < 3; ++t)
  30426. for (int r = 0; r < 3; ++r)
  30427. if (! (t == 2 && r == 0))
  30428. {
  30429. lynx::Clip clip;
  30430. clip.pattern = t;
  30431. clip.length = 4 * lynx::ppq;
  30432. lynx::launcher::setClip (s, t, r, clip);
  30433. }
  30434. auto& grid = lynx::launcher::ensureGrid (s);
  30435. grid.scenes.resize (4);
  30436. const char* scenes[] { "Intro", "Verse", "Drop" };
  30437. for (int r = 0; r < 3; ++r)
  30438. grid.scenes[(std::size_t) r].name = scenes[r];
  30439. lynx::session::setSceneTempo (s, 1, 128.0);
  30440. lynx::session::setSceneSignature (s, 1, 3, 4); // (as the live check's "Verse": 3 / 4)
  30441. lynx::session::setSceneSignature (s, 2, 6, 8); // (round 190em: a denominator of its own)
  30442. grid.scenes[2].colour = 0xFF8E5BD6u;
  30443. }, false);
  30444. offline.dispatchPendingMessages();
  30445. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  30446. offline.dispatchPendingMessages();
  30447. ui.resized();
  30448. auto* gridView = ui.getClipGridForSnapshot();
  30449. if (gridView == nullptr)
  30450. {
  30451. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid\n");
  30452. return;
  30453. }
  30454. lynx::clipGridSceneTempoShown() = true;
  30455. lynx::refreshClipGrid (*gridView);
  30456. lynx::selectClipGridScene (*gridView, 1);
  30457. write (*gridView, "01-scene-fields");
  30458. {
  30459. // round 190em: a plain scene's launch triangle in Live's dark grey (#1E1E1E), scene 4 (row 3)
  30460. const auto image = lynx::shot::snapshot (*gridView);
  30461. int dark = 0;
  30462. for (int y = 0; y < image.getHeight(); ++y)
  30463. for (int x = image.getWidth() - 240; x < image.getWidth() - 180; ++x)
  30464. if (const auto p = image.getPixelAt (x, y); y > 3 * 24 + 26 && y < 4 * 24 + 26 && std::abs (p.getRed() - 0x1e) <= 2
  30465. && std::abs (p.getGreen() - 0x1e) <= 2 && std::abs (p.getBlue() - 0x1e) <= 2)
  30466. ++dark;
  30467. check ("plain scene triangle in Live's #1E1E1E (" + juce::String (dark) + " px)", dark >= 20);
  30468. }
  30469. saveMenus (juce::StringArray { "Scene menu (Verse)" }, std::vector<juce::PopupMenu> { lynx::clipGridSceneMenu (*gridView, 1) }, prefix + "-02-scene-menu.png");
  30470. saveMenus (juce::StringArray { "Scene tempo field", "Scene time signature field" },
  30471. std::vector<juce::PopupMenu> { lynx::clipGridSceneFieldMenu (*gridView, 1, 1), lynx::clipGridSceneFieldMenu (*gridView, 2, 2) },
  30472. prefix + "-03-field-menus.png");
  30473. saveMenus (juce::StringArray { "Column title (Bass)" }, std::vector<juce::PopupMenu> { lynx::clipGridHeaderMenu (*gridView, 1) }, prefix + "-04-title-menu.png");
  30474. const auto clipsIn = [&offline] (int row) {
  30475. int n = 0;
  30476. if (const auto& g = offline.getSong().clipGrid)
  30477. for (int t = 0; t < 8; ++t)
  30478. n += lynx::launcher::clipAt (*g, t, row) != nullptr ? 1 : 0;
  30479. return n;
  30480. };
  30481. const auto before = clipsIn (1);
  30482. const auto dup = lynx::duplicateClipGridScene (*gridView, 1);
  30483. offline.dispatchPendingMessages();
  30484. const auto& scenesNow = offline.getSong().clipGrid->scenes;
  30485. check ("duplicate: Verse's copy is row 2, with its clips and tempo", dup == 2 && clipsIn (2) == before && scenesNow.size() > 2
  30486. && scenesNow[2].name == "Verse" && scenesNow[2].tempo == 128.0);
  30487. write (*gridView, "05-scene-duplicated");
  30488. const auto cap = lynx::captureClipGridScene (*gridView, 3, { 0, 2, 1 }); // Drums row 0, Bass row 2, Keys row 1
  30489. offline.dispatchPendingMessages();
  30490. check ("capture: a new row 4 with the three playing clips", cap == 4 && clipsIn (4) == 3);
  30491. {
  30492. const auto& sc = offline.getSong().clipGrid->scenes;
  30493. check ("capture while playing: the new scene is plain (no name, fields off)", sc.size() > 4 && sc[4] == lynx::ClipGridScene {});
  30494. }
  30495. write (*gridView, "06-scene-captured");
  30496. // round 190em: nothing plays: an empty scene like the selected one (name, tempo, signature), selected
  30497. const auto empty = lynx::captureClipGridScene (*gridView, 1, { -1, -1 });
  30498. offline.dispatchPendingMessages();
  30499. {
  30500. const auto& sc = offline.getSong().clipGrid->scenes;
  30501. check ("capture with nothing playing: an empty row 2 named Verse, 128 BPM, 3 / 4", empty == 2 && clipsIn (2) == 0 && sc[2].name == "Verse"
  30502. && sc[2].tempo == 128.0 && sc[2].beatsPerBar == 3 && sc[2].beatUnit == 4);
  30503. }
  30504. write (*gridView, "06b-scene-captured-stopped");
  30505. // round 190em: Capture and Insert while clips play: playback moves to the new row (the runtime view shows what
  30506. // the player reports once the published song holds the moved slots)
  30507. {
  30508. const auto rowsBefore = offline.getSong().clipGrid->scenes.size();
  30509. lynx::selectClipGridScene (*gridView, 0);
  30510. const auto at = lynx::captureClipGridScene (*gridView, 0, { 0, 0, -1 });
  30511. offline.dispatchPendingMessages();
  30512. const auto& g = *offline.getSong().clipGrid;
  30513. check ("capture while playing: row 1 holds the moved playing slots", at == 1 && g.scenes.size() == rowsBefore + 1
  30514. && clipsIn (1) == 2 && clipsIn (0) == 2 && g.scenes[1] == lynx::ClipGridScene {});
  30515. if (auto* runtime = offline.launcherStateForSnapshot())
  30516. for (int t = 0; t < 2; ++t)
  30517. runtime->tracks[(std::size_t) t].playing.store (1);
  30518. lynx::refreshClipGrid (*gridView);
  30519. write (*gridView, "09-capture-playing-moves");
  30520. if (auto* runtime = offline.launcherStateForSnapshot())
  30521. for (int t = 0; t < 2; ++t)
  30522. runtime->tracks[(std::size_t) t].playing.store (-1);
  30523. }
  30524. // round 190em: the fields as "n / d", a selected field, Del = Return to Default
  30525. lynx::clipGridSceneTempoShown() = true;
  30526. lynx::refreshClipGrid (*gridView);
  30527. {
  30528. const auto& sc = offline.getSong().clipGrid->scenes;
  30529. int verse = -1;
  30530. for (int r = 0; r < (int) sc.size() && verse < 0; ++r)
  30531. if (sc[(std::size_t) r].name == "Verse" && sc[(std::size_t) r].tempo > 0.0)
  30532. verse = r;
  30533. lynx::selectClipGridSceneField (*gridView, verse, 1);
  30534. write (*gridView, "10-field-selected");
  30535. gridView->keyPressed (juce::KeyPress (juce::KeyPress::deleteKey));
  30536. offline.dispatchPendingMessages();
  30537. const auto& after = offline.getSong().clipGrid->scenes;
  30538. check ("Del on a selected tempo field returns it to default (scene kept)", verse >= 0 && after.size() == sc.size()
  30539. && after[(std::size_t) verse].tempo == 0.0 && after[(std::size_t) verse].beatsPerBar == 3);
  30540. write (*gridView, "11-field-returned-to-default");
  30541. }
  30542. // round 190em: Capture MIDI to the armed track (Bass), the selected scene's slot, the tempo from the phrase
  30543. {
  30544. offline.stop();
  30545. offline.setGridTrackArmed (1, true, true);
  30546. lynx::selectClipGridScene (*gridView, 0);
  30547. int empty = 0;
  30548. while (lynx::launcher::clipAt (*offline.getSong().clipGrid, 1, empty) != nullptr)
  30549. ++empty;
  30550. const auto now = juce::Time::getMillisecondCounterHiRes();
  30551. const auto beat = 60000.0 / 148.0;
  30552. for (int i = 0; i < 8; ++i)
  30553. {
  30554. const auto at = now - 9.0 * beat + i * beat;
  30555. offline.logPlayedNoteForTest (at, 0, 60 + (i % 4) * 2, 0.8f, true);
  30556. offline.logPlayedNoteForTest (at + beat * 0.5, 0, 60 + (i % 4) * 2, 0.8f, false);
  30557. }
  30558. int placed = -1;
  30559. bool into = true;
  30560. const auto r = offline.captureMidiToSlot (1, empty, placed, into);
  30561. offline.dispatchPendingMessages();
  30562. check ("Capture MIDI: 8 notes into Bass row " + juce::String (placed) + ", tempo " + juce::String (offline.getSong().bpm, 2),
  30563. r.notes == 8 && placed == empty && ! into && std::abs (offline.getSong().bpm - 148.0) < 0.5 && offline.getTransport().playing.load());
  30564. const auto& capturedGrid = *offline.getSong().clipGrid;
  30565. const auto* capturedClip = lynx::launcher::clipAt (capturedGrid, 1, placed);
  30566. const auto* slot = capturedClip != nullptr ? &capturedGrid.slots[(std::size_t) capturedClip->gridSlot] : nullptr;
  30567. check ("Capture MIDI: the clip has no name of its own (blank label, as Live)", slot != nullptr && slot->name.empty() && slot->blankName);
  30568. if (auto* runtime = offline.launcherStateForSnapshot())
  30569. runtime->tracks[1].playing.store (placed);
  30570. lynx::refreshClipGrid (*gridView);
  30571. write (*gridView, "12-capture-midi");
  30572. if (auto* runtime = offline.launcherStateForSnapshot())
  30573. runtime->tracks[1].playing.store (-1);
  30574. offline.stop();
  30575. }
  30576. write (ui, "07-window");
  30577. lynx::clipGridSceneTempoShown() = false;
  30578. lynx::refreshClipGrid (*gridView);
  30579. write (*gridView, "08-fields-off");
  30580. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  30581. }
  30582. void runDrawShot190ef (const juce::String& prefix)
  30583. {
  30584. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30585. lynx::AudioEngine offline (false);
  30586. lynx::MainComponent ui (offline, false);
  30587. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  30588. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30589. const auto write = [&prefix] (juce::Component& c, const char* name) {
  30590. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  30591. file.deleteFile();
  30592. juce::FileOutputStream out (file);
  30593. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  30594. };
  30595. juce::String checks;
  30596. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  30597. ui.setVisible (true);
  30598. ui.setClipLaunchWorkflow (true);
  30599. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  30600. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  30601. lynx::autolanes::setShown (true);
  30602. offline.editSong ([] (lynx::Song& s) {
  30603. if (s.mixer.size() < 4)
  30604. s.mixer.resize (4);
  30605. s.mixer[1].name = "Bass";
  30606. s.mixer[2].name = "Pad";
  30607. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  30608. s.playlistTracks[0].name = "Bass";
  30609. s.playlistTracks[0].mode = lynx::PlaylistTrackMode::audio;
  30610. s.playlistTracks[0].mixerTrack = 1;
  30611. s.playlistTracks[1].name = "Pad";
  30612. s.playlistTracks[1].mode = lynx::PlaylistTrackMode::audio;
  30613. s.playlistTracks[1].mixerTrack = 2;
  30614. }, false);
  30615. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0);
  30616. lynx::createAutomationLane (offline, { lynx::AutomationTargetKind::mixerPan, 2, 0, 0 }, 1);
  30617. offline.editSong ([] (lynx::Song& s) {
  30618. for (int t = 0; t < 2; ++t)
  30619. if (! s.playlistTracks[(std::size_t) t].lanes.empty())
  30620. s.playlistTracks[(std::size_t) t].lanes[0].height = 110;
  30621. }, false);
  30622. offline.dispatchPendingMessages();
  30623. auto& playlist = ui.getPlaylistForSnapshot();
  30624. playlist.setViewForSnapshot (180.0, 0, 0);
  30625. ui.resized();
  30626. offline.dispatchPendingMessages();
  30627. const auto& song = offline.getSong();
  30628. const auto laneA = song.playlistTracks[0].lanes.empty() ? -1 : song.playlistTracks[0].lanes[0].automation;
  30629. const auto laneB = song.playlistTracks[1].lanes.empty() ? -1 : song.playlistTracks[1].lanes[0].automation;
  30630. check ("two lanes made", laneA >= 0 && laneB >= 0);
  30631. if (laneA < 0 || laneB < 0)
  30632. {
  30633. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  30634. return;
  30635. }
  30636. write (ui, "00-lanes-before");
  30637. const auto before = song.automations[(std::size_t) laneA].points;
  30638. // a drag through the Playlist's own handlers (the events a real mouse sends)
  30639. auto source = juce::Desktop::getInstance().getMainMouseSource();
  30640. const auto now = juce::Time::getCurrentTime();
  30641. const auto stroke = [&] (int track, const std::vector<juce::Point<float>>& path, juce::ModifierKeys extra) {
  30642. const juce::ModifierKeys mods (juce::ModifierKeys::leftButtonModifier | extra.getRawFlags());
  30643. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
  30644. return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, path.front(), now, 1, dragged);
  30645. };
  30646. juce::ignoreUnused (track);
  30647. // (the engine joins the edits of one press into one undo step while a button is down)
  30648. const auto held = juce::ModifierKeys::currentModifiers;
  30649. juce::ModifierKeys::currentModifiers = mods;
  30650. playlist.mouseDown (event (path.front(), mods, false));
  30651. for (std::size_t i = 1; i < path.size(); ++i)
  30652. playlist.mouseDrag (event (path[i], mods, true));
  30653. juce::ModifierKeys::currentModifiers = held;
  30654. playlist.mouseUp (event (path.back(), extra, true));
  30655. };
  30656. const auto bodyA = playlist.laneBodyForSnapshot (0, 0), bodyB = playlist.laneBodyForSnapshot (1, 0);
  30657. const auto bar = (double) (4 * lynx::ppq);
  30658. const auto x = [&] (double bars) { return (float) playlist.xOfTickForSnapshot (bars * bar); };
  30659. const auto y = [] (juce::Rectangle<float> body, float v) { return body.getBottom() - v * body.getHeight(); };
  30660. lynx::drawmode::set (true);
  30661. // steps: a rise over bar 1 and a fall over bar 2, at the Playlist's grid (Line, at this zoom)
  30662. std::vector<juce::Point<float>> steps;
  30663. for (int k = 0; k <= 16; ++k)
  30664. steps.push_back ({ x (1.0 + k / 16.0) + 2.0f, y (bodyA, 0.15f + 0.05f * (float) k) });
  30665. for (int k = 0; k <= 16; ++k)
  30666. steps.push_back ({ x (2.0 + k / 16.0) + 2.0f, y (bodyA, 0.95f - 0.05f * (float) k) });
  30667. stroke (0, steps, {});
  30668. const auto& afterSteps = offline.getSong().automations[(std::size_t) laneA].points;
  30669. check ("Draw Mode drag made steps (" + juce::String ((int) afterSteps.size()) + " points)", afterSteps.size() > before.size() + 4);
  30670. bool unchangedOutside = true;
  30671. for (double t = 0.0; t < 6.0 * bar; t += 37.0)
  30672. if ((t < bar - 1.0 || t > 3.1 * bar) && std::abs (lynx::automationCurveAt (before, t) - lynx::automationCurveAt (afterSteps, t)) > 1.0e-4f)
  30673. unchangedOutside = false;
  30674. check ("the curve outside the drawn bars is unchanged", unchangedOutside);
  30675. {
  30676. // flat inside each drawn cell: the values in a cell's first and last tick are the same
  30677. int flatCells = 0, cells = 0;
  30678. for (double t = bar; t < 3.0 * bar; t += lynx::ppq / 4.0)
  30679. {
  30680. ++cells;
  30681. if (std::abs (lynx::automationCurveAt (afterSteps, t + 1.0) - lynx::automationCurveAt (afterSteps, t + lynx::ppq / 4.0 - 1.0)) < 1.0e-5f)
  30682. ++flatCells;
  30683. }
  30684. check ("each sixteenth inside bars 2-3 is flat (" + juce::String (flatCells) + " / " + juce::String (cells) + ")", flatCells == cells);
  30685. }
  30686. // freehand: Alt (no grid) on the pad's pan lane, a wave over bars 1-4
  30687. const auto panBefore = offline.getSong().automations[(std::size_t) laneB].points;
  30688. // (off-screen every press has the same mouse-down time, which the undo history uses to join one press's edits:
  30689. // an edit with no button down in between separates the two strokes, as a real second press does)
  30690. offline.editSong ([] (lynx::Song&) {});
  30691. std::vector<juce::Point<float>> wave;
  30692. for (int k = 0; k <= 60; ++k)
  30693. wave.push_back ({ x (1.0 + 3.0 * k / 60.0), y (bodyB, 0.5f + 0.4f * std::sin ((float) k * 0.3f)) });
  30694. stroke (1, wave, juce::ModifierKeys (juce::ModifierKeys::altModifier));
  30695. const auto& pan = offline.getSong().automations[(std::size_t) laneB].points;
  30696. check ("Alt drag drew freehand (" + juce::String ((int) pan.size()) + " points)", pan.size() > 30);
  30697. playlist.repaint();
  30698. write (ui, "01-draw-mode-steps-and-freehand");
  30699. if (auto* parent = playlist.getParentComponent())
  30700. write (*parent, "01b-playlist");
  30701. // one stroke is one undo step
  30702. offline.undo();
  30703. check ("one undo takes the whole freehand stroke back", offline.getSong().automations[(std::size_t) laneB].points == panBefore);
  30704. // Draw Mode off: the same press adds one point, as before
  30705. lynx::drawmode::set (false);
  30706. const auto countOff = offline.getSong().automations[(std::size_t) laneA].points.size();
  30707. stroke (0, { { x (4.5), y (bodyA, 0.8f) } }, {});
  30708. check ("Draw Mode off: a press adds one point", offline.getSong().automations[(std::size_t) laneA].points.size() == countOff + 1);
  30709. // the Options menu (Clip-launch layout) with the switch
  30710. lynx::drawmode::set (true);
  30711. {
  30712. const auto names = ui.getMenuNamesForSnapshot();
  30713. const auto index = names.indexOf (TRANS ("Options"));
  30714. if (index >= 0)
  30715. saveMenus (juce::StringArray { "Options" }, std::vector<juce::PopupMenu> { ui.getMenuForSnapshot (index) }, prefix + "-02-options-menu.png");
  30716. check ("Options menu found", index >= 0);
  30717. }
  30718. lynx::drawmode::set (false);
  30719. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  30720. }
  30721. void runClipEnvShot190gi (const juce::String& prefix)
  30722. {
  30723. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30724. lynx::AudioEngine offline (false);
  30725. lynx::MainComponent ui (offline, false);
  30726. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  30727. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  30728. const auto write = [&prefix] (juce::Component& c, const char* name) {
  30729. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  30730. file.deleteFile();
  30731. juce::FileOutputStream out (file);
  30732. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  30733. };
  30734. juce::String checks;
  30735. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  30736. // two files: a sustained pad (4 s, a slow swell, for the envelope over its waveform) and a one-bar loop of clicks
  30737. const auto writeWav = [] (const juce::File& file, int seconds, const std::function<float (int, double)>& fn) {
  30738. const double rate = 48000.0;
  30739. juce::AudioBuffer<float> buffer (2, (int) (rate * seconds));
  30740. for (int ch = 0; ch < 2; ++ch)
  30741. for (int i = 0; i < buffer.getNumSamples(); ++i)
  30742. buffer.setSample (ch, i, fn (i, rate));
  30743. file.deleteFile();
  30744. if (auto out = std::unique_ptr<juce::FileOutputStream> (file.createOutputStream()))
  30745. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  30746. {
  30747. out.release();
  30748. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  30749. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  30750. }
  30751. return file;
  30752. };
  30753. const auto pad = writeWav (juce::File (prefix + "-pad.wav"), 4, [] (int i, double rate) {
  30754. const auto t = i / rate;
  30755. return (float) (0.45 * (std::sin (juce::MathConstants<double>::twoPi * 220.0 * t) + 0.5 * std::sin (juce::MathConstants<double>::twoPi * 331.0 * t))
  30756. * (0.7 + 0.3 * std::sin (juce::MathConstants<double>::twoPi * 1.5 * t)));
  30757. });
  30758. const auto loop = writeWav (juce::File (prefix + "-loop.wav"), 2, [] (int i, double) {
  30759. const auto k = i % 12000;
  30760. const auto hit = i / 12000;
  30761. return k < 3000 ? (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8) : 0.0f;
  30762. });
  30763. ui.setVisible (true);
  30764. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::playlist });
  30765. offline.editSong ([&] (lynx::Song& s) {
  30766. const auto add = [&s] (const char* name, const juce::File& file) {
  30767. lynx::ChannelDef ch;
  30768. ch.name = name;
  30769. ch.instrument = lynx::InstrumentKind::audioClip;
  30770. ch.samplePath = file.getFullPathName().toStdString();
  30771. s.channels.push_back (ch);
  30772. return (int) s.channels.size() - 1;
  30773. };
  30774. const auto padChannel = add ("Pad", pad), loopChannel = add ("Loop", loop);
  30775. s.playlist.clear();
  30776. lynx::Clip a;
  30777. a.kind = lynx::ClipKind::audio;
  30778. a.channel = padChannel;
  30779. a.length = 8 * lynx::ppq;
  30780. a.track = 0;
  30781. s.playlist.push_back (a);
  30782. a.track = 1;
  30783. s.playlist.push_back (a);
  30784. lynx::Clip b = a;
  30785. b.channel = loopChannel;
  30786. b.track = 2;
  30787. b.length = 4 * lynx::ppq;
  30788. s.playlist.push_back (b);
  30789. // the first clip: a volume envelope (a swell, a dip, FL's curve modes on two segments)
  30790. auto& e = lynx::clipenv::own (s, s.playlist[0]);
  30791. e.shown = lynx::clipenv::volumeLane;
  30792. e.volume = { { 0, 0.15f, 0.0f, 0 }, { lynx::ppq * 2, 1.0f, -0.6f, 0 }, { lynx::ppq * 4, 1.0f, 0.0f, 0 },
  30793. { lynx::ppq * 5, 0.45f, 0.0f, 2 }, { lynx::ppq * 6, 0.9f, 0.0f, 0 }, { lynx::ppq * 8, 0.9f, 0.0f, 0 } };
  30794. // the second: its pan lane shown (only pan made)
  30795. lynx::clipenv::show (s, s.playlist[1], lynx::clipenv::panLane);
  30796. auto& p = lynx::clipenv::own (s, s.playlist[1]);
  30797. 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 } };
  30798. if (s.playlistTracks.size() < 3)
  30799. s.playlistTracks.resize (3);
  30800. for (int t = 0; t < 3; ++t)
  30801. s.playlistTracks[(std::size_t) t].height = 96;
  30802. }, false);
  30803. offline.dispatchPendingMessages();
  30804. auto& playlist = ui.getPlaylistForSnapshot();
  30805. playlist.setViewForSnapshot (360.0, 0, 0);
  30806. ui.resized();
  30807. offline.dispatchPendingMessages();
  30808. (void) lynx::shot::snapshot (ui); // (a paint starts the waveform analyses; the shot waits for them)
  30809. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  30810. offline.dispatchPendingMessages();
  30811. write (ui, "01-playlist-envelopes");
  30812. // the clip menu: LYNX's extras with Clip envelope ›, Auto-warp, Quantize audio (Auto-warp run from it on the loop)
  30813. {
  30814. const auto menu = playlist.getClipMenuForSnapshot (2);
  30815. const juce::PopupMenu* envelopeMenu = nullptr;
  30816. bool autoWarp = false, quantize = false;
  30817. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  30818. {
  30819. if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
  30820. envelopeMenu = it.getItem().subMenu.get();
  30821. autoWarp = autoWarp || (it.getItem().text == lynx::tr ("Auto-warp") && it.getItem().isEnabled);
  30822. quantize = quantize || (it.getItem().text == lynx::tr ("Quantize audio") && it.getItem().isEnabled);
  30823. }
  30824. check ("clip menu: Clip envelope submenu, Auto-warp, Quantize audio", envelopeMenu != nullptr && autoWarp && quantize);
  30825. saveMenus (juce::StringArray { lynx::tr ("Audio clip"), lynx::tr ("Clip envelope") },
  30826. std::vector<juce::PopupMenu> { menu, envelopeMenu != nullptr ? *envelopeMenu : juce::PopupMenu() }, prefix + "-02-clip-menu.png");
  30827. check ("Auto-warp from the clip menu places markers", clickMenuItem (menu, lynx::tr ("Auto-warp")));
  30828. offline.dispatchPendingMessages();
  30829. const auto& s = offline.getSong();
  30830. const auto& loopClip = s.playlist[2];
  30831. check ("the loop's channel is warped", s.channels[(std::size_t) loopClip.channel].sampler.warp.size() >= 2
  30832. && s.channels[(std::size_t) loopClip.channel].sampler.keepPitch);
  30833. // the first clip's menu: Show volume envelope ticked
  30834. const auto first = playlist.getClipMenuForSnapshot (0);
  30835. bool ticked = false;
  30836. for (juce::PopupMenu::MenuItemIterator it (first); it.next();)
  30837. if (it.getItem().text == lynx::tr ("Clip envelope") && it.getItem().subMenu != nullptr)
  30838. for (juce::PopupMenu::MenuItemIterator sub (*it.getItem().subMenu); sub.next();)
  30839. ticked = ticked || (sub.getItem().text == lynx::tr ("Show volume envelope") && sub.getItem().isTicked);
  30840. check ("Show volume envelope is ticked on the first clip", ticked);
  30841. }
  30842. // gestures through the Playlist's own handlers
  30843. auto source = juce::Desktop::getInstance().getMainMouseSource();
  30844. const auto now = juce::Time::getCurrentTime();
  30845. const auto press = [&] (juce::Point<float> from, juce::Point<float> to, juce::ModifierKeys button, juce::ModifierKeys extra) {
  30846. const juce::ModifierKeys mods (button.getRawFlags() | extra.getRawFlags());
  30847. const auto event = [&] (juce::Point<float> p, juce::ModifierKeys m, bool dragged) {
  30848. return juce::MouseEvent (source, p, m, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist, now, from, now, 1, dragged);
  30849. };
  30850. const auto held = juce::ModifierKeys::currentModifiers;
  30851. juce::ModifierKeys::currentModifiers = mods;
  30852. playlist.mouseDown (event (from, mods, false));
  30853. if (to != from)
  30854. playlist.mouseDrag (event (to, mods, true));
  30855. juce::ModifierKeys::currentModifiers = held;
  30856. playlist.mouseUp (event (to, extra, to != from));
  30857. };
  30858. const auto x = [&] (double beats) { return (float) playlist.xOfTickForSnapshot (beats * lynx::ppq); };
  30859. {
  30860. const auto body = playlist.curveBodyForSnapshot (0);
  30861. const auto points = offline.getSong().clipEnvelopes[(std::size_t) offline.getSong().playlist[0].envelope].volume.size();
  30862. // [RMB] in the curve's area adds a point there (FL's in-Playlist automation editing, round 165)
  30863. press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.3f * body.getHeight() },
  30864. juce::ModifierKeys::rightButtonModifier, {});
  30865. offline.dispatchPendingMessages();
  30866. const auto& s = offline.getSong();
  30867. const auto* e = lynx::clipenv::of (s, s.playlist[0]);
  30868. check ("[RMB] on the clip's volume lane adds a point", e != nullptr && e->volume.size() == points + 1
  30869. && std::abs (lynx::automationCurveAt (e->volume, 7.0 * lynx::ppq) - 0.3f) < 0.05f);
  30870. // drag that point up with the Pencil
  30871. press ({ x (7.0), body.getBottom() - 0.3f * body.getHeight() }, { x (7.0), body.getBottom() - 0.7f * body.getHeight() },
  30872. juce::ModifierKeys::leftButtonModifier, {});
  30873. offline.dispatchPendingMessages();
  30874. const auto* moved = lynx::clipenv::of (offline.getSong(), offline.getSong().playlist[0]);
  30875. check ("dragging the point moves it", moved != nullptr && std::abs (lynx::automationCurveAt (moved->volume, 7.0 * lynx::ppq) - 0.7f) < 0.05f);
  30876. check ("the edits are undoable", offline.canUndo());
  30877. }
  30878. write (ui, "03-playlist-edited");
  30879. {
  30880. // warp: a double-click on the loop clip's flag strip adds a marker; Alt + drag on its line (mid clip) moves it
  30881. const auto bounds = playlist.clipBoundsForSnapshot (2);
  30882. const auto channelOf = [&] { return offline.getSong().playlist[2].channel; };
  30883. const auto markers = [&] { return offline.getSong().channels[(std::size_t) channelOf()].sampler.warp; };
  30884. const auto before = markers().size();
  30885. const juce::Point<float> strip { x (1.5), (float) bounds.getY() + 13.0f + 3.0f };
  30886. playlist.mouseDoubleClick (juce::MouseEvent (source, strip, juce::ModifierKeys::leftButtonModifier, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, &playlist, &playlist,
  30887. now, strip, now, 2, false));
  30888. offline.dispatchPendingMessages();
  30889. check ("a double-click on the flag strip adds a warp marker", markers().size() == before + 1);
  30890. if (markers().size() != before + 1)
  30891. checks << " (strip seconds " << playlist.warpStripSecondsForSnapshot (2, strip.toInt()) << ", played markers "
  30892. << (int) playlist.warpMarkerCountForSnapshot (2) << ", file seconds " << playlist.clipFileSecondsForSnapshot (2)
  30893. << ", channel markers " << (int) before << ", clip at " << bounds.toString() << ", strip " << strip.toString() << ")\n";
  30894. int added = -1;
  30895. for (int k = 0; k < (int) markers().size(); ++k)
  30896. if (std::abs (markers()[(std::size_t) k].beats - 1.5) < 0.05)
  30897. added = k;
  30898. check ("the marker sits on the beat it was added on", added > 0);
  30899. if (added > 0)
  30900. {
  30901. const juce::Point<float> line { x (1.5), (float) bounds.getCentreY() + 10.0f };
  30902. press (line, line.translated (x (1.75) - x (1.5), 0.0f), juce::ModifierKeys::leftButtonModifier, juce::ModifierKeys::altModifier);
  30903. offline.dispatchPendingMessages();
  30904. 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);
  30905. }
  30906. }
  30907. write (ui, "04-playlist-warp");
  30908. // the Clip-launch layout: the Clip View's Envelopes tab of a grid audio clip
  30909. offline.editSong ([&] (lynx::Song& s) {
  30910. auto clip = s.playlist[0];
  30911. clip.start = 0;
  30912. lynx::launcher::setClip (s, 0, 0, clip);
  30913. lynx::launcher::ensureGrid (s).scenes.resize (std::max<std::size_t> (1, lynx::launcher::ensureGrid (s).scenes.size()));
  30914. }, false);
  30915. offline.dispatchPendingMessages();
  30916. const auto shootPanel = [&] (const char* name, bool envelopes, std::uint8_t lane) {
  30917. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  30918. if (panel == nullptr)
  30919. return false;
  30920. panel->setSize (1100, 300);
  30921. for (auto* child : panel->getChildren())
  30922. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (envelopes ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
  30923. if (b->onClick)
  30924. b->onClick();
  30925. if (lane != 0)
  30926. offline.editSong ([lane] (lynx::Song& s) {
  30927. if (s.clipGrid)
  30928. if (auto* c = const_cast<lynx::Clip*> (lynx::launcher::clipAt (*s.clipGrid, 0, 0)); c != nullptr)
  30929. lynx::clipenv::show (s, *c, lane);
  30930. }, false);
  30931. offline.dispatchPendingMessages();
  30932. write (*panel, name);
  30933. return true;
  30934. };
  30935. check ("Clip View: Sample tab", shootPanel ("05-clipview-sample", false, 0));
  30936. check ("Clip View: Envelopes tab, Clip > Gain", shootPanel ("06-clipview-envelopes-gain", true, lynx::clipenv::volumeLane));
  30937. check ("Clip View: Envelopes tab, Mixer > Track Panning", shootPanel ("07-clipview-envelopes-pan", true, lynx::clipenv::panLane));
  30938. {
  30939. const auto* c = offline.getSong().clipGrid ? lynx::launcher::clipAt (*offline.getSong().clipGrid, 0, 0) : nullptr;
  30940. check ("the grid clip keeps the volume envelope", c != nullptr && lynx::clipenv::activeOf (offline.getSong(), *c) != nullptr);
  30941. }
  30942. shootPanel ("08-clipview-sample-again", false, 0); // (the tab choice back to Sample for the next run)
  30943. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  30944. }
  30945. void runGapsShot190kf (const juce::String& prefix, const juce::String& wavPath)
  30946. {
  30947. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  30948. lynx::AudioEngine offline (false);
  30949. juce::String checks;
  30950. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  30951. // 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)
  30952. auto wav = juce::File (wavPath);
  30953. if (! wav.existsAsFile())
  30954. {
  30955. wav = juce::File (prefix + "-probe.wav");
  30956. wav.deleteFile();
  30957. const double rate = 44100.0;
  30958. juce::AudioBuffer<float> buffer (1, (int) (rate * 8.421));
  30959. for (int k = 0; k < buffer.getNumSamples(); ++k)
  30960. {
  30961. const auto t = std::fmod (k / rate, 0.5);
  30962. buffer.setSample (0, k, (float) (0.5 * std::exp (-t * 6.0) * std::sin (2.0 * juce::MathConstants<double>::pi * 220.0 * k / rate)));
  30963. }
  30964. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  30965. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  30966. {
  30967. out.release();
  30968. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  30969. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  30970. }
  30971. }
  30972. double seconds = 0.0;
  30973. {
  30974. juce::AudioFormatManager formats;
  30975. formats.registerBasicFormats();
  30976. if (std::unique_ptr<juce::AudioFormatReader> r (formats.createReaderFor (wav)); r != nullptr && r->sampleRate > 0.0)
  30977. seconds = (double) r->lengthInSamples / r->sampleRate;
  30978. }
  30979. check ("probe file " + wav.getFileName() + " " + juce::String (seconds, 3) + " s", seconds > 1.0);
  30980. const auto beats = seconds * 2.0; // (warped at 120 BPM, its own tempo)
  30981. offline.editSong ([&] (lynx::Song& s) {
  30982. s.bpm = 120.0;
  30983. lynx::ChannelDef ch;
  30984. ch.name = "warped";
  30985. ch.instrument = lynx::InstrumentKind::audioClip;
  30986. ch.samplePath = wav.getFullPathName().toStdString();
  30987. ch.sampler.keepPitch = true;
  30988. ch.sampler.stretchMethod = lynx::StretchMethod::complex;
  30989. ch.sampler.stretchBeats = (float) beats;
  30990. ch.sampler.warp = { { 0.0, 0.0 }, { seconds * 0.3, beats * 0.25 }, { seconds * 0.55, beats * 0.5 }, { seconds, beats } };
  30991. s.channels.push_back (ch);
  30992. const auto c = (int) s.channels.size() - 1;
  30993. lynx::Clip audio;
  30994. audio.kind = lynx::ClipKind::audio;
  30995. audio.channel = c;
  30996. audio.offset = 2 * lynx::ppq; // (Loop Position 1.3, Length 2.0.0 → 3.3, Start 1.4: the probe set's)
  30997. audio.length = 8 * lynx::ppq;
  30998. lynx::launcher::setClip (s, 0, 0, audio);
  30999. lynx::launcher::ensureGrid (s).scenes.resize (1);
  31000. auto& grid = *s.clipGrid;
  31001. for (auto& g : grid.clips)
  31002. if (g.gridSlot >= 0)
  31003. {
  31004. grid.slots[(std::size_t) g.gridSlot].loop = true;
  31005. grid.slots[(std::size_t) g.gridSlot].startMarker = lynx::ppq;
  31006. }
  31007. }, false);
  31008. offline.dispatchPendingMessages();
  31009. const auto editorOf = [] (juce::Component& panel) -> juce::Component* {
  31010. for (auto* child : panel.getChildren())
  31011. if (child->isVisible() && child->getWidth() > 400 && dynamic_cast<juce::Button*> (child) == nullptr)
  31012. return child;
  31013. return nullptr;
  31014. };
  31015. const auto write = [&] (juce::Component& panel, const char* name) {
  31016. offline.dispatchPendingMessages();
  31017. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  31018. file.deleteFile();
  31019. juce::FileOutputStream out (file);
  31020. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (panel), out);
  31021. };
  31022. const auto slotOf = [&] (auto&& fn) {
  31023. offline.editSong ([&] (lynx::Song& s) {
  31024. for (auto& g : s.clipGrid->clips)
  31025. if (g.gridSlot >= 0)
  31026. fn (g, s.clipGrid->slots[(std::size_t) g.gridSlot]);
  31027. }, false);
  31028. offline.dispatchPendingMessages();
  31029. };
  31030. {
  31031. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  31032. check ("the Clip View panel", panel != nullptr);
  31033. if (panel == nullptr)
  31034. return;
  31035. panel->setSize (1390, 670);
  31036. if (auto* e = editorOf (*panel)) // (the Clip-launch layout's beat-time view; off-screen there is no layout)
  31037. lynx::setAudioEditorBeatTimeForSnapshot (*e, 1);
  31038. write (*panel, "01-loop-on-start-marker");
  31039. // perf (round gaps190kf): the sample editor painted 40 times with the warp time line (a grid clip's editor)
  31040. // and without it (the same channel's editor panel, no grid clip) — ms per full paint
  31041. {
  31042. const auto timeIt = [] (juce::Component& c) {
  31043. juce::Image image (juce::Image::ARGB, c.getWidth(), c.getHeight(), true);
  31044. const auto t0 = juce::Time::getMillisecondCounterHiRes();
  31045. for (int k = 0; k < 40; ++k)
  31046. {
  31047. juce::Graphics g (image);
  31048. c.paintEntireComponent (g, false);
  31049. }
  31050. return (juce::Time::getMillisecondCounterHiRes() - t0) / 40.0;
  31051. };
  31052. if (auto* withLane = editorOf (*panel))
  31053. {
  31054. auto plain = lynx::makeAudioEditorPanel (offline, (int) offline.getSong().channels.size() - 1, -1, true);
  31055. plain->setSize (withLane->getWidth(), withLane->getHeight());
  31056. lynx::setAudioEditorBeatTimeForSnapshot (*plain, 1);
  31057. offline.dispatchPendingMessages();
  31058. timeIt (*withLane);
  31059. timeIt (*plain);
  31060. double a = 0.0, b = 0.0;
  31061. for (int round = 0; round < 3; ++round)
  31062. {
  31063. a += timeIt (*withLane) / 3.0;
  31064. b += timeIt (*plain) / 3.0;
  31065. }
  31066. check ("paint ms: with the warp time line " + juce::String (a, 3) + ", without " + juce::String (b, 3), true);
  31067. }
  31068. }
  31069. auto* editor = editorOf (*panel);
  31070. check ("its sample editor", editor != nullptr);
  31071. if (editor != nullptr)
  31072. {
  31073. lynx::selectAudioEditorBraceForSnapshot (*editor, true);
  31074. write (*panel, "02-brace-selected");
  31075. lynx::selectAudioEditorBraceForSnapshot (*editor, false);
  31076. lynx::holdAudioEditorBraceForSnapshot (*editor, 2, 12 * lynx::ppq); // (the loop's end dragged to 4.1)
  31077. write (*panel, "03-loop-end-held-at-4.1");
  31078. lynx::holdAudioEditorBraceForSnapshot (*editor, 0, 0);
  31079. }
  31080. }
  31081. slotOf ([] (lynx::Clip& c, lynx::ClipGridSlot& slot) {
  31082. slot.loop = false;
  31083. slot.startMarker = 0;
  31084. c.offset = 0;
  31085. c.length = (std::int64_t) std::llround (10.0 * lynx::ppq);
  31086. });
  31087. {
  31088. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  31089. if (panel != nullptr)
  31090. {
  31091. panel->setSize (1390, 670);
  31092. if (auto* e = editorOf (*panel))
  31093. lynx::setAudioEditorBeatTimeForSnapshot (*e, 1);
  31094. write (*panel, "04-loop-off-start-end");
  31095. }
  31096. }
  31097. offline.editSong ([&] (lynx::Song& s) { lynx::clipsample::setWarp (s, (int) s.channels.size() - 1, false, seconds); }, false);
  31098. offline.dispatchPendingMessages();
  31099. {
  31100. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  31101. if (panel != nullptr)
  31102. {
  31103. panel->setSize (1390, 670);
  31104. if (auto* e = editorOf (*panel))
  31105. lynx::setAudioEditorBeatTimeForSnapshot (*e, 1);
  31106. write (*panel, "05-unwarped-seconds");
  31107. }
  31108. }
  31109. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  31110. }
  31111. void runLiveFactsShot190gx (const juce::String& prefix)
  31112. {
  31113. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31114. lynx::AudioEngine offline (false);
  31115. juce::String checks;
  31116. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  31117. // a 1 kHz sine, 20 s at 48 kHz (Live's 190gu clip-envelope stimulus), −9 dBFS
  31118. const auto wav = juce::File (prefix + "-sine1k.wav");
  31119. wav.deleteFile();
  31120. {
  31121. const double rate = 48000.0;
  31122. juce::AudioBuffer<float> buffer (2, (int) (rate * 20.0));
  31123. for (int k = 0; k < buffer.getNumSamples(); ++k)
  31124. for (int ch = 0; ch < 2; ++ch)
  31125. buffer.setSample (ch, k, (float) (0.3535 * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * k / rate)));
  31126. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  31127. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  31128. {
  31129. out.release();
  31130. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  31131. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  31132. }
  31133. }
  31134. offline.editSong ([&wav] (lynx::Song& s) {
  31135. s.bpm = 120.0;
  31136. lynx::ChannelDef ch;
  31137. ch.name = "sine1k";
  31138. ch.instrument = lynx::InstrumentKind::audioClip;
  31139. ch.samplePath = wav.getFullPathName().toStdString();
  31140. s.channels.push_back (ch);
  31141. const auto c = (int) s.channels.size() - 1;
  31142. lynx::clipsample::setWarp (s, c, true, 20.0);
  31143. lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats);
  31144. lynx::Clip audio;
  31145. audio.kind = lynx::ClipKind::audio;
  31146. audio.channel = c;
  31147. audio.length = 40 * lynx::ppq;
  31148. // Live's Clip Gain staircase of the 190gu render (−1 … 1 in 0.1 steps, 2 beats each), as LYNX lane values
  31149. lynx::ClipEnvelope e;
  31150. for (int k = 0; k <= 20; ++k)
  31151. {
  31152. const auto v = lynx::clipenv::fromLive (lynx::clipenv::volumeLane, -1.0 + 0.1 * k);
  31153. for (const auto at : { 2 * k, 2 * k + 2 })
  31154. {
  31155. lynx::AutomationPoint p;
  31156. p.tick = (std::int64_t) at * lynx::ppq;
  31157. p.value = v;
  31158. e.volume.push_back (p);
  31159. }
  31160. }
  31161. e.shown = lynx::clipenv::volumeLane;
  31162. s.clipEnvelopes.push_back (e);
  31163. audio.envelope = (int) s.clipEnvelopes.size() - 1;
  31164. lynx::launcher::setClip (s, 0, 0, audio);
  31165. lynx::launcher::ensureGrid (s).scenes.resize (1);
  31166. }, false);
  31167. offline.dispatchPendingMessages();
  31168. const auto channelOf = [&] {
  31169. const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, 0);
  31170. return c != nullptr ? c->channel : -1;
  31171. };
  31172. const auto shoot = [&] (const char* name, int w, int h, int tab) {
  31173. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  31174. if (panel == nullptr)
  31175. return std::unique_ptr<juce::Component>();
  31176. panel->setSize (w, h);
  31177. if (tab != 0)
  31178. for (auto* child : panel->getChildren())
  31179. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == (tab == 2 ? lynx::tr ("Envelopes") : lynx::tr ("Sample")))
  31180. if (b->onClick)
  31181. b->onClick();
  31182. offline.dispatchPendingMessages();
  31183. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  31184. file.deleteFile();
  31185. juce::FileOutputStream out (file);
  31186. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
  31187. return panel;
  31188. };
  31189. const auto visibleText = [] (juce::Component& panel, const juce::String& text) {
  31190. for (auto* child : panel.getChildren())
  31191. if (auto* b = dynamic_cast<juce::TextButton*> (child); b != nullptr && b->getButtonText() == text)
  31192. return b->isVisible();
  31193. return false;
  31194. };
  31195. const auto setMode = [&] (int method) {
  31196. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf(), method); }, false);
  31197. offline.dispatchPendingMessages();
  31198. };
  31199. check ("01 Beats (Preserve label + chooser, loop icon + Transient Envelope)", shoot ("01-audio-beats", 900, 250, 1) != nullptr);
  31200. setMode ((int) lynx::StretchMethod::tones);
  31201. check ("02 Tones (Grain Size 30.00)", shoot ("02-audio-tones", 900, 250, 1) != nullptr);
  31202. setMode ((int) lynx::StretchMethod::texture);
  31203. check ("03 Texture (Grain Size 65.00, Flux only when it plays)", shoot ("03-audio-texture", 900, 250, 1) != nullptr);
  31204. { // (round 190ik: Complex Pro plays, its Formants and Envelope show)
  31205. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setComplexPro (s, channelOf()); }, false);
  31206. offline.dispatchPendingMessages();
  31207. check ("04 Complex Pro (Formants 100.00, Envelope 128)", shoot ("04-audio-complex-pro", 900, 250, 1) != nullptr);
  31208. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setWarpLaw (s, channelOf(), 0); }, false);
  31209. offline.dispatchPendingMessages();
  31210. check ("04b Complex Pro of a project saved before 0.1.30 (law chooser, no Formants / Envelope)",
  31211. shoot ("04b-audio-complex-pro-classic", 900, 250, 1) != nullptr);
  31212. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setWarpLaw (s, channelOf(), 1); }, false);
  31213. offline.dispatchPendingMessages();
  31214. }
  31215. setMode ((int) lynx::StretchMethod::beats);
  31216. {
  31217. auto panel = shoot ("05-envelopes-clip-gain-staircase", 1390, 420, 2);
  31218. check ("05 Envelopes tab shown on a warped clip", panel != nullptr && visibleText (*panel, lynx::tr ("Envelopes")));
  31219. }
  31220. offline.editSong ([&] (lynx::Song& s) { lynx::clipsample::setWarp (s, channelOf(), false, 20.0); }, false);
  31221. offline.dispatchPendingMessages();
  31222. {
  31223. auto panel = shoot ("06-unwarped-sample-only", 1390, 420, 2);
  31224. check ("06 an unwarped clip has no Envelopes tab (Live)", panel != nullptr && ! visibleText (*panel, lynx::tr ("Envelopes"))
  31225. && visibleText (*panel, lynx::tr ("Sample")));
  31226. }
  31227. // the law: Live's staircase values round trip through the lane values
  31228. bool law = true;
  31229. for (int k = 0; k <= 20; ++k)
  31230. {
  31231. const auto L = -1.0 + 0.1 * k;
  31232. law = law && std::abs (lynx::clipenv::toLive (lynx::clipenv::volumeLane, lynx::clipenv::fromLive (lynx::clipenv::volumeLane, L)) - L) < 2.0e-3;
  31233. }
  31234. check ("Clip Gain values round trip (Live → lane → Live)", law);
  31235. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  31236. }
  31237. void runDvShot190hr (const juce::String& prefix)
  31238. {
  31239. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31240. lynx::AudioEngine offline (false);
  31241. lynx::MainComponent ui (offline, false);
  31242. ui.setSize (1600, 900);
  31243. juce::String checks;
  31244. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  31245. const auto write = [&prefix] (juce::Component& c, const char* name) {
  31246. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  31247. file.deleteFile();
  31248. juce::FileOutputStream out (file);
  31249. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  31250. };
  31251. ui.setVisible (true);
  31252. lynx::DetailView::shownSetting = true;
  31253. ui.selectTabForSnapshot (2);
  31254. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  31255. offline.editSong ([] (lynx::Song& s) {
  31256. const int ch = (int) s.channels.size();
  31257. s.channels.resize ((std::size_t) ch + 1);
  31258. s.channels[(std::size_t) ch].name = "Keys";
  31259. s.channels[(std::size_t) ch].instrument = lynx::InstrumentKind::synth;
  31260. while (s.patterns.empty())
  31261. s.patterns.emplace_back();
  31262. auto& p = s.patterns[0];
  31263. p.name = "Riff";
  31264. p.notes.clear();
  31265. const int keys[] { 62, 65, 69, 72, 64, 67 };
  31266. for (int i = 0; i < 6; ++i)
  31267. {
  31268. lynx::Note n;
  31269. n.channel = ch;
  31270. n.key = keys[i];
  31271. n.start = i * lynx::ppq / 2 + (i % 2 ? 37 : -0) + 11; // a little off the 1/16 grid
  31272. n.length = lynx::ppq / 3;
  31273. p.notes.push_back (n);
  31274. }
  31275. p.lengthTicks = 4 * lynx::ppq;
  31276. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  31277. s.playlistTracks[0].name = "Keys";
  31278. lynx::Clip clip;
  31279. clip.pattern = 0;
  31280. clip.length = 4 * lynx::ppq;
  31281. const auto id = lynx::launcher::setClip (s, 0, 0, clip);
  31282. lynx::launcher::setClip (s, 0, 1, clip);
  31283. auto& grid = lynx::launcher::ensureGrid (s);
  31284. grid.scenes.resize (3);
  31285. if (id >= 0)
  31286. {
  31287. auto& slot = grid.slots[(std::size_t) id];
  31288. slot.name = "Riff";
  31289. slot.startMarker = 2 * lynx::ppq; // Start 1. 3. 1 inside the loop 1. 1. 1 + 1 bar
  31290. slot.ownScale = true;
  31291. slot.scaleRoot = 2; // D, the scale list's first (Major)
  31292. slot.scaleIndex = (std::int16_t) lynx::projectkey::commonFirst().front();
  31293. slot.follow.enabled = true;
  31294. slot.follow.a = lynx::FollowKind::next;
  31295. slot.follow.b = lynx::FollowKind::jump;
  31296. slot.follow.jumpB = 1;
  31297. slot.follow.chanceA = 70;
  31298. slot.follow.chanceB = 30;
  31299. slot.follow.linked = true;
  31300. slot.follow.iterations = 2;
  31301. }
  31302. }, false);
  31303. offline.dispatchPendingMessages();
  31304. ui.resized();
  31305. auto* detail = ui.getDetailViewForSnapshot();
  31306. if (detail == nullptr)
  31307. {
  31308. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no detail view\n");
  31309. return;
  31310. }
  31311. detail->showSelection (0, 0);
  31312. detail->setPage (lynx::DetailView::Page::clip);
  31313. offline.dispatchPendingMessages();
  31314. ui.resized();
  31315. write (ui, "01-clip-view-midi");
  31316. write (*detail, "01b-detail-alone");
  31317. auto& roll = ui.getPianoRollForSnapshot();
  31318. check ("the docked editor uses the reference's grid (" + roll.liveGridTextForCheck() + ")", roll.liveGridOn() && roll.liveGridTextForCheck().isNotEmpty());
  31319. 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);
  31320. {
  31321. std::vector<juce::PopupMenu> menus { roll.liveGridMenu() };
  31322. saveMenus (juce::StringArray { "Grid" }, menus, prefix + "-02-grid-menu.png");
  31323. }
  31324. roll.liveGrid.fixed = true;
  31325. roll.liveGrid.fixedIndex = lynx::livegrid::defaultFixed;
  31326. roll.resized();
  31327. const auto sixteenth = roll.gridStepForCheck();
  31328. roll.runAction ("pianoRoll.liveGridNarrower");
  31329. const auto narrower = roll.gridStepForCheck();
  31330. roll.runAction ("pianoRoll.liveGridTriplet");
  31331. const auto triplet = roll.gridStepForCheck();
  31332. 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) + ")",
  31333. sixteenth == lynx::ppq / 4 && narrower == lynx::ppq / 8 && triplet == lynx::ppq / 12);
  31334. write (roll, "03-editor-grid-1-32T");
  31335. roll.runAction ("pianoRoll.liveGridTriplet");
  31336. roll.runAction ("pianoRoll.liveGridWider");
  31337. const auto before = offline.getSong().patterns[0].notes;
  31338. roll.runAction ("pianoRoll.liveQuantize"); // (Live 12: Edit › Quantize, the Quantize tool's settings: Grid = 1/16 here)
  31339. offline.dispatchPendingMessages();
  31340. {
  31341. const auto& after = offline.getSong().patterns[0].notes;
  31342. bool onGrid = ! after.empty();
  31343. for (const auto& n : after)
  31344. onGrid = onGrid && n.start % (lynx::ppq / 4) == 0;
  31345. check ("Ctrl+U quantized every note start onto the editor's 1/16 grid", onGrid && after.size() == before.size() && after != before);
  31346. }
  31347. roll.runAction ("pianoRoll.liveQuantizeSettings"); // (Live 12: Quantize Settings… opens the MIDI Tools' Quantize tool)
  31348. offline.dispatchPendingMessages();
  31349. check ("Ctrl+Shift+U shows the MIDI Tools' Quantize tool", detail->midiToolsForSnapshot().getTool() == lynx::MidiToolsPanel::quantize
  31350. && detail->midiToolsForSnapshot().isVisible());
  31351. ui.resized();
  31352. write (*detail, "04-after-quantize-tool");
  31353. // an audio clip transposed +30 st 25 ct (Live's ±48 st)
  31354. const auto wav = juce::File (prefix + "-tone.wav");
  31355. wav.deleteFile();
  31356. {
  31357. const double rate = 48000.0;
  31358. juce::AudioBuffer<float> buffer (1, (int) (rate * 2.0));
  31359. for (int k = 0; k < buffer.getNumSamples(); ++k)
  31360. buffer.setSample (0, k, (float) (0.5 * std::sin (k * 0.05)));
  31361. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  31362. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  31363. {
  31364. out.release();
  31365. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  31366. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  31367. }
  31368. }
  31369. offline.editSong ([&wav] (lynx::Song& s) {
  31370. lynx::ChannelDef ch;
  31371. ch.name = "Tone";
  31372. ch.instrument = lynx::InstrumentKind::audioClip;
  31373. ch.samplePath = wav.getFullPathName().toStdString();
  31374. s.channels.push_back (ch);
  31375. lynx::Clip audio;
  31376. audio.kind = lynx::ClipKind::audio;
  31377. audio.channel = (int) s.channels.size() - 1;
  31378. audio.length = 4 * lynx::ppq;
  31379. audio.pitch = 30.25f;
  31380. lynx::launcher::setClip (s, 1, 0, audio);
  31381. }, false);
  31382. offline.dispatchPendingMessages();
  31383. if (auto panel = lynx::makeClipAudioPanel (offline, 1, 0))
  31384. {
  31385. panel->setSize (900, 250);
  31386. write (*panel, "06-audio-transpose-30");
  31387. check ("audio clip transpose +30.25 st kept", std::abs (lynx::launcher::clipAt (*offline.getSong().clipGrid, 1, 0)->pitch - 30.25f) < 1e-4f);
  31388. }
  31389. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  31390. }
  31391. void runWarpShot190fm (const juce::String& prefix)
  31392. {
  31393. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31394. lynx::AudioEngine offline (false);
  31395. juce::String checks;
  31396. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  31397. // a one-bar loop of clicks (2 s at 48 kHz) for the audio clips
  31398. const auto wav = juce::File (prefix + "-loop.wav");
  31399. wav.deleteFile();
  31400. {
  31401. const double rate = 48000.0;
  31402. juce::AudioBuffer<float> buffer (2, (int) (rate * 2.0));
  31403. buffer.clear();
  31404. for (int hit = 0; hit < 8; ++hit)
  31405. for (int k = 0; k < 3000; ++k)
  31406. for (int ch = 0; ch < 2; ++ch)
  31407. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
  31408. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  31409. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  31410. {
  31411. out.release();
  31412. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  31413. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  31414. }
  31415. }
  31416. offline.editSong ([&wav] (lynx::Song& s) {
  31417. lynx::ChannelDef ch;
  31418. ch.name = "Loop";
  31419. ch.instrument = lynx::InstrumentKind::audioClip;
  31420. ch.samplePath = wav.getFullPathName().toStdString();
  31421. s.channels.push_back (ch);
  31422. const auto c = (int) s.channels.size() - 1;
  31423. lynx::clipsample::setWarp (s, c, true, 2.0);
  31424. lynx::warpmodes::setMode (s, c, (int) lynx::StretchMethod::beats); // (keeps the pitch: Beats, not Re-Pitch)
  31425. lynx::Clip audio;
  31426. audio.kind = lynx::ClipKind::audio;
  31427. audio.channel = c;
  31428. audio.length = 4 * lynx::ppq;
  31429. lynx::launcher::setClip (s, 0, 0, audio);
  31430. lynx::launcher::setClip (s, 0, 1, audio); // (a second clip on the same channel: O16)
  31431. lynx::launcher::ensureGrid (s).scenes.resize (2);
  31432. }, false);
  31433. offline.dispatchPendingMessages();
  31434. const auto shoot = [&] (const char* name) {
  31435. auto panel = lynx::makeClipAudioPanel (offline, 0, 0);
  31436. if (panel == nullptr)
  31437. return false;
  31438. panel->setSize (900, 250);
  31439. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  31440. file.deleteFile();
  31441. juce::FileOutputStream out (file);
  31442. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (*panel), out);
  31443. return true;
  31444. };
  31445. const auto channelOf = [&] (int scene) {
  31446. const auto* c = lynx::warpmodes::gridAudioClip (const_cast<lynx::Song&> (offline.getSong()), 0, scene);
  31447. return c != nullptr ? c->channel : -1;
  31448. };
  31449. const auto beatsOn = [&] { const auto& sm = offline.getSong().channels[(std::size_t) channelOf (0)].sampler; return sm.keepPitch && sm.stretchMethod == lynx::StretchMethod::beats; };
  31450. check ("01 Beats panel (defaults: Transients, Back-and-Forth, 100)", beatsOn() && shoot ("01-beats-defaults"));
  31451. offline.editSong ([&] (lynx::Song& s) {
  31452. const auto c = lynx::warpmodes::ownChannelForGridClip (s, 0, 0);
  31453. lynx::warpmodes::setPreserve (s, c, 3);
  31454. lynx::warpmodes::setLoopMode (s, c, 0);
  31455. lynx::warpmodes::setEnvelope (s, c, 40.0);
  31456. }, false);
  31457. offline.dispatchPendingMessages();
  31458. 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);
  31459. check ("02 Beats panel (1/8, Loop Off, 40)", beatsOn() && shoot ("02-beats-set"));
  31460. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::tones); }, false);
  31461. offline.dispatchPendingMessages();
  31462. check ("03 Tones panel (Grain Size 30)", shoot ("03-tones"));
  31463. offline.editSong ([&] (lynx::Song& s) {
  31464. lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::texture);
  31465. lynx::warpmodes::setGrain (s, channelOf (0), 120.0);
  31466. }, false);
  31467. offline.dispatchPendingMessages();
  31468. check ("04 Texture panel (Grain Size 120)", shoot ("04-texture"));
  31469. check ("Texture grain kept 120, Tones grain still 30", offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.textureGrain == 120.0f
  31470. && offline.getSong().channels[(std::size_t) channelOf (0)].sampler.warpModes.tonesGrain == 30.0f);
  31471. offline.editSong ([&] (lynx::Song& s) { lynx::warpmodes::setMode (s, channelOf (0), (int) lynx::StretchMethod::complex); }, false);
  31472. offline.dispatchPendingMessages();
  31473. check ("05 Complex panel (no settings row)", shoot ("05-complex"));
  31474. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  31475. }
  31476. // LYNX --livelook190jnshot prefix [set.als]: round 190jn off screen (design190ia slices 13 CL-D, 17 CL-E, 18 CL-H,
  31477. // 19 CL-F, 25 CL-I: the Clip-launch layout in Ableton Live's look) — the Session mixer (selected, armed, muted,
  31478. // soloed, I/O on and off, peak pills), the Device View (cards, a card off and one folded, the hot-swap link, a Drum
  31479. // Rack's pads, an Instrument Rack's macros), the Clip View (MIDI and audio, three detail heights), the Info View with a
  31480. // hovered control and the status strip; with a Live set: its Arrangement in 19 px lanes, the 38 px option and a tall
  31481. // audio lane; every view once more in the classic LYNX look (View › Classic LYNX look). prefix-checks.txt
  31482. void runLiveLook190jnShot (const juce::String& prefix, const juce::String& set)
  31483. {
  31484. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31485. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  31486. juce::String checks;
  31487. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  31488. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  31489. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  31490. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  31491. const auto area = [&prefix] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) { saveArea (c, r, prefix + "-" + name + ".png"); };
  31492. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  31493. const auto w = juce::jlimit (800, 3840, size[0].getIntValue()), h = juce::jlimit (450, 2160, size[1].getIntValue());
  31494. const auto classicBefore = lynx::clipGridClassicLook();
  31495. const auto tallBefore = lynx::playlistTallLiveLanes();
  31496. lynx::clipGridClassicLook() = false;
  31497. lynx::playlistTallLiveLanes() = false;
  31498. lynx::DetailView::infoViewShown = true;
  31499. // ---- A. a synthetic set (round 190dr's, with a Drum Rack and an audio loop) -----------------------------------
  31500. const auto wav = juce::File (prefix + "-loop.wav");
  31501. wav.deleteFile();
  31502. {
  31503. const double rate = 48000.0;
  31504. juce::AudioBuffer<float> buffer (2, (int) (rate * 4.0));
  31505. buffer.clear();
  31506. for (int hit = 0; hit < 16; ++hit)
  31507. for (int k = 0; k < 9000 && hit * 12000 + k < buffer.getNumSamples(); ++k)
  31508. for (int ch = 0; ch < 2; ++ch)
  31509. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 2500.0) * 0.8));
  31510. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  31511. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  31512. {
  31513. out.release();
  31514. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  31515. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  31516. }
  31517. }
  31518. {
  31519. lynx::AudioEngine offline (false);
  31520. lynx::MainComponent ui (offline, false);
  31521. ui.setSize (w, h);
  31522. const auto settle = [&] {
  31523. for (int k = 0; k < 3; ++k)
  31524. offline.dispatchPendingMessages();
  31525. };
  31526. ui.setVisible (true);
  31527. lynx::DetailView::shownSetting = true;
  31528. lynx::DetailView::devicesPage = true;
  31529. lynx::DetailView::preferredHeight = 228;
  31530. ui.setClipLaunchWorkflow (true);
  31531. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  31532. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  31533. settle();
  31534. int audioChannel = -1;
  31535. const auto selectedChannel = offline.getSelectedChannel();
  31536. offline.editSong ([&audioChannel, selectedChannel] (lynx::Song& s) {
  31537. lynx::Clip audio;
  31538. if (! s.playlist.empty())
  31539. {
  31540. audio = s.playlist.front();
  31541. audioChannel = audio.channel;
  31542. s.playlist.clear();
  31543. }
  31544. const int channels = (int) s.channels.size();
  31545. s.channels.resize ((std::size_t) channels + 3);
  31546. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  31547. for (int k = 0; k < 3; ++k)
  31548. {
  31549. auto& ch = s.channels[(std::size_t) (channels + k)];
  31550. ch.name = names[k];
  31551. ch.instrument = k == 0 ? lynx::InstrumentKind::patcher : lynx::InstrumentKind::synth;
  31552. ch.mixerTrack = k + 1;
  31553. }
  31554. // the Drum kit: a Drum Rack with Live's 909 pad names, its two first macros mapped
  31555. {
  31556. auto& kit = s.channels[(std::size_t) channels].patcher;
  31557. kit = lynx::rack::makeDrumRack();
  31558. const char* pads[] { "Bass Drum", "Rim Shot", "Snare Drum", "Hand Clap", "Snare Drum", "Closed Hi Hat", "Snare Drum", "Bass Drum",
  31559. "Low Tom", "Mid Tom", "Open Hi Hat", "Hi Tom", "Crash", "Crash", "Ride", "Ride" };
  31560. for (int p = 0; p < 16; ++p)
  31561. {
  31562. lynx::PatchNode n;
  31563. n.generator = true;
  31564. n.channel.instrument = lynx::InstrumentKind::sampler;
  31565. n.channel.name = pads[p];
  31566. lynx::rack::addPad (kit, 36 + p, pads[p], n);
  31567. }
  31568. if (auto* r = lynx::rack::rackOf (kit))
  31569. {
  31570. r->name = "909 Core Kit";
  31571. r->showMacros = true;
  31572. r->showPads = true;
  31573. r->shownMacros = 8;
  31574. r->macros[0].name = "Low Gain";
  31575. r->macros[1].name = "Mid Gain";
  31576. }
  31577. for (int m = 0; m < 2; ++m)
  31578. {
  31579. lynx::RackMapping map;
  31580. map.target = lynx::RackMapping::Target::chainVolume;
  31581. map.chain = m;
  31582. lynx::rack::map (kit, m, map);
  31583. }
  31584. lynx::rack::compile (kit);
  31585. }
  31586. if (audioChannel >= 0)
  31587. s.channels[(std::size_t) audioChannel].mixerTrack = 5;
  31588. if (s.mixer.size() < 8)
  31589. s.mixer.resize (8);
  31590. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Loop", "Reverb", "Delay" };
  31591. for (int i = 1; i < 8; ++i)
  31592. s.mixer[(std::size_t) i].name = inserts[i];
  31593. s.mixer[1].volume = lynx::sessionmixer::positionForDb (-3.0);
  31594. s.mixer[2].pan = 0.3f;
  31595. s.mixer[2].effects.clear();
  31596. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay, lynx::EffectKind::reverb })
  31597. {
  31598. lynx::EffectSlot fx;
  31599. fx.kind = kind;
  31600. const auto& info = lynx::effectInfo (kind);
  31601. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  31602. fx.params[k] = info.params[k].defaultValue;
  31603. s.mixer[2].effects.push_back (fx);
  31604. }
  31605. s.mixer[2].effects[2].enabled = false; // (the Delay off: Live dims a device that is off)
  31606. s.mixer[3].muted = true; // the Keys' activator off
  31607. s.mixer[4].inputChannel = 0;
  31608. s.mixer[4].inputStereo = true;
  31609. s.mixer[4].monitor = lynx::InputMonitor::automatic;
  31610. s.mixer[5].solo = false; // (soloed later: Live greys every activator while a track is soloed)
  31611. 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 } })
  31612. {
  31613. lynx::MixerSend send;
  31614. send.target = to;
  31615. send.level = lynx::faderGain (level);
  31616. s.mixer[(std::size_t) from].sends.push_back (send);
  31617. }
  31618. while (s.patterns.size() < 3)
  31619. s.patterns.emplace_back();
  31620. const char* patterns[] { "Beat", "Bassline", "Chords" };
  31621. for (int p = 0; p < 3; ++p)
  31622. {
  31623. auto& pattern = s.patterns[(std::size_t) p];
  31624. pattern.name = patterns[p];
  31625. pattern.notes.clear();
  31626. for (int k = 0; k < 6; ++k)
  31627. {
  31628. lynx::Note n;
  31629. n.channel = channels + p;
  31630. n.key = (p == 0 ? 36 : 48) + (k * 5) % 12 + p * 2;
  31631. n.start = (std::int64_t) k * lynx::ppq / 2;
  31632. n.length = lynx::ppq / 2;
  31633. n.velocity = 0.55f + 0.07f * (float) k;
  31634. pattern.notes.push_back (n);
  31635. }
  31636. pattern.lengthTicks = 4 * lynx::ppq;
  31637. }
  31638. // a "Lead" clip on the FX track for the Clip View's MIDI shot: notes of the rack's selected channel (the docked
  31639. // Piano roll edits its notes) in the Piano roll's opening rows
  31640. {
  31641. const auto kick = juce::jlimit (0, channels - 1, selectedChannel); // (the docked Piano roll edits the selected channel's notes)
  31642. lynx::Pattern lead;
  31643. lead.name = "Lead";
  31644. for (int k = 0; k < 6; ++k)
  31645. {
  31646. lynx::Note n;
  31647. n.channel = kick;
  31648. n.key = 79 + (k * 5) % 6; // (G6 .. C7 in FL's names, C5 = 60: the rows the docked Piano roll opens on)
  31649. n.start = (std::int64_t) k * lynx::ppq / 2;
  31650. n.length = lynx::ppq / 2;
  31651. n.velocity = 0.55f + 0.07f * (float) k;
  31652. lead.notes.push_back (n);
  31653. }
  31654. lead.lengthTicks = 4 * lynx::ppq;
  31655. s.patterns.push_back (lead);
  31656. }
  31657. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  31658. const char* tracks[] { "Drums", "Bass", "Keys", "Vox", "Loop", "FX" };
  31659. const std::uint32_t colours[] { 0xff9bc48d, 0xffd2e498, 0xffa595b5, 0xffcdf1f8, 0xfff7f47c, 0xffc6928b }; // (Live's palette)
  31660. for (int t = 0; t < 6; ++t)
  31661. {
  31662. s.playlistTracks[(std::size_t) t].name = tracks[t];
  31663. s.playlistTracks[(std::size_t) t].colour = colours[t];
  31664. }
  31665. s.playlistTracks[3].mode = lynx::PlaylistTrackMode::audio;
  31666. s.playlistTracks[3].mixerTrack = 4;
  31667. for (int t = 0; t < 3; ++t)
  31668. for (int r = 0; r < 3; ++r)
  31669. if (! (t == 2 && r == 0))
  31670. {
  31671. lynx::Clip clip;
  31672. clip.pattern = t;
  31673. clip.length = 4 * lynx::ppq;
  31674. lynx::launcher::setClip (s, t, r, clip);
  31675. }
  31676. {
  31677. lynx::Clip lead;
  31678. lead.pattern = (int) s.patterns.size() - 1;
  31679. lead.length = 4 * lynx::ppq;
  31680. lynx::launcher::setClip (s, 5, 0, lead);
  31681. }
  31682. if (audioChannel >= 0)
  31683. {
  31684. lynx::clipsample::setWarp (s, audioChannel, true, 4.0);
  31685. audio.track = 4;
  31686. audio.start = 0;
  31687. lynx::launcher::setClip (s, 4, 0, audio);
  31688. lynx::launcher::setClip (s, 4, 1, audio);
  31689. }
  31690. auto& grid = lynx::launcher::ensureGrid (s);
  31691. const char* scenes[] { "Intro", "Verse", "Drop" };
  31692. grid.scenes.resize (5);
  31693. for (int r = 0; r < 3; ++r)
  31694. grid.scenes[(std::size_t) r].name = scenes[r];
  31695. }, false);
  31696. settle();
  31697. offline.setGridTrackArmed (3, true);
  31698. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  31699. settle();
  31700. ui.resized();
  31701. auto* gridView = ui.getClipGridForSnapshot();
  31702. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  31703. auto* detail = ui.getDetailViewForSnapshot();
  31704. if (gridView == nullptr || mixer == nullptr || detail == nullptr)
  31705. {
  31706. check ("a grid, a Session mixer and a detail view", false);
  31707. return;
  31708. }
  31709. check ("the Live look is on (Clip-launch, classic off)", lynx::theme::livelook::active());
  31710. const auto meters = [&] {
  31711. mixer->tick();
  31712. const float peaks[] { 0.9f, 0.5f, 0.7f, 0.0f, 0.3f, 0.45f, 0.2f, 0.12f };
  31713. for (int i = 0; i < 8; ++i)
  31714. mixer->setMeterForSnapshot (i, peaks[i], peaks[i] * 0.85f, peaks[i] * 1.1f, peaks[i], i == 1 ? 1.2f : peaks[i] * 1.15f);
  31715. };
  31716. if (auto* runtime = offline.launcherStateForSnapshot())
  31717. {
  31718. runtime->tracks[0].playing.store (1);
  31719. runtime->tracks[0].progress.store (0.3f);
  31720. runtime->tracks[1].playing.store (1);
  31721. runtime->tracks[1].progress.store (0.3f);
  31722. runtime->tracks[4].playing.store (0);
  31723. runtime->tracks[4].progress.store (0.5f);
  31724. runtime->running.store (true);
  31725. }
  31726. lynx::selectClipGridSlotForSnapshot (*gridView, 1, 1); // (the Bass track selected: its strip #464646)
  31727. settle();
  31728. meters();
  31729. gridView->resized();
  31730. write (ui, "13-window");
  31731. write (*gridView, "13-grid-mixer");
  31732. area (*gridView, mixer->getBoundsInParent(), "13-mixer");
  31733. using Part = lynx::SessionMixerComponent::Part;
  31734. check ("mixer: the Drums strip has a peak pill in Live's look", ! mixer->partBounds (0, Part::peak).isEmpty());
  31735. check ("mixer: the Drums peak pill reads the clipped peak", mixer->loudestPeak (1) >= 1.0f);
  31736. line ("mixer: activator " + mixer->partBounds (0, Part::activator).toString() + ", solo " + mixer->partBounds (0, Part::solo).toString()
  31737. + ", arm " + mixer->partBounds (0, Part::arm).toString() + ", pan " + mixer->partBounds (0, Part::pan).toString()
  31738. + ", volume " + mixer->partBounds (0, Part::volume).toString() + ", peak " + mixer->partBounds (0, Part::peak).toString());
  31739. 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());
  31740. mixer->setHoverForSnapshot ({ 1, Part::solo, 0 });
  31741. area (*gridView, mixer->getBoundsInParent(), "13-mixer-hover-solo");
  31742. mixer->setHoverForSnapshot ({});
  31743. // the I/O section off (View › Mixer › I/O)
  31744. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.io = false; }, false);
  31745. settle();
  31746. gridView->resized();
  31747. meters();
  31748. area (*gridView, mixer->getBoundsInParent(), "13-mixer-io-off");
  31749. // a track soloed: Live greys every active activator (#757575, captured in shots/ref/live-mixer-solo-deactivated.png)
  31750. offline.editSong ([] (lynx::Song& s) { s.mixer[5].solo = true; }, false);
  31751. settle();
  31752. meters();
  31753. area (*gridView, mixer->getBoundsInParent(), "13-mixer-soloing");
  31754. offline.editSong ([] (lynx::Song& s) { s.mixer[5].solo = false; }, false);
  31755. settle();
  31756. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.io = true; }, false);
  31757. settle();
  31758. gridView->resized();
  31759. // ---- 19 + 25: the Device View of the Bass track (EQ, Compressor, Delay off, Reverb folded), the Info View ----
  31760. detail->showSelection (1, 1);
  31761. detail->setPage (lynx::DetailView::Page::devices);
  31762. settle();
  31763. ui.resized();
  31764. settle();
  31765. const auto cards = detail->cardCountForCheck();
  31766. line ("device view: " + juce::String (cards) + " cards, insert " + juce::String (detail->chainInsertForCheck()));
  31767. if (cards >= 5)
  31768. detail->toggleFoldForCheck (4);
  31769. detail->selectCardForCheck (1);
  31770. meters();
  31771. // the Info View with a hovered control: the Bass strip's activator, as the hint timer would give it
  31772. {
  31773. lynx::ui::Hint hint; // (the mixer's hint is its tooltip, read at the mouse: off screen its text for the part)
  31774. hint.text = mixer->tipForSnapshot ({ 1, Part::activator, 0 });
  31775. detail->setInfoHint (hint);
  31776. line ("info view: title '" + detail->infoViewForSnapshot().getTitleText() + "', body '" + detail->infoViewForSnapshot().getBodyText() + "'");
  31777. check ("info view: the hovered activator's hint shows", detail->infoViewForSnapshot().getBodyText().isNotEmpty());
  31778. }
  31779. write (ui, "19-window-devices");
  31780. write (*detail, "19-detail-devices");
  31781. area (*detail, detail->getLocalBounds().withTrimmedTop (detail->getHeight() - lynx::DetailView::stripHeight), "25-status-strip");
  31782. area (*detail, detail->getLocalBounds().withWidth (260), "25-info-view");
  31783. check ("device view: four effect cards and the instrument", cards >= 5);
  31784. check ("device view: the folded card stays folded", cards < 5 || detail->isFoldedForCheck (4));
  31785. // the hot-swap link on the selected card (Q)
  31786. ui.runActionForSnapshot ("view.hotSwap");
  31787. settle();
  31788. write (*detail, "19-detail-hotswap");
  31789. ui.runActionForSnapshot ("view.hotSwap");
  31790. settle();
  31791. // the Drum Rack (the Drums track's instrument)
  31792. detail->showSelection (0, 1);
  31793. settle();
  31794. detail->selectCardForCheck (0);
  31795. write (*detail, "19-detail-drumrack");
  31796. // an Instrument Rack (Keys grouped: Ctrl+G on the instrument card)
  31797. detail->showSelection (2, 1);
  31798. settle();
  31799. check ("device view: the Keys instrument grouped into an Instrument Rack", detail->groupCardForCheck (0, false));
  31800. settle();
  31801. write (*detail, "19-detail-instrumentrack");
  31802. // the Info View off (its (i) button), then back
  31803. detail->toggleInfoView();
  31804. write (*detail, "25-detail-info-off");
  31805. detail->toggleInfoView();
  31806. // ---- 17: the Clip View: a MIDI clip, then the audio clip at three detail heights --------------------------
  31807. detail->showSelection (5, 0); // (the FX track's Lead clip)
  31808. detail->setPage (lynx::DetailView::Page::clip);
  31809. settle();
  31810. ui.resized();
  31811. settle();
  31812. write (ui, "17-window-clip-midi");
  31813. write (*detail, "17-detail-clip-midi");
  31814. // Launch (folded at first, as Live shows it) and Pitch & Time open, the column scrolled to them
  31815. detail->clipSectionsForSnapshot (true, true, true, 0);
  31816. write (*detail, "17-detail-clip-midi-launch-open");
  31817. detail->clipSectionsForSnapshot (true, true, true, 160);
  31818. write (*detail, "17-detail-clip-midi-scrolled");
  31819. detail->clipSectionsForSnapshot (true, false, true, 0);
  31820. detail->showSelection (4, 0);
  31821. settle();
  31822. for (const auto height : { 190, 260, 350 })
  31823. {
  31824. lynx::DetailView::preferredHeight = height;
  31825. ui.resized();
  31826. if (auto* parent = detail->getParentComponent()) // (the Playlist area lays its docked detail view out)
  31827. parent->resized();
  31828. settle();
  31829. write (*detail, "17-detail-clip-audio-" + juce::String (height));
  31830. check ("audio box at " + juce::String (height) + " px: the detail view is that high", detail->getHeight() == height);
  31831. }
  31832. lynx::DetailView::preferredHeight = 228;
  31833. ui.resized();
  31834. if (auto* parent = detail->getParentComponent())
  31835. parent->resized();
  31836. settle();
  31837. write (ui, "17-window-clip-audio");
  31838. // ---- the same views in the classic LYNX look (View › Classic LYNX look in the Clip-launch layout) --------
  31839. lynx::clipGridClassicLook() = true;
  31840. lynx::refreshClipGrid (*gridView);
  31841. ui.getPlaylistForSnapshot().liveLanesChanged();
  31842. ui.resized();
  31843. detail->resized();
  31844. settle();
  31845. check ("classic look: the Live look is off", ! lynx::theme::livelook::active());
  31846. write (ui, "classic-window-clip-audio");
  31847. detail->setPage (lynx::DetailView::Page::devices);
  31848. detail->showSelection (1, 1);
  31849. settle();
  31850. meters();
  31851. write (ui, "classic-window-devices");
  31852. lynx::clipGridClassicLook() = false;
  31853. lynx::refreshClipGrid (*gridView);
  31854. ui.getPlaylistForSnapshot().liveLanesChanged();
  31855. ui.resized();
  31856. settle();
  31857. // ---- 18: the synthetic set's Arrangement (Song view) ------------------------------------------------------
  31858. offline.editSong ([audioChannel] (lynx::Song& s) {
  31859. for (int t = 0; t < 3; ++t)
  31860. for (int bar = 0; bar < 8; bar += 2)
  31861. {
  31862. lynx::Clip clip;
  31863. clip.pattern = t;
  31864. clip.track = t;
  31865. clip.start = (std::int64_t) bar * 4 * lynx::ppq + (t == 2 ? 4 * lynx::ppq : 0);
  31866. clip.length = 4 * lynx::ppq * (t == 1 ? 2 : 1);
  31867. if (! (t == 1 && bar % 4 != 0))
  31868. s.playlist.push_back (clip);
  31869. }
  31870. if (audioChannel >= 0)
  31871. for (int bar = 0; bar < 8; bar += 2)
  31872. {
  31873. lynx::Clip audio;
  31874. audio.channel = audioChannel;
  31875. audio.track = 4;
  31876. audio.start = (std::int64_t) bar * 4 * lynx::ppq;
  31877. audio.length = 8 * lynx::ppq;
  31878. audio.kind = lynx::ClipKind::audio;
  31879. s.playlist.push_back (audio);
  31880. }
  31881. }, false);
  31882. settle();
  31883. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  31884. settle();
  31885. ui.resized();
  31886. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (30000);
  31887. settle();
  31888. ui.getPlaylistForSnapshot().repaint();
  31889. write (ui, "18-synthetic-arrangement-19");
  31890. lynx::playlistTallLiveLanes() = true;
  31891. ui.getPlaylistForSnapshot().liveLanesChanged();
  31892. settle();
  31893. write (ui, "18-synthetic-arrangement-38");
  31894. lynx::playlistTallLiveLanes() = false;
  31895. ui.getPlaylistForSnapshot().liveLanesChanged();
  31896. settle();
  31897. }
  31898. // ---- B. the Live set (its Arrangement with real audio) ----------------------------------------------------------
  31899. if (set.isNotEmpty() && juce::File (set).existsAsFile())
  31900. {
  31901. lynx::AudioEngine offline (false);
  31902. lynx::MainComponent ui (offline, false);
  31903. ui.setSize (w, h);
  31904. const auto settle = [&] {
  31905. for (int k = 0; k < 3; ++k)
  31906. offline.dispatchPendingMessages();
  31907. };
  31908. ui.setVisible (true);
  31909. lynx::DetailView::shownSetting = true;
  31910. lynx::DetailView::devicesPage = true;
  31911. ui.selectTabForSnapshot (2);
  31912. ui.setClipLaunchWorkflow (true); // (first: the import takes Live's colour table in this layout, CL-6)
  31913. settle();
  31914. ui.openFile (juce::File (set));
  31915. settle();
  31916. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  31917. settle();
  31918. ui.resized();
  31919. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  31920. settle();
  31921. const auto& song = offline.getSong();
  31922. line ("set: " + juce::String ((int) song.playlist.size()) + " Arrangement clips, " + juce::String ((int) song.playlistTracks.size()) + " tracks");
  31923. int drums = -1;
  31924. for (int t = 0; t < (int) song.playlistTracks.size() && drums < 0; ++t)
  31925. if (juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str()).containsIgnoreCase ("drum"))
  31926. drums = t;
  31927. if (drums >= 0)
  31928. line ("set: Drums track colour #" + juce::String::toHexString ((int) (song.playlistTracks[(std::size_t) drums].colour & 0xffffff)).paddedLeft ('0', 6));
  31929. check ("set: the Drums track has Live's colour #9BC48D (CL-6)", drums >= 0 && (song.playlistTracks[(std::size_t) drums].colour & 0xffffff) == 0x9bc48d);
  31930. write (ui, "18-als-arrangement-19");
  31931. // the set's Session mixer (the coordinator's 190jn follow-up: every Patience track has its strip)
  31932. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  31933. settle();
  31934. ui.resized();
  31935. settle();
  31936. if (auto* gridView = ui.getClipGridForSnapshot())
  31937. if (auto* mixer = lynx::clipGridMixer (*gridView))
  31938. {
  31939. int strips = 0;
  31940. for (int t = 0; t < 64; ++t)
  31941. strips += mixer->partBounds (t, lynx::SessionMixerComponent::Part::volume).isEmpty() ? 0 : 1;
  31942. line ("set: Session mixer strips with a volume: " + juce::String (strips) + ", mixer " + mixer->getBounds().toString()
  31943. + ", grid " + gridView->getBounds().toString());
  31944. write (ui, "13-als-window");
  31945. area (*gridView, mixer->getBoundsInParent(), "13-als-mixer");
  31946. }
  31947. ui.setClipGridView (lynx::PlaylistArea::GridView::song);
  31948. settle();
  31949. write (ui.getPlaylistForSnapshot(), "18-als-playlist-19");
  31950. lynx::playlistTallLiveLanes() = true;
  31951. ui.getPlaylistForSnapshot().liveLanesChanged();
  31952. settle();
  31953. write (ui, "18-als-arrangement-38");
  31954. // a tall audio lane (live-arrangement-audiolane.png: Vocal Main at ~250 px)
  31955. int vocal = -1;
  31956. for (int t = 0; t < (int) song.playlistTracks.size() && vocal < 0; ++t)
  31957. if (juce::String::fromUTF8 (song.playlistTracks[(std::size_t) t].name.c_str()).containsIgnoreCase ("vocal"))
  31958. vocal = t;
  31959. if (vocal >= 0)
  31960. {
  31961. offline.editSong ([vocal] (lynx::Song& s) { s.playlistTracks[(std::size_t) vocal].height = 250; }, false);
  31962. lynx::playlistTallLiveLanes() = false;
  31963. ui.getPlaylistForSnapshot().liveLanesChanged();
  31964. settle();
  31965. write (ui, "18-als-audiolane");
  31966. }
  31967. line ("set: Vocal track " + juce::String (vocal));
  31968. lynx::clipGridClassicLook() = true;
  31969. ui.getPlaylistForSnapshot().liveLanesChanged();
  31970. settle();
  31971. write (ui, "classic-als-arrangement");
  31972. lynx::clipGridClassicLook() = false;
  31973. }
  31974. lynx::clipGridClassicLook() = classicBefore;
  31975. lynx::playlistTallLiveLanes() = tallBefore;
  31976. wav.deleteFile();
  31977. line ("done");
  31978. }
  31979. // LYNX --fllook190joshot prefix project.flp: round 190jo off screen (design190ia slices 12 FM-S6, 21 FM-S4, 23 FW-S4)
  31980. void runFllook190joShot (const juce::String& prefix, const juce::String& project)
  31981. {
  31982. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  31983. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  31984. lynx::ui::motion::enabled() = false; // (hover states drawn at once, no fade)
  31985. juce::String checks;
  31986. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  31987. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  31988. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  31989. lynx::AudioEngine offline (false);
  31990. lynx::MainComponent ui (offline, false);
  31991. ui.setSize (1920, 1080);
  31992. const auto settle = [&] {
  31993. for (int k = 0; k < 3; ++k)
  31994. offline.dispatchPendingMessages();
  31995. };
  31996. const auto area = [&] (juce::Rectangle<int> r, const juce::String& name) { saveArea (ui, r, prefix + "-" + name + ".png"); };
  31997. ui.selectTabForSnapshot (2);
  31998. if (project.isNotEmpty())
  31999. {
  32000. ui.openFile (juce::File (project));
  32001. settle();
  32002. }
  32003. check ("the project opened", ! offline.getSong().channels.empty());
  32004. const auto bar = [&ui] { return ui.getLocalBounds().withHeight (juce::jmin (ui.getHeight(), 90)); };
  32005. const std::pair<int, int> sizes[] { { 1920, 1080 }, { 1600, 900 }, { 1366, 768 }, { 1280, 800 } };
  32006. // ---- slice 12: the Pattern toolbar ------------------------------------------------------------------------------
  32007. for (const auto& [w, h] : sizes)
  32008. {
  32009. ui.setSize (w, h);
  32010. settle();
  32011. area (bar(), "tb-" + juce::String (w));
  32012. int tiles = 0;
  32013. for (auto* c : ui.getChildren())
  32014. if (auto* b = dynamic_cast<lynx::IconButton*> (c); b != nullptr && b->isVisible() && b->getLook() == lynx::IconButton::Look::flTile)
  32015. ++tiles;
  32016. line ("toolbar " + juce::String (w) + ": " + juce::String (tiles) + " tiled buttons");
  32017. }
  32018. ui.setSize (1920, 1080);
  32019. settle();
  32020. std::vector<lynx::IconButton*> tiled;
  32021. for (auto* c : ui.getChildren())
  32022. if (auto* b = dynamic_cast<lynx::IconButton*> (c); b != nullptr && b->isVisible() && b->getLook() == lynx::IconButton::Look::flTile)
  32023. tiled.push_back (b);
  32024. check ("the Pattern toolbar's buttons are FL tiles (" + juce::String ((int) tiled.size()) + ")", tiled.size() >= 25);
  32025. std::vector<bool> lit;
  32026. for (auto* b : tiled)
  32027. lit.push_back (b->getToggleState());
  32028. area (bar(), "tb-states-idle");
  32029. for (const auto& [state, name] : { std::pair<juce::Button::ButtonState, const char*> { juce::Button::buttonOver, "hover" }, { juce::Button::buttonDown, "pressed" } })
  32030. {
  32031. for (auto* b : tiled)
  32032. b->setState (state);
  32033. area (bar(), juce::String ("tb-states-") + name);
  32034. for (auto* b : tiled)
  32035. b->setState (juce::Button::buttonNormal);
  32036. }
  32037. for (auto* b : tiled)
  32038. b->setToggleState (true, juce::dontSendNotification);
  32039. area (bar(), "tb-states-on");
  32040. for (auto* b : tiled)
  32041. b->setState (juce::Button::buttonOver);
  32042. area (bar(), "tb-states-on-hover");
  32043. for (std::size_t k = 0; k < tiled.size(); ++k)
  32044. {
  32045. tiled[k]->setState (juce::Button::buttonNormal);
  32046. tiled[k]->setToggleState (lit[k], juce::dontSendNotification);
  32047. tiled[k]->setEnabled (false);
  32048. }
  32049. area (bar(), "tb-states-disabled");
  32050. for (auto* b : tiled)
  32051. b->setEnabled (true);
  32052. // one switch and one plain button under the mouse, as FL's capture (its audio editor button lit)
  32053. if (auto* metronome = dynamic_cast<lynx::IconButton*> (ui.toolbarPartForSnapshot ("metronome")))
  32054. {
  32055. metronome->setState (juce::Button::buttonOver);
  32056. area (bar(), "tb-hover-switch");
  32057. metronome->setState (juce::Button::buttonNormal);
  32058. }
  32059. // the time panel in B:S:T at bar 3, step 05, tick 12 (FL: "3:05:12"), the tempo, and the hint bar
  32060. {
  32061. auto& transport = offline.getTransport();
  32062. const auto& song = offline.getSong();
  32063. transport.positionTicks.store ((double) (2 * song.barTicks()) + 4.0 * lynx::ticksPerStep + lynx::ticksPerStep / 2.0);
  32064. ui.transportTickForSnapshot();
  32065. auto* time = ui.toolbarPartForSnapshot ("position");
  32066. auto* tempo = ui.toolbarPartForSnapshot ("tempo");
  32067. if (time != nullptr && tempo != nullptr)
  32068. {
  32069. area (time->getBounds().getUnion (tempo->getBounds()).expanded (8, 6), "tb-time");
  32070. if (auto* hs = dynamic_cast<lynx::ui::HintSource*> (time))
  32071. line ("time panel: " + hs->hintAt ({}).value);
  32072. check ("the time panel reads FL's B:S:T (3:05:12)", dynamic_cast<lynx::ui::HintSource*> (time) != nullptr
  32073. && dynamic_cast<lynx::ui::HintSource*> (time)->hintAt ({}).value == "3:05:12");
  32074. }
  32075. transport.positionTicks.store (0.0);
  32076. ui.transportTickForSnapshot();
  32077. }
  32078. const auto hintColumn = juce::Rectangle<int> (0, 0, 360, 80);
  32079. if (auto* knob = dynamic_cast<lynx::ui::HintSource*> (ui.toolbarPartForSnapshot ("masterVolume")))
  32080. {
  32081. ui.setHintForSnapshot (knob->hintAt ({}));
  32082. area (hintColumn, "tb-hint-knob");
  32083. }
  32084. if (auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record")))
  32085. {
  32086. ui.setHintForSnapshot ({ rec->getTooltip().upToFirstOccurrenceOf ("\n", false, false), {}, false, true });
  32087. area (hintColumn, "tb-hint-button");
  32088. }
  32089. ui.setHintForSnapshot ({});
  32090. area (hintColumn, "tb-menu");
  32091. // ---- slice 21: the Piano roll ----------------------------------------------------------------------------------
  32092. ui.selectTabForSnapshot (1);
  32093. settle();
  32094. saveSnapshot (ui, prefix + "-pr.png");
  32095. auto& roll = ui.getPianoRollForSnapshot();
  32096. line ("piano roll rows: " + juce::String (roll.rowHeight) + " px");
  32097. check ("FL's 18 px rows by default", roll.rowHeight == 18);
  32098. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::piano;
  32099. roll.repaint();
  32100. saveSnapshot (ui, prefix + "-pr-pianokeys.png");
  32101. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::flat;
  32102. lynx::notenames::everyKey.store (true);
  32103. roll.repaint();
  32104. saveSnapshot (ui, prefix + "-pr-allnames.png");
  32105. lynx::notenames::everyKey.store (false);
  32106. roll.repaint();
  32107. ui.setHintForSnapshot (roll.hoverForSnapshot());
  32108. saveSnapshot (ui, prefix + "-pr-hover.png");
  32109. ui.setHintForSnapshot ({});
  32110. {
  32111. // FL's ghost capture: "Synth Bass" (no notes of its own in this pattern) over the other channels' notes
  32112. const auto& song = offline.getSong();
  32113. int bass = -1;
  32114. for (int c = 0; c < (int) song.channels.size() && bass < 0; ++c)
  32115. if (juce::String (song.channels[(std::size_t) c].name).equalsIgnoreCase ("Synth Bass"))
  32116. bass = c;
  32117. const auto kept = offline.getSelectedChannel();
  32118. if (bass >= 0)
  32119. {
  32120. offline.setSelectedChannel (bass);
  32121. settle();
  32122. roll.rowHeight = 18;
  32123. roll.repaint();
  32124. saveSnapshot (ui, prefix + "-pr-ghosts.png");
  32125. offline.setSelectedChannel (kept);
  32126. settle();
  32127. }
  32128. check ("Synth Bass found for the ghosts", bass >= 0);
  32129. }
  32130. {
  32131. // the note label against the note over the velocity range of each note colour group (WCAG)
  32132. float worst = 99.0f;
  32133. for (int group = 0; group < 16; ++group)
  32134. for (float v = 0.0f; v <= 1.0001f; v += 0.05f)
  32135. {
  32136. const auto fill = lynx::theme::noteGroupColour (group, v);
  32137. const auto label = fill.getPerceivedBrightness() > 0.5f ? lynx::theme::colour::bg0 : lynx::theme::colour::textPrimary;
  32138. worst = juce::jmin (worst, lynx::theme::contrast (label, fill));
  32139. }
  32140. line ("note label contrast, worst of 16 colour groups x velocity 0..1: " + juce::String (worst, 2) + ":1");
  32141. const auto red = lynx::theme::noteGroupColour (0, 0.78f);
  32142. line ("default note " + red.toDisplayString (false) + " label " + juce::String (lynx::theme::contrast (lynx::theme::colour::bg0, red), 2) + ":1");
  32143. check ("note labels >= 4.5:1 on the default red notes", lynx::theme::contrast (lynx::theme::colour::bg0, red) >= 4.5f);
  32144. }
  32145. ui.selectTabForSnapshot (2);
  32146. settle();
  32147. // ---- slice 23: the audio editor in Edison's layout -------------------------------------------------------------
  32148. {
  32149. const juce::File breaker ("C:\\Program Files\\Image-Line\\FL Studio 2026\\Data\\Patches\\Packs\\Loops\\DL Breaker.wav");
  32150. const auto wav = breaker.existsAsFile() ? breaker : juce::File (juce::SystemStats::getEnvironmentVariable ("LYNX_190JO_WAV", ""));
  32151. check ("FL's DL Breaker.wav", wav.existsAsFile());
  32152. if (wav.existsAsFile())
  32153. if (auto editor = lynx::makeAudioEditorForFileSnapshot (offline, wav))
  32154. {
  32155. for (const auto& [w, h] : { std::pair { 1120, 600 }, std::pair { 960, 520 } })
  32156. {
  32157. editor->setSize (w, h);
  32158. saveSnapshot (*editor, prefix + "-ed-breaker-" + juce::String (w) + ".png");
  32159. }
  32160. editor->setSize (760, 320); // (the compact form: a short dock)
  32161. saveSnapshot (*editor, prefix + "-ed-compact.png");
  32162. }
  32163. const auto at = lynx::addEdisonSlot (offline, 1);
  32164. settle();
  32165. if (at >= 0)
  32166. if (auto slot = lynx::makeEdisonSlotEditor (offline, 1, at))
  32167. {
  32168. slot->setSize (1120, 630);
  32169. saveSnapshot (*slot, prefix + "-ed-slot.png");
  32170. }
  32171. check ("an Edison slot editor", at >= 0);
  32172. const auto& song = offline.getSong();
  32173. int sampled = -1;
  32174. for (int c = 0; c < (int) song.channels.size() && sampled < 0; ++c)
  32175. if (! song.channels[(std::size_t) c].samplePath.empty())
  32176. sampled = c;
  32177. if (sampled >= 0)
  32178. if (auto panel = lynx::makeAudioEditorPanel (offline, sampled, -1))
  32179. {
  32180. panel->setSize (1100, 300);
  32181. saveSnapshot (*panel, prefix + "-ed-panel.png");
  32182. }
  32183. }
  32184. lynx::ui::motion::enabled() = true;
  32185. }
  32186. // Round 190kc (see --cliplaunch190kcshot above): the Patience set in the Clip-launch layout
  32187. void runClipLaunch190kcShot (const juce::String& prefix, const juce::String& set)
  32188. {
  32189. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32190. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  32191. juce::String checks;
  32192. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  32193. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  32194. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  32195. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  32196. const auto area = [&prefix] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) { saveArea (c, r, prefix + "-" + name + ".png"); };
  32197. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  32198. const auto w = juce::jlimit (800, 3840, size[0].getIntValue()), h = juce::jlimit (450, 2160, size[1].getIntValue());
  32199. const auto classicBefore = lynx::clipGridClassicLook();
  32200. lynx::clipGridClassicLook() = false;
  32201. if (set.isEmpty() || ! juce::File (set).existsAsFile())
  32202. {
  32203. check ("the Live set given", false);
  32204. return;
  32205. }
  32206. using Part = lynx::SessionMixerComponent::Part;
  32207. lynx::AudioEngine offline (false);
  32208. lynx::MainComponent ui (offline, false);
  32209. ui.setSize (w, h);
  32210. const auto settle = [&] {
  32211. for (int k = 0; k < 3; ++k)
  32212. offline.dispatchPendingMessages();
  32213. };
  32214. ui.setVisible (true);
  32215. lynx::DetailView::shownSetting = true;
  32216. lynx::DetailView::devicesPage = true;
  32217. ui.selectTabForSnapshot (2);
  32218. ui.setClipLaunchWorkflow (true);
  32219. settle();
  32220. ui.openFile (juce::File (set));
  32221. settle();
  32222. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  32223. settle();
  32224. ui.resized();
  32225. settle();
  32226. auto* gridView = ui.getClipGridForSnapshot();
  32227. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  32228. if (gridView == nullptr || mixer == nullptr)
  32229. {
  32230. check ("a clip grid with its Session mixer", false);
  32231. return;
  32232. }
  32233. const auto& song = offline.getSong();
  32234. const auto returns = lynx::sessionmixer::returnsOf (song);
  32235. line ("returns: " + juce::String ((int) returns.size()) + ", return strips " + juce::String (mixer->returnColumnCount()));
  32236. check ("the set's two returns are Live return tracks (A Reverb, B Delay)",
  32237. returns.size() == 2 && lynx::sessionmixer::returnTitle (song, returns[0]) == "A Reverb" && lynx::sessionmixer::returnTitle (song, returns[1]) == "B Delay");
  32238. check ("two return strips beside the tracks", mixer->returnColumnCount() == 2);
  32239. check ("every track shows a Sends row per return (the sends at -inf)",
  32240. mixer->sendTargets() == returns && ! mixer->partBounds (0, Part::send, 1).isEmpty());
  32241. const auto retA = lynx::SessionMixerComponent::returnColumn (0);
  32242. check ("a return strip: Sends, volume, activator, Solo, no Arm",
  32243. ! mixer->partBounds (retA, Part::send, 1).isEmpty() && ! mixer->partBounds (retA, Part::activator).isEmpty()
  32244. && ! mixer->partBounds (retA, Part::solo).isEmpty() && mixer->partBounds (retA, Part::arm).isEmpty());
  32245. check ("the Main strip: a Pre / Post toggle per return", ! mixer->partBounds (-2, Part::post, 0).isEmpty() && ! mixer->partBounds (-2, Part::post, 1).isEmpty());
  32246. line ("Post A " + mixer->partBounds (-2, Part::post, 0).toString() + ", Post B " + mixer->partBounds (-2, Part::post, 1).toString()
  32247. + ", return A activator " + mixer->partBounds (retA, Part::activator).toString());
  32248. write (ui, "window");
  32249. area (*gridView, mixer->getBoundsInParent(), "mixer");
  32250. area (*gridView, { 0, 0, gridView->getWidth(), 240 }, "grid-top");
  32251. area (*gridView, mixer->getBoundsInParent().withTrimmedLeft (mixer->getWidth() - 260), "mixer-returns");
  32252. // a return's send to the other one, switched on; Pre on return B
  32253. offline.editSong ([&returns] (lynx::Song& s) {
  32254. lynx::sessionmixer::setSendEnabled (s, returns[0], returns[1], true);
  32255. lynx::sessionmixer::setPre (s, returns[1], true);
  32256. });
  32257. settle();
  32258. area (*gridView, mixer->getBoundsInParent(), "mixer-sendon-pre");
  32259. area (*gridView, mixer->getBoundsInParent().withTrimmedLeft (mixer->getWidth() - 260), "mixer-returns-sendon-pre");
  32260. 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]));
  32261. saveMenus (juce::StringArray { "Return send" }, std::vector<juce::PopupMenu> { mixer->sendMenu ({ lynx::SessionMixerComponent::returnColumn (1), Part::send, 0 }) },
  32262. prefix + "-menu-send.png");
  32263. offline.editSong ([&returns] (lynx::Song& s) {
  32264. lynx::sessionmixer::setSendEnabled (s, returns[0], returns[1], false);
  32265. lynx::sessionmixer::setPre (s, returns[1], false);
  32266. });
  32267. // the crossfader section: track 1 on A, track 2 on B, the crossfader a little towards A
  32268. const auto i0 = lynx::sessionmixer::stripOf (song, 0).insert, i1 = lynx::sessionmixer::stripOf (song, 1).insert;
  32269. offline.editSong ([i0, i1] (lynx::Song& s) {
  32270. lynx::launcher::ensureGrid (s).mixerView.crossfader = true;
  32271. if (i0 > 0)
  32272. s.mixer[(std::size_t) i0].crossfade = lynx::CrossfadeAssign::a;
  32273. if (i1 > 0)
  32274. s.mixer[(std::size_t) i1].crossfade = lynx::CrossfadeAssign::b;
  32275. s.crossfader = -0.3f;
  32276. });
  32277. settle();
  32278. gridView->resized(); // (the menu item does this: the grid gives the mixer its new height)
  32279. settle();
  32280. check ("the Crossfader section: A / B on a track, the crossfader on Main",
  32281. ! mixer->partBounds (0, Part::xfadeA).isEmpty() && ! mixer->partBounds (0, Part::xfadeB).isEmpty() && ! mixer->partBounds (-2, Part::crossfader).isEmpty());
  32282. line ("A " + mixer->partBounds (0, Part::xfadeA).toString() + ", B " + mixer->partBounds (0, Part::xfadeB).toString() + ", crossfader "
  32283. + mixer->partBounds (-2, Part::crossfader).toString());
  32284. area (*gridView, mixer->getBoundsInParent(), "mixer-crossfader");
  32285. area (*gridView, mixer->getBoundsInParent().withTrimmedLeft (mixer->getWidth() - 260), "mixer-returns-crossfader");
  32286. saveMenus (juce::StringArray { "Crossfader" }, std::vector<juce::PopupMenu> { mixer->crossfaderMenu() }, prefix + "-menu-curve.png");
  32287. lynx::clipGridClassicLook() = true;
  32288. lynx::refreshClipGrid (*gridView);
  32289. ui.resized();
  32290. settle();
  32291. area (*gridView, mixer->getBoundsInParent(), "classic-mixer-crossfader");
  32292. write (ui, "classic-window");
  32293. lynx::clipGridClassicLook() = false;
  32294. lynx::refreshClipGrid (*gridView);
  32295. ui.resized();
  32296. settle();
  32297. // the map modes: a key on a slot, a scene, Scene Down, the crossfader's left position
  32298. using namespace lynx::remotemap;
  32299. offline.editSong ([] (lynx::Song& s) {
  32300. assignKey (s, Target::slot (0, 0), 'Q');
  32301. assignKey (s, Target::sceneLaunch (0), 'W');
  32302. assignKey (s, Target::of (lynx::RemoteAction::sceneDown), 'J');
  32303. assignKey (s, Target::of (lynx::RemoteAction::crossfaderLeft), 'Z');
  32304. });
  32305. for (const auto mode : { Mode::key, Mode::midi })
  32306. {
  32307. ui.setMapMode (mode);
  32308. settle();
  32309. if (auto* overlay = ui.mapOverlayForSnapshot())
  32310. {
  32311. overlay->refresh();
  32312. const auto& spots = overlay->spots();
  32313. 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; }); };
  32314. line (juce::String (mode == Mode::key ? "key" : "midi") + " map: " + juce::String ((int) spots.size()) + " spots; relative strip "
  32315. + juce::String (count (lynx::RemoteAction::sceneUp) + count (lynx::RemoteAction::sceneDown) + count (lynx::RemoteAction::launchSelectedScene)
  32316. + count (lynx::RemoteAction::cancelLaunch))
  32317. + ", per-track launch " + juce::String (count (lynx::RemoteAction::launchSelectedClip)) + ", crossfader positions "
  32318. + juce::String (count (lynx::RemoteAction::crossfaderLeft) + count (lynx::RemoteAction::crossfaderCentre) + count (lynx::RemoteAction::crossfaderRight)));
  32319. check (juce::String (mode == Mode::key ? "Key" : "MIDI") + " Map Mode: the relative strip and the crossfader's three positions are mappable",
  32320. count (lynx::RemoteAction::sceneUp) == 1 && count (lynx::RemoteAction::sceneDown) == 1 && count (lynx::RemoteAction::launchSelectedScene) == 1
  32321. && count (lynx::RemoteAction::cancelLaunch) == 1 && count (lynx::RemoteAction::launchSelectedClip) >= 4
  32322. && count (lynx::RemoteAction::crossfaderLeft) == 1 && count (lynx::RemoteAction::crossfaderRight) == 1);
  32323. }
  32324. write (ui, mode == Mode::key ? "keymap" : "midimap");
  32325. }
  32326. ui.setMapMode (Mode::off);
  32327. settle();
  32328. // grooves on clips: a groove of LYNX's bank on the first MIDI clip and on an audio clip; the Clip View's Commit
  32329. int midiTrack = -1, midiScene = -1, audioTrack = -1, audioScene = -1;
  32330. if (song.clipGrid)
  32331. for (const auto& c : song.clipGrid->clips)
  32332. {
  32333. const auto scene = c.gridSlot >= 0 && c.gridSlot < (int) song.clipGrid->slots.size() ? song.clipGrid->slots[(std::size_t) c.gridSlot].scene : -1;
  32334. if (c.kind == lynx::ClipKind::pattern && midiTrack < 0)
  32335. midiTrack = c.track, midiScene = scene;
  32336. if (c.kind == lynx::ClipKind::audio && audioTrack < 0)
  32337. audioTrack = c.track, audioScene = scene;
  32338. }
  32339. line ("MIDI clip " + juce::String (midiTrack) + "/" + juce::String (midiScene) + ", audio clip " + juce::String (audioTrack) + "/" + juce::String (audioScene));
  32340. std::uint32_t grooveId = 0;
  32341. offline.editSong ([&grooveId, midiTrack, midiScene, audioTrack, audioScene] (lynx::Song& s) {
  32342. auto g = lynx::groove::factoryBank().front().groove;
  32343. g.timing = 1.0f;
  32344. grooveId = lynx::groove::add (s.grooves, g);
  32345. lynx::groove::setClipGroove (s, midiTrack, midiScene, grooveId);
  32346. lynx::groove::setClipGroove (s, audioTrack, audioScene, grooveId);
  32347. });
  32348. settle();
  32349. if (auto* detail = ui.getDetailViewForSnapshot(); detail != nullptr && midiTrack >= 0 && audioTrack >= 0)
  32350. {
  32351. detail->showSelection (midiTrack, midiScene);
  32352. detail->setPage (lynx::DetailView::Page::clip);
  32353. settle();
  32354. write (*detail, "clip-midi-groove");
  32355. detail->showSelection (audioTrack, audioScene);
  32356. detail->setPage (lynx::DetailView::Page::clip);
  32357. settle();
  32358. write (*detail, "clip-audio-groove");
  32359. const auto* audio = lynx::launcher::clipAt (*song.clipGrid, audioTrack, audioScene);
  32360. const auto sample = audio != nullptr && audio->channel >= 0 ? offline.getSampleLibrary().load (juce::String::fromUTF8 (song.channels[(std::size_t) audio->channel].samplePath.c_str()))
  32361. : nullptr;
  32362. check ("the audio clip's file loads", sample != nullptr);
  32363. if (sample != nullptr && audio != nullptr)
  32364. {
  32365. const auto hits = lynx::grooveaudio::hitsOf (song, *audio, *sample);
  32366. {
  32367. const auto all = lynx::clipwarp::attacks (*sample);
  32368. const auto& sm = song.channels[(std::size_t) audio->channel].sampler;
  32369. line ("audio file: " + juce::String ((int) sample->frames()) + " frames at " + juce::String (sample->sampleRate) + " Hz, "
  32370. + juce::String ((int) all.size()) + " attacks (first " + juce::String (all.empty() ? -1.0 : all.front(), 3) + " s); clip offset "
  32371. + juce::String (audio->offset) + " length " + juce::String (audio->length) + " stretch " + juce::String (audio->stretch, 3)
  32372. + "; warp " + juce::String ((int) sm.warp.size()) + " markers, keepPitch " + juce::String ((int) sm.keepPitch)
  32373. + ", first content beat " + juce::String (all.empty() ? 0.0 : lynx::grooveaudio::contentBeat (sm, all.front(), song.bpm), 3));
  32374. }
  32375. const auto pool = song.grooves.grooves.size();
  32376. offline.editSong ([&] (lynx::Song& s) {
  32377. if (const auto* c = lynx::launcher::clipAt (*s.clipGrid, audioTrack, audioScene))
  32378. if (auto g = lynx::grooveaudio::extract (s, *c, *sample, lynx::GrooveBase::sixteenth, "Vocal groove"); ! g.points.empty())
  32379. lynx::groove::add (s.grooves, std::move (g));
  32380. });
  32381. line ("audio clip: " + juce::String ((int) hits.size()) + " attacks; pool " + juce::String ((int) pool) + " -> " + juce::String ((int) song.grooves.grooves.size()));
  32382. check ("Extract Groove from the audio clip adds a groove", song.grooves.grooves.size() == pool + 1);
  32383. int placed = -1;
  32384. offline.editSong ([&] (lynx::Song& s) { placed = lynx::grooveaudio::commit (s, audioTrack, audioScene, *sample); });
  32385. auto gridCopy = *song.clipGrid;
  32386. const auto* slot = lynx::launcher::settingsAt (gridCopy, audioTrack, audioScene);
  32387. line ("commit on audio: " + juce::String (placed) + " warp markers");
  32388. check ("Commit on the audio clip writes warp markers and sets its groove to None", placed > 0 && slot != nullptr && slot->groove == 0);
  32389. }
  32390. }
  32391. lynx::clipGridClassicLook() = classicBefore;
  32392. line ("done");
  32393. }
  32394. // LYNX --capfix190jjshot prefix project.flp set.als: round 190jj off screen (capture190ji's "Change in LYNX" lines) —
  32395. // the Simple capsule idle / playing / count-in / recording with the master meter, the pads at rest and pressed, the
  32396. // keys held in the track's colour, the drop lane's ghosts; Live's control bar idle / playing / recording / punch;
  32397. // FL's C-11 picker drop ghost with the drag image, the drop, and the picker's playing mark; prefix-checks.txt
  32398. void runCapfix190jjShot (const juce::String& prefix, const juce::String& project, const juce::String& set)
  32399. {
  32400. namespace st = lynx::simpletracks;
  32401. namespace sp = lynx::simplepads;
  32402. using Look = lynx::toolbarlayout::Look;
  32403. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32404. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true);
  32405. juce::String checks;
  32406. const auto flush = [&] { juce::File (lynx::shot::file (juce::File (prefix + "-checks.txt"))).replaceWithText (checks); };
  32407. const auto check = [&] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; flush(); };
  32408. const auto line = [&] (const juce::String& what) { checks << " " << what << "\n"; flush(); };
  32409. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  32410. const auto area = [&prefix] (juce::Component& c, juce::Rectangle<int> r, const juce::String& name) { saveArea (c, r, prefix + "-" + name + ".png"); };
  32411. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  32412. const auto w = juce::jlimit (800, 3840, size[0].getIntValue()), h = juce::jlimit (450, 2160, size[1].getIntValue());
  32413. // ---- A. Simple ----------------------------------------------------------------------------------------------------
  32414. {
  32415. lynx::AudioEngine offline (false);
  32416. lynx::MainComponent ui (offline, false);
  32417. ui.setSize (w, h);
  32418. const auto settle = [&] {
  32419. for (int k = 0; k < 3; ++k)
  32420. offline.dispatchPendingMessages();
  32421. };
  32422. ui.selectTabForSnapshot (2);
  32423. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  32424. settle();
  32425. auto* simple = ui.getSimpleWorkflowForSnapshot();
  32426. auto& playlist = ui.getPlaylistForSnapshot();
  32427. if (simple == nullptr)
  32428. {
  32429. check ("a Simple workflow", false);
  32430. return;
  32431. }
  32432. offline.setSong ([] {
  32433. lynx::Song s;
  32434. s.mixer = lynx::Song::defaultMixer();
  32435. s.bpm = 120.0;
  32436. return s;
  32437. }());
  32438. settle();
  32439. simple->hideChooser();
  32440. const auto dir = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-190jj");
  32441. dir.deleteRecursively();
  32442. dir.createDirectory();
  32443. const auto writeWav = [] (const juce::File& wav, int frames, const std::function<float (int)>& f) {
  32444. wav.getParentDirectory().createDirectory();
  32445. juce::AudioBuffer<float> audio (1, frames);
  32446. for (int i = 0; i < frames; ++i)
  32447. audio.setSample (0, i, f (i));
  32448. juce::WavAudioFormat format;
  32449. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  32450. if (auto* wr = format.createWriterFor (out.get(), 48000.0, 1, 16, {}, 0))
  32451. {
  32452. out.release();
  32453. std::unique_ptr<juce::AudioFormatWriter> writer (wr);
  32454. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  32455. }
  32456. return wav;
  32457. };
  32458. const auto pi = juce::MathConstants<double>::pi;
  32459. juce::Random rnd (190);
  32460. // a 4-bar loop at 120 bpm (8 s), as BandLab's "TRAP_160_Piano1_Bm_4bars" is four bars
  32461. const auto loop = writeWav (dir.getChildFile ("TRAP_120_Piano1_Bm_4bars.wav"), 384000, [pi] (int i) {
  32462. const auto t = i / 48000.0, inBeat = std::fmod (t, 0.5);
  32463. return (float) (0.6 * std::exp (-inBeat * 6.0) * std::sin (2.0 * pi * 247.0 * t));
  32464. });
  32465. std::vector<juce::File> padSounds;
  32466. const char* padNames[] { "Kick", "Snare", "Hat", "Clap", "Stab", "Vox", "Perc", "Bass" };
  32467. for (int k = 0; k < 8; ++k)
  32468. padSounds.push_back (writeWav (dir.getChildFile (juce::String ("pads/") + padNames[k] + ".wav"), 12000 + 3000 * k, [&rnd, k] (int i) {
  32469. return (float) ((rnd.nextFloat() * 2.0f - 1.0f) * 0.6f * std::exp (-i / (600.0f + 500.0f * (float) k)));
  32470. }));
  32471. int vocal = -1, keys = -1;
  32472. offline.editSong ([&] (lynx::Song& s) {
  32473. st::Request q;
  32474. q.kind = st::Kind::audio;
  32475. q.name = "Piano loop";
  32476. q.audioFile = loop.getFullPathName().toStdString();
  32477. q.audioLength = 16 * lynx::ppq;
  32478. q.audioBeats = 16.0f;
  32479. vocal = st::addTrack (s, q).track;
  32480. q = {};
  32481. q.kind = st::Kind::instrument;
  32482. q.name = "Instrument";
  32483. lynx::ChannelDef synth;
  32484. synth.instrument = lynx::InstrumentKind::synth;
  32485. q.channel = synth;
  32486. keys = st::addTrack (s, q).track;
  32487. });
  32488. settle();
  32489. check ("the Sampler (pads) track was added", simple->addPads());
  32490. settle();
  32491. const auto& song = offline.getSong();
  32492. int pads = -1;
  32493. for (int t = 0; t < (int) song.playlistTracks.size() && pads < 0; ++t)
  32494. if (st::kindOf (song, t) == st::Kind::pads)
  32495. pads = t;
  32496. simple->hideChooser();
  32497. playlist.selectTrack (keys);
  32498. settle();
  32499. // 1. the transport capsule (+ tempo, key, master) in its four states
  32500. const auto bar = [&ui] {
  32501. juce::Rectangle<int> r;
  32502. for (const auto* name : { "play", "stop", "record", "position", "metronome", "tempo", "signature", "key", "masterVolume", "masterPitch" })
  32503. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible())
  32504. r = r.isEmpty() ? c->getBounds() : r.getUnion (c->getBounds());
  32505. return r.expanded (8, 6);
  32506. };
  32507. auto& transport = offline.getTransport();
  32508. auto* tempo = ui.toolbarPartForSnapshot ("tempo");
  32509. auto* stopButton = dynamic_cast<lynx::IconButton*> (ui.toolbarPartForSnapshot ("stop"));
  32510. auto* playButton = dynamic_cast<lynx::IconButton*> (ui.toolbarPartForSnapshot ("play"));
  32511. auto* master = dynamic_cast<lynx::toolbar::MasterKnob*> (ui.toolbarPartForSnapshot ("masterVolume"));
  32512. ui.transportTickForSnapshot();
  32513. area (ui, bar(), "simple-bar-idle");
  32514. check ("idle: Play shows Play, the second button Back-to-start", playButton != nullptr && playButton->getIcon() == lynx::Icon::play
  32515. && stopButton != nullptr && stopButton->getIcon() == lynx::Icon::toStart);
  32516. transport.positionTicks.store ((double) (2 * song.barTicks()) + 0.3 * lynx::ppq);
  32517. transport.playing.store (true);
  32518. if (master != nullptr)
  32519. master->meterForSnapshot ({ 0.62f, 0.57f });
  32520. ui.transportTickForSnapshot();
  32521. area (ui, bar(), "simple-bar-playing");
  32522. check ("playing: Pause and Stop (BandLab)", playButton != nullptr && playButton->getIcon() == lynx::Icon::pause && stopButton->getIcon() == lynx::Icon::stop);
  32523. transport.playing.store (false);
  32524. transport.positionTicks.store (0.0);
  32525. offline.setRecording (true);
  32526. transport.countIn.store (0.85 * (double) song.barTicks()); // (-1.7 s of a 2 s bar at 120 bpm)
  32527. ui.transportTickForSnapshot();
  32528. area (ui, bar(), "simple-bar-countin");
  32529. check ("count-in: tempo greyed, Pause shown", tempo != nullptr && ! tempo->isEnabled() && playButton->getIcon() == lynx::Icon::pause);
  32530. transport.countIn.store (0.0);
  32531. transport.playing.store (true);
  32532. transport.positionTicks.store (0.45 * (double) song.barTicks());
  32533. ui.transportTickForSnapshot();
  32534. area (ui, bar(), "simple-bar-recording");
  32535. line ("record start kept: " + juce::String (ui.simpleRecordStartForCheck(), 1) + " ticks");
  32536. check ("recording: the take's start is kept (the count-in's target, 0)", ui.simpleRecordStartForCheck() == 0.0);
  32537. auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record"));
  32538. const auto litA = rec != nullptr && rec->getToggleState();
  32539. juce::Thread::sleep (260);
  32540. ui.transportTickForSnapshot();
  32541. const auto litB = rec != nullptr && rec->getToggleState();
  32542. check ("recording: Record steady (lit 260 ms apart, no blink in Simple)", litA && litB);
  32543. transport.seekRequest.store (-1.0);
  32544. ui.stopForCheck();
  32545. line ("seek after Stop: " + juce::String (transport.seekRequest.load(), 1));
  32546. check ("Stop after a take goes back to where it started", transport.seekRequest.load() == 0.0);
  32547. offline.setRecording (false);
  32548. transport.playing.store (false);
  32549. ui.transportTickForSnapshot();
  32550. check ("stopped: tempo enabled again", tempo != nullptr && tempo->isEnabled());
  32551. if (master != nullptr)
  32552. {
  32553. area (ui, master->getBounds().expanded (6, 4), "simple-master-idle");
  32554. master->meterForSnapshot ({ 0.62f, 0.57f });
  32555. area (ui, master->getBounds().expanded (6, 4), "simple-master-playing");
  32556. master->meterForSnapshot ({ 0.0f, 0.0f });
  32557. }
  32558. // 2. the dock: pads at rest and pressed, keys held
  32559. if (auto* dock = simple->dockForSnapshot(); dock != nullptr && pads >= 0)
  32560. {
  32561. simple->trackSelected (pads);
  32562. settle();
  32563. for (int p = 0; p < 8; ++p)
  32564. dock->padsLoadForCheck (p, padSounds[(std::size_t) p]);
  32565. offline.editSong ([pads] (lynx::Song& s) {
  32566. for (int p = 0; p < 8; ++p)
  32567. if (const auto c = sp::padChannel (s, pads, p); c >= 0)
  32568. s.channels[(std::size_t) c].simplePad.colour = (std::uint8_t) (p + 1);
  32569. });
  32570. dock->padsSelectForCheck (0);
  32571. dock->padsUpdateForCheck();
  32572. settle();
  32573. write (*dock, "dock-pads-rest");
  32574. dock->padsPressForSnapshot (3, 1.0f);
  32575. dock->padsPressForSnapshot (5, 0.5f);
  32576. write (*dock, "dock-pads-pressed");
  32577. dock->padsPressForSnapshot (3, 0.0f);
  32578. dock->padsPressForSnapshot (5, 0.0f);
  32579. simple->trackSelected (keys);
  32580. settle();
  32581. dock->showKeyboard();
  32582. settle();
  32583. if (auto* kb = dock->keyboardForSnapshot())
  32584. {
  32585. lynx::keyboardPressForSnapshot (*kb);
  32586. write (*dock, "dock-keys-held");
  32587. }
  32588. }
  32589. // 3. the drop lane while the loop is dragged (the Browser's file drag)
  32590. simple->hideChooser();
  32591. playlist.selectTrack (vocal);
  32592. settle();
  32593. const auto lane = st::nextEmptyTrack (offline.getSong());
  32594. const juce::var drag (juce::String ("lynx-arquivo|") + loop.getFullPathName());
  32595. const auto x = (int) playlist.xOfTickForSnapshot (9.0 * (double) song.barTicks()) + 6;
  32596. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (lane).getCentreY() });
  32597. write (playlist, "simple-drop-lane");
  32598. check ("over the lane: a ghost, no reason", ! playlist.dropGhostAreaForCheck().isEmpty() && playlist.dropGhostReasonForCheck().isEmpty());
  32599. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (vocal).getCentreY() });
  32600. write (playlist, "simple-drop-audio-track");
  32601. check ("over an audio track: no reason", playlist.dropGhostReasonForCheck().isEmpty());
  32602. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (pads).getCentreY() });
  32603. write (playlist, "simple-drop-refused");
  32604. check ("over the Sampler track: red, with the reason", playlist.dropGhostReasonForCheck().isNotEmpty());
  32605. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (keys).getCentreY() });
  32606. check ("over an instrument track: red, with the reason", playlist.dropGhostReasonForCheck().isNotEmpty());
  32607. playlist.dragOverForSnapshot (drag, { x, playlist.trackRowForSnapshot (lane).getBottom() + 60 });
  32608. write (playlist, "simple-drop-below");
  32609. check ("below the lane: only the tag", playlist.dropGhostTagOnlyForCheck());
  32610. playlist.dragOverForSnapshot ({}, {});
  32611. check ("after the drag: nothing left to paint", playlist.dropGhostAreaForCheck().isEmpty());
  32612. const auto clipsBefore = offline.getSong().playlist.size();
  32613. playlist.filesDropped ({ loop.getFullPathName() }, x, playlist.trackRowForSnapshot (pads).getCentreY());
  32614. settle();
  32615. check ("a loop dropped on the Sampler track is refused", offline.getSong().playlist.size() == clipsBefore);
  32616. write (ui, "simple-window");
  32617. dir.deleteRecursively();
  32618. }
  32619. // ---- B. Clip-launch: Live's control bar ----------------------------------------------------------------------------
  32620. if (set.isNotEmpty())
  32621. {
  32622. lynx::AudioEngine offline (false);
  32623. lynx::MainComponent ui (offline, false);
  32624. ui.setSize (w, h);
  32625. ui.openFile (juce::File (set));
  32626. offline.dispatchPendingMessages();
  32627. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch, false);
  32628. offline.dispatchPendingMessages();
  32629. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  32630. offline.dispatchPendingMessages();
  32631. const auto centre = [&ui] {
  32632. juce::Rectangle<int> r;
  32633. for (const auto* name : { "backToArrangement", "position", "play", "stop", "record", "overdub", "capture", "sessionRecord", "punch" })
  32634. if (auto* c = ui.toolbarPartForSnapshot (name); c != nullptr && c->isVisible())
  32635. r = r.isEmpty() ? c->getBounds() : r.getUnion (c->getBounds());
  32636. return r.expanded (8, 8);
  32637. };
  32638. auto& transport = offline.getTransport();
  32639. ui.transportTickForSnapshot();
  32640. area (ui, centre(), "live-bar-idle");
  32641. transport.playing.store (true);
  32642. ui.transportTickForSnapshot();
  32643. area (ui, centre(), "live-bar-playing");
  32644. offline.setRecording (true);
  32645. ui.transportTickForSnapshot();
  32646. area (ui, centre(), "live-bar-recording");
  32647. auto* rec = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("record"));
  32648. const auto litA = rec != nullptr && rec->getToggleState();
  32649. juce::Thread::sleep (260);
  32650. ui.transportTickForSnapshot();
  32651. check ("Live look: Record steady while recording (no blink)", litA && rec->getToggleState());
  32652. if (auto* punch = dynamic_cast<juce::Button*> (ui.toolbarPartForSnapshot ("punch")))
  32653. {
  32654. punch->setToggleState (true, juce::dontSendNotification);
  32655. area (ui, centre(), "live-bar-punch-lit");
  32656. punch->setToggleState (false, juce::dontSendNotification);
  32657. }
  32658. offline.setRecording (false);
  32659. transport.playing.store (false);
  32660. ui.transportTickForSnapshot();
  32661. }
  32662. // ---- C. Pattern (FL): C-11 drop ghost + drag image, the drop, the picker's playing mark ----------------------------------
  32663. if (project.isNotEmpty())
  32664. {
  32665. lynx::layoutstyle::setCurrent (lynx::layoutstyle::Style::pattern); // (the style is global: A and B changed it)
  32666. lynx::AudioEngine offline (false);
  32667. lynx::MainComponent ui (offline, false);
  32668. ui.setSize (w, h);
  32669. ui.openFile (juce::File (project));
  32670. offline.dispatchPendingMessages();
  32671. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern, false);
  32672. ui.selectTabForSnapshot (2);
  32673. offline.dispatchPendingMessages();
  32674. auto& playlist = ui.getPlaylistForSnapshot();
  32675. auto& picker = ui.getPickerForSnapshot();
  32676. const auto& song = offline.getSong();
  32677. write (playlist, "warmup");
  32678. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  32679. offline.dispatchPendingMessages();
  32680. juce::File (lynx::shot::file (juce::File (prefix + "-warmup.png"))).deleteFile();
  32681. int synthBass = 0;
  32682. for (int p = 0; p < (int) song.patterns.size(); ++p)
  32683. if (juce::String::fromUTF8 (song.patterns[(std::size_t) p].name.c_str()).equalsIgnoreCase ("Synth Bass"))
  32684. {
  32685. synthBass = p;
  32686. break;
  32687. }
  32688. // an empty track low in the view (FL's capture: Track 43 / 47, past the song's tracks)
  32689. // (an unnamed track past the song's own, as FL's Track 43 / 47)
  32690. const auto target = (int) song.playlistTracks.size() + 2;
  32691. for (int first = juce::jmax (0, target - 30); first <= target; ++first) // (the row in the lower part of the view)
  32692. {
  32693. playlist.setViewForSnapshot (15.6, 0, first);
  32694. if (playlist.trackRowForSnapshot (target).getBottom() < playlist.getHeight() - 40)
  32695. break;
  32696. }
  32697. offline.dispatchPendingMessages();
  32698. const auto row = playlist.trackRowForSnapshot (target);
  32699. const auto mouse = juce::Point<int> ((int) playlist.xOfTickForSnapshot (9.1 * (double) song.barTicks()), row.getCentreY());
  32700. const juce::var drag (lynx::PlaylistComponent::pickerDragDescription (lynx::ClipKind::pattern, { synthBass }));
  32701. playlist.dragOverForSnapshot (drag, mouse);
  32702. {
  32703. // the window as the drag shows it: the ghost in the row, the entry's picture below right of the mouse
  32704. auto image = lynx::shot::snapshot (ui);
  32705. const auto scale = (float) image.getWidth() / (float) juce::jmax (1, ui.getWidth());
  32706. const auto listRow = picker.listRowOfPattern (synthBass);
  32707. if (listRow >= 0)
  32708. {
  32709. const auto entry = picker.dragImageOf (listRow);
  32710. const auto at = ui.getLocalPoint (&playlist, mouse) + lynx::PatternPicker::dragImageOffset();
  32711. juce::Graphics g (image);
  32712. g.addTransform (juce::AffineTransform::scale (scale));
  32713. g.drawImageAt (entry, at.x, at.y);
  32714. g.setColour (juce::Colours::white);
  32715. juce::Path arrow; // (the mouse pointer, so the pair reads as FL's film still)
  32716. arrow.startNewSubPath ((float) ui.getLocalPoint (&playlist, mouse).x, (float) ui.getLocalPoint (&playlist, mouse).y);
  32717. arrow.lineTo (arrow.getCurrentPosition() + juce::Point<float> (0.0f, 16.0f));
  32718. arrow.lineTo (arrow.getCurrentPosition() + juce::Point<float> (4.0f, -4.0f));
  32719. arrow.lineTo (arrow.getCurrentPosition() + juce::Point<float> (7.0f, 0.0f));
  32720. arrow.closeSubPath();
  32721. g.fillPath (arrow);
  32722. g.setColour (juce::Colours::black);
  32723. g.strokePath (arrow, juce::PathStrokeType (1.0f));
  32724. }
  32725. savePng (image, prefix + "-fl-c11-drag.png");
  32726. }
  32727. const auto ghost = playlist.dropGhostAreaForCheck();
  32728. line ("ghost " + ghost.toString() + ", row " + row.toString() + ", mouse " + mouse.toString());
  32729. check ("C-11: the ghost lies in the row under the mouse", ! ghost.isEmpty() && ghost.getY() >= row.getY() - 2 && ghost.getBottom() <= row.getBottom() + 2);
  32730. const auto first = (int) offline.getSong().playlist.size();
  32731. playlist.dropForSnapshot (drag, mouse);
  32732. offline.dispatchPendingMessages();
  32733. const auto& dropped = offline.getSong(); // (an edit publishes a new Song: read it again; the Playlist sorts its clips)
  32734. int onRow = 0, at = -1;
  32735. for (int c = 0; c < (int) dropped.playlist.size(); ++c)
  32736. if (dropped.playlist[(std::size_t) c].track == target)
  32737. {
  32738. ++onRow;
  32739. at = c;
  32740. }
  32741. line ("clips " + juce::String (first) + " -> " + juce::String ((int) dropped.playlist.size()) + ", on the row " + juce::String (onRow));
  32742. check ("C-11: the drop places one clip on the row", (int) dropped.playlist.size() == first + 1 && onRow == 1);
  32743. check ("C-11: the dropped clip is selected", at >= 0 && playlist.isClipSelectedForCheck (at));
  32744. check ("C-11: nothing of the ghost is left", playlist.dropGhostAreaForCheck().isEmpty());
  32745. write (ui, "fl-c11-dropped");
  32746. // the picker's playing mark: Synth Bass plays in the first bars; then another pattern selected
  32747. offline.getTransport().positionTicks.store (0.5 * (double) offline.getSong().barTicks());
  32748. offline.getTransport().playing.store (true);
  32749. offline.getTransport().songMode = true;
  32750. playlist.frameStepForSnapshot();
  32751. playlist.frameStepForSnapshot();
  32752. write (picker, "fl-picker-playing");
  32753. line ("playing patterns: " + juce::String ((int) picker.playingForCheck().size()));
  32754. const auto other = juce::jmin ((int) offline.getSong().patterns.size() - 1, 7);
  32755. offline.editSong ([other] (lynx::Song& s) { s.currentPattern = other; }, false);
  32756. offline.dispatchPendingMessages();
  32757. playlist.frameStepForSnapshot();
  32758. write (picker, "fl-picker-playing-other-selected");
  32759. check ("DC-3: the mark follows what plays, not the selection",
  32760. std::find (picker.playingForCheck().begin(), picker.playingForCheck().end(), other) == picker.playingForCheck().end()
  32761. || std::count_if (offline.getSong().playlist.begin(), offline.getSong().playlist.end(), [&] (const lynx::Clip& c) {
  32762. return c.kind == lynx::ClipKind::pattern && c.pattern == other && (double) c.start <= 0.5 * (double) offline.getSong().barTicks()
  32763. && (double) c.end() > 0.5 * (double) offline.getSong().barTicks();
  32764. }) > 0);
  32765. offline.getTransport().playing.store (false);
  32766. playlist.frameStepForSnapshot();
  32767. write (picker, "fl-picker-stopped");
  32768. check ("DC-3: no mark once stopped", picker.playingForCheck().empty());
  32769. }
  32770. line ("done");
  32771. }
  32772. void runDetails190imShot (const juce::String& prefix, const juce::String& project, const juce::String& set)
  32773. {
  32774. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  32775. const juce::ScopedValueSetter<bool> shown (lynx::ui::showingForShots(), true); // (the live frame steps run off-screen)
  32776. juce::String checks;
  32777. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  32778. const auto line = [&checks] (const juce::String& what) { checks << " " << what << "\n"; };
  32779. const auto write = [&prefix] (juce::Component& c, const juce::String& name) { savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png"); };
  32780. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  32781. {
  32782. // ---- Pattern layout, the FL demo
  32783. lynx::AudioEngine offline (false);
  32784. lynx::MainComponent ui (offline, false);
  32785. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  32786. if (project.isNotEmpty())
  32787. ui.openFile (juce::File (project));
  32788. offline.dispatchPendingMessages();
  32789. ui.selectTabForSnapshot (2);
  32790. auto& playlist = ui.getPlaylistForSnapshot();
  32791. offline.dispatchPendingMessages();
  32792. const auto settle = [&] {
  32793. write (playlist, "warmup");
  32794. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  32795. offline.dispatchPendingMessages();
  32796. juce::File (prefix + "-warmup.png").deleteFile();
  32797. };
  32798. const auto& song = offline.getSong();
  32799. offline.editSong ([] (lynx::Song& s) { for (auto& t : s.playlistTracks) t.height = 50; }, false);
  32800. offline.dispatchPendingMessages();
  32801. const auto toolbar = ui.getToolbarBoundsForSnapshot();
  32802. // R1: the automation clip with the most points in view, its second point dragged, its first segment bent
  32803. int autoClip = -1;
  32804. for (int c = 0; c < (int) song.playlist.size(); ++c)
  32805. if (const auto& clip = song.playlist[(std::size_t) c]; clip.kind == lynx::ClipKind::automation && clip.automation >= 0
  32806. && clip.automation < (int) song.automations.size() && song.automations[(std::size_t) clip.automation].points.size() >= 3
  32807. && (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()))
  32808. autoClip = c;
  32809. check ("R1: an automation clip with points in the project", autoClip >= 0);
  32810. if (autoClip >= 0)
  32811. {
  32812. const auto& clip = song.playlist[(std::size_t) autoClip];
  32813. const auto bar = (int) (clip.start / song.barTicks());
  32814. playlist.setViewForSnapshot (39.75, juce::jmax (0, bar - 2), juce::jmax (0, clip.track - 3));
  32815. settle();
  32816. const auto point = playlist.dragHintForSnapshot (autoClip, 1, false);
  32817. line ("point drag hint: " + point.text + " | " + point.value);
  32818. check ("R1: a dragged automation-clip point shows its value (DE-117)", point.value.isNotEmpty());
  32819. ui.setHintForSnapshot (point);
  32820. saveArea (ui, toolbar, prefix + "-r1-hint-point.png");
  32821. write (ui, "r1-window-point");
  32822. int bent = 0; // (a segment that is bent, when the clip has one)
  32823. const auto& points = song.automations[(std::size_t) clip.automation].points;
  32824. for (int k = 0; k + 1 < (int) points.size(); ++k)
  32825. if (points[(std::size_t) k].tension != 0.0f)
  32826. {
  32827. bent = k;
  32828. break;
  32829. }
  32830. const auto tension = playlist.dragHintForSnapshot (autoClip, bent, true);
  32831. line ("tension drag hint: " + tension.text + " | " + tension.value);
  32832. check ("R1: a bent segment shows its tension (DE-118)", tension.value.startsWith (lynx::tr ("Tension: {0}", { "" }).upToFirstOccurrenceOf (" ", false, false).trimEnd()));
  32833. ui.setHintForSnapshot (tension);
  32834. saveArea (ui, toolbar, prefix + "-r1-hint-tension.png");
  32835. const auto body = playlist.curveBodyForSnapshot (autoClip);
  32836. const auto hoverX = juce::jlimit (playlist.headerWidthForSnapshot() + 20, playlist.getWidth() - 40, (int) body.getX() + 80);
  32837. const auto hover = playlist.hintAt ({ hoverX, (int) body.getCentreY() });
  32838. line ("hover hint: " + hover.text + " | " + hover.value);
  32839. check ("R1: hovering the curve shows the value at the mouse (DE-119)", hover.value.contains (" "));
  32840. ui.setHintForSnapshot (hover);
  32841. saveArea (ui, toolbar, prefix + "-r1-hint-hover.png");
  32842. }
  32843. // R5: playing at bar 33 (FL's fl-playing.png), the meters fed so the activity strips show their steps
  32844. playlist.setViewForSnapshot (39.75, 20, 24);
  32845. settle();
  32846. offline.getTransport().positionTicks.store ((double) (32 * song.barTicks()));
  32847. offline.getTransport().playing.store (true);
  32848. const auto feed = [&offline] {
  32849. const float levels[] { 1.0f, 0.3f, 0.08f, 0.02f };
  32850. for (int k = 1; k < lynx::maxMixerTracks; ++k)
  32851. offline.getMeters().accumulate (k, levels[k % 4], levels[k % 4]);
  32852. };
  32853. feed();
  32854. playlist.frameStepForSnapshot();
  32855. feed();
  32856. playlist.frameStepForSnapshot();
  32857. write (ui, "r5-playing");
  32858. write (ui.getPickerForSnapshot(), "r5-picker-playing");
  32859. const auto px = (int) playlist.xOfTickForSnapshot (32.0 * (double) song.barTicks());
  32860. saveArea (playlist, { px - 40, lynx::PlaylistComponent::headerHeight, 60, 120 }, prefix + "-r5-playhead.png");
  32861. saveArea (playlist, { 0, lynx::PlaylistComponent::toolbarHeight, playlist.getWidth(), lynx::PlaylistComponent::overviewHeight }, prefix + "-r5-overview.png");
  32862. saveArea (playlist, { 0, lynx::PlaylistComponent::headerHeight, playlist.headerWidthForSnapshot() + 4, playlist.getHeight() - lynx::PlaylistComponent::headerHeight }, prefix + "-r5-headers.png");
  32863. lynx::ui::motion::enabled() = false;
  32864. playlist.frameStepForSnapshot();
  32865. saveArea (playlist, { px - 40, lynx::PlaylistComponent::headerHeight, 60, 120 }, prefix + "-r5-playhead-noanim.png");
  32866. lynx::ui::motion::enabled() = true;
  32867. playlist.frameStepForSnapshot();
  32868. // a drop preview: two patterns dragged from the Picker (issue #177's description) over track 4, bar 36
  32869. const auto row = playlist.trackRowForSnapshot (27);
  32870. playlist.dragOverForSnapshot (juce::var ("lynx-picker|0|0,1"), { (int) playlist.xOfTickForSnapshot (35.6 * (double) song.barTicks()), row.getCentreY() });
  32871. write (ui, "r5-drop-preview");
  32872. playlist.dragOverForSnapshot ({}, {});
  32873. offline.getTransport().playing.store (false);
  32874. playlist.frameStepForSnapshot();
  32875. write (ui, "r5-stopped");
  32876. write (ui.getPickerForSnapshot(), "r5-picker-stopped");
  32877. saveArea (playlist, { 0, lynx::PlaylistComponent::toolbarHeight, playlist.getWidth(), lynx::PlaylistComponent::overviewHeight }, prefix + "-r5-overview-stopped.png");
  32878. // R15: a scroll by hand while playing — Pattern layout: Follow goes on (off by default); the option on: it pauses
  32879. auto& globals = lynx::EditorGlobals::get();
  32880. const auto scrollWhilePlaying = [&] {
  32881. offline.getTransport().playing.store (true);
  32882. playlist.frameStepForSnapshot();
  32883. playlist.setScrollTickForSnapshot (playlist.scrollTicksForSnapshot() + 4.0 * (double) song.barTicks());
  32884. playlist.frameStepForSnapshot();
  32885. const auto paused = playlist.followPausedForSnapshot();
  32886. offline.getTransport().playing.store (false);
  32887. playlist.frameStepForSnapshot();
  32888. return paused;
  32889. };
  32890. check ("R15: Pattern layout (option off by default): no pause", ! globals.followPausing() && ! scrollWhilePlaying());
  32891. globals.followPausesOnEdit = 1;
  32892. check ("R15: option on: a scroll while playing pauses Follow", scrollWhilePlaying());
  32893. check ("R15: a stop lifts the pause", ! playlist.followPausedForSnapshot());
  32894. globals.followPausesOnEdit = -1;
  32895. }
  32896. {
  32897. // ---- R11: the Sampler's handles (a 1 s tone, loop points on)
  32898. lynx::AudioEngine engine (false);
  32899. const auto tone = juce::File (prefix).getParentDirectory().getChildFile ("details190im-tone.wav");
  32900. {
  32901. juce::AudioBuffer<float> buffer (1, 44100);
  32902. for (int i = 0; i < buffer.getNumSamples(); ++i)
  32903. buffer.setSample (0, i, (float) (0.6 * std::sin (juce::MathConstants<double>::twoPi * 110.0 * i / 44100.0) * (1.0 - i / 44100.0)));
  32904. tone.deleteFile();
  32905. juce::WavAudioFormat wav;
  32906. if (auto out = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (tone.createOutputStream().release(), 44100.0, 1, 16, {}, 0)))
  32907. out->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  32908. }
  32909. engine.editSong ([&] (lynx::Song& s) {
  32910. if (s.channels.empty())
  32911. s.channels.resize (1);
  32912. lynx::audioclips::loadSampleInto (s.channels[0], tone.getFullPathName().toStdString(), "Tone");
  32913. });
  32914. const auto sampler = [&engine] { return engine.getSong().channels[0].sampler; };
  32915. auto frame = lynx::makeChannelFrame (engine, 0, 0);
  32916. frame->setSize (frame->getWidth() > 0 ? frame->getWidth() : 700, frame->getHeight() > 0 ? frame->getHeight() : 720);
  32917. frame->createComponentSnapshot (frame->getLocalBounds());
  32918. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (8000);
  32919. auto& f = *frame;
  32920. lynx::samplerPageTurn (f, "useLoops", 1.0);
  32921. lynx::samplerPageTurn (f, "loopStart", 11025.0);
  32922. lynx::samplerPageTurn (f, "loopEnd", 22050.0);
  32923. lynx::samplerPageTurn (f, "smpStart", 0.0);
  32924. savePng (f.createComponentSnapshot (f.getLocalBounds()), prefix + "-r11-sampler-before.png");
  32925. for (const auto* h : { "Start", "LoopStart", "LoopEnd" })
  32926. line (juce::String ("press on the drawn ") + h + " handle takes: " + lynx::samplerPageQuery (f, juce::String ("handleAt") + h));
  32927. check ("R11: a press on the loop start line takes the loop start", lynx::samplerPageQuery (f, "handleAtLoopStart") == "loopStart");
  32928. check ("R11: a press on the loop end line takes the loop end", lynx::samplerPageQuery (f, "handleAtLoopEnd") == "loopEnd");
  32929. check ("R11: a press on the Start marker takes the start", lynx::samplerPageQuery (f, "handleAtStart") == "start");
  32930. lynx::samplerPageTurn (f, "dragLoopEnd", 0.75);
  32931. check ("R11: the loop end dragged to 3/4", std::abs ((double) sampler().loopEnd - 0.75 * 44099.0) < 2.0);
  32932. lynx::samplerPageTurn (f, "dragLoopStart", 0.375, true);
  32933. check ("R11: Shift drags the whole loop", sampler().loopStart > 16000 && sampler().loopEnd - sampler().loopStart > 22000);
  32934. line ("loop after the drags: " + juce::String (sampler().loopStart) + " - " + juce::String (sampler().loopEnd));
  32935. lynx::samplerPageTurn (f, "dragStart", 0.2);
  32936. check ("R11: the Start marker dragged to 20 %", std::abs (sampler().startOffset - 0.2f) < 0.01f);
  32937. savePng (f.createComponentSnapshot (f.getLocalBounds()), prefix + "-r11-sampler-after.png");
  32938. tone.deleteFile();
  32939. }
  32940. if (set.isNotEmpty())
  32941. {
  32942. // ---- Clip-launch layout, the Live set
  32943. lynx::AudioEngine offline (false);
  32944. lynx::MainComponent ui (offline, false);
  32945. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  32946. ui.setVisible (true);
  32947. ui.selectTabForSnapshot (2);
  32948. ui.setClipLaunchWorkflow (true);
  32949. offline.dispatchPendingMessages();
  32950. ui.openFile (juce::File (set));
  32951. offline.dispatchPendingMessages();
  32952. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  32953. offline.dispatchPendingMessages();
  32954. ui.resized();
  32955. auto* gridView = ui.getClipGridForSnapshot();
  32956. auto* runtime = offline.launcherStateForSnapshot();
  32957. const auto& song = offline.getSong();
  32958. check ("grid and launcher", gridView != nullptr && runtime != nullptr && song.clipGrid.has_value());
  32959. if (gridView == nullptr || runtime == nullptr || ! song.clipGrid.has_value())
  32960. {
  32961. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  32962. return;
  32963. }
  32964. auto& grid = *gridView;
  32965. gridView->resized();
  32966. const auto firstClip = [&song] (int track, lynx::ClipKind kind) {
  32967. for (int r = 0; r < 64; ++r)
  32968. if (const auto* c = lynx::launcher::clipAt (*song.clipGrid, track, r); c != nullptr && c->kind == kind)
  32969. return r;
  32970. return -1;
  32971. };
  32972. const auto bigCrop = [&] (const juce::String& name, juce::Rectangle<int> area) { saveArea (grid, area, prefix + "-" + name + ".png"); };
  32973. // R6: track 0 plays a one-shot (Loop off), track 1 loops in its 2nd pass, track 2's clip has a follow action
  32974. int rows[3] { -1, -1, -1 };
  32975. for (int t = 0; t < 3; ++t)
  32976. for (const auto kind : { lynx::ClipKind::audio, lynx::ClipKind::pattern })
  32977. if (rows[t] < 0)
  32978. rows[t] = firstClip (t, kind);
  32979. offline.editSong ([&rows] (lynx::Song& s) {
  32980. if (rows[0] >= 0)
  32981. lynx::launcher::settingsAt (*s.clipGrid, 0, rows[0])->loop = false;
  32982. if (rows[2] >= 0)
  32983. {
  32984. auto& f = lynx::launcher::settingsAt (*s.clipGrid, 2, rows[2])->follow;
  32985. f.enabled = true;
  32986. f.a = lynx::FollowKind::next;
  32987. }
  32988. }, false);
  32989. offline.dispatchPendingMessages();
  32990. runtime->running.store (true);
  32991. for (int t = 0; t < 2; ++t)
  32992. if (rows[t] >= 0)
  32993. {
  32994. const auto length = (double) lynx::launcher::clipAt (*song.clipGrid, t, rows[t])->length;
  32995. runtime->tracks[(std::size_t) t].playing.store (rows[t]);
  32996. runtime->tracks[(std::size_t) t].progress.store (0.4f);
  32997. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  32998. runtime->clockNow.store (length * 1.4);
  32999. }
  33000. lynx::tickClipGridForSnapshot (grid);
  33001. grid.repaint();
  33002. write (grid, "r6-grid-playing");
  33003. bigCrop ("r6-status-oneshot", lynx::clipGridCellForSnapshot (grid, 1, 0, 0).getUnion (lynx::clipGridCellForSnapshot (grid, 1, 1, 0)));
  33004. if (rows[2] >= 0)
  33005. {
  33006. const auto cell = lynx::clipGridCellForSnapshot (grid, 0, 2, rows[2]);
  33007. bigCrop ("r6-follow-stripes", cell);
  33008. }
  33009. // the queued scene's pulse, both phases, then the next scene selected
  33010. const auto scene = juce::jmax (0, rows[1]);
  33011. lynx::setClipGridBlinkPhaseForSnapshot (1);
  33012. lynx::launchClipGridSceneForSnapshot (grid, scene);
  33013. grid.repaint();
  33014. bigCrop ("r6-scene-queued-lit", lynx::clipGridCellForSnapshot (grid, 2, 0, scene));
  33015. lynx::setClipGridBlinkPhaseForSnapshot (0);
  33016. grid.repaint();
  33017. bigCrop ("r6-scene-queued-dark", lynx::clipGridCellForSnapshot (grid, 2, 0, scene));
  33018. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  33019. const auto [selected, sceneSelected] = lynx::clipGridSceneSelectionForSnapshot (grid);
  33020. 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);
  33021. write (grid, "r6-grid-scene-launched");
  33022. // the hints of each part
  33023. const auto hintAt = [&] (const juce::String& what, juce::Point<int> p) {
  33024. const auto [text, value] = lynx::clipGridHintForSnapshot (grid, p);
  33025. line ("hint " + what + ": " + text + " | " + value);
  33026. return text;
  33027. };
  33028. const auto slot = lynx::clipGridCellForSnapshot (grid, 0, 1, juce::jmax (0, rows[1]));
  33029. const auto launchHint = hintAt ("clip launch button", { slot.getX() + 7, slot.getCentreY() });
  33030. hintAt ("clip", { slot.getCentreX(), slot.getCentreY() });
  33031. hintAt ("stop button", { lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getX() + 7, lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getCentreY() });
  33032. hintAt ("status", { lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getCentreX(), lynx::clipGridCellForSnapshot (grid, 1, 1, 0).getCentreY() });
  33033. const auto sceneCell = lynx::clipGridCellForSnapshot (grid, 2, 0, 0);
  33034. hintAt ("scene launch button", { sceneCell.getX() + 6, sceneCell.getCentreY() });
  33035. hintAt ("scene", { sceneCell.getCentreX(), sceneCell.getCentreY() });
  33036. check ("R6: the grid's parts have hints (DL-21)", launchHint.isNotEmpty());
  33037. ui.setHintForSnapshot ({ launchHint, {}, false, false });
  33038. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-r6-hint-launch.png");
  33039. // R12: 0 on the selected clip deactivates it (greyed), again activates it; the scene column's font
  33040. lynx::selectClipGridSlotForSnapshot (grid, 1, juce::jmax (0, rows[1]));
  33041. grid.grabKeyboardFocus();
  33042. 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; };
  33043. check ("R12: 0 is taken by the grid", lynx::clipGridKeyForSnapshot (grid, juce::KeyPress ('0')));
  33044. offline.dispatchPendingMessages();
  33045. check ("R12: 0 deactivates the selected clip", ! activeNow());
  33046. for (auto& v : runtime->tracks)
  33047. v.playing.store (-1);
  33048. grid.repaint();
  33049. write (grid, "r12-clip-deactivated");
  33050. bigCrop ("r12-clip-deactivated-cell", slot);
  33051. lynx::clipGridKeyForSnapshot (grid, juce::KeyPress ('0'));
  33052. offline.dispatchPendingMessages();
  33053. check ("R12: 0 again activates it", activeNow());
  33054. 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))));
  33055. // R13: the Clip View of a launched MIDI clip: the Piano roll's playhead at the clip's position
  33056. int midiTrack = -1, midiRow = -1;
  33057. for (int t = 0; t < 16 && midiTrack < 0; ++t)
  33058. if (const auto r = firstClip (t, lynx::ClipKind::pattern); r >= 0)
  33059. {
  33060. midiTrack = t;
  33061. midiRow = r;
  33062. }
  33063. check ("R13: the set has a MIDI clip", midiTrack >= 0);
  33064. if (auto* detail = ui.getDetailViewForSnapshot(); detail != nullptr && midiTrack >= 0)
  33065. {
  33066. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  33067. lynx::DetailView::shownSetting = true;
  33068. detail->showSelection (midiTrack, midiRow);
  33069. detail->setPage (lynx::DetailView::Page::clip);
  33070. offline.dispatchPendingMessages();
  33071. ui.resized();
  33072. const auto& clip = *lynx::launcher::clipAt (*song.clipGrid, midiTrack, midiRow);
  33073. runtime->running.store (true);
  33074. runtime->tracks[(std::size_t) midiTrack].playing.store (midiRow);
  33075. runtime->tracks[(std::size_t) midiTrack].anchor.store (0.0);
  33076. runtime->clockNow.store ((double) clip.length * 2.3);
  33077. offline.getTransport().playing.store (true);
  33078. auto& roll = ui.getPianoRollForSnapshot();
  33079. roll.frameStepForSnapshot();
  33080. const auto expect = (double) clip.offset + 0.3 * (double) clip.length;
  33081. line ("piano roll playhead " + juce::String (roll.playheadForSnapshot(), 1) + ", the launched clip at " + juce::String (expect, 1));
  33082. check ("R13: the docked Piano roll shows the launched clip's position (DL-74)", std::abs (roll.playheadForSnapshot() - expect) < (double) lynx::ppq);
  33083. write (ui, "r13-clipview-midi");
  33084. offline.getTransport().playing.store (false);
  33085. runtime->tracks[(std::size_t) midiTrack].playing.store (-1);
  33086. roll.frameStepForSnapshot();
  33087. }
  33088. }
  33089. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33090. }
  33091. void runDesign190igShot (const juce::String& prefix, const juce::String& project)
  33092. {
  33093. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33094. lynx::AudioEngine offline (false);
  33095. lynx::MainComponent ui (offline, false);
  33096. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1920x1080"), "x", "");
  33097. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  33098. const auto write = [&prefix] (juce::Component& c, const char* name) {
  33099. savePng (lynx::shot::snapshot (c), prefix + "-" + name + ".png");
  33100. };
  33101. if (project.isNotEmpty())
  33102. ui.openFile (juce::File (project));
  33103. offline.dispatchPendingMessages();
  33104. ui.selectTabForSnapshot (2); // the Playlist, maximized
  33105. auto& playlist = ui.getPlaylistForSnapshot();
  33106. offline.dispatchPendingMessages();
  33107. const auto settle = [&] { // (the waveforms are analysed in the background on the first paint)
  33108. write (playlist, "warmup");
  33109. lynx::ui::WaveformCache::getInstance()->waitUntilIdle (60000);
  33110. offline.dispatchPendingMessages();
  33111. juce::File (prefix + "-warmup.png").deleteFile();
  33112. };
  33113. const auto heights = [&] (int h) {
  33114. offline.editSong ([h] (lynx::Song& s) {
  33115. for (auto& t : s.playlistTracks)
  33116. t.height = h;
  33117. }, false);
  33118. offline.dispatchPendingMessages();
  33119. };
  33120. // 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
  33121. heights (26);
  33122. playlist.setViewForSnapshot (15.6, 20, 0);
  33123. playlist.setScrollYForSnapshot (19 * 26);
  33124. settle();
  33125. write (ui, "01-default");
  33126. write (playlist, "01-default-playlist");
  33127. // 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
  33128. heights (50);
  33129. playlist.setViewForSnapshot (39.75, 20, 0);
  33130. playlist.setScrollYForSnapshot (24 * 50 + 4);
  33131. settle();
  33132. write (ui, "02-zoom17");
  33133. write (playlist, "02-zoom17-playlist");
  33134. // playing (shots/ref/fl-playing.png): the playhead at bar 33, the activity column lit for the tracks that sound
  33135. offline.getTransport().positionTicks.store ((double) (32 * offline.getSong().barTicks()));
  33136. offline.getTransport().playing.store (true);
  33137. playlist.frameStepForSnapshot();
  33138. playlist.frameStepForSnapshot();
  33139. write (ui, "03-playing");
  33140. offline.getTransport().playing.store (false);
  33141. playlist.frameStepForSnapshot();
  33142. heights (26);
  33143. playlist.setViewForSnapshot (15.6, 0, 0);
  33144. playlist.setScrollYForSnapshot (0);
  33145. write (ui, "04-default-start");
  33146. // round 190jd (live check 190iw Q4): FL's grid levels at its Ctrl+wheel steps — bars only at 9.9 px a beat, beat
  33147. // 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
  33148. heights (32);
  33149. for (const auto beat : { 9.9, 11.5, 18.4, 21.5 })
  33150. {
  33151. playlist.setViewForSnapshot (beat * 4.0, 8, 0);
  33152. playlist.setScrollYForSnapshot (0);
  33153. write (playlist, ("05-grid-" + juce::String (beat, 1) + "px-beat").toRawUTF8());
  33154. }
  33155. // round 190jd: NEW automation clips from the first channel's volume and pan knobs take FL's colours by parameter
  33156. // (#8C5F5F, #7F8C5E; shots/q4-fl-new-automation-clip-zoom2.png); the editor windows they open are closed again
  33157. if (! offline.getSong().channels.empty())
  33158. {
  33159. // (the channels of FL's capture: Synth Bass pan + volume, Grv Kick 27 volume + pan; else the first channel)
  33160. const auto channelNamed = [&offline] (const char* name) {
  33161. const auto& channels = offline.getSong().channels;
  33162. for (int c = 0; c < (int) channels.size(); ++c)
  33163. if (juce::String (channels[(std::size_t) c].name).startsWithIgnoreCase (name))
  33164. return c;
  33165. return 0;
  33166. };
  33167. juce::String report;
  33168. offline.editSong ([] (lynx::Song& s) { s.loopStart = s.loopEnd = 0; }, false);
  33169. offline.getTransport().positionTicks.store (0.0);
  33170. const auto before = offline.getSong().automations.size();
  33171. for (const auto& [name, kind] : { std::pair { "Synth Bass", lynx::AutomationTargetKind::channelPan },
  33172. std::pair { "Grv Kick", lynx::AutomationTargetKind::channelVolume },
  33173. std::pair { "Synth Bass", lynx::AutomationTargetKind::channelVolume },
  33174. std::pair { "Grv Kick", lynx::AutomationTargetKind::channelPan } })
  33175. {
  33176. lynx::AutomationTarget t;
  33177. t.kind = kind;
  33178. t.index = channelNamed (name);
  33179. lynx::createAutomationClip (offline, t);
  33180. offline.dispatchPendingMessages();
  33181. }
  33182. lynx::closeAutomationEditors();
  33183. offline.dispatchPendingMessages();
  33184. int first = -1;
  33185. for (std::size_t a = before; a < offline.getSong().automations.size(); ++a)
  33186. {
  33187. const auto& au = offline.getSong().automations[a];
  33188. for (const auto& c : offline.getSong().playlist)
  33189. if (c.kind == lynx::ClipKind::automation && c.automation == (int) a)
  33190. {
  33191. first = first < 0 ? c.track : std::min (first, c.track);
  33192. report << "new clip '" << au.name << "' track " << (c.track + 1) << " colour #"
  33193. << juce::String::toHexString ((int) (au.colour & 0xFFFFFF)).paddedLeft ('0', 6).toUpperCase() << "\n";
  33194. }
  33195. }
  33196. report << "automations " << (int) before << " -> " << (int) offline.getSong().automations.size() << "\n";
  33197. juce::File (prefix + "-190jd-automation.txt").replaceWithText (report);
  33198. heights (50);
  33199. playlist.setViewForSnapshot (39.75, 0, 0);
  33200. playlist.setScrollYForSnapshot (std::max (0, first - 1) * 50);
  33201. write (playlist, "06-new-automation-clips");
  33202. }
  33203. // round 190jd (live check 190iw Q7, shots/q7-fl-countin-sheet.png): a 1-bar count-in — the time display reads
  33204. // "REC IN 4" on its first beat and "REC IN 1" on its last, Play shows its Pause glyph, Record stays lit
  33205. for (const auto beatsLeft : { 4, 1 })
  33206. {
  33207. offline.getTransport().countIn.store ((double) beatsLeft * lynx::ppq - 1.0);
  33208. ui.tickLinkForSnapshot();
  33209. ui.transportForSnapshot (true, true);
  33210. write (ui, ("07-countin-" + juce::String (beatsLeft)).toRawUTF8());
  33211. }
  33212. offline.getTransport().countIn.store (0.0);
  33213. }
  33214. void runDesign190igS4Shot (const juce::String& prefix, const juce::String& projectPath)
  33215. {
  33216. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33217. lynx::AudioEngine offline (false);
  33218. lynx::MainComponent ui (offline, false);
  33219. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  33220. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  33221. juce::String checks;
  33222. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  33223. const auto write = [&prefix] (juce::Component& c, const juce::String& name) {
  33224. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33225. file.deleteFile();
  33226. juce::FileOutputStream out (file);
  33227. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  33228. };
  33229. ui.setVisible (true);
  33230. ui.selectTabForSnapshot (2);
  33231. ui.setClipLaunchWorkflow (true); // (first: an .als opened in the Clip-launch layout takes Live's own colours)
  33232. offline.dispatchPendingMessages();
  33233. if (projectPath.isNotEmpty())
  33234. {
  33235. ui.openFile (juce::File (projectPath));
  33236. offline.dispatchPendingMessages();
  33237. }
  33238. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  33239. offline.dispatchPendingMessages();
  33240. ui.resized();
  33241. auto* gridView = ui.getClipGridForSnapshot();
  33242. auto* runtime = offline.launcherStateForSnapshot();
  33243. const auto& song = offline.getSong();
  33244. if (gridView == nullptr || ! song.clipGrid)
  33245. {
  33246. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid\n");
  33247. return;
  33248. }
  33249. if (! song.mixer.empty())
  33250. checks << "first mixer colours:";
  33251. for (std::size_t m = 1; m < std::min<std::size_t> (song.mixer.size(), 6); ++m)
  33252. checks << " " << juce::String::toHexString ((int) (song.mixer[m].colour & 0xffffff)).paddedLeft ('0', 6);
  33253. checks << "\n";
  33254. gridView->resized();
  33255. write (ui, "01-window-idle");
  33256. write (*gridView, "02-grid-idle");
  33257. if (runtime == nullptr)
  33258. {
  33259. check ("a launcher runtime exists", false);
  33260. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33261. return;
  33262. }
  33263. // the frame strip: the first five tracks; the scene each plays or waits for, by the clips the set has
  33264. const auto& grid = *song.clipGrid;
  33265. const auto rowWithClip = [&grid] (int track, int from) {
  33266. for (int r = from; r < 64; ++r)
  33267. if (lynx::launcher::clipAt (grid, track, r) != nullptr)
  33268. return r;
  33269. return -1;
  33270. };
  33271. const auto reset = [&] {
  33272. for (auto& v : runtime->tracks)
  33273. {
  33274. v.playing.store (-1);
  33275. v.pending.store (-1);
  33276. v.stopping.store (false);
  33277. v.recording.store (-1);
  33278. v.recordPending.store (-1);
  33279. v.progress.store (0.0f);
  33280. }
  33281. runtime->running.store (true);
  33282. };
  33283. const auto bar = (double) song.barTicks();
  33284. const auto state = [&] (const juce::String& name) {
  33285. gridView->repaint();
  33286. write (*gridView, name);
  33287. };
  33288. // playing (Live frame 1): tracks 0..3 play their first clip, a third of the way into its second loop
  33289. reset();
  33290. for (int t = 0; t < 4; ++t)
  33291. if (const auto r = rowWithClip (t, 0); r >= 0)
  33292. {
  33293. runtime->tracks[(std::size_t) t].playing.store (r);
  33294. runtime->tracks[(std::size_t) t].progress.store (0.33f);
  33295. const auto length = (double) lynx::launcher::clipAt (grid, t, r)->length;
  33296. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  33297. runtime->clockNow.store (length * 1.33);
  33298. }
  33299. state ("10-playing");
  33300. // queued (Live frames 2 and 3): the same, and each track's next clip waits for its start; both blink phases
  33301. for (int t = 0; t < 4; ++t)
  33302. if (const auto r = runtime->tracks[(std::size_t) t].playing.load(); r >= 0)
  33303. if (const auto next = rowWithClip (t, r + 1); next >= 0)
  33304. runtime->tracks[(std::size_t) t].pending.store (next);
  33305. lynx::setClipGridBlinkPhaseForSnapshot (0);
  33306. state ("11-queued-dark");
  33307. lynx::setClipGridBlinkPhaseForSnapshot (1);
  33308. state ("12-queued-lit");
  33309. // Animations off: the lit green, steady
  33310. lynx::ui::motion::enabled() = false;
  33311. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  33312. state ("13-queued-animations-off");
  33313. lynx::ui::motion::enabled() = true;
  33314. // a stop waiting (both phases)
  33315. reset();
  33316. for (int t = 0; t < 4; ++t)
  33317. if (const auto r = rowWithClip (t, 0); r >= 0)
  33318. {
  33319. runtime->tracks[(std::size_t) t].playing.store (r);
  33320. runtime->tracks[(std::size_t) t].progress.store (0.5f);
  33321. runtime->tracks[(std::size_t) t].stopping.store (t % 2 == 0);
  33322. }
  33323. lynx::setClipGridBlinkPhaseForSnapshot (0);
  33324. state ("14-stopping-dark");
  33325. lynx::setClipGridBlinkPhaseForSnapshot (1);
  33326. state ("15-stopping-lit");
  33327. // recording into an empty slot of track 1 (the counter one beat in) and a launch waiting on an empty slot (a stop)
  33328. reset();
  33329. {
  33330. int empty = -1;
  33331. for (int r = 0; r < 16 && empty < 0; ++r)
  33332. if (lynx::launcher::clipAt (grid, 1, r) == nullptr)
  33333. empty = r;
  33334. if (empty >= 0)
  33335. {
  33336. runtime->tracks[1].recording.store (empty);
  33337. runtime->tracks[1].recordFrom.store (0.0);
  33338. runtime->clockNow.store ((double) lynx::ppq);
  33339. }
  33340. check ("recording: an empty slot on track 2", empty >= 0);
  33341. }
  33342. state ("16-recording");
  33343. // the status pie at 25 / 50 / 75 % in the second loop
  33344. 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) })
  33345. {
  33346. reset();
  33347. for (int t = 0; t < 4; ++t)
  33348. if (const auto r = rowWithClip (t, 0); r >= 0)
  33349. {
  33350. const auto length = (double) lynx::launcher::clipAt (grid, t, r)->length;
  33351. runtime->tracks[(std::size_t) t].playing.store (r);
  33352. runtime->tracks[(std::size_t) t].progress.store (p);
  33353. runtime->tracks[(std::size_t) t].anchor.store (0.0);
  33354. runtime->clockNow.store (length * (1.0 + (double) p));
  33355. }
  33356. state (name);
  33357. }
  33358. juce::ignoreUnused (bar);
  33359. // round 181a's look, the option (View › Classic LYNX look for the clip grid)
  33360. reset();
  33361. for (int t = 0; t < 4; ++t)
  33362. if (const auto r = rowWithClip (t, 0); r >= 0)
  33363. runtime->tracks[(std::size_t) t].playing.store (r);
  33364. lynx::clipGridClassicLook() = true;
  33365. lynx::refreshClipGrid (*gridView);
  33366. state ("20-classic-look-option");
  33367. lynx::clipGridClassicLook() = false;
  33368. lynx::refreshClipGrid (*gridView);
  33369. lynx::setClipGridBlinkPhaseForSnapshot (-1);
  33370. reset();
  33371. runtime->running.store (false);
  33372. write (ui, "21-window-after");
  33373. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33374. ui.setClipLaunchWorkflow (false);
  33375. }
  33376. void runLiveShot190dr (const juce::String& prefix)
  33377. {
  33378. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33379. lynx::AudioEngine offline (false);
  33380. lynx::MainComponent ui (offline, false);
  33381. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  33382. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  33383. const auto write = [&prefix] (juce::Component& c, const char* name) {
  33384. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33385. file.deleteFile();
  33386. juce::FileOutputStream out (file);
  33387. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  33388. };
  33389. juce::String checks;
  33390. const auto check = [&checks] (const juce::String& what, bool ok) { checks << (ok ? "ok " : "FAIL ") << what << "\n"; };
  33391. // a two-bar loop of clicks for the audio clip
  33392. const auto wav = juce::File (prefix + "-loop.wav");
  33393. wav.deleteFile();
  33394. {
  33395. const double rate = 48000.0;
  33396. juce::AudioBuffer<float> buffer (2, (int) (rate * 4.0));
  33397. buffer.clear();
  33398. for (int hit = 0; hit < 16; ++hit)
  33399. for (int k = 0; k < 3000 && hit * 12000 + k < buffer.getNumSamples(); ++k)
  33400. for (int ch = 0; ch < 2; ++ch)
  33401. buffer.setSample (ch, hit * 12000 + k, (float) (std::sin (k * (hit % 4 == 0 ? 0.05 : 0.3)) * std::exp (-k / 500.0) * 0.8));
  33402. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  33403. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 2, 16, {}, 0))
  33404. {
  33405. out.release();
  33406. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  33407. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  33408. }
  33409. }
  33410. ui.setVisible (true);
  33411. lynx::DetailView::shownSetting = true;
  33412. lynx::DetailView::devicesPage = false;
  33413. ui.setClipLaunchWorkflow (true);
  33414. ui.showPanelsForSnapshot ({ lynx::workspace::Panel::browser, lynx::workspace::Panel::playlist });
  33415. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  33416. offline.dispatchPendingMessages();
  33417. int audioChannel = -1;
  33418. offline.editSong ([&audioChannel] (lynx::Song& s) {
  33419. lynx::Clip audio;
  33420. if (! s.playlist.empty())
  33421. {
  33422. audio = s.playlist.front();
  33423. audioChannel = audio.channel;
  33424. s.playlist.clear();
  33425. }
  33426. const int channels = (int) s.channels.size();
  33427. s.channels.resize ((std::size_t) channels + 3);
  33428. const char* names[] { "Drum kit", "Bass synth", "Keys" };
  33429. for (int k = 0; k < 3; ++k)
  33430. {
  33431. auto& ch = s.channels[(std::size_t) (channels + k)];
  33432. ch.name = names[k];
  33433. ch.instrument = k == 0 ? lynx::InstrumentKind::sampler : lynx::InstrumentKind::synth;
  33434. ch.mixerTrack = k + 1;
  33435. }
  33436. if (audioChannel >= 0)
  33437. s.channels[(std::size_t) audioChannel].mixerTrack = 5;
  33438. if (s.mixer.size() < 8)
  33439. s.mixer.resize (8);
  33440. const char* inserts[] { "Master", "Drums", "Bass", "Keys", "Vox", "Loop", "Reverb", "Delay" };
  33441. for (int i = 1; i < 8; ++i)
  33442. s.mixer[(std::size_t) i].name = inserts[i];
  33443. s.mixer[1].volume = lynx::sessionmixer::positionForDb (-3.0);
  33444. s.mixer[2].pan = 0.3f;
  33445. s.mixer[2].effects.clear();
  33446. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::delay })
  33447. {
  33448. lynx::EffectSlot fx;
  33449. fx.kind = kind;
  33450. const auto& info = lynx::effectInfo (kind);
  33451. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  33452. fx.params[k] = info.params[k].defaultValue;
  33453. s.mixer[2].effects.push_back (fx);
  33454. }
  33455. s.mixer[3].muted = true; // the Keys' activator off
  33456. s.mixer[4].inputChannel = 0;
  33457. s.mixer[4].inputStereo = true;
  33458. s.mixer[4].monitor = lynx::InputMonitor::automatic;
  33459. s.mixer[4].effects.clear();
  33460. {
  33461. lynx::EffectSlot fx;
  33462. fx.kind = lynx::EffectKind::reverb;
  33463. s.mixer[4].effects.push_back (fx);
  33464. }
  33465. s.mixer[5].solo = true;
  33466. 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 } })
  33467. {
  33468. lynx::MixerSend send;
  33469. send.target = to;
  33470. send.level = lynx::faderGain (level);
  33471. s.mixer[(std::size_t) from].sends.push_back (send);
  33472. }
  33473. while (s.patterns.size() < 3)
  33474. s.patterns.emplace_back();
  33475. const char* patterns[] { "Beat", "Bassline", "Chords" };
  33476. for (int p = 0; p < 3; ++p)
  33477. {
  33478. auto& pattern = s.patterns[(std::size_t) p];
  33479. pattern.name = patterns[p];
  33480. lynx::Note n;
  33481. n.channel = channels + p;
  33482. n.key = 48 + p * 5;
  33483. pattern.notes = { n };
  33484. pattern.lengthTicks = 4 * lynx::ppq;
  33485. }
  33486. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 8));
  33487. const char* tracks[] { "Drums", "Bass", "Keys", "Vox", "Loop", "FX" };
  33488. for (int t = 0; t < 6; ++t)
  33489. s.playlistTracks[(std::size_t) t].name = tracks[t];
  33490. s.playlistTracks[3].mode = lynx::PlaylistTrackMode::audio;
  33491. s.playlistTracks[3].mixerTrack = 4;
  33492. for (int t = 0; t < 3; ++t)
  33493. for (int r = 0; r < 3; ++r)
  33494. if (! (t == 2 && r == 0))
  33495. {
  33496. lynx::Clip clip;
  33497. clip.pattern = t;
  33498. clip.length = 4 * lynx::ppq;
  33499. lynx::launcher::setClip (s, t, r, clip);
  33500. }
  33501. if (audioChannel >= 0)
  33502. {
  33503. lynx::clipsample::setWarp (s, audioChannel, true, 4.0); // (Warp on, as a dropped loop in Live)
  33504. audio.track = 4;
  33505. audio.start = 0;
  33506. lynx::launcher::setClip (s, 4, 0, audio);
  33507. lynx::launcher::setClip (s, 4, 1, audio);
  33508. }
  33509. auto& grid = lynx::launcher::ensureGrid (s);
  33510. const char* scenes[] { "Intro", "Verse", "Drop" };
  33511. grid.scenes.resize (5);
  33512. for (int r = 0; r < 3; ++r)
  33513. grid.scenes[(std::size_t) r].name = scenes[r];
  33514. }, false);
  33515. offline.dispatchPendingMessages();
  33516. offline.setGridTrackArmed (3, true);
  33517. ui.setClipGridView (lynx::PlaylistArea::GridView::grid);
  33518. offline.dispatchPendingMessages();
  33519. ui.resized();
  33520. auto* gridView = ui.getClipGridForSnapshot();
  33521. auto* mixer = gridView != nullptr ? lynx::clipGridMixer (*gridView) : nullptr;
  33522. auto* detail = ui.getDetailViewForSnapshot();
  33523. if (gridView == nullptr || mixer == nullptr || detail == nullptr)
  33524. {
  33525. juce::File (prefix + "-checks.txt").replaceWithText ("FAIL no grid, mixer or detail view\n");
  33526. return;
  33527. }
  33528. // the meters: a level per insert, as a playing song leaves them (offscreen nothing plays), two ticks
  33529. const auto levels = [&] {
  33530. for (int k = 0; k < 2; ++k)
  33531. {
  33532. const float peaks[] { 0.9f, 0.5f, 0.7f, 0.0f, 0.3f, 0.45f, 0.2f, 0.12f };
  33533. for (int i = 0; i < 8; ++i)
  33534. offline.getMeters().accumulate (i, peaks[i], peaks[i] * 0.85f);
  33535. mixer->tick();
  33536. }
  33537. };
  33538. if (auto* runtime = offline.launcherStateForSnapshot())
  33539. {
  33540. runtime->tracks[0].playing.store (1);
  33541. runtime->tracks[0].progress.store (0.3f);
  33542. runtime->tracks[1].playing.store (1);
  33543. runtime->tracks[1].progress.store (0.3f);
  33544. runtime->tracks[4].playing.store (0);
  33545. runtime->tracks[4].progress.store (0.5f);
  33546. runtime->running.store (true);
  33547. }
  33548. levels();
  33549. gridView->resized();
  33550. write (ui, "01-session-mixer");
  33551. write (*gridView, "01b-grid-alone");
  33552. using Part = lynx::SessionMixerComponent::Part;
  33553. check ("mixer: Sends rows are the two buses (Reverb 6, Delay 7)", mixer->sendTargets() == std::vector<int> { 6, 7 });
  33554. check ("mixer: the arm buttons moved into the Volume section", mixer->armsShown());
  33555. check ("mixer: Drums strip has activator, solo, arm, pan, volume", ! mixer->partBounds (0, Part::activator).isEmpty() && ! mixer->partBounds (0, Part::solo).isEmpty()
  33556. && ! mixer->partBounds (0, Part::arm).isEmpty() && ! mixer->partBounds (0, Part::pan).isEmpty()
  33557. && ! mixer->partBounds (0, Part::volume).isEmpty());
  33558. check ("mixer: Vox strip (audio track) has Audio From, its channel, Monitor and Audio To", ! mixer->partBounds (3, Part::inType).isEmpty()
  33559. && ! mixer->partBounds (3, Part::inChannel).isEmpty()
  33560. && ! mixer->partBounds (3, Part::monAuto).isEmpty()
  33561. && ! mixer->partBounds (3, Part::output).isEmpty());
  33562. check ("mixer: Bass strip (instrument) shows MIDI From, no Monitor", mixer->partBounds (1, Part::monIn).isEmpty() && ! mixer->partBounds (1, Part::output).isEmpty());
  33563. check ("mixer: FX strip (no clips) has no activator but an arm", mixer->partBounds (5, Part::activator).isEmpty() && ! mixer->partBounds (5, Part::arm).isEmpty());
  33564. check ("mixer: Main strip has volume and pan, no activator", ! mixer->partBounds (-2, Part::volume).isEmpty() && mixer->partBounds (-2, Part::activator).isEmpty());
  33565. {
  33566. const auto hit = mixer->hitAt (mixer->partBounds (2, Part::solo).getCentre());
  33567. check ("mixer: a click on the Keys' S is its solo", hit.column == 2 && hit.part == Part::solo);
  33568. const auto send = mixer->hitAt (mixer->partBounds (1, Part::send, 1).getCentre());
  33569. check ("mixer: the Bass' second knob is its send to Delay", send.column == 1 && send.part == Part::send && send.row == 1);
  33570. }
  33571. {
  33572. juce::PopupMenu menu;
  33573. mixer->addViewItems (menu);
  33574. saveMenus (juce::StringArray { "Mixer (footer button)" }, std::vector<juce::PopupMenu> { menu }, prefix + "-02-mixer-view-menu.png");
  33575. }
  33576. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.trackOptions = true; }, false);
  33577. offline.dispatchPendingMessages();
  33578. gridView->resized();
  33579. levels();
  33580. write (*gridView, "03-mixer-track-options");
  33581. offline.editSong ([] (lynx::Song& s) {
  33582. auto& v = lynx::launcher::ensureGrid (s).mixerView;
  33583. v.trackOptions = v.io = v.sends = false;
  33584. }, false);
  33585. offline.dispatchPendingMessages();
  33586. gridView->resized();
  33587. levels();
  33588. write (*gridView, "04-mixer-volume-only");
  33589. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView.shown = false; }, false);
  33590. offline.dispatchPendingMessages();
  33591. gridView->resized();
  33592. write (*gridView, "05-mixer-hidden");
  33593. check ("mixer hidden: the arm buttons are back in the status row", ! mixer->armsShown() && mixer->getHeight() == 0);
  33594. offline.editSong ([] (lynx::Song& s) { lynx::launcher::ensureGrid (s).mixerView = {}; }, false);
  33595. offline.dispatchPendingMessages();
  33596. gridView->resized();
  33597. // the Clip page of the Loop clip (track 4, scene 0) while it plays: Warp on, the Set buttons lit, the title
  33598. detail->showSelection (4, 0);
  33599. detail->setPage (lynx::DetailView::Page::clip);
  33600. offline.editSong ([] (lynx::Song&) {}, false); // (a change message: the Clip panel reads the playing state)
  33601. offline.dispatchPendingMessages();
  33602. write (ui, "06-clip-audio-warp-on");
  33603. // round 190ig (round 190ia CL-20a, the BPM row bug): the Audio box at Live's 190 px, 260 px and 350 px detail
  33604. // heights, in Re-Pitch (no settings rows) and in Beats (three rows: the most a mode shows)
  33605. if (audioChannel >= 0)
  33606. {
  33607. const auto heightBefore = lynx::DetailView::preferredHeight;
  33608. for (const auto beats : { false, true })
  33609. {
  33610. offline.editSong ([audioChannel, beats] (lynx::Song& s) {
  33611. auto& sampler = s.channels[(std::size_t) audioChannel].sampler;
  33612. sampler.keepPitch = beats;
  33613. sampler.stretchMethod = beats ? lynx::StretchMethod::beats : sampler.stretchMethod;
  33614. }, false);
  33615. offline.dispatchPendingMessages();
  33616. for (const auto h : { 190, 260, 350 })
  33617. {
  33618. lynx::DetailView::preferredHeight = h;
  33619. ui.resized();
  33620. if (auto* area = detail->getParentComponent()) // (the Playlist area lays its docked detail view out)
  33621. area->resized();
  33622. offline.dispatchPendingMessages();
  33623. write (ui, (juce::String ("06h-audio-box-") + (beats ? "beats-" : "repitch-") + juce::String (h)).toRawUTF8());
  33624. check ("audio box at " + juce::String (h) + " px: the detail view is that high", detail->getHeight() == h);
  33625. }
  33626. }
  33627. offline.editSong ([audioChannel] (lynx::Song& s) { s.channels[(std::size_t) audioChannel].sampler.keepPitch = false; }, false);
  33628. offline.dispatchPendingMessages();
  33629. lynx::DetailView::preferredHeight = heightBefore;
  33630. ui.resized();
  33631. if (auto* area = detail->getParentComponent())
  33632. area->resized();
  33633. offline.dispatchPendingMessages();
  33634. }
  33635. if (audioChannel >= 0)
  33636. {
  33637. const auto beforeLength = lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length;
  33638. offline.editSong ([audioChannel] (lynx::Song& s) { lynx::clipsample::setWarp (s, audioChannel, false, 4.0); });
  33639. offline.dispatchPendingMessages();
  33640. write (ui, "07-clip-audio-warp-off");
  33641. check ("warp off: the channel plays at its own speed", ! lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  33642. offline.undo();
  33643. offline.dispatchPendingMessages();
  33644. check ("warp: undo gives the clip back as it was", lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0)->length == beforeLength
  33645. && lynx::clipsample::isWarped (offline.getSong().channels[(std::size_t) audioChannel].sampler));
  33646. // Set (start) at the play position, half way: one undo step
  33647. const auto clipBefore = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  33648. offline.editSong ([] (lynx::Song& s) {
  33649. for (auto& c : s.clipGrid->clips)
  33650. if (c.track == 4 && c.gridSlot >= 0 && s.clipGrid->slots[(std::size_t) c.gridSlot].scene == 0)
  33651. lynx::clipsample::setStartAt (c, lynx::clipsample::playPosition (c, 0.5f));
  33652. });
  33653. const auto& after = *lynx::launcher::clipAt (*offline.getSong().clipGrid, 4, 0);
  33654. check ("set start: the clip starts half way and ends where it did", after.offset == clipBefore.offset + clipBefore.length / 2
  33655. && after.offset + after.length == clipBefore.offset + clipBefore.length);
  33656. offline.undo();
  33657. offline.dispatchPendingMessages();
  33658. }
  33659. // a MIDI clip's Clip page too (the Set buttons are there for every clip), playing through a groove of the pool
  33660. offline.editSong ([] (lynx::Song& s) {
  33661. const auto& bank = lynx::groove::factoryBank();
  33662. if (bank.size() > 9)
  33663. lynx::groove::setClipGroove (s, 0, 1, lynx::groove::add (s.grooves, bank[9].groove));
  33664. }, false);
  33665. detail->showSelection (0, 1);
  33666. offline.editSong ([] (lynx::Song&) {}, false);
  33667. offline.dispatchPendingMessages();
  33668. write (ui, "08-clip-midi-set-buttons");
  33669. // the Device View of Bass (insert 2): its compressor dragged onto Keys (insert 3), then Ctrl-dragged onto Vox
  33670. detail->showSelection (1, 0);
  33671. detail->setPage (lynx::DetailView::Page::devices);
  33672. offline.dispatchPendingMessages();
  33673. write (ui, "09-devices-bass-before");
  33674. lynx::setClipGridDeviceDropForSnapshot (*gridView, 2);
  33675. write (ui, "10-device-dragged-over-keys");
  33676. lynx::setClipGridDeviceDropForSnapshot (*gridView, -1);
  33677. int fromId = 0;
  33678. {
  33679. const auto& s = offline.getSong();
  33680. fromId = (int) (s.mixer[2].effects[1].instance.id & 0x7fffffff);
  33681. }
  33682. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 1, 3, false); });
  33683. offline.dispatchPendingMessages();
  33684. check ("drag to Keys: the compressor moved (same device)", offline.getSong().mixer[2].effects.size() == 2 && offline.getSong().mixer[3].effects.size() == 1
  33685. && (int) (offline.getSong().mixer[3].effects[0].instance.id & 0x7fffffff) == fromId);
  33686. detail->showSelection (2, 1);
  33687. offline.dispatchPendingMessages();
  33688. write (ui, "11-devices-keys-after-move");
  33689. offline.editSongStructural ([] (lynx::Song& s) { lynx::detailchain::moveEffectToInsert (s, 2, 0, 4, true); });
  33690. offline.dispatchPendingMessages();
  33691. check ("Ctrl-drag to Vox: a copy of the EQ after its reverb, Bass keeps its own", offline.getSong().mixer[4].effects.size() == 2
  33692. && offline.getSong().mixer[4].effects[1].kind == lynx::EffectKind::eq
  33693. && offline.getSong().mixer[2].effects[0].kind == lynx::EffectKind::eq);
  33694. offline.undo();
  33695. offline.undo();
  33696. offline.dispatchPendingMessages();
  33697. check ("undo twice: Bass has its three devices again, Keys none", offline.getSong().mixer[2].effects.size() == 3 && offline.getSong().mixer[3].effects.empty()
  33698. && offline.getSong().mixer[4].effects.size() == 1);
  33699. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33700. wav.deleteFile();
  33701. }
  33702. void runWarpShot (const juce::String& prefix)
  33703. {
  33704. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33705. lynx::AudioEngine offline (false);
  33706. lynx::MainComponent ui (offline, false);
  33707. ui.setSize (1600, 900);
  33708. const auto write = [&prefix] (juce::Component& c, const char* name) {
  33709. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33710. file.deleteFile();
  33711. juce::FileOutputStream out (file);
  33712. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (c), out);
  33713. };
  33714. // a two-bar loop of clicks, a little off the grid (what Quantize is for)
  33715. const auto wav = juce::File (prefix + "-loop.wav");
  33716. wav.deleteFile();
  33717. {
  33718. const double rate = 44100.0;
  33719. juce::AudioBuffer<float> buffer (1, (int) (rate * 4.0));
  33720. buffer.clear();
  33721. for (int hit = 0; hit < 8; ++hit)
  33722. {
  33723. const auto at = (int) ((hit * 0.5 + (hit % 3) * 0.035) * rate);
  33724. for (int k = 0; k < 4000 && at + k < buffer.getNumSamples(); ++k)
  33725. buffer.setSample (0, at + k, (float) (std::sin (k * (hit % 2 ? 0.25 : 0.06)) * std::exp (-k / 700.0) * 0.8));
  33726. }
  33727. if (auto out = std::unique_ptr<juce::FileOutputStream> (wav.createOutputStream()))
  33728. if (auto* writer = juce::WavAudioFormat().createWriterFor (out.get(), rate, 1, 16, {}, 0))
  33729. {
  33730. out.release();
  33731. std::unique_ptr<juce::AudioFormatWriter> owned (writer);
  33732. owned->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
  33733. }
  33734. }
  33735. ui.setVisible (true);
  33736. lynx::DetailView::shownSetting = true;
  33737. ui.selectTabForSnapshot (2);
  33738. ui.setLayoutStyle (lynx::layoutstyle::Style::clipLaunch);
  33739. lynx::autolanes::setShown (true);
  33740. ui.getPlaylistForSnapshot().addAudioClipAtPlayhead (wav);
  33741. offline.dispatchPendingMessages();
  33742. int channel = -1;
  33743. offline.editSong ([&channel] (lynx::Song& s) {
  33744. if (s.playlist.empty())
  33745. return;
  33746. auto audio = s.playlist.front();
  33747. channel = audio.channel;
  33748. audio.track = 1;
  33749. s.playlist.front() = audio;
  33750. for (int k = 1; k < 3; ++k)
  33751. {
  33752. auto more = audio;
  33753. more.start = audio.start + k * 8 * lynx::ppq;
  33754. s.playlist.push_back (more);
  33755. }
  33756. while (s.patterns.size() < 1)
  33757. s.patterns.emplace_back();
  33758. for (int t = 2; t < 5; ++t)
  33759. for (int k = 0; k < 4; ++k)
  33760. {
  33761. lynx::Clip c;
  33762. c.pattern = 0;
  33763. c.track = t;
  33764. c.start = k * 4 * lynx::ppq;
  33765. c.length = 4 * lynx::ppq;
  33766. s.playlist.push_back (c);
  33767. }
  33768. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 6));
  33769. s.playlistTracks[1].name = "Loop";
  33770. s.playlistTracks[2].name = "Drums";
  33771. s.playlistTracks[3].name = "Kick";
  33772. s.playlistTracks[4].name = "Hats";
  33773. s.playlistTracks[4].folded = true;
  33774. lynx::noteedit::groupWithAbove (s, 3);
  33775. lynx::noteedit::groupWithAbove (s, 4);
  33776. lynx::arrange::makeGroupBus (s, 3);
  33777. lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::tempo, 0, 0, 0 }, "Tempo", lynx::valueFromTempo (s.bpm));
  33778. if (! s.automations.empty())
  33779. s.automations.back().points = { { 0, lynx::valueFromTempo (120.0), 0.0f }, { 8 * lynx::ppq, lynx::valueFromTempo (120.0), 0.0f },
  33780. { 12 * lynx::ppq, lynx::valueFromTempo (180.0), 0.0f }, { 16 * lynx::ppq, lynx::valueFromTempo (140.0), 0.0f } };
  33781. s.addMarker ({ 4 * lynx::ppq, "Verse", 0, 0 });
  33782. s.addMarker ({ 8 * lynx::ppq, {}, 3, 4 });
  33783. s.addMarker ({ 14 * lynx::ppq, {}, 4, 4 });
  33784. s.loopStart = 4 * lynx::ppq;
  33785. s.loopEnd = 12 * lynx::ppq;
  33786. s.loopOff = true;
  33787. s.tempoViewLow = 60.0; // the tempo lane's range
  33788. s.tempoViewHigh = 200.0;
  33789. std::stable_sort (s.playlist.begin(), s.playlist.end(), [] (const lynx::Clip& a, const lynx::Clip& b) { return a.start < b.start; });
  33790. // the same audio in the clip grid, for the Clip page
  33791. lynx::Clip slot = audio;
  33792. slot.start = 0;
  33793. slot.pitch = -2.25f;
  33794. slot.gain = 0.7f;
  33795. lynx::launcher::setClip (s, 1, 0, slot);
  33796. // a few warp markers, as Quantize leaves them
  33797. if (channel >= 0 && channel < (int) s.channels.size())
  33798. {
  33799. auto& sampler = s.channels[(std::size_t) channel].sampler;
  33800. lynx::warpedit::ensureMarkers (sampler, 4.0, s.bpm);
  33801. std::vector<double> attacks;
  33802. for (int hit = 1; hit < 8; ++hit)
  33803. attacks.push_back (hit * 0.5 + (hit % 3) * 0.035);
  33804. lynx::warptools::quantize (sampler, attacks, 0.0, 4.0, 0.5, 1.0);
  33805. lynx::warpedit::syncLength (sampler, 4.0);
  33806. }
  33807. }, false);
  33808. offline.dispatchPendingMessages();
  33809. ui.resized();
  33810. write (ui, "arrangement-loop-off");
  33811. offline.editSong ([] (lynx::Song& s) { s.loopOff = false; }, false);
  33812. offline.dispatchPendingMessages();
  33813. write (ui, "arrangement-loop-on");
  33814. juce::String facts;
  33815. {
  33816. const auto& s = offline.getSong();
  33817. facts << "channel " << channel << ", warp markers " << (channel >= 0 ? (int) s.channels[(std::size_t) channel].sampler.warp.size() : -1)
  33818. << ", group bus insert " << lynx::arrange::groupBus (s, 3) << ", folded track 4: " << (lynx::arrange::isFolded (s, 4) ? 1 : 0) << "\n";
  33819. }
  33820. if (auto* detail = ui.getDetailViewForSnapshot())
  33821. {
  33822. detail->showSelection (1, 0);
  33823. detail->setPage (lynx::DetailView::Page::clip);
  33824. offline.dispatchPendingMessages();
  33825. write (ui, "clip-audio");
  33826. }
  33827. if (channel >= 0)
  33828. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  33829. {
  33830. editor->setSize (1120, 600);
  33831. write (*editor, "audio-editor-warp");
  33832. // round 190cy (Live 12.4.16 live check 190cw shot 09): a plain drag of marker 3 holds it two sixteenths
  33833. // later (its audio goes there); Shift + drag slides the audio under it. Round 190db: the Clip-launch
  33834. // workflow draws the warped clip in beats, so the held drag shows the audio stretched around the marker
  33835. // (plain) or slid under it, its attack later (Shift, to the right as in Live's shot)
  33836. const auto& w = offline.getSong().channels[(std::size_t) channel].sampler.warp;
  33837. if (w.size() > 4)
  33838. {
  33839. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].beats + 0.5, false);
  33840. write (*editor, "audio-editor-drag-stretch");
  33841. lynx::holdAudioEditorWarpDragForSnapshot (*editor, 3, w[3].seconds - 0.12, true);
  33842. write (*editor, "audio-editor-drag-slide");
  33843. }
  33844. // the same clip in file time (the Pattern workflow's view, or "Show the audio in beats" off)
  33845. if (auto inFileTime = lynx::makeAudioEditorPanel (offline, channel, 0, true))
  33846. {
  33847. inFileTime->setSize (1120, 600);
  33848. lynx::setAudioEditorBeatTimeForSnapshot (*inFileTime, 0);
  33849. write (*inFileTime, "audio-editor-file-time");
  33850. if (w.size() > 4)
  33851. {
  33852. lynx::holdAudioEditorWarpDragForSnapshot (*inFileTime, 3, w[3].beats + 0.5, false);
  33853. write (*inFileTime, "audio-editor-file-time-drag");
  33854. }
  33855. }
  33856. }
  33857. // round 190cy (Live 12.4.16 live check 190cw shot 02): ÷2 from the editor of the first Playlist clip halves that
  33858. // clip's length with the markers' beats; ÷2 on the grid clip's Clip page halves the grid clip
  33859. {
  33860. const auto lengthOf = [&offline] (int index) { return index < (int) offline.getSong().playlist.size() ? offline.getSong().playlist[(std::size_t) index].length : -1; };
  33861. const auto gridLength = [&offline] {
  33862. const auto& s = offline.getSong();
  33863. const auto* c = s.clipGrid ? lynx::launcher::clipAt (*s.clipGrid, 1, 0) : nullptr;
  33864. return c != nullptr ? c->length : (std::int64_t) -1;
  33865. };
  33866. const auto first = [&offline] {
  33867. const auto& s = offline.getSong();
  33868. for (int i = 0; i < (int) s.playlist.size(); ++i)
  33869. if (s.playlist[(std::size_t) i].kind == lynx::ClipKind::audio)
  33870. return i;
  33871. return -1;
  33872. }();
  33873. facts << "halve: playlist clip " << first << " length " << lengthOf (first);
  33874. if (first >= 0)
  33875. if (auto editor = lynx::makeAudioEditorPanel (offline, offline.getSong().playlist[(std::size_t) first].channel, first, true))
  33876. {
  33877. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  33878. offline.dispatchPendingMessages();
  33879. }
  33880. facts << " -> " << lengthOf (first) << "; grid clip length " << gridLength();
  33881. if (channel >= 0)
  33882. if (auto editor = lynx::makeAudioEditorPanel (offline, channel, -1, true))
  33883. {
  33884. lynx::setAudioEditorGridClip (*editor, 1, 0);
  33885. lynx::scaleAudioEditorTempoForSnapshot (*editor, 0.5);
  33886. offline.dispatchPendingMessages();
  33887. }
  33888. facts << " -> " << gridLength() << "\n";
  33889. ui.resized();
  33890. write (ui, "arrangement-halved");
  33891. // Duplicate Time over beats 4-8 holding the locator "Verse" (beat 4): a second "Verse" at beat 8
  33892. offline.editSong ([] (lynx::Song& s) { lynx::arrange::duplicateTime (s, 4 * lynx::ppq, 8 * lynx::ppq); });
  33893. offline.dispatchPendingMessages();
  33894. int verses = 0;
  33895. for (const auto& m : offline.getSong().markers())
  33896. verses += m.name == "Verse" ? 1 : 0;
  33897. facts << "duplicate time: locators named Verse " << verses << "\n";
  33898. write (ui, "arrangement-duplicated-time");
  33899. }
  33900. juce::File (prefix + "-facts.txt").replaceWithText (facts);
  33901. lynx::autolanes::setShown (false);
  33902. }
  33903. void runMtShot190fm (const juce::String& prefix)
  33904. {
  33905. lynx::AudioEngine offline (false);
  33906. offline.editSong ([] (lynx::Song& s) {
  33907. if (s.patterns.empty())
  33908. s.patterns.emplace_back();
  33909. s.patterns[0].notes.clear();
  33910. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  33911. s.currentPattern = 0;
  33912. }, false);
  33913. lynx::MidiToolsPanel panel (offline, [] {
  33914. lynx::MidiToolsPanel::Target t;
  33915. t.pattern = 0;
  33916. t.grid = lynx::ppq / 4;
  33917. t.channel = 0;
  33918. t.length = 4 * lynx::ppq; // one bar, no time selection
  33919. return t;
  33920. });
  33921. panel.setSize (lynx::MidiToolsPanel::panelWidth, lynx::MidiToolsPanel::panelHeight);
  33922. panel.setSection (lynx::MidiToolsPanel::generateSection);
  33923. panel.setGenerateShotSettingsForSnapshot();
  33924. const auto write = [&prefix] (const juce::Image& image, const juce::String& name) {
  33925. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33926. file.deleteFile();
  33927. juce::FileOutputStream out (file);
  33928. juce::PNGImageFormat().writeImageToStream (image, out);
  33929. };
  33930. std::vector<juce::Image> images;
  33931. juce::String checks;
  33932. for (int g = 0; g < lynx::midigen::Settings::toolCount; ++g)
  33933. {
  33934. panel.setGenerator (g);
  33935. const auto name = juce::String (lynx::midigen::toolName (g)).toLowerCase();
  33936. images.push_back (lynx::shot::paint (panel, lynx::theme::colour::bg2));
  33937. write (images.back(), "generate-" + name);
  33938. panel.generateNow();
  33939. offline.dispatchPendingMessages();
  33940. const auto made = (int) offline.getSong().patterns[0].notes.size();
  33941. offline.undo();
  33942. offline.dispatchPendingMessages();
  33943. const auto after = (int) offline.getSong().patterns[0].notes.size();
  33944. checks << name << ": generated " << made << " notes, after undo " << after << (made > 0 && after == 0 ? " OK" : " FAIL") << "\n";
  33945. }
  33946. // the five side by side (6 px apart, on the window's background)
  33947. const auto gap = juce::roundToInt (6.0f * lynx::shot::scale());
  33948. int width = gap, height = 0;
  33949. for (const auto& image : images)
  33950. {
  33951. width += image.getWidth() + gap;
  33952. height = std::max (height, image.getHeight());
  33953. }
  33954. juce::Image strip (juce::Image::RGB, width, height + 2 * gap, true);
  33955. {
  33956. juce::Graphics g (strip);
  33957. g.fillAll (lynx::theme::colour::bg0);
  33958. int x = gap;
  33959. for (const auto& image : images)
  33960. {
  33961. g.drawImageAt (image, x, gap);
  33962. x += image.getWidth() + gap;
  33963. }
  33964. }
  33965. write (strip, "generate-panels");
  33966. checks << "settings saved with the project: " << (offline.getSong().midiGenerate.stacksOptions.sequence.size() == 2 ? "OK" : "FAIL") << "\n";
  33967. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  33968. }
  33969. // Round 190hy: see --mpeshot190hy
  33970. void runMpeShot190hy (const juce::String& prefix)
  33971. {
  33972. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  33973. lynx::AudioEngine offline (false);
  33974. lynx::MainComponent ui (offline, false);
  33975. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  33976. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  33977. const auto write = [&prefix, &ui] (const char* name) {
  33978. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  33979. file.deleteFile();
  33980. juce::FileOutputStream out (file);
  33981. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  33982. };
  33983. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  33984. offline.editSong ([] (lynx::Song& s) {
  33985. if (s.channels.empty())
  33986. s.channels.resize (1);
  33987. s.channels[0].name = "MPE lead";
  33988. s.channels[0].mixerTrack = 1;
  33989. if (s.mixer.size() < 2)
  33990. s.mixer.resize (2);
  33991. while (s.patterns.empty())
  33992. s.patterns.emplace_back();
  33993. auto& p = s.patterns[0];
  33994. p.name = "MPE take";
  33995. p.notes.clear();
  33996. // four notes as an MPE controller plays them: a slide up an octave, a vibrato, a fall, a held chord tone
  33997. const auto note = [&p] (std::int64_t start, std::int64_t length, int key, lynx::NoteCurves c, float modX = 0.5f) {
  33998. lynx::Note n;
  33999. n.channel = 0;
  34000. n.start = start;
  34001. n.length = length;
  34002. n.key = key;
  34003. n.modX = modX;
  34004. n.curves = std::move (c);
  34005. p.notes.push_back (n);
  34006. };
  34007. const auto beat = (float) lynx::ppq;
  34008. lynx::NoteCurves glide;
  34009. glide.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { beat * 0.5f, 0.0f }, { beat * 1.5f, 1200.0f }, { beat * 2.0f, 1200.0f } };
  34010. glide.lane (lynx::NoteCurveLane::timbre) = { { 0.0f, 0.3f }, { beat * 2.0f, 0.85f } };
  34011. glide.lane (lynx::NoteCurveLane::pressure) = { { 0.0f, 0.2f }, { beat * 0.4f, 0.9f }, { beat * 1.6f, 0.7f }, { beat * 2.0f, 0.0f } };
  34012. note (0, 2 * lynx::ppq, 60, glide, 0.3f);
  34013. lynx::NoteCurves vibrato;
  34014. for (int k = 0; k <= 24; ++k)
  34015. vibrato.lane (lynx::NoteCurveLane::pitch).push_back ({ beat * 0.0833f * (float) k, k < 4 ? 0.0f : 40.0f * std::sin ((float) k * 1.5708f) });
  34016. vibrato.lane (lynx::NoteCurveLane::pressure) = { { 0.0f, 0.5f }, { beat * 1.0f, 0.95f }, { beat * 2.0f, 0.4f } };
  34017. note (2 * lynx::ppq, 2 * lynx::ppq, 67, vibrato);
  34018. lynx::NoteCurves fall;
  34019. fall.lane (lynx::NoteCurveLane::pitch) = { { 0.0f, 0.0f }, { beat * 0.75f, 0.0f }, { beat * 1.0f, -500.0f } };
  34020. fall.lane (lynx::NoteCurveLane::timbre) = { { 0.0f, 0.6f }, { beat * 1.0f, 0.2f } };
  34021. note (4 * lynx::ppq, lynx::ppq, 72, fall, 0.6f);
  34022. note (5 * lynx::ppq, 3 * lynx::ppq, 64, {}); // (a note without curves: its own values, dashed)
  34023. p.lengthTicks = 8 * lynx::ppq;
  34024. }, false);
  34025. offline.dispatchPendingMessages();
  34026. juce::String checks;
  34027. auto& roll = ui.getPianoRollForSnapshot();
  34028. ui.selectTabForSnapshot (1);
  34029. roll.selectMidiToolResult ({ 0 });
  34030. roll.scrollToNotes();
  34031. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneMpePitch, "pitch" },
  34032. { lynx::PianoRollComponent::laneMpeSlide, "slide" },
  34033. { lynx::PianoRollComponent::laneMpePressure, "pressure" } })
  34034. {
  34035. roll.setLaneForSnapshot (lane);
  34036. offline.dispatchPendingMessages();
  34037. write (name);
  34038. checks << "lane " << name << ": areas " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  34039. }
  34040. roll.setLaneForSnapshot (lynx::PianoRollComponent::laneVelocity);
  34041. int curved = 0;
  34042. for (const auto& n : offline.getSong().patterns[0].notes)
  34043. curved += n.curves.has() ? 1 : 0;
  34044. checks << "notes with curves: " << curved << " of " << (int) offline.getSong().patterns[0].notes.size() << "\n";
  34045. // the Clip-launch layout: the clip's Notes tab, then its MPE tab (Live 11+'s note expression lanes)
  34046. ui.selectTabForSnapshot (2);
  34047. lynx::DetailView::shownSetting = true;
  34048. lynx::DetailView::devicesPage = false;
  34049. ui.setClipLaunchWorkflow (true);
  34050. offline.editSong ([] (lynx::Song& s) {
  34051. lynx::Clip clip;
  34052. clip.pattern = 0;
  34053. clip.length = 8 * lynx::ppq;
  34054. lynx::launcher::setClip (s, 0, 0, clip);
  34055. }, false);
  34056. offline.dispatchPendingMessages();
  34057. if (auto* detail = ui.getDetailViewForSnapshot())
  34058. {
  34059. detail->showSelection (0, 0);
  34060. detail->setPage (lynx::DetailView::Page::clip);
  34061. detail->setClipTab (false);
  34062. offline.dispatchPendingMessages();
  34063. roll.scrollToNotes();
  34064. write ("clip-notes");
  34065. checks << "clip notes tab: mpe view " << (roll.isMpeView() ? 1 : 0) << "\n";
  34066. detail->setMpeTab();
  34067. offline.dispatchPendingMessages();
  34068. roll.selectMidiToolResult ({ 0 });
  34069. roll.scrollToNotes();
  34070. write ("clip-mpe");
  34071. checks << "clip MPE tab: mpe view " << (roll.isMpeView() ? 1 : 0) << ", lanes " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  34072. // round 190jd (Live 12.4's MPE tab): the value ghost point on note 1's Pressure line, the "Show Lane:" menu,
  34073. // then all four lanes shown (Slide, Pressure, Velocity, Release Velocity)
  34074. checks << "ghost on the Pressure line: '" << roll.hoverMpeLineForSnapshot (lynx::PianoRollComponent::laneMpePressure, (double) lynx::ppq) << "'\n";
  34075. write ("clip-mpe-ghost190jd");
  34076. roll.hoverMpeLineForSnapshot (0, 0.0);
  34077. saveMenus (juce::StringArray { "MPE tab: Show Lane" }, std::vector<juce::PopupMenu> { roll.getMpeLaneMenuForSnapshot() },
  34078. prefix + "-clip-mpe-showlane190jd.png");
  34079. roll.setMpeLanesForSnapshot (lynx::mpetab::allLanes);
  34080. offline.dispatchPendingMessages();
  34081. write ("clip-mpe-lanes4-190jd");
  34082. checks << "four lanes: " << (int) roll.mpeLaneAreasForTests().size() << "\n";
  34083. roll.setMpeLanesForSnapshot (lynx::mpetab::defaultLanes);
  34084. detail->setClipTab (false);
  34085. offline.dispatchPendingMessages();
  34086. checks << "back to Notes: mpe view " << (roll.isMpeView() ? 1 : 0) << "\n";
  34087. }
  34088. else
  34089. checks << "no detail view\n";
  34090. lynx::shot::file (juce::File (prefix + "-checks.txt")).replaceWithText (checks);
  34091. }
  34092. // round 190kk: Live's Erosion / Vinyl Distortion / Corpus imported, their LYNX engines on the Device View
  34093. void runMeldShot190ko (const juce::String& prefix, const juce::String& meld, const juce::String& time, const juce::String& resonator)
  34094. {
  34095. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34096. lynx::AudioEngine offline (false);
  34097. lynx::MainComponent ui (offline, false);
  34098. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  34099. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  34100. juce::String checks;
  34101. // a Live device preset (.adv, gzip) → its device element's text
  34102. const auto deviceOf = [] (const juce::String& path, lynx::xml::Document& doc) {
  34103. juce::MemoryBlock raw;
  34104. juce::File (path).loadFileAsData (raw);
  34105. juce::MemoryInputStream in (raw, false);
  34106. juce::GZIPDecompressorInputStream gz (&in, false, juce::GZIPDecompressorInputStream::gzipFormat);
  34107. const auto text = gz.readEntireStreamAsString();
  34108. if (! doc.parse (text.toStdString()))
  34109. return lynx::xml::Element();
  34110. const auto kids = doc.root().children();
  34111. return kids.empty() ? lynx::xml::Element() : kids.front();
  34112. };
  34113. lynx::ChannelDef braid;
  34114. braid.instrument = lynx::InstrumentKind::braid;
  34115. braid.name = "Meld";
  34116. {
  34117. lynx::xml::Document doc;
  34118. lynx::alsdev::Notes notes;
  34119. const auto d = deviceOf (meld, doc);
  34120. const auto ok = (bool) d && lynx::alsdev::meldToBraid (d, braid, notes);
  34121. checks << (ok ? "ok " : "FAIL ") << "Meld -> Braid: " << meld << "\n";
  34122. braid.name = juce::File (meld).getFileNameWithoutExtension().toStdString();
  34123. }
  34124. std::vector<lynx::EffectSlot> slots;
  34125. for (const auto& path : { time, resonator })
  34126. {
  34127. lynx::xml::Document doc;
  34128. const auto d = deviceOf (path, doc);
  34129. if (const auto t = d ? lynx::alsdev::effectFromLiveDevice (d) : std::nullopt)
  34130. {
  34131. slots.push_back (t->slot);
  34132. checks << "ok " << t->from << " -> " << t->to << ": " << path << "\n";
  34133. }
  34134. else
  34135. checks << "FAIL NOT TRANSLATED: " << path << "\n";
  34136. }
  34137. offline.editSong ([&slots, &braid] (lynx::Song& s) {
  34138. if (s.channels.empty())
  34139. s.channels.resize (1);
  34140. braid.mixerTrack = 2;
  34141. s.channels[0] = braid;
  34142. if (s.mixer.size() < 3)
  34143. s.mixer.resize (3);
  34144. s.mixer[2].name = braid.name;
  34145. s.mixer[2].effects = slots;
  34146. while (s.patterns.empty())
  34147. s.patterns.emplace_back();
  34148. s.patterns[0].name = "Chords";
  34149. s.patterns[0].notes.clear();
  34150. for (const int key : { 48, 52, 55 })
  34151. {
  34152. lynx::Note note;
  34153. note.channel = 0;
  34154. note.start = 0;
  34155. note.length = 2 * lynx::ppq;
  34156. note.key = key;
  34157. s.patterns[0].notes.push_back (note);
  34158. }
  34159. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  34160. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  34161. s.playlistTracks[1].name = braid.name;
  34162. }, false);
  34163. offline.dispatchPendingMessages();
  34164. ui.setVisible (true);
  34165. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  34166. ui.selectTabForSnapshot (2);
  34167. ui.setClipLaunchWorkflow (true);
  34168. offline.editSong ([] (lynx::Song& s) {
  34169. lynx::Clip clip;
  34170. clip.pattern = 0;
  34171. clip.length = 4 * lynx::ppq;
  34172. lynx::launcher::setClip (s, 1, 0, clip);
  34173. }, false);
  34174. offline.dispatchPendingMessages();
  34175. if (auto* detail = ui.getDetailViewForSnapshot())
  34176. {
  34177. detail->showSelection (1, 0);
  34178. detail->setPage (lynx::DetailView::Page::devices);
  34179. offline.dispatchPendingMessages();
  34180. const auto file = lynx::shot::file (juce::File (prefix + "-devices.png"));
  34181. file.deleteFile();
  34182. juce::FileOutputStream out (file);
  34183. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  34184. checks << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << "\n";
  34185. }
  34186. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  34187. }
  34188. void runLiveDevShot190kk (const juce::String& prefix)
  34189. {
  34190. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34191. lynx::AudioEngine offline (false);
  34192. lynx::MainComponent ui (offline, false);
  34193. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  34194. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  34195. const auto par = [] (const char* name, double v) { return juce::String ("<") + name + "><Manual Value=\"" + juce::String (v) + "\" /></" + name + ">"; };
  34196. // the Core Library presets' values (Erosion "Fizzle", Vinyl Distortion "Crack" with Tracing on, Corpus "Pipe Resonator" closed)
  34197. const juce::String erosion = "<Erosion2 Id=\"1\"><On><Manual Value=\"true\" /></On>" + par ("Amount", 0.9) + par ("Frequency", 16000) +
  34198. par ("FilterWidth", 1.734) + par ("NoiseBlend", 1) + par ("StereoWidth", 1) + "</Erosion2>";
  34199. const juce::String vinyl = "<Vinyl Id=\"1\"><On><Manual Value=\"true\" /></On><Band1On><Manual Value=\"true\" /></Band1On>" + par ("Gain1", 0.5) +
  34200. par ("BandFreq1", 7500) + par ("BandQ1", 3) + "<Band2On><Manual Value=\"false\" /></Band2On>" + par ("Gain2", 0.35) +
  34201. par ("BandFreq2", 5366) + par ("BandQ2", 0.32) + par ("Drive", 1) + par ("SoftHard", 0) + par ("NormalMono", 0) +
  34202. par ("CracleDensity", 50) + par ("CracleVolume", 1) + "</Vinyl>";
  34203. juce::String corpus = "<Corpus Id=\"1\"><On><Manual Value=\"true\" /></On><FilterOn><Manual Value=\"false\" /></FilterOn>";
  34204. for (const auto& [k, v] : std::initializer_list<std::pair<const char*, double>> { { "ResonanceType", 5 }, { "ResonatorQuality", 3 },
  34205. { "Frequency", 0.4603 }, { "Decay", 0.6032 }, { "FreqDamping", 0 }, { "AmpFreq", 0 }, { "Inharmonics", 0 }, { "Radius", 0.8642 },
  34206. { "TubeOpening", 1 }, { "Ratio", 0.5 }, { "ExcitationX", 0.5 }, { "ListeningXL", 0.1 }, { "ListeningXR", 0.9 }, { "Detune", 0.047 },
  34207. { "Drive", 0.405 }, { "Bleed", 0 }, { "DryWet", 0.696 }, { "StereoWidth", 1 }, { "FilterMidFreq", 1000 }, { "FilterBandWidth", 4 } })
  34208. corpus += par (k, v);
  34209. corpus += "</Corpus>";
  34210. std::vector<lynx::EffectSlot> slots;
  34211. juce::String checks;
  34212. for (const auto& text : { erosion, vinyl, corpus })
  34213. {
  34214. lynx::xml::Document doc;
  34215. doc.parse (text.toStdString());
  34216. if (const auto t = lynx::alsdev::effectFromLiveDevice (doc.root()))
  34217. {
  34218. slots.push_back (t->slot);
  34219. checks << t->from << " -> " << t->to << "\n";
  34220. }
  34221. else
  34222. checks << "NOT TRANSLATED\n";
  34223. }
  34224. offline.editSong ([&slots] (lynx::Song& s) {
  34225. if (s.channels.empty())
  34226. s.channels.resize (1);
  34227. s.channels[0].name = "Drums";
  34228. s.channels[0].mixerTrack = 2;
  34229. if (s.mixer.size() < 3)
  34230. s.mixer.resize (3);
  34231. s.mixer[2].name = "Drums";
  34232. s.mixer[2].effects = slots;
  34233. while (s.patterns.empty())
  34234. s.patterns.emplace_back();
  34235. s.patterns[0].name = "Beat";
  34236. s.patterns[0].notes.clear();
  34237. for (int n = 0; n < 4; ++n)
  34238. {
  34239. lynx::Note note;
  34240. note.channel = 0;
  34241. note.start = n * lynx::ppq;
  34242. note.key = 36;
  34243. s.patterns[0].notes.push_back (note);
  34244. }
  34245. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  34246. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 2));
  34247. s.playlistTracks[1].name = "Drums";
  34248. }, false);
  34249. offline.dispatchPendingMessages();
  34250. ui.setVisible (true);
  34251. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  34252. ui.selectTabForSnapshot (2);
  34253. ui.setClipLaunchWorkflow (true);
  34254. offline.editSong ([] (lynx::Song& s) {
  34255. lynx::Clip clip;
  34256. clip.pattern = 0;
  34257. clip.length = 4 * lynx::ppq;
  34258. lynx::launcher::setClip (s, 1, 0, clip);
  34259. }, false);
  34260. offline.dispatchPendingMessages();
  34261. if (auto* detail = ui.getDetailViewForSnapshot())
  34262. {
  34263. detail->showSelection (1, 0);
  34264. detail->setPage (lynx::DetailView::Page::devices);
  34265. const auto file = lynx::shot::file (juce::File (prefix + "-devices.png"));
  34266. file.deleteFile();
  34267. juce::FileOutputStream out (file);
  34268. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  34269. checks << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << "\n";
  34270. }
  34271. juce::File (prefix + "-checks.txt").replaceWithText (checks);
  34272. }
  34273. void runDetailShot (const juce::String& prefix)
  34274. {
  34275. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34276. lynx::AudioEngine offline (false);
  34277. lynx::MainComponent ui (offline, false);
  34278. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  34279. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  34280. const auto write = [&prefix, &ui] (const char* name) {
  34281. const auto file = lynx::shot::file (juce::File (prefix + "-" + name + ".png"));
  34282. file.deleteFile();
  34283. juce::FileOutputStream out (file);
  34284. juce::PNGImageFormat().writeImageToStream (lynx::shot::snapshot (ui), out);
  34285. };
  34286. ui.setVisible (true); // (not on the desktop: only so the Clip page sees itself shown and docks the Piano roll)
  34287. lynx::DetailView::shownSetting = lynx::DetailView::devicesPage = true;
  34288. ui.selectTabForSnapshot (2); // the Playlist panel, maximized
  34289. offline.editSong ([] (lynx::Song& s) {
  34290. if (s.channels.size() < 2)
  34291. s.channels.resize (2);
  34292. s.channels[0].name = "Bass synth";
  34293. s.channels[0].mixerTrack = 2;
  34294. s.channels[1].mixerTrack = 3;
  34295. if (s.mixer.size() < 4)
  34296. s.mixer.resize (4);
  34297. s.mixer[2].name = "Bass";
  34298. s.mixer[2].effects.clear();
  34299. for (auto kind : { lynx::EffectKind::eq, lynx::EffectKind::compressor, lynx::EffectKind::reverb, lynx::EffectKind::delay })
  34300. {
  34301. lynx::EffectSlot fx;
  34302. fx.kind = kind;
  34303. const auto& info = lynx::effectInfo (kind);
  34304. for (std::size_t k = 0; k < info.params.size() && k < fx.params.size(); ++k)
  34305. fx.params[k] = info.params[k].defaultValue;
  34306. fx.enabled = kind != lynx::EffectKind::compressor; // one switched off
  34307. s.mixer[2].effects.push_back (fx);
  34308. }
  34309. while (s.patterns.size() < 2)
  34310. s.patterns.emplace_back();
  34311. s.patterns[0].name = "Bass line";
  34312. s.patterns[0].notes.clear();
  34313. for (int n = 0; n < 4; ++n)
  34314. {
  34315. lynx::Note note;
  34316. note.channel = 0;
  34317. note.start = n * lynx::ppq;
  34318. note.key = 36 + (n % 2) * 7;
  34319. s.patterns[0].notes.push_back (note);
  34320. }
  34321. s.patterns[0].lengthTicks = 4 * lynx::ppq;
  34322. lynx::PatternEvents lane; // a volume swell for the Envelopes tab (slice 3)
  34323. lane.target = lynx::AutomationTarget { lynx::AutomationTargetKind::channelVolume, 0 };
  34324. for (int e = 0; e < 16; ++e)
  34325. lane.events.push_back ({ e * lynx::ppq / 4, 0.3f + 0.6f * (float) e / 15.0f });
  34326. s.patterns[0].events = { lane };
  34327. s.playlistTracks.resize (std::max<std::size_t> (s.playlistTracks.size(), 3));
  34328. s.playlistTracks[1].name = "Bass";
  34329. }, false);
  34330. offline.dispatchPendingMessages();
  34331. write ("pattern"); // Pattern workflow: no detail view exists
  34332. ui.setClipLaunchWorkflow (true);
  34333. offline.editSong ([] (lynx::Song& s) {
  34334. lynx::Clip clip;
  34335. clip.pattern = 0;
  34336. clip.length = 4 * lynx::ppq;
  34337. lynx::launcher::setClip (s, 1, 0, clip);
  34338. }, false);
  34339. offline.dispatchPendingMessages();
  34340. juce::String counts;
  34341. if (auto* detail = ui.getDetailViewForSnapshot())
  34342. {
  34343. detail->showSelection (1, 0);
  34344. detail->setPage (lynx::DetailView::Page::devices);
  34345. write ("devices");
  34346. counts << "cards " << detail->cardCountForCheck() << ", insert " << detail->chainInsertForCheck() << ", channel " << detail->chainChannelForCheck() << "\n";
  34347. detail->toggleFoldForCheck (3); // the reverb (card 0 is the instrument)
  34348. write ("folded");
  34349. counts << "folded card 3: " << (detail->isFoldedForCheck (3) ? 1 : 0) << "\n";
  34350. detail->showSelection (2, 0); // an empty track
  34351. write ("empty-track");
  34352. detail->showSelection (1, 0);
  34353. detail->setPage (lynx::DetailView::Page::clip);
  34354. offline.dispatchPendingMessages();
  34355. ui.getPianoRollForSnapshot().scrollToNotes(); // (the app does it on the message loop, which this shot doesn't run)
  34356. write ("clip"); // slice 2: the Piano roll docked here
  34357. {
  34358. // round 190s: the Transform panel with each MIDI tool, then Arpeggiate applied (and undone again)
  34359. auto& tools = detail->midiToolsForSnapshot();
  34360. for (int t = 0; t < lynx::MidiToolsPanel::toolCount; ++t)
  34361. {
  34362. tools.setTool (t);
  34363. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase()).toRawUTF8());
  34364. }
  34365. // round 190aa: the pages again with the settings of the Live shots they are compared with
  34366. tools.setAuto (false);
  34367. tools.setLiveShotSettingsForSnapshot();
  34368. for (int t : { (int) lynx::MidiToolsPanel::chop, (int) lynx::MidiToolsPanel::quantize, (int) lynx::MidiToolsPanel::timeWarp })
  34369. {
  34370. tools.setTool (t);
  34371. write (("clip-mt-" + juce::String (lynx::MidiToolsPanel::toolName (t)).toLowerCase() + "-set").toRawUTF8());
  34372. }
  34373. tools.setAuto (true);
  34374. tools.setTool (lynx::MidiToolsPanel::arpeggiate);
  34375. tools.transformNow();
  34376. offline.dispatchPendingMessages();
  34377. write ("clip-mt-applied");
  34378. counts << "midi tools: arpeggiate made " << (int) offline.getSong().patterns[0].notes.size() << " notes of 4\n";
  34379. offline.undo();
  34380. offline.dispatchPendingMessages();
  34381. counts << "midi tools: undo gives " << (int) offline.getSong().patterns[0].notes.size() << " notes\n";
  34382. }
  34383. counts << "piano roll docked: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  34384. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() == detail ? 1 : 0) << "\n";
  34385. detail->setClipTab (true); // slice 3: the pattern's events in the Envelopes tab
  34386. offline.dispatchPendingMessages();
  34387. write ("envelopes");
  34388. detail->setClipTab (false);
  34389. detail->setPage (lynx::DetailView::Page::devices);
  34390. // round 183c-card: an Audio Effect Rack in the chain draws as its own card (the rack's view, Rand / Map in its
  34391. // title bar), as Live's Device View shows a rack
  34392. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.insert (s.mixer[2].effects.begin() + 1, shotRack()); }, false);
  34393. offline.dispatchPendingMessages();
  34394. detail->showSelection (2, 0);
  34395. detail->showSelection (1, 0);
  34396. write ("devices-rack");
  34397. counts << "rack card: cards " << detail->cardCountForCheck() << "\n";
  34398. offline.editSong ([] (lynx::Song& s) { s.mixer[2].effects.erase (s.mixer[2].effects.begin() + 1); }, false);
  34399. offline.dispatchPendingMessages();
  34400. counts << "piano roll back in its panel: " << (ui.getPianoRollForSnapshot().getParentComponent() != nullptr
  34401. && ui.getPianoRollForSnapshot().getParentComponent()->getParentComponent() != detail ? 1 : 0) << "\n";
  34402. }
  34403. else
  34404. counts << "no detail view\n";
  34405. ui.setClipLaunchWorkflow (false);
  34406. offline.dispatchPendingMessages();
  34407. write ("pattern-after");
  34408. juce::File (prefix + "-counts.txt").replaceWithText (counts);
  34409. }
  34410. void runPerfShot (const juce::String& prefix, const juce::String& projectPath)
  34411. {
  34412. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34413. lynx::AudioEngine offline (false);
  34414. {
  34415. lynx::MainComponent ui (offline, false);
  34416. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1600x900"), "x", "");
  34417. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  34418. if (projectPath.isNotEmpty())
  34419. ui.openFile (juce::File (projectPath));
  34420. offline.dispatchPendingMessages();
  34421. // LYNX_PERFSHOT_PREPARE=1: Tools › Macros › Prepare for performance mode first (16 one-bar columns)
  34422. if (juce::SystemStats::getEnvironmentVariable ("LYNX_PERFSHOT_PREPARE", {}) == "1")
  34423. offline.editSong ([] (lynx::Song& s) { lynx::perf::prepareForPerformance (s, 16, 4 * lynx::ppq); }, false);
  34424. offline.editSong ([] (lynx::Song& s) { s.performanceMode = true; s.mode = lynx::PlayMode::song; }, false);
  34425. offline.dispatchPendingMessages();
  34426. // what the Player would publish: on each of the first tracks with zone clips, one clip playing (part way)
  34427. // and on every other one the next clip waiting for its sync point
  34428. const auto& song = offline.getSong();
  34429. auto& live = offline.performanceStateForSnapshot();
  34430. const auto zone = lynx::perf::zoneClips (song);
  34431. int lastTrack = -1, launched = 0;
  34432. for (const auto index : zone)
  34433. {
  34434. const auto& c = song.playlist[(std::size_t) index];
  34435. if (c.track == lastTrack || c.track >= lynx::perf::maxTracks)
  34436. continue;
  34437. lastTrack = c.track;
  34438. std::int64_t clips[64];
  34439. const auto n = lynx::perf::trackZoneClips (song, zone, c.track, clips, 64);
  34440. auto& view = live.tracks[(std::size_t) c.track];
  34441. view.playing.store (clips[(std::size_t) ((launched % 3) % n)]);
  34442. view.progress.store (0.2f + 0.15f * (float) (launched % 5));
  34443. if (launched % 2 == 1 && n > 1)
  34444. view.pending.store (clips[(std::size_t) ((launched % 3 + 1) % n)]);
  34445. ++launched;
  34446. }
  34447. live.anyPlaying.store (launched > 0);
  34448. ui.selectTabForSnapshot (2);
  34449. offline.dispatchPendingMessages();
  34450. auto& playlist = ui.getPlaylistForSnapshot();
  34451. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-song.png");
  34452. playlist.runAction ("playlist.zoomPerformance"); // as FL opens these demos: the zone fills the view
  34453. offline.dispatchPendingMessages();
  34454. saveSnapshot (ui, prefix + "-playlist.png");
  34455. savePng (lynx::shot::snapshot (playlist), prefix + "-playlist-only.png");
  34456. // patcherize: the first insert with effects (all of them) and the first channel that can be
  34457. auto patched = offline.getSong();
  34458. for (int t = 0; t < (int) patched.mixer.size(); ++t)
  34459. if (lynx::patcherize::slotsForAll (patched, t).size() > 1)
  34460. {
  34461. lynx::patcherize::patcherizeSlots (patched, t, 0, true);
  34462. break;
  34463. }
  34464. for (int c = 0; c < (int) patched.channels.size(); ++c)
  34465. if (lynx::patcherize::patcherizeChannel (patched, c))
  34466. break;
  34467. juce::String error;
  34468. lynx::ProjectFile::save (patched, juce::File (prefix + "-patcherized.lynx"), error);
  34469. }
  34470. }
  34471. void runPatcherShot (const juce::String& prefix, const juce::String& projectPath)
  34472. {
  34473. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34474. lynx::AudioEngine offline (false);
  34475. {
  34476. lynx::MainComponent ui (offline, false);
  34477. ui.setSize (1280, 720);
  34478. if (projectPath.isNotEmpty())
  34479. ui.openFile (juce::File (projectPath));
  34480. else
  34481. {
  34482. auto song = lynx::Song::makeDefault();
  34483. song.mixer.resize (4);
  34484. auto slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
  34485. slot.patcher.wires.clear();
  34486. for (auto [kind, x, y] : { std::tuple { lynx::EffectKind::frequencySplitter, 200.0f, 60.0f }, { lynx::EffectKind::reverb, 420.0f, 0.0f },
  34487. { lynx::EffectKind::fruityDelay3, 420.0f, 120.0f }, { lynx::EffectKind::peakController, 200.0f, 260.0f } })
  34488. {
  34489. lynx::PatchNode n;
  34490. n.effect = lynx::makeEffectSlot (kind);
  34491. n.x = x;
  34492. n.y = y;
  34493. slot.patcher.nodes.push_back (n);
  34494. }
  34495. { // round 165c: a Hardware Insert node (its editor opens from the node)
  34496. lynx::PatchNode n;
  34497. n.effect = lynx::makeEffectSlot (lynx::EffectKind::hardwareInsert);
  34498. n.x = 420.0f, n.y = 260.0f;
  34499. slot.patcher.nodes.push_back (n);
  34500. }
  34501. auto wire = [&] (int from, int fromPort, int to, int toPort, float gain = 1.0f, lynx::PatchWire::Kind kind = lynx::PatchWire::Kind::audio) {
  34502. lynx::PatchWire w;
  34503. w.kind = kind;
  34504. w.from = from, w.fromPort = fromPort, w.to = to, w.toPort = toPort, w.gain = gain;
  34505. slot.patcher.wires.push_back (w);
  34506. };
  34507. wire (lynx::patchFromHost, 0, 0, 0);
  34508. wire (0, 1, 1, 0);
  34509. wire (0, 3, 2, 0, 0.5f);
  34510. wire (1, 0, lynx::patchToHost, 0);
  34511. wire (2, 0, lynx::patchToHost, 0);
  34512. wire (lynx::patchFromHost, 1, 3, 0);
  34513. wire (3, 1, 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  34514. wire (0, 2, lynx::patchToHost, 1, 0.7f);
  34515. // round 171b (issue #65): a Surface knob on the reverb's parameter input 1, the reverb's parameter 0 out to
  34516. // the delay's parameter input 2 (FL's Inputs / Outputs › Parameters)
  34517. {
  34518. lynx::SurfaceControl knob;
  34519. knob.name = "Knob 1";
  34520. knob.value = 0.6f;
  34521. slot.patcher.surface = { knob };
  34522. slot.patcher.surfaceX = 200.0f, slot.patcher.surfaceY = 380.0f;
  34523. lynx::patcher::setParamInput (slot.patcher, 1, 1, true, "Reverb - 2");
  34524. lynx::patcher::setParamOutput (slot.patcher, 1, 0, true);
  34525. lynx::patcher::setParamInput (slot.patcher, 2, 2, true, "Delay - 3");
  34526. wire (lynx::patchSurface, 0, 1, 1, 1.0f, lynx::PatchWire::Kind::control);
  34527. wire (1, lynx::patchParamOutput (0), 2, 2, 1.0f, lynx::PatchWire::Kind::control);
  34528. }
  34529. slot.patcher.outputTracks = { 3 };
  34530. slot.patcher.inputX = -20.0f;
  34531. slot.patcher.outputX = 660.0f;
  34532. song.mixer[1].effects = { slot };
  34533. lynx::ChannelDef ch;
  34534. ch.name = "Patcher";
  34535. ch.instrument = lynx::InstrumentKind::patcher;
  34536. lynx::PatchNode synth, chorus;
  34537. synth.generator = true;
  34538. synth.channel.instrument = lynx::InstrumentKind::synth;
  34539. synth.channel.name = "Synth";
  34540. synth.x = 220.0f;
  34541. chorus.effect = lynx::makeEffectSlot (lynx::EffectKind::chorus);
  34542. chorus.x = 420.0f;
  34543. // round 162: a MIDI Out node between the "MIDI port 5" pin and "To LYNX" MIDI port 3, an Envelope Controller
  34544. // on the notes moving the chorus
  34545. lynx::PatchNode midiOut, envelope;
  34546. midiOut.generator = envelope.generator = true;
  34547. midiOut.channel.instrument = lynx::InstrumentKind::midiOut;
  34548. midiOut.channel.name = "MIDI Out";
  34549. lynx::midictl::writeMidiOut (midiOut.channel.pluginState, { 3, 0, 0, -1, -1 });
  34550. midiOut.x = 220.0f, midiOut.y = 160.0f;
  34551. envelope.channel.instrument = lynx::InstrumentKind::controller;
  34552. envelope.channel.name = "Envelope Controller";
  34553. envelope.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
  34554. envelope.x = 220.0f, envelope.y = 260.0f;
  34555. lynx::PatchNode osc; // round 164f: an FL engine node (its editor opens from the node)
  34556. osc.generator = true;
  34557. osc.channel = lynx::natives::makeChannel (lynx::InstrumentKind::threeosc, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  34558. osc.channel.instrument = lynx::InstrumentKind::threeosc;
  34559. osc.channel.name = "3x Osc";
  34560. osc.x = 420.0f, osc.y = 260.0f;
  34561. // round 165c: Keyboard Controller, SoundFont player, Granulizer and Dashboard nodes (their editors open from the node)
  34562. lynx::PatchNode keys, soundfont, granulizer, dashboard;
  34563. keys.generator = soundfont.generator = granulizer.generator = dashboard.generator = true;
  34564. keys.channel.instrument = lynx::InstrumentKind::controller;
  34565. keys.channel.name = "Keyboard Controller";
  34566. {
  34567. lynx::KeyboardControllerData ramp;
  34568. for (std::size_t k = 0; k < ramp.keys.size(); ++k)
  34569. ramp.keys[k] = (float) k / (float) (ramp.keys.size() - 1);
  34570. lynx::writeKeyboardController (ramp, keys.channel.controllerState);
  34571. }
  34572. soundfont.channel = lynx::sf::makeChannel();
  34573. granulizer.channel = lynx::natives::makeChannel (lynx::InstrumentKind::granulizer, lynx::flStudioAccess()).value_or (lynx::ChannelDef {});
  34574. granulizer.channel.instrument = lynx::InstrumentKind::granulizer;
  34575. granulizer.channel.name = "Fruity Granulizer";
  34576. dashboard.channel.instrument = lynx::InstrumentKind::dashboard;
  34577. dashboard.channel.name = "Dashboard";
  34578. dashboard.channel.patcher.surface = lynx::surface::starterControls();
  34579. keys.x = 20.0f, keys.y = 440.0f;
  34580. soundfont.x = 220.0f, soundfont.y = 440.0f;
  34581. granulizer.x = 420.0f, granulizer.y = 440.0f;
  34582. dashboard.x = 20.0f, dashboard.y = 540.0f;
  34583. // and a Layer node playing the SoundFont and Granulizer nodes on its Children pin (crossfaded)
  34584. lynx::PatchNode layerNode;
  34585. layerNode.generator = true;
  34586. layerNode.channel.instrument = lynx::InstrumentKind::layer;
  34587. layerNode.channel.name = "Layer";
  34588. layerNode.channel.layer.crossfade = true;
  34589. layerNode.channel.layer.fade = 0.35f;
  34590. layerNode.x = 220.0f, layerNode.y = 540.0f;
  34591. ch.patcher.nodes = { synth, chorus, midiOut, envelope, osc, keys, soundfont, granulizer, dashboard, layerNode };
  34592. lynx::PatchWire notes, a, b, portIn, portOut, envNotes, envControl;
  34593. notes.kind = lynx::PatchWire::Kind::midi, notes.to = 0;
  34594. a.from = 0, a.to = 1;
  34595. b.from = 1;
  34596. portIn.kind = lynx::PatchWire::Kind::midi, portIn.fromPort = lynx::patchMidiPortPin (5), portIn.to = 2;
  34597. portOut.kind = lynx::PatchWire::Kind::midi, portOut.from = 2, portOut.to = lynx::patchToHost, portOut.toPort = 3;
  34598. envNotes.kind = lynx::PatchWire::Kind::midi, envNotes.to = 3;
  34599. envControl.kind = lynx::PatchWire::Kind::control, envControl.from = 3, envControl.to = 1, envControl.toPort = 0;
  34600. lynx::PatchWire oscNotes, oscOut;
  34601. oscNotes.kind = lynx::PatchWire::Kind::midi, oscNotes.to = 4;
  34602. oscOut.from = 4;
  34603. lynx::PatchWire layerNotes, layerToFont, layerToGrains, fontOut, grainsOut;
  34604. layerNotes.kind = layerToFont.kind = layerToGrains.kind = lynx::PatchWire::Kind::midi;
  34605. layerNotes.to = 9;
  34606. layerToFont.from = 9, layerToFont.to = 6;
  34607. layerToGrains.from = 9, layerToGrains.to = 7;
  34608. fontOut.from = 6;
  34609. grainsOut.from = 7;
  34610. ch.patcher.wires = { notes, a, b, portIn, portOut, envNotes, envControl, oscNotes, oscOut, layerNotes, layerToFont, layerToGrains, fontOut, grainsOut };
  34611. ch.patcher.fromMidiPorts = { 1, 5 };
  34612. ch.patcher.toMidiPorts = { 3 };
  34613. ch.patcher.outputX = 640.0f;
  34614. song.channels.push_back (ch);
  34615. // LYNX_PATCHERSHOT_SAVE=file.lynx: the demo as a project (a GUI check of the same Patchers, round 164f)
  34616. if (const auto save = juce::SystemStats::getEnvironmentVariable ("LYNX_PATCHERSHOT_SAVE", {}); save.isNotEmpty())
  34617. {
  34618. if (! song.patterns.empty())
  34619. for (int k = 0; k < 4; ++k)
  34620. 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 });
  34621. juce::String error;
  34622. lynx::ProjectFile::save (song, juce::File (save), error);
  34623. // round 171b: the saved Patchers come back the same (parameter ports, event cables, published)
  34624. juce::String report;
  34625. if (const auto loaded = lynx::ProjectFile::load (juce::File (save), error))
  34626. {
  34627. const auto same = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty()
  34628. && loaded->mixer[1].effects[0].patcher == song.mixer[1].effects[0].patcher;
  34629. const auto& d = loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty() ? loaded->mixer[1].effects[0].patcher : lynx::PatcherDoc {};
  34630. report << "patcher round trip: " << (same ? "OK" : "DIFFERENT") << "\n";
  34631. if (! same && loaded->mixer.size() > 1 && ! loaded->mixer[1].effects.empty())
  34632. {
  34633. const auto& a = song.mixer[1].effects[0].patcher;
  34634. report << "wires " << (a.wires == d.wires ? "same" : "differ") << ", published " << (a.published == d.published ? "same" : "differ")
  34635. << ", surface " << (a.surface == d.surface ? "same" : "differ") << "\n";
  34636. for (std::size_t n = 0; n < std::min (a.nodes.size(), d.nodes.size()); ++n)
  34637. if (! (a.nodes[n] == d.nodes[n]))
  34638. report << "node " << (int) n << " differs: ports " << (a.nodes[n].paramIns == d.nodes[n].paramIns && a.nodes[n].paramOuts == d.nodes[n].paramOuts ? "same" : "differ")
  34639. << ", effect " << (a.nodes[n].effect == d.nodes[n].effect ? "same" : "differ") << ", xy "
  34640. << (a.nodes[n].x == d.nodes[n].x && a.nodes[n].y == d.nodes[n].y ? "same" : "differ") << "\n";
  34641. }
  34642. for (int n = 0; n < (int) d.nodes.size(); ++n)
  34643. report << "node " << n << " paramIns " << (int) d.nodes[(std::size_t) n].paramIns.size() << " paramOuts "
  34644. << (int) d.nodes[(std::size_t) n].paramOuts.size() << "\n";
  34645. for (const auto& w : d.wires)
  34646. if (w.kind == lynx::PatchWire::Kind::control)
  34647. report << "control " << w.from << ":" << w.fromPort << " -> " << w.to << ":" << w.toPort << "\n";
  34648. for (const auto& p : d.published)
  34649. report << "published " << p.node << ":" << p.param << " " << juce::String::fromUTF8 (p.name.c_str()) << "\n";
  34650. }
  34651. else
  34652. report << "patcher round trip: load failed: " << error << "\n";
  34653. juce::File (prefix + "-roundtrip.txt").replaceWithText (report);
  34654. }
  34655. offline.setSong (std::move (song));
  34656. }
  34657. offline.dispatchPendingMessages();
  34658. const auto& song = offline.getSong();
  34659. auto shootOpen = [&] (const juce::String& name) {
  34660. for (int k = 0; k < juce::TopLevelWindow::getNumTopLevelWindows(); ++k)
  34661. if (auto* w = dynamic_cast<juce::DocumentWindow*> (juce::TopLevelWindow::getTopLevelWindow (k)))
  34662. if (w->getName().startsWith (lynx::tr ("Patcher")) && w->getContentComponent() != nullptr)
  34663. {
  34664. auto* c = w->getContentComponent();
  34665. savePng (lynx::shot::snapshot (*c), prefix + name);
  34666. delete w;
  34667. return;
  34668. }
  34669. };
  34670. int shots = 0;
  34671. for (int t = 0; t < (int) song.mixer.size() && shots < 12; ++t)
  34672. for (int s = 0; s < (int) song.mixer[(std::size_t) t].effects.size(); ++s)
  34673. if (song.mixer[(std::size_t) t].effects[(std::size_t) s].kind == lynx::EffectKind::patcher)
  34674. {
  34675. lynx::PatcherWindows::openSlot (offline, t, s);
  34676. shootOpen ("-insert" + juce::String (t) + "-slot" + juce::String (s) + ".png");
  34677. // each built-in node's editor, as a double-click opens it (round 165c)
  34678. lynx::PatcherWindows::shootNodeEditors (offline, false, t, s, [&] (const juce::Image& image, int n) {
  34679. savePng (image, prefix + "-insert" + juce::String (t) + "-slot" + juce::String (s) + "-node" + juce::String (n) + ".png");
  34680. });
  34681. ++shots;
  34682. if (shots == 1) // its menus (round 162)
  34683. lynx::PatcherWindows::shootMenus (offline, false, t, s, [&] (const juce::Image& image, const juce::String& name) {
  34684. savePng (image, prefix + "-menu-" + name + ".png");
  34685. });
  34686. }
  34687. for (int c = 0; c < (int) song.channels.size(); ++c)
  34688. if (song.channels[(std::size_t) c].instrument == lynx::InstrumentKind::patcher)
  34689. {
  34690. lynx::PatcherWindows::openChannel (offline, c);
  34691. shootOpen ("-channel" + juce::String (c) + ".png");
  34692. // each node's editor, as a double-click opens it (round 164f; every built-in node since round 165c)
  34693. lynx::PatcherWindows::shootNodeEditors (offline, true, c, 0, [&] (const juce::Image& image, int n) {
  34694. savePng (image, prefix + "-channel" + juce::String (c) + "-node" + juce::String (n) + ".png");
  34695. });
  34696. lynx::PatcherWindows::shootMenus (offline, true, c, 0, [&] (const juce::Image& image, const juce::String& name) {
  34697. savePng (image, prefix + "-channel" + juce::String (c) + "-menu-" + name + ".png");
  34698. });
  34699. }
  34700. }
  34701. }
  34702. // Issue #64: FL's letter keys in a plugin menu (quickpick::showMenu), checked on the real menu windows
  34703. struct TypeAheadTest final : private juce::Timer
  34704. {
  34705. juce::File out;
  34706. juce::StringArray log;
  34707. int step = 0, picked = 0;
  34708. bool ok = true, menuShown = false;
  34709. std::unique_ptr<juce::DocumentWindow> owner;
  34710. juce::PopupMenu pending;
  34711. static juce::String highlighted()
  34712. {
  34713. if (auto* window = juce::Component::getCurrentlyModalComponent())
  34714. for (auto* child : window->getChildren())
  34715. if (auto* h = child->getAccessibilityHandler(); h != nullptr && h->hasFocus (false))
  34716. return h->getTitle();
  34717. return "(none)";
  34718. }
  34719. static void press (const juce::KeyPress& key)
  34720. {
  34721. if (auto* window = juce::Component::getCurrentlyModalComponent())
  34722. if (auto* peer = window->getPeer())
  34723. peer->handleKeyPress (key);
  34724. }
  34725. void expect (const juce::String& what, const juce::String& got, const juce::String& wanted)
  34726. {
  34727. const auto good = got == wanted;
  34728. ok = ok && good;
  34729. log.add ((good ? "ok " : "FAIL ") + what + ": " + got + (good ? juce::String() : " (wanted " + wanted + ")"));
  34730. }
  34731. void start()
  34732. {
  34733. juce::PopupMenu menu, sub;
  34734. auto item = [this] (juce::PopupMenu& m, int id, const char* text, bool enabled = true) {
  34735. m.addItem (text, enabled, false, [this, id] { picked = id; });
  34736. };
  34737. menu.addSectionHeader ("LYNX SHARE");
  34738. item (menu, 1, "Echoform");
  34739. item (menu, 2, "EQ");
  34740. item (menu, 3, "Halo");
  34741. menu.addSectionHeader ("Misc");
  34742. item (menu, 4, "Effector");
  34743. item (menu, 5, "Exciter (unavailable)", false);
  34744. item (sub, 10, "Delay");
  34745. item (sub, 11, "Edison");
  34746. item (sub, 12, "Eventide");
  34747. menu.addSubMenu ("Tree", sub);
  34748. // the menu belongs to a window in the foreground, as when the user right-clicks a mixer slot (JUCE closes a
  34749. // menu of a background process at once)
  34750. owner = std::make_unique<juce::DocumentWindow> ("LYNX type-ahead test", juce::Colours::black, 0);
  34751. owner->setBounds (200, 200, 300, 200);
  34752. owner->setVisible (true);
  34753. lynx::forceForegroundForTest (*owner);
  34754. pending = menu; // shown once the window is up and active (X11 maps and activates it asynchronously)
  34755. startTimer (300);
  34756. }
  34757. void timerCallback() override
  34758. {
  34759. const auto e = juce::KeyPress ('e', {}, 'e');
  34760. if (step == 0 && owner != nullptr && ! menuShown)
  34761. {
  34762. menuShown = true;
  34763. lynx::forceForegroundForTest (*owner);
  34764. lynx::quickpick::showMenu (pending, juce::PopupMenu::Options().withTargetComponent (owner.get()), {});
  34765. return;
  34766. }
  34767. switch (step++)
  34768. {
  34769. case 0: expect ("menu open", juce::String ((int) (juce::Component::getCurrentlyModalComponent() != nullptr)), "1"); break;
  34770. case 1: press (e); expect ("e", highlighted(), "Echoform"); break;
  34771. case 2: press (e); expect ("e again", highlighted(), "EQ"); break;
  34772. case 3: press (juce::KeyPress ('E', juce::ModifierKeys::shiftModifier, 'E')); expect ("E (shift)", highlighted(), "Effector"); break;
  34773. case 4: press (e); expect ("e wraps (skips the disabled one)", highlighted(), "Echoform"); break;
  34774. case 5: press (juce::KeyPress ('m', {}, 'm')); expect ("m (only a heading starts with it: no move)", highlighted(), "Echoform"); break;
  34775. case 6: press (juce::KeyPress (juce::KeyPress::downKey)); expect ("down arrow", highlighted(), "EQ"); break;
  34776. case 7: press (e); expect ("e after the arrow", highlighted(), "Effector"); break;
  34777. case 8: press (juce::KeyPress ('t', {}, 't')); expect ("t", highlighted(), "Tree"); break;
  34778. case 9: press (juce::KeyPress (juce::KeyPress::rightKey)); break; // opens the submenu (it takes the keys)
  34779. case 10: press (e); expect ("e in the submenu", highlighted(), "Edison"); break;
  34780. case 11: press (e); expect ("e again in the submenu", highlighted(), "Eventide"); break;
  34781. case 12: expect ("nothing picked by the letters", juce::String (picked), "0"); press (juce::KeyPress (juce::KeyPress::returnKey)); break;
  34782. case 13: break;
  34783. default:
  34784. expect ("Enter closed the menu", juce::String ((int) (juce::Component::getCurrentlyModalComponent() == nullptr)), "1");
  34785. expect ("Enter picked", juce::String (picked), "12");
  34786. stopTimer();
  34787. owner.reset();
  34788. log.add (ok ? "result=OK" : "result=FAIL");
  34789. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  34790. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  34791. juce::JUCEApplication::quit();
  34792. return;
  34793. }
  34794. }
  34795. };
  34796. std::unique_ptr<TypeAheadTest> typeAheadTest;
  34797. struct ChooserTest final : private juce::Timer
  34798. {
  34799. juce::File out, file;
  34800. juce::StringArray log;
  34801. std::unique_ptr<juce::FileChooser> chooser;
  34802. double started = 0;
  34803. bool shot = false, done = false;
  34804. void start()
  34805. {
  34806. log.add ("LYNX_FILE_DIALOG=" + juce::SystemStats::getEnvironmentVariable ("LYNX_FILE_DIALOG", {}));
  34807. log.add ("native=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  34808. chooser = lynx::ui::makeFileChooser ("Open audio file", file.getParentDirectory(), "*.wav;*.flac");
  34809. started = juce::Time::getMillisecondCounterHiRes();
  34810. lynx::ui::launchChooser (chooser, juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles,
  34811. [this] (const juce::FileChooser& fc) { finish (fc.getResult()); });
  34812. startTimer (200);
  34813. }
  34814. static juce::FileChooserDialogBox* builtInDialog()
  34815. {
  34816. for (int i = 0; i < juce::Desktop::getInstance().getNumComponents(); ++i)
  34817. if (auto* box = dynamic_cast<juce::FileChooserDialogBox*> (juce::Desktop::getInstance().getComponent (i)); box != nullptr && box->isShowing())
  34818. return box;
  34819. return nullptr;
  34820. }
  34821. static juce::FileBrowserComponent* findBrowser (juce::Component& c)
  34822. {
  34823. if (auto* b = dynamic_cast<juce::FileBrowserComponent*> (&c))
  34824. return b;
  34825. for (auto* child : c.getChildren())
  34826. if (auto* b = findBrowser (*child))
  34827. return b;
  34828. return nullptr;
  34829. }
  34830. void timerCallback() override
  34831. {
  34832. if (done)
  34833. return;
  34834. if (auto* box = builtInDialog(); box != nullptr && ! shot)
  34835. {
  34836. shot = true;
  34837. log.add ("built-in dialog shown after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms");
  34838. const auto image = lynx::shot::snapshot (*box);
  34839. juce::FileOutputStream png (out.getSiblingFile (out.getFileName() + ".png"));
  34840. if (png.openedOk())
  34841. {
  34842. png.setPosition (0), png.truncate();
  34843. juce::PNGImageFormat().writeImageToStream (image, png);
  34844. }
  34845. if (auto* browser = findBrowser (*box))
  34846. {
  34847. browser->setRoot (file.getParentDirectory());
  34848. browser->setFileName (file.getFileName());
  34849. log.add ("typed " + file.getFileName());
  34850. box->exitModalState (1);
  34851. }
  34852. else
  34853. log.add ("no file browser in the dialog");
  34854. }
  34855. if (juce::Time::getMillisecondCounterHiRes() - started > 30000.0)
  34856. finish ({}, "timeout");
  34857. }
  34858. void finish (const juce::File& result, const juce::String& why = {})
  34859. {
  34860. if (done)
  34861. return;
  34862. done = true;
  34863. stopTimer();
  34864. log.add ("callback after " + juce::String (juce::roundToInt (juce::Time::getMillisecondCounterHiRes() - started)) + " ms: "
  34865. + (why.isNotEmpty() ? why : result.getFullPathName().isEmpty() ? juce::String ("(no file)") : result.getFullPathName()));
  34866. log.add ("native now=" + juce::String ((int) lynx::ui::filechooser::nativeDialogs()));
  34867. const auto ok = result == file && result.existsAsFile();
  34868. log.add (ok ? "result=OK" : "result=FAIL");
  34869. out.replaceWithText (log.joinIntoString ("\n") + "\n");
  34870. juce::JUCEApplication::getInstance()->setApplicationReturnValue (ok ? 0 : 1);
  34871. juce::MessageManager::callAsync ([] { juce::JUCEApplication::quit(); });
  34872. }
  34873. };
  34874. std::unique_ptr<ChooserTest> chooserTest;
  34875. void runChooserTest (const juce::File& out, const juce::File& file)
  34876. {
  34877. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34878. chooserTest = std::make_unique<ChooserTest>();
  34879. chooserTest->out = out;
  34880. chooserTest->file = file;
  34881. chooserTest->start();
  34882. }
  34883. void runTypeAheadTest (const juce::File& out)
  34884. {
  34885. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34886. typeAheadTest = std::make_unique<TypeAheadTest>();
  34887. typeAheadTest->out = out;
  34888. typeAheadTest->start();
  34889. }
  34890. void runStabilityShot (const juce::String& folder)
  34891. {
  34892. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34893. const juce::File dir (folder);
  34894. dir.createDirectory();
  34895. {
  34896. lynx::AudioEngine offline (false);
  34897. const auto save = [&dir] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  34898. juce::Component frame;
  34899. frame.setSize (c->getWidth(), c->getHeight());
  34900. frame.setOpaque (true);
  34901. if (c->isOnDesktop()) // (an AlertWindow: never shown, so it takes no foreground)
  34902. c->removeFromDesktop();
  34903. frame.addAndMakeVisible (*c);
  34904. c->setTopLeftPosition (0, 0);
  34905. const auto image = lynx::shot::paint (frame, lynx::theme::panel);
  34906. const auto file = dir.getChildFile (name);
  34907. file.deleteFile();
  34908. juce::PNGImageFormat png;
  34909. if (auto out = file.createOutputStream())
  34910. png.writeImageToStream (image, *out);
  34911. };
  34912. save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "crash-prompt.png");
  34913. save (lynx::PluginWindows::makeCrashPromptPanel ("Serum", true), "crash-prompt-onload.png");
  34914. save (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "crash-notice.png");
  34915. save (lynx::makePluginManagerPanel (offline, false), "plugin-manager.png");
  34916. save (lynx::makePluginMonitorPanel (offline), "plugin-monitor.png");
  34917. }
  34918. setApplicationReturnValue (0);
  34919. quit();
  34920. }
  34921. void runDetails190ihShot (const juce::String& prefix)
  34922. {
  34923. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  34924. juce::String report;
  34925. auto line = [&report] (const juce::String& t) { report << t << "\n"; };
  34926. {
  34927. // R2: Gross Beat on Insert 1 — the first time slot and a half-beat volume gate, as in FL's capture ("Empty",
  34928. // "1/2 Bt Gate")
  34929. lynx::AudioEngine offline (false);
  34930. lynx::Song song;
  34931. song.mixer = lynx::Song::defaultMixer (2);
  34932. song.bpm = 150.0;
  34933. auto gb = lynx::makeEffectSlot (lynx::EffectKind::grossBeat);
  34934. const auto names = lynx::grossbeat::slotNames (gb.state, true);
  34935. int gate = 0;
  34936. for (int k = 0; k < (int) names.size(); ++k)
  34937. if (names[(std::size_t) k] == "Gate 1/2 beat") // (LYNX's factory slot for FL's "1/2 Bt Gate")
  34938. gate = k;
  34939. gb.params[0] = lynx::grossbeat::paramFromRaw (0, 0);
  34940. gb.params[1] = lynx::grossbeat::paramFromRaw (1, gate);
  34941. song.mixer[1].effects.push_back (gb);
  34942. offline.setSong (std::move (song));
  34943. offline.dispatchPendingMessages();
  34944. // the real effect played to beat 2.9 of its bar: its published outputs go where the rack writes them
  34945. auto run = lynx::makeEffect (gb);
  34946. run->prepare (48000.0);
  34947. const auto tps = 150.0 / 60.0 * lynx::ppq / 48000.0;
  34948. std::vector<float> l (480, 0.3f), r (480, 0.3f);
  34949. std::size_t done = 0;
  34950. auto block = [&] (lynx::EffectParams& params) {
  34951. run->setSongPosition ((double) done * tps);
  34952. run->process (l.data(), r.data(), 480, params, 150.0);
  34953. done += 480;
  34954. };
  34955. auto publish = [&] (bool playing) {
  34956. const auto key = (std::size_t) (1 * lynx::maxEffectSlots + 0) * lynx::ProcessTimes::meterOutputs;
  34957. if (auto* times = offline.getProcessTimes())
  34958. for (int k = 0; k < lynx::ProcessTimes::meterOutputs; ++k)
  34959. times->effectMeters[key + (std::size_t) k].store (run->controlOutput (k), std::memory_order_relaxed);
  34960. else
  34961. line ("no process times: the editor shows nothing live");
  34962. offline.getTransport().playing.store (playing);
  34963. juce::String values;
  34964. for (int k = 0; k < 7; ++k)
  34965. values << " " << juce::String (run->controlOutput (k), 3);
  34966. line ("gross beat outputs:" + values);
  34967. };
  34968. while ((double) done * tps / lynx::ppq < 2.9)
  34969. block (gb.params);
  34970. auto editor = lynx::makeNativeEffectEditor (offline, 1, 0, 1.0f);
  34971. editor->setSize (editor->getWidth(), editor->getHeight());
  34972. for (const int view : { 1, 0 })
  34973. {
  34974. lynx::showGrossBeatEnvelopeForSnapshot (*editor, view);
  34975. publish (true);
  34976. lynx::tickNativeEffectEditor (*editor);
  34977. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-playing-" + (view == 1 ? "volume" : "time") + ".png");
  34978. }
  34979. lynx::ui::motion::enabled() = false;
  34980. lynx::tickNativeEffectEditor (*editor);
  34981. editor->repaint();
  34982. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-playing-noanim.png");
  34983. lynx::ui::motion::enabled() = true;
  34984. // a click on another time slot: queued until the next 4 beats
  34985. auto queued = gb.params;
  34986. queued[0] = lynx::grossbeat::paramFromRaw (0, 5);
  34987. block (queued);
  34988. publish (true);
  34989. lynx::tickNativeEffectEditor (*editor);
  34990. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-queued.png");
  34991. publish (false); // stopped: no locator, no fill
  34992. lynx::tickNativeEffectEditor (*editor);
  34993. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-stopped.png");
  34994. // round 190jd (live check 190iw Q7): the locator in FL's colours (the editor's Options menu) on the beat (cream,
  34995. // 3 px trail), a third into it (orange) and near its end (dusty red); LYNX's playhead colour stays the default
  34996. lynx::gblocator::setFlStyle (true);
  34997. lynx::showGrossBeatEnvelopeForSnapshot (*editor, 1);
  34998. for (const auto at : { 4.02, 4.35, 4.9 })
  34999. {
  35000. while ((double) done * tps / lynx::ppq < at)
  35001. block (queued);
  35002. publish (true);
  35003. juce::Thread::sleep (60); // (the editor's frame budget: ~21 frames a second in this style)
  35004. lynx::tickNativeEffectEditor (*editor);
  35005. savePng (lynx::shot::snapshot (*editor), prefix + "-r2-grossbeat-fl-colours-" + juce::String (at - 4.0, 2) + ".png");
  35006. }
  35007. lynx::gblocator::setFlStyle (false);
  35008. offline.getTransport().playing.store (false);
  35009. }
  35010. {
  35011. // R7: the Envelope Controller's Keyboard / Velocity mapping pages after a note (key 64, velocity 0.8)
  35012. lynx::AudioEngine offline (false);
  35013. lynx::Song song;
  35014. lynx::ChannelDef env;
  35015. env.name = "Envelope Controller";
  35016. env.instrument = lynx::InstrumentKind::controller;
  35017. auto ec = lynx::defaultEnvelopeController();
  35018. ec[0].maps[lynx::mapKeyboard].count = 2;
  35019. ec[0].maps[lynx::mapKeyboard].time = { 0.2f, 0.8f };
  35020. ec[0].maps[lynx::mapKeyboard].level = { 0.0f, 1.0f };
  35021. ec[0].maps[lynx::mapVelocity] = ec[0].maps[lynx::mapKeyboard];
  35022. env.controllerState = lynx::writeEnvelopeController (ec);
  35023. song.channels.push_back (env);
  35024. song.patterns.emplace_back();
  35025. offline.setSong (std::move (song));
  35026. offline.dispatchPendingMessages();
  35027. auto editor = lynx::makeEnvelopeControllerEditor (
  35028. offline, [] (lynx::Song& s) -> lynx::ChannelDef* { return s.channels.empty() ? nullptr : &s.channels[0]; }, 0,
  35029. [] (int k) { return k == 8 ? 64.0f : k == 9 ? 0.8f : 0.5f; });
  35030. for (const int part : { 2, 3 })
  35031. {
  35032. for (auto* child : editor->getChildren())
  35033. if (auto* box = dynamic_cast<juce::ComboBox*> (child))
  35034. box->setSelectedItemIndex (part, juce::sendNotificationSync);
  35035. savePng (lynx::shot::snapshot (*editor), prefix + "-r7-ec-" + (part == 2 ? "keyboard" : "velocity") + "-line.png");
  35036. }
  35037. }
  35038. {
  35039. lynx::AudioEngine offline (false);
  35040. lynx::MainComponent ui (offline, false);
  35041. ui.setSize (1920, 1080);
  35042. lynx::Song song;
  35043. song.mixer = lynx::Song::defaultMixer (4);
  35044. for (const auto* name : { "Grv Kick 27", "Snare", "Hat", "Bass (locked)" })
  35045. {
  35046. lynx::ChannelDef c;
  35047. c.name = name;
  35048. c.instrument = lynx::InstrumentKind::sampler;
  35049. song.channels.push_back (c);
  35050. }
  35051. song.channels[3].receiveFrom = "MIDI keyboard";
  35052. song.patterns.emplace_back();
  35053. offline.setSong (std::move (song));
  35054. offline.dispatchPendingMessages();
  35055. ui.showDesktopForSnapshot (false);
  35056. offline.dispatchPendingMessages();
  35057. // R4: the rack's activity light — before, at note-on, held, after the release; a locked channel lit (orange)
  35058. auto& rack = ui.getRackForSnapshot();
  35059. const std::pair<const char*, float> states[] { { "before", 0.0f }, { "noteon", 1.0f }, { "held", lynx::activity::held }, { "after", 0.0f } };
  35060. for (const auto& [name, level] : states)
  35061. {
  35062. rack.setActivityForSnapshot (0, level);
  35063. rack.setActivityForSnapshot (3, level);
  35064. savePng (lynx::shot::snapshot (rack), prefix + "-r4-rack-" + name + ".png");
  35065. }
  35066. rack.setActivityForSnapshot (0, 0.0f);
  35067. rack.setActivityForSnapshot (3, 0.0f);
  35068. // R3: the transport stopped, playing, recording (both blink phases), armed and stopped; the hint bar
  35069. const auto toolbar = ui.getToolbarBoundsForSnapshot();
  35070. auto& transport = offline.getTransport();
  35071. ui.transportForSnapshot (false, true);
  35072. saveArea (ui, toolbar, prefix + "-r3-toolbar-stopped.png");
  35073. transport.playing.store (true);
  35074. ui.transportForSnapshot (true, true);
  35075. saveArea (ui, toolbar, prefix + "-r3-toolbar-playing.png");
  35076. transport.recording.store (true);
  35077. ui.transportForSnapshot (true, true);
  35078. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-lit.png");
  35079. ui.transportForSnapshot (true, false);
  35080. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-dark.png");
  35081. lynx::ui::motion::enabled() = false;
  35082. ui.transportForSnapshot (true, false);
  35083. saveArea (ui, toolbar, prefix + "-r3-toolbar-recording-noanim.png");
  35084. lynx::ui::motion::enabled() = true;
  35085. transport.playing.store (false);
  35086. ui.transportForSnapshot (false, false);
  35087. saveArea (ui, toolbar, prefix + "-r3-toolbar-armed-stopped.png");
  35088. transport.recording.store (false);
  35089. ui.transportForSnapshot (false, true);
  35090. for (const bool on : { true, false })
  35091. {
  35092. offline.markLiveNote (60, 100, on);
  35093. const auto hint = ui.liveNoteHintForSnapshot();
  35094. line ("hint: " + hint);
  35095. ui.setHintForSnapshot ({ hint, {}, false, false });
  35096. saveArea (ui, toolbar, prefix + "-r3-hint-note" + (on ? "on" : "off") + ".png");
  35097. }
  35098. offline.editSong ([] (lynx::Song& s) { s.bpm = 128.0; }); // (a change: the project is modified)
  35099. offline.dispatchPendingMessages();
  35100. const auto reminder = ui.saveReminderForSnapshot();
  35101. line ("reminder: " + reminder);
  35102. ui.setHintForSnapshot ({ reminder, {}, false, false });
  35103. saveArea (ui, toolbar, prefix + "-r3-save-reminder.png");
  35104. // R14: the Simple dock's input level
  35105. ui.setLayoutStyle (lynx::layoutstyle::Style::simple);
  35106. offline.dispatchPendingMessages();
  35107. if (auto* simple = ui.getSimpleWorkflowForSnapshot())
  35108. if (auto* dock = simple->dockForSnapshot())
  35109. {
  35110. dock->inputLevelForSnapshot (0.72f);
  35111. offline.dispatchPendingMessages();
  35112. savePng (lynx::shot::snapshot (*dock), prefix + "-r14-dock-input-level.png");
  35113. line ("dock: " + juce::String (dock->getWidth()) + "x" + juce::String (dock->getHeight()));
  35114. }
  35115. ui.setLayoutStyle (lynx::layoutstyle::Style::pattern);
  35116. offline.dispatchPendingMessages();
  35117. }
  35118. juce::File (prefix + "-report.txt").replaceWithText (report);
  35119. }
  35120. void runSnapshot (const juce::String& prefix, const juce::String& projectPath)
  35121. {
  35122. juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
  35123. // LYNX_SNAPSHOT_THEME=file.lynxtheme: the pictures in that theme (round 162d)
  35124. if (const auto themeFile = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_THEME", {}); themeFile.isNotEmpty())
  35125. if (const auto spec = lynx::themeui::loadFile (juce::File (themeFile)))
  35126. lynx::themeui::apply (*spec, false);
  35127. {
  35128. lynx::AudioEngine offline (false);
  35129. lynx::MainComponent ui (offline, false); // default layout and keys, nothing saved
  35130. // LYNX_SNAPSHOT_SIZE=WxH (default 1280x720)
  35131. const auto size = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIZE", "1280x720"), "x", "");
  35132. ui.setSize (juce::jlimit (800, 3840, size[0].getIntValue()), juce::jlimit (450, 2160, size[1].getIntValue()));
  35133. if (projectPath.isNotEmpty())
  35134. ui.openFile (juce::File (projectPath));
  35135. offline.dispatchPendingMessages(); // change notifications are asynchronous
  35136. ui.waitForBrowserForSnapshot();
  35137. // the workspace desktop: the default layout, then with the Piano Roll and Mixer floating too
  35138. // (and a sample hint in the status strip, as when hovering a knob)
  35139. ui.showDesktopForSnapshot (false);
  35140. ui.setMetersForSnapshot (0.23, (std::int64_t) 412 << 20, 6);
  35141. offline.dispatchPendingMessages();
  35142. saveSnapshot (ui, prefix + "-desktop.png");
  35143. // the first start: the setup wizard over the main window (round 140), also on a small screen (it scrolls)
  35144. {
  35145. const auto size = ui.getBounds();
  35146. ui.showSetupWizard();
  35147. offline.dispatchPendingMessages();
  35148. saveSnapshot (ui, prefix + "-desktop-setup.png");
  35149. ui.setSize (1024, 600);
  35150. offline.dispatchPendingMessages();
  35151. saveSnapshot (ui, prefix + "-desktop-setup-small.png");
  35152. ui.closeSetupWizardForSnapshot();
  35153. ui.setBounds (size);
  35154. offline.dispatchPendingMessages();
  35155. }
  35156. // the start-up desktop and the toolbar at the usual window sizes: the untouched default layout
  35157. // follows the window (default rects, not scaled ones); panels drop from the toolbar by priority
  35158. {
  35159. const auto size = ui.getBounds();
  35160. for (const auto& [w, h] : std::vector<std::pair<int, int>> { { 1280, 720 }, { 1366, 768 }, { 1600, 900 }, { 1920, 1080 }, { 2560, 1440 }, { 3840, 2160 } })
  35161. {
  35162. ui.setSize (w, h);
  35163. offline.dispatchPendingMessages();
  35164. saveSnapshot (ui, prefix + "-desktop-" + juce::String (w) + ".png");
  35165. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + juce::String (w) + ".png");
  35166. if (w == 1920) // the rack scrolled to its last steps: the controls column stays in view (round 90)
  35167. {
  35168. ui.scrollRackForSnapshot (100000);
  35169. offline.dispatchPendingMessages();
  35170. saveSnapshot (ui, prefix + "-desktop-rack-scrolled.png");
  35171. ui.scrollRackForSnapshot (0);
  35172. }
  35173. }
  35174. // the toolbar with small and large icons, and a customized one (groups hidden and reordered)
  35175. ui.setSize (1600, 900);
  35176. for (auto [iconSize, name] : { std::pair { lynx::toolbarlayout::IconSize::small, "small" }, { lynx::toolbarlayout::IconSize::large, "large" } })
  35177. {
  35178. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  35179. layout.iconSize = iconSize;
  35180. ui.setToolbarLayoutForSnapshot (layout);
  35181. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-" + name + "-1600.png");
  35182. }
  35183. {
  35184. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  35185. layout.move (lynx::toolbarlayout::Group::windows, -3);
  35186. layout.setShown (lynx::toolbarlayout::Group::record, false);
  35187. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  35188. ui.setToolbarLayoutForSnapshot (layout);
  35189. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-custom-1600.png");
  35190. }
  35191. {
  35192. // round 170e: the toolbar after a knob was moved: the last tweaked read-out (its caption) and the snap magnet
  35193. ui.setSize (1920, 1080); // the read-out needs room beside the hint bar
  35194. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  35195. lynx::AutomationTarget t;
  35196. t.kind = lynx::AutomationTargetKind::mixerVolume;
  35197. t.index = 0;
  35198. offline.noteTweaked (t);
  35199. ui.refreshTweakReadoutForSnapshot();
  35200. offline.dispatchPendingMessages();
  35201. saveArea (ui, ui.getToolbarBoundsForSnapshot(), prefix + "-toolbar-tweak-1920.png");
  35202. ui.setSize (1600, 900);
  35203. }
  35204. {
  35205. // the toolbar's edit mode (round 115): outlined panels and the tray of panels under it
  35206. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  35207. auto layout = lynx::toolbarlayout::Layout::makeDefault();
  35208. layout.setShown (lynx::toolbarlayout::Group::meters, false);
  35209. ui.setToolbarLayoutForSnapshot (layout);
  35210. ui.setToolbarEditingForSnapshot (true);
  35211. offline.dispatchPendingMessages();
  35212. saveArea (ui, ui.getToolbarBoundsForSnapshot().withHeight (ui.getToolbarAndTrayHeightForSnapshot()), prefix + "-toolbar-edit-1600.png");
  35213. ui.setToolbarEditingForSnapshot (false);
  35214. // Ctrl+F11: only the menu and the hint bar
  35215. layout = lynx::toolbarlayout::Layout::makeDefault();
  35216. layout.visible = false;
  35217. ui.setToolbarLayoutForSnapshot (layout);
  35218. saveArea (ui, ui.getLocalBounds().withHeight (120), prefix + "-toolbar-hidden-1600.png");
  35219. }
  35220. ui.setToolbarLayoutForSnapshot (lynx::toolbarlayout::Layout::makeDefault());
  35221. // quick tips: the toolbar and title bars with a few name bubbles, and every tip on one sheet
  35222. offline.dispatchPendingMessages();
  35223. saveQuickTips (ui, prefix);
  35224. ui.setBounds (size);
  35225. offline.dispatchPendingMessages();
  35226. }
  35227. // the hint bar: a value control while it is dragged (live value), a gesture line with mouse and key
  35228. // glyphs, and a text too long for one line (two lines)
  35229. {
  35230. const auto toolbar = ui.getToolbarBoundsForSnapshot().withWidth (juce::jmin (ui.getWidth(), 900));
  35231. const lynx::ui::Hint hints[] = {
  35232. { lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "-3.2 dB", true, true },
  35233. { lynx::tr ("Piano Roll: [LMB] add a note, drag to move [RMB] delete [Ctrl][LMB] drag to select [Ctrl][Wheel] zoom"), {}, false, false },
  35234. { lynx::tr ("Global snap: the grid of the Piano Roll and Playlist (when they follow it) and the quantise of recorded notes "
  35235. "[LMB] choose [Wheel] step [RMB] length of new notes [Backspace] snap on/off [Alt] while dragging: no snap"), {}, false, true },
  35236. };
  35237. for (int i = 0; i < 3; ++i)
  35238. {
  35239. ui.setHintForSnapshot (hints[i], i == 0);
  35240. saveArea (ui, toolbar, prefix + "-hint-" + juce::String (i + 1) + ".png");
  35241. }
  35242. }
  35243. ui.showDesktopForSnapshot (true);
  35244. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  35245. saveSnapshot (ui, prefix + "-desktop-all.png");
  35246. ui.selectTabForSnapshot (0);
  35247. saveSnapshot (ui, prefix + "-rack.png");
  35248. // round 190io (design190ia FM-10…14): steps on the first channels, audio clip channels included (they show
  35249. // their steps as in FL), a few selected rows, a muted channel; then the project as it was
  35250. {
  35251. const auto& kept = offline.getSong();
  35252. const auto keptSelection = offline.getSelectedChannels();
  35253. const auto keptPrimary = offline.getSelectedChannel();
  35254. const auto channels = (int) kept.channels.size();
  35255. offline.editSong ([channels] (lynx::Song& s) {
  35256. auto& p = s.activePattern();
  35257. for (int c = 0; c < juce::jmin (12, channels); ++c)
  35258. for (const auto step : { 0, 4 + (c % 3) * 2, 8, 12 + (c % 2) * 2 })
  35259. if (! p.hasStep (c, step))
  35260. p.toggleStep (c, step);
  35261. if (channels > 5)
  35262. s.channels[5].muted = true;
  35263. });
  35264. if (channels > 3)
  35265. offline.setChannelSelection ({ 1, 2, 3 }, 2);
  35266. offline.dispatchPendingMessages();
  35267. saveSnapshot (ui, prefix + "-rack190io-steps.png");
  35268. offline.undo(); // (one undo step: the project and its history as they were)
  35269. offline.setChannelSelection (keptSelection, keptPrimary);
  35270. offline.dispatchPendingMessages();
  35271. }
  35272. {
  35273. // a pattern with piano-roll notes: those rows show a miniature instead of steps (round 90)
  35274. int found = -1;
  35275. const auto before = offline.getSong().currentPattern;
  35276. {
  35277. const auto& song = offline.getSong();
  35278. for (int p = 0; p < (int) song.patterns.size() && found < 0; ++p)
  35279. for (int c = 0; c < (int) song.channels.size() && found < 0; ++c)
  35280. if (lynx::showsNotePreview (song.patterns[(std::size_t) p], c))
  35281. found = p;
  35282. }
  35283. if (found >= 0)
  35284. {
  35285. offline.editSong ([found] (lynx::Song& s) { s.currentPattern = found; }, false);
  35286. offline.dispatchPendingMessages();
  35287. saveSnapshot (ui, prefix + "-rack-preview.png");
  35288. offline.editSong ([before] (lynx::Song& s) { s.currentPattern = before; }, false);
  35289. offline.dispatchPendingMessages();
  35290. }
  35291. }
  35292. ui.selectTabForSnapshot (1);
  35293. saveSnapshot (ui, prefix + "-pianoroll.png");
  35294. {
  35295. // View › Keyboard style › Piano keys (round 190j, discussion #136), also with tall keys
  35296. auto& roll = ui.getPianoRollForSnapshot();
  35297. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::piano;
  35298. roll.repaint();
  35299. saveSnapshot (ui, prefix + "-pianoroll-pianokeys.png");
  35300. lynx::PianoRollComponent::keyStyle = lynx::pianokeys::Style::flat;
  35301. roll.repaint();
  35302. // round 190j (discussion #10): the toolbar in a narrow window: the chord stamp as an icon button, and
  35303. // the menu button still there
  35304. for (int narrower : { 150, 270, 330 })
  35305. {
  35306. roll.squeezeToolbarForSnapshot (narrower);
  35307. saveSnapshot (ui, prefix + "-pianoroll-narrow" + juce::String (narrower) + ".png");
  35308. roll.squeezeToolbarForSnapshot (-narrower);
  35309. }
  35310. }
  35311. if (const auto strip = ui.getToolStripAreaForSnapshot (false); ! strip.isEmpty())
  35312. saveArea (ui, strip, prefix + "-pianoroll-tools.png");
  35313. // the editors' mouse feel: the hovered note / clip edge (grip, outline) and its hint in the hint bar
  35314. ui.setHintForSnapshot (ui.getPianoRollForSnapshot().hoverForSnapshot());
  35315. saveSnapshot (ui, prefix + "-pianoroll-hover.png");
  35316. {
  35317. // a pattern with note Chance or a Velocity Range (round 187c): the Piano roll with those lanes
  35318. const auto& song = offline.getSong();
  35319. const auto& notes = song.patterns[(std::size_t) std::clamp (song.currentPattern, 0, (int) song.patterns.size() - 1)].notes;
  35320. if (std::any_of (notes.begin(), notes.end(), [] (const lynx::Note& n) { return n.hasChance(); }))
  35321. {
  35322. auto& roll = ui.getPianoRollForSnapshot();
  35323. ui.setHintForSnapshot ({});
  35324. for (const auto& [lane, name] : { std::pair { lynx::PianoRollComponent::laneChance, "chance" },
  35325. { lynx::PianoRollComponent::laneVelocityRange, "velrange" },
  35326. { lynx::PianoRollComponent::laneVelocity, "velocity" } })
  35327. {
  35328. roll.setLaneForSnapshot (lane);
  35329. offline.dispatchPendingMessages();
  35330. saveSnapshot (ui, prefix + "-pianoroll-" + name + ".png");
  35331. }
  35332. }
  35333. }
  35334. ui.selectTabForSnapshot (2);
  35335. saveSnapshot (ui, prefix + "-playlist.png");
  35336. {
  35337. // round 190nr: the same with the song zoomed to fit (the site's and the Store's Playlist picture: at FL's
  35338. // open zoom the demo song fills only the first fifth)
  35339. auto& pl = ui.getPlaylistForSnapshot();
  35340. const auto view = pl.viewForSnapshot();
  35341. pl.zoomAllForSnapshot();
  35342. saveSnapshot (ui, prefix + "-playlist-fit.png");
  35343. pl.restoreViewForSnapshot (view);
  35344. }
  35345. if (const auto strip = ui.getToolStripAreaForSnapshot (true); ! strip.isEmpty())
  35346. saveArea (ui, strip, prefix + "-playlist-tools.png");
  35347. ui.setHintForSnapshot (ui.getPlaylistForSnapshot().hoverForSnapshot());
  35348. saveSnapshot (ui, prefix + "-playlist-hover.png");
  35349. ui.setHintForSnapshot ({ lynx::tr ("Volume") + " - " + lynx::tr ("drag (Ctrl: fine), wheel, Alt+click resets"), "78%", true, true });
  35350. // the Playlist with a time selection over bars 2-3 (it selects the clips it touches) and the Knife tool
  35351. ui.getPlaylistForSnapshot().setTimeSelectionForSnapshot (1, 3);
  35352. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::knife);
  35353. offline.dispatchPendingMessages();
  35354. saveSnapshot (ui, prefix + "-playlist-timesel.png");
  35355. ui.getPlaylistForSnapshot().setToolForSnapshot (lynx::EditTool::pencil);
  35356. // round 177b: automation lanes on (two lanes under track 2: a volume ramp and a pan wobble)
  35357. {
  35358. const auto before = offline.getSong();
  35359. offline.editSong ([] (lynx::Song& s) {
  35360. s.loopStart = s.loopEnd = 0; // (no time selection in this one)
  35361. const auto bar = s.barTicks();
  35362. const auto vol = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, "Insert 1 - Volume", 0.3f);
  35363. s.automations[(std::size_t) vol].points = { { 0, 0.3f, 0.0f }, { bar * 2, 0.8f, 0.4f }, { bar * 4, 0.6f, 0.0f } };
  35364. const auto pan = lynx::autolanes::addLane (s, 1, { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, "Insert 1 - Pan", 0.5f);
  35365. 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 } };
  35366. }, false);
  35367. lynx::autolanes::setShown (true);
  35368. ui.getPlaylistForSnapshot().resized();
  35369. offline.dispatchPendingMessages();
  35370. saveSnapshot (ui, prefix + "-playlist-lanes.png");
  35371. lynx::autolanes::setShown (false);
  35372. offline.editSong ([before] (lynx::Song& s) { s = before; }, false);
  35373. offline.dispatchPendingMessages();
  35374. }
  35375. // round 104: a folded track group (FL's thin member rows) and the Picker's audio tab
  35376. {
  35377. int header = -1;
  35378. for (int t = 0; t < (int) offline.getSong().playlistTracks.size() && header < 0; ++t)
  35379. if (lynx::noteedit::isGroupHeader (offline.getSong(), t))
  35380. header = t;
  35381. if (header >= 0)
  35382. {
  35383. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, true); }, false);
  35384. offline.dispatchPendingMessages();
  35385. saveSnapshot (ui, prefix + "-playlist-group-folded.png");
  35386. offline.editSong ([header] (lynx::Song& s) { lynx::noteedit::setGroupCollapsed (s, header, false); }, false);
  35387. }
  35388. ui.getPickerForSnapshot().setView (1);
  35389. offline.dispatchPendingMessages();
  35390. saveSnapshot (ui, prefix + "-playlist-picker-audio.png");
  35391. ui.getPickerForSnapshot().setView (0);
  35392. }
  35393. // round 104: the Channel Rack filtered to its first filter group
  35394. if (! offline.getSong().channelGroups.empty())
  35395. {
  35396. ui.selectTabForSnapshot (0);
  35397. ui.getRackForSnapshot().setFilterGroup (0);
  35398. offline.dispatchPendingMessages();
  35399. saveSnapshot (ui, prefix + "-rack-filter.png");
  35400. ui.getRackForSnapshot().setFilterGroup (-1);
  35401. }
  35402. ui.selectTabForSnapshot (3);
  35403. // LYNX_SNAPSHOT_ARRANGE=1 (round 186c): Mixer menu › "Arrange inserts like the Playlist" first
  35404. if (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_ARRANGE", {}) == "1")
  35405. {
  35406. offline.editSong ([] (lynx::Song& s) { lynx::mixerops::arrangeLikePlaylist (s); });
  35407. offline.dispatchPendingMessages();
  35408. }
  35409. // LYNX_SNAPSHOT_TRACK=n: shows the effects of that mixer track
  35410. if (const auto track = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_TRACK", {}); track.isNotEmpty())
  35411. {
  35412. ui.selectMixerTrackForSnapshot (track.getIntValue(),
  35413. juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SLOT", "-1").getIntValue());
  35414. offline.dispatchPendingMessages();
  35415. }
  35416. saveSnapshot (ui, prefix + "-mixer.png");
  35417. // round 190ir (Discord report, "it isnt picking up my audio input"): an armed insert without an input says so
  35418. // in its input box (record colour)
  35419. // (the first insert no channel plays into: armed without an input, it records silence)
  35420. {
  35421. const auto& song = offline.getSong();
  35422. auto target = -1;
  35423. for (int t = 1; t < (int) song.mixer.size() && target < 0; ++t)
  35424. if (song.mixer[(std::size_t) t].inputChannel < 0
  35425. && std::none_of (song.channels.begin(), song.channels.end(), [t] (const lynx::ChannelDef& c) { return c.mixerTrack == t; }))
  35426. target = t;
  35427. if (target > 0)
  35428. {
  35429. offline.setInsertArmed (target, true);
  35430. ui.selectMixerTrackForSnapshot (target, -1);
  35431. offline.dispatchPendingMessages();
  35432. saveSnapshot (ui, prefix + "-mixer190ir-armed-noinput.png");
  35433. offline.setInsertArmed (target, false);
  35434. offline.dispatchPendingMessages();
  35435. }
  35436. }
  35437. // round 190am: LYNX's two mixer extras, before and after (the demo project leaves most inserts unused). The
  35438. // loudness panel shows a real measurement of 12 s of a test tone (a 1 kHz sine at -14 dBFS after a quieter
  35439. // stretch, pushed through the Master's tap as the audio thread does)
  35440. {
  35441. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  35442. saveSnapshot (ui, prefix + "-mixer190am-before.png");
  35443. strips.setShowUsedOnly (true);
  35444. offline.dispatchPendingMessages();
  35445. saveSnapshot (ui, prefix + "-mixer190am-usedonly.png");
  35446. strips.setShowUsedOnly (false);
  35447. strips.setShowLoudness (true);
  35448. {
  35449. const double sr = 48000.0;
  35450. std::vector<float> tone (480);
  35451. auto& tap = offline.getMeters().loudness;
  35452. for (int block = 0; block < 1200; ++block)
  35453. {
  35454. const auto gain = std::pow (10.0, (block < 400 ? -20.0 : -14.0) / 20.0);
  35455. for (int i = 0; i < 480; ++i)
  35456. tone[(std::size_t) i] = (float) (gain * std::sin (2.0 * juce::MathConstants<double>::pi * 1000.0 * (block * 480 + i) / sr));
  35457. tap.push (tone.data(), tone.data(), 480, sr);
  35458. }
  35459. }
  35460. strips.refreshLoudnessForSnapshot();
  35461. offline.dispatchPendingMessages();
  35462. saveSnapshot (ui, prefix + "-mixer190am-loudness.png");
  35463. for (const auto l : { lynx::mixerlayout::Layout::compact, lynx::mixerlayout::Layout::extraLarge })
  35464. {
  35465. const auto was = lynx::MixerStrips::layout;
  35466. strips.setLayout (l);
  35467. offline.dispatchPendingMessages();
  35468. saveSnapshot (ui, prefix + "-mixer190am-loudness-" + juce::String ((int) l) + ".png");
  35469. strips.setLayout (was);
  35470. }
  35471. strips.setShowUsedOnly (true);
  35472. offline.dispatchPendingMessages();
  35473. saveSnapshot (ui, prefix + "-mixer190am-both.png");
  35474. strips.setShowUsedOnly (false);
  35475. strips.setShowLoudness (false);
  35476. offline.dispatchPendingMessages();
  35477. }
  35478. // round 168h (issue #52): FL's 8 Mixer layouts
  35479. {
  35480. const auto before = lynx::MixerStrips::layout;
  35481. for (int l = 0; l < lynx::mixerlayout::layoutCount; ++l)
  35482. {
  35483. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout ((lynx::mixerlayout::Layout) l);
  35484. offline.dispatchPendingMessages();
  35485. saveSnapshot (ui, prefix + "-mixer168h-" + juce::String (l) + ".png");
  35486. }
  35487. ui.getMixerForSnapshot().getStripsForSnapshot().setLayout (before);
  35488. offline.dispatchPendingMessages();
  35489. }
  35490. // round 163: the Mixer at short heights (UI zoom 150%+): the EQ folds, then the effects panel scrolls
  35491. {
  35492. const auto size = ui.getBounds();
  35493. for (auto h : { 450, 560, 680, 820 })
  35494. {
  35495. ui.setSize (size.getWidth(), h);
  35496. offline.dispatchPendingMessages();
  35497. saveSnapshot (ui, prefix + "-mixer163-" + juce::String (h) + ".png");
  35498. }
  35499. ui.setBounds (size);
  35500. offline.dispatchPendingMessages();
  35501. }
  35502. // round 170b (Busy Works Beats' review): inserts 1-3 selected and routed together to insert 4, a single effect
  35503. // moved down into slot 2 (FL's slot places), and the plugin menus grouped by category, LYNX SHARE first
  35504. {
  35505. const auto before = offline.getSong();
  35506. offline.editSong ([] (lynx::Song& s) {
  35507. if (s.mixer.size() < 5)
  35508. return;
  35509. s.mixer[1].effects.clear();
  35510. lynx::EffectSlot fx;
  35511. fx.kind = lynx::EffectKind::compressor;
  35512. s.mixer[1].effects.push_back (fx);
  35513. lynx::mixerops::moveEffectBy (s, 1, 0, 1);
  35514. lynx::mixerops::switchSelectedRoute (s, { 1, 2, 3 }, 4, true);
  35515. });
  35516. ui.selectMixerTrackForSnapshot (1);
  35517. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 1);
  35518. offline.dispatchPendingMessages();
  35519. saveSnapshot (ui, prefix + "-mixer170b.png");
  35520. juce::PopupMenu effects, generators;
  35521. lynx::quickpick::addFolderGroups (effects, offline, std::function<void (lynx::EffectSlot)> ([] (lynx::EffectSlot) {}));
  35522. lynx::quickpick::addFolderViewItems (effects, offline);
  35523. lynx::quickpick::addGeneratorMenu (generators, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  35524. lynx::quickpick::addFolderViewItems (generators, offline);
  35525. saveMenus (juce::StringArray { "Mixer slot: add an effect", "Channel Rack: add" }, { effects, generators }, prefix + "-menus170b.png");
  35526. // round 190bf (fl190be Q3): the Channel Rack's "+" menu in FL's three views, with two root entries (plugins
  35527. // at the top of the database, in no folder) and the Categories / Simple / Tree switch at the end
  35528. {
  35529. auto& host = offline.getPluginHost();
  35530. const auto keep = host.databaseFolders();
  35531. auto folders = keep;
  35532. int added = 0;
  35533. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  35534. if (e.folder == 3 && e.available && added < 2) // (installed plugins: FL's root entries are such)
  35535. {
  35536. folders.top.insert (e.key);
  35537. ++added;
  35538. }
  35539. for (const auto& e : lynx::quickpick::generatorEntries (offline))
  35540. if (e.folder != 3 && added < 2)
  35541. {
  35542. folders.top.insert (e.key);
  35543. ++added;
  35544. }
  35545. static const char* const views[] { "categories", "simple", "tree" };
  35546. for (int v = 0; v < 3; ++v)
  35547. {
  35548. folders.view = v;
  35549. host.setDatabaseFolders (folders);
  35550. juce::PopupMenu plus;
  35551. lynx::quickpick::addGeneratorMenu (plus, offline, [] (lynx::ChannelDef) {}, {}, nullptr, nullptr);
  35552. lynx::quickpick::addFolderViewItems (plus, offline);
  35553. saveMenus (juce::StringArray { juce::String ("Channel Rack +: ") + views[v] }, { plus }, prefix + "-menus190bf-" + views[v] + ".png");
  35554. }
  35555. host.setDatabaseFolders (keep);
  35556. }
  35557. offline.setSong (before);
  35558. offline.dispatchPendingMessages();
  35559. }
  35560. // standalone windows, with the theme background
  35561. auto saveWindow = [&prefix] (std::unique_ptr<juce::Component> c, const juce::String& name) {
  35562. juce::Component frame;
  35563. frame.setSize (c->getWidth(), c->getHeight());
  35564. frame.setOpaque (true);
  35565. // an AlertWindow is built on the desktop: shown there first, it would take the foreground from whoever has it
  35566. // (TopLevelWindow::visibilityChanged calls toFront (true)). Off the desktop, its control that showing it would
  35567. // have focused (what grabKeyboardFocus picks) is marked, so the picture keeps that control's focus ring
  35568. if (c->isOnDesktop())
  35569. {
  35570. c->removeFromDesktop();
  35571. auto* focus = c.get();
  35572. for (int depth = 0; focus != nullptr && depth < 32; ++depth)
  35573. {
  35574. if (focus->getWantsKeyboardFocus() && (focus->isEnabled() || focus == c.get()))
  35575. {
  35576. focus->getProperties().set ("lynxSnapshotFocus", true);
  35577. break;
  35578. }
  35579. auto traverser = focus->createKeyboardFocusTraverser();
  35580. focus = traverser != nullptr ? traverser->getDefaultComponent (focus) : nullptr;
  35581. }
  35582. }
  35583. frame.addAndMakeVisible (*c);
  35584. c->setTopLeftPosition (0, 0);
  35585. checkTextFit (*c, name.fromFirstOccurrenceOf ("-", false, false).upToLastOccurrenceOf (".", false, false));
  35586. auto image = lynx::shot::paint (frame, lynx::theme::panel);
  35587. const auto file = lynx::shot::file (juce::File (prefix + name));
  35588. file.deleteFile();
  35589. juce::PNGImageFormat png;
  35590. if (auto out = file.createOutputStream())
  35591. png.writeImageToStream (image, *out);
  35592. };
  35593. saveWindow (lynx::makeExportPanel (offline), "-export.png");
  35594. saveWindow (lynx::makeExportPanel (offline, 1), "-export-mp3.png");
  35595. saveWindow (lynx::makeExportPanel (offline, 3), "-export-flac-stems.png");
  35596. saveWindow (lynx::makeExportPanel (offline, 4), "-export-aiff.png"); // owner decision D5
  35597. if (lynx::aac::available())
  35598. saveWindow (lynx::makeExportPanel (offline, 5), "-export-m4a.png");
  35599. {
  35600. // REA round 165f-mixer: the mixer track's Track latency / routing submenus, Disk recording, PDC, and the
  35601. // Export window for "Render selected tracks to wave file(s)"
  35602. const auto before = offline.getSong();
  35603. offline.editSong ([] (lynx::Song& s) {
  35604. if (s.mixer.size() > 3)
  35605. {
  35606. s.mixer[1].latencyMs = 5.0f;
  35607. s.mixer[1].latencyBypass = lynx::LatencyBypass::whenRecordingOrStopped;
  35608. s.mixer[2].latencyMs = -1.5f;
  35609. }
  35610. });
  35611. offline.dispatchPendingMessages();
  35612. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  35613. strips.setSelection ({ 1, 2, 3 }, 1);
  35614. const auto menu = strips.buildMenu (1);
  35615. juce::StringArray names { "Mixer track" };
  35616. std::vector<juce::PopupMenu> menus { menu };
  35617. const auto latencyPrefix = lynx::tr ("Track latency: {0}", { juce::String() });
  35618. const juce::String wanted[] = { lynx::tr ("Selected tracks ⇄ this track"), lynx::tr ("Disk recording"),
  35619. lynx::tr ("Plugin delay compensation") };
  35620. for (juce::PopupMenu::MenuItemIterator it (menu); it.next();)
  35621. {
  35622. const auto& item = it.getItem();
  35623. if (item.subMenu != nullptr && (item.text.startsWith (latencyPrefix) || std::find (std::begin (wanted), std::end (wanted), item.text) != std::end (wanted)))
  35624. {
  35625. names.add (item.text.upToFirstOccurrenceOf (":", false, false));
  35626. menus.push_back (*item.subMenu);
  35627. }
  35628. }
  35629. saveMenus (names, menus, prefix + "-menus165-mixer.png");
  35630. saveWindow (lynx::makeExportPanelForTracks (offline, { 1, 2, 3 }), "-export165-tracks.png");
  35631. offline.setSong (before);
  35632. offline.dispatchPendingMessages();
  35633. }
  35634. saveSplashFrames (prefix);
  35635. saveIconSheet (prefix + "-icons.png", 1.0f);
  35636. saveIconSheet (prefix + "-icons-150.png", 1.5f);
  35637. saveStateSheet (prefix + "-states190je.png", 1.0f); // round 190je: the one state rule, per button kind
  35638. saveStateSheet (prefix + "-states190je-z3.png", 3.0f);
  35639. saveWindow (lynx::MainComponent::makeHelpContent (nullptr, [] {}), "-help.png"); // (round 190ns: with its Manage shortcuts link)
  35640. saveWindow (lynx::ui::makeTrackIconGrid (5, {}), "-trackicons168h.png"); // round 168h: the icon picker
  35641. saveWindow (std::make_unique<lynx::toolbar::CustomizePanel> (lynx::toolbarlayout::Layout::makeDefault()), "-customize-toolbar.png");
  35642. // two moved controls: Tools › Last tweaked and Add › Automation for last tweaked parameter show them (REA round 143)
  35643. offline.noteTweaked ({ lynx::AutomationTargetKind::channelVolume, 0 });
  35644. offline.noteTweaked ({ lynx::AutomationTargetKind::mixerVolume, 0 });
  35645. saveMenus (ui, prefix + "-menus.png");
  35646. {
  35647. // the windows' own menus (title bars) and the toolbar's recording menu
  35648. juce::StringArray names;
  35649. std::vector<juce::PopupMenu> menus;
  35650. for (auto [panel, name] : { std::pair { lynx::workspace::Panel::playlist, "Playlist" }, { lynx::workspace::Panel::channelRack, "Channel Rack" },
  35651. { lynx::workspace::Panel::pianoRoll, "Piano Roll" }, { lynx::workspace::Panel::mixer, "Mixer" },
  35652. { lynx::workspace::Panel::browser, "Browser" } })
  35653. {
  35654. names.add (name);
  35655. menus.push_back (ui.getPanelMenuForSnapshot (panel));
  35656. }
  35657. names.add ("Recording");
  35658. menus.push_back (ui.getRecordMenuForSnapshot());
  35659. names.add ("Toolbar");
  35660. menus.push_back (ui.getToolbarMenuForSnapshot());
  35661. saveMenus (names, menus, prefix + "-panel-menus.png");
  35662. }
  35663. // round 189e: the Playlist menu's Edit and Select submenus (FL's items and order) and the header drop question
  35664. saveMenus (juce::StringArray { "Playlist: Edit", "Playlist: Select" },
  35665. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().editMenu(), ui.getPlaylistForSnapshot().selectMenu() },
  35666. prefix + "-playlist-edit189e.png");
  35667. saveWindow (lynx::PlaylistComponent::makeHeaderDropDialog(), "-header-drop189e.png");
  35668. {
  35669. // round 189i: FL's fade handle menu (right-click on an audio clip's fade handle), on the song's first audio
  35670. // clip, or on one added for the shot
  35671. const auto before = offline.getSong();
  35672. auto clipIndex = -1;
  35673. for (std::size_t i = 0; i < before.playlist.size() && clipIndex < 0; ++i)
  35674. if (before.playlist[i].kind == lynx::ClipKind::audio)
  35675. clipIndex = (int) i;
  35676. if (clipIndex < 0)
  35677. {
  35678. auto song = before;
  35679. lynx::ChannelDef channel;
  35680. channel.instrument = lynx::InstrumentKind::audioClip;
  35681. channel.name = "Audio clip";
  35682. song.channels.push_back (channel);
  35683. lynx::Clip clip;
  35684. clip.kind = lynx::ClipKind::audio;
  35685. clip.channel = (int) song.channels.size() - 1;
  35686. clip.length = lynx::ppq * 4;
  35687. song.playlist.push_back (clip);
  35688. clipIndex = (int) song.playlist.size() - 1;
  35689. offline.setSong (song);
  35690. offline.dispatchPendingMessages();
  35691. }
  35692. saveMenus (juce::StringArray { "Fade handle" },
  35693. std::vector<juce::PopupMenu> { ui.getPlaylistForSnapshot().fadeHandleMenu (clipIndex, 1) },
  35694. prefix + "-fade-handle189i.png");
  35695. if (offline.getSong().playlist.size() != before.playlist.size())
  35696. {
  35697. offline.setSong (before);
  35698. offline.dispatchPendingMessages();
  35699. }
  35700. }
  35701. {
  35702. // round 189n: FL's gain handle menu with two overlapping clips selected (Normalize selection individually / as a
  35703. // group) and the later clip's fade in menu (Create crossfade enabled); FL shots in /mnt/e/lynx-work/flgap189n
  35704. const auto before = offline.getSong();
  35705. auto song = before;
  35706. lynx::ChannelDef channel;
  35707. channel.instrument = lynx::InstrumentKind::audioClip;
  35708. channel.name = "Audio clip";
  35709. song.channels.push_back (channel);
  35710. int lane = 0;
  35711. for (const auto& c : song.playlist)
  35712. lane = std::max (lane, c.track + 1);
  35713. for (int k = 0; k < 2; ++k)
  35714. {
  35715. lynx::Clip clip;
  35716. clip.kind = lynx::ClipKind::audio;
  35717. clip.channel = (int) song.channels.size() - 1;
  35718. clip.track = lane;
  35719. clip.start = k * lynx::ppq * 3;
  35720. clip.length = lynx::ppq * 4;
  35721. song.playlist.push_back (clip);
  35722. }
  35723. const auto second = (int) song.playlist.size() - 1;
  35724. song.autoCrossfades = true; // FL's capture: Thief has Automatic crossfades on
  35725. offline.setSong (song);
  35726. offline.dispatchPendingMessages();
  35727. auto& playlist = ui.getPlaylistForSnapshot();
  35728. playlist.selectForSnapshot ({ second - 1, second });
  35729. auto gain = playlist.gainMenu (second);
  35730. auto fadeIn = playlist.fadeHandleMenu (second, 0); // (both selected, as in FL's capture)
  35731. playlist.selectForSnapshot ({});
  35732. saveMenus (juce::StringArray { "Gain handle, 2 selected", "Fade in, overlapping" },
  35733. std::vector<juce::PopupMenu> { gain, fadeIn }, prefix + "-fade-gain189n.png");
  35734. // round 189o: the audio clip menu with both overlapping clips selected (FL's Fades › Crossfade selected
  35735. // shown) and with none selected (hidden)
  35736. playlist.selectForSnapshot ({ second - 1, second });
  35737. auto clipSelected = playlist.getClipMenuForSnapshot (second);
  35738. playlist.selectForSnapshot ({});
  35739. auto clipAlone = playlist.getClipMenuForSnapshot (second);
  35740. saveMenus (juce::StringArray { "Audio clip, 2 selected", "Audio clip, none selected" },
  35741. std::vector<juce::PopupMenu> { clipSelected, clipAlone }, prefix + "-xfadesel189o.png");
  35742. offline.setSong (before);
  35743. offline.dispatchPendingMessages();
  35744. }
  35745. {
  35746. // REA round 143: the piano roll Tools menu, a Playlist track menu and a mixer insert menu (FL's layouts)
  35747. std::vector<juce::PopupMenu> menus { ui.getPianoRollForSnapshot().getToolsMenuForSnapshot(),
  35748. ui.getPlaylistForSnapshot().getTrackMenuForSnapshot (0),
  35749. ui.getMixerForSnapshot().getStripsForSnapshot().buildMenu (1) };
  35750. saveMenus (juce::StringArray { "Piano roll tools", "Playlist track", "Mixer track" }, menus, prefix + "-menus143.png");
  35751. // round 190as: the Piano roll's scripts (FL's Tools › Scripts column) and a script's form
  35752. saveMenus (juce::StringArray { "Piano roll scripts" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getScriptsMenuForSnapshot() },
  35753. prefix + "-prscripts-menu.png");
  35754. {
  35755. lynx::prscript::Score score;
  35756. const auto out = lynx::prscript::run (lynx::prscript::builtins().front().source, score, {});
  35757. if (out.status == lynx::prscript::Outcome::Status::needsForm)
  35758. {
  35759. lynx::ScriptPanel::Options options;
  35760. options.acceptText = lynx::tr ("Accept");
  35761. saveWindow (std::make_unique<lynx::ScriptPanel> (out.form, [] (const lynx::scriptform::Form&) {}, [] (const lynx::scriptform::Form&) {},
  35762. nullptr, options),
  35763. "-prscript-form.png");
  35764. }
  35765. }
  35766. // round 190j (discussion #10): the Piano roll menu's Chord stamp list
  35767. saveMenus (juce::StringArray { "Chord stamp" }, std::vector<juce::PopupMenu> { ui.getPianoRollForSnapshot().getStampMenuForSnapshot() },
  35768. prefix + "-stamp-menu.png");
  35769. // round 167l: the channel menu ("Lock active/mute state")
  35770. if (! offline.getSong().channels.empty())
  35771. saveMenus (juce::StringArray { "Channel" }, std::vector<juce::PopupMenu> { ui.getRackForSnapshot().getChannelMenuForSnapshot (0) }, prefix + "-channel-menu.png");
  35772. // round 163: menu density, compact (default) and comfortable, on a Browser folder menu
  35773. {
  35774. juce::PopupMenu folder;
  35775. folder.addSectionHeader ("Documents");
  35776. folder.addItem (1, "Expand all");
  35777. folder.addItem (2, "Collapse all");
  35778. folder.addSeparator();
  35779. folder.addItem (3, "Refresh");
  35780. folder.addSectionHeader ("System");
  35781. folder.addItem (4, "Open");
  35782. folder.addItem (5, "Copy the file path");
  35783. folder.addSectionHeader ("Tags");
  35784. folder.addItem (6, "Starred", true, true);
  35785. folder.addSeparator();
  35786. folder.addItem (7, "Add folder...");
  35787. const auto wasCompact = lynx::theme::menus::compact();
  35788. lynx::theme::menus::setCompact (true);
  35789. saveMenus (juce::StringArray { "Compact" }, { folder }, prefix + "-menu163-compact.png");
  35790. lynx::theme::menus::setCompact (false);
  35791. saveMenus (juce::StringArray { "Comfortable" }, { folder }, prefix + "-menu163-comfortable.png");
  35792. lynx::theme::menus::setCompact (wasCompact);
  35793. }
  35794. // and the clip menus of the first pattern, audio and automation clips of the project
  35795. juce::StringArray clipNames;
  35796. std::vector<juce::PopupMenu> clipMenus;
  35797. for (auto [kind, name] : { std::pair { lynx::ClipKind::pattern, "Pattern clip" }, { lynx::ClipKind::audio, "Audio clip" },
  35798. { lynx::ClipKind::automation, "Automation clip" } })
  35799. for (int c = 0; c < (int) offline.getSong().playlist.size(); ++c)
  35800. if (offline.getSong().playlist[(std::size_t) c].kind == kind)
  35801. {
  35802. clipNames.add (name);
  35803. clipMenus.push_back (ui.getPlaylistForSnapshot().getClipMenuForSnapshot (c));
  35804. break;
  35805. }
  35806. if (! clipMenus.empty())
  35807. saveMenus (clipNames, clipMenus, prefix + "-menus143-clips.png");
  35808. }
  35809. auto saveAlert = [&] (std::unique_ptr<juce::AlertWindow> alert, const juce::String& name) {
  35810. alert->setOpaque (true);
  35811. saveWindow (std::move (alert), name);
  35812. };
  35813. saveAlert (ui.makeConfirmDiscardWindow(), "-confirm.png");
  35814. saveAlert (lynx::MainComponent::makeAboutWindow(), "-about.png");
  35815. saveAlert (lynx::support::makeSupportWindow(), "-support.png"); // round 190fq: Help › Support LYNX SHARE...
  35816. saveAlert (lynx::makeNameAndColourDialog (lynx::tr ("Rename pattern"), "Pattern 2", lynx::lynxPalette()[6]), "-rename.png");
  35817. saveAlert (lynx::makeRecordChoiceDialog(), "-record-dialog.png");
  35818. // round 190ah: Online Sessions — a guest's "go back in?" at start-up, the host's question at a guest's file limit
  35819. saveAlert (lynx::liveui::makeRejoinDialog ("Ana", juce::Time (2026, 10, 10, 21, 40).toString (true, true, false, true)), "-live-rejoin.png");
  35820. saveAlert (lynx::liveui::makeMediaLimitDialog ("Pedro", (juce::int64) 1010 << 20, (juce::int64) 1 << 30), "-live-media-limit.png");
  35821. saveAlert (lynx::makeSamplePitchDialog (7.25f, true, true), "-sample-pitch.png"); // round 163c
  35822. saveAlert (lynx::makeGradientColourDialog (juce::Colour (0xffe5383b), juce::Colour (0xff3a7bd5), 8), "-gradient.png"); // round 177a
  35823. saveAlert (lynx::makeMidiImportDialog(), "-midi-import-dialog.png"); // File › Import › MIDI file (REA round 143)
  35824. // round 186c: FL's mixer "Delete" questions and its Settings › General › Manage messages menu
  35825. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Delete tracks"), lynx::tr ("This will |delete| {0} selected mixer track(s). Are you sure?", { "1" }),
  35826. { lynx::tr ("Yes"), lynx::tr ("No") }, true }),
  35827. "-delete-tracks.png");
  35828. saveAlert (lynx::makeFlMessageDialog ({ lynx::tr ("Playlist tracks"),
  35829. lynx::tr ("One or more mixer tracks that will be deleted are connected to instrument/audio tracks.") + "\n"
  35830. + lynx::tr ("Do you want to unlink the tracks and channels or delete them?"),
  35831. { lynx::tr ("Delete tracks and channels"), lynx::tr ("Unlink tracks and channels"), lynx::tr ("Cancel") }, false }),
  35832. "-delete-tracks-linked.png");
  35833. saveMenus (juce::StringArray { "Manage messages" }, std::vector<juce::PopupMenu> { lynx::messages::manageMenu() }, prefix + "-manage-messages.png");
  35834. saveWindow (lynx::makeSetupWizardContent (offline, {}, {}), "-setup.png");
  35835. saveWindow (lynx::crashreporter::makeDialogForSnapshot (false), "-crash-report.png"); // round 159
  35836. saveWindow (lynx::crashreporter::makeDialogForSnapshot (true), "-report-problem.png");
  35837. // round 166b: the update bar in its states (available, downloading, failed, ready) and the release notes window
  35838. {
  35839. struct Bars final : juce::Component
  35840. {
  35841. Bars()
  35842. {
  35843. constexpr int h = lynx::updater::UpdateBar::height;
  35844. setSize (1100, 6 * (h + 6));
  35845. for (int state = 0; state < 6; ++state) // (round 190gh: 4 going back, 5 went back)
  35846. {
  35847. bars[state].setBounds (0, state * (h + 6), getWidth(), h);
  35848. bars[state].showForSnapshot (state);
  35849. addAndMakeVisible (bars[state]);
  35850. }
  35851. }
  35852. lynx::updater::UpdateBar bars[6];
  35853. };
  35854. saveWindow (std::make_unique<Bars>(), "-update-bar.png");
  35855. saveWindow (lynx::updater::makeReleaseNotesForSnapshot(), "-update-notes.png");
  35856. // round 190gh (B23): Help › Test audio output... in its states
  35857. for (int state = 0; state < 5; ++state)
  35858. saveWindow (lynx::makeAudioCheckForSnapshot (offline, state), "-audio-check-" + juce::String (state) + ".png");
  35859. }
  35860. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 0, 1), "-missing-files.png");
  35861. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 1), "-missing-plugins.png");
  35862. saveWindow (lynx::makeMissingFilesPanel (lynx::missingFilesSnapshotInfo(), 2), "-missing-found.png");
  35863. {
  35864. // the Settings pages, with credits like a project imported from FL would carry
  35865. offline.editSong ([] (lynx::Song& s) {
  35866. s.info = { "Night Drive", "LYNX SHARE demo", "Synthwave", "https://lynx-share.com",
  35867. "Made with LYNX SHARE.\nDrums and bass from the Channel Rack, pads from the Browser.", false };
  35868. }, false);
  35869. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::project), "-settings-project.png");
  35870. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::info), "-settings-info.png");
  35871. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::files), "-settings-files.png");
  35872. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::general), "-settings-general.png");
  35873. {
  35874. // round 189o: the whole General page (the Editing and Plugins sections hold FL's "Monophonic painting in
  35875. // piano roll" and "Limit the number of open plugin editors")
  35876. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  35877. tall->setSize (tall->getWidth(), 3200);
  35878. saveWindow (std::move (tall), "-settings-general-tall189o.png");
  35879. }
  35880. {
  35881. // the whole General page (round 186a: the Startup section is below the first screen)
  35882. auto tall = lynx::makeSettingsPanel (offline, lynx::SettingsPage::general);
  35883. tall->setSize (tall->getWidth(), 1500);
  35884. saveWindow (std::move (tall), "-settings-general-tall.png");
  35885. }
  35886. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::theme), "-settings-theme.png");
  35887. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::extras), "-settings-extras.png"); // round 190am
  35888. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::audio), "-settings-audio.png");
  35889. saveWindow (lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi), "-settings-midi.png");
  35890. {
  35891. // round 190bj (QA): the MIDI page in a small window keeps each row's switch and device name
  35892. auto small = lynx::makeSettingsPanel (offline, lynx::SettingsPage::midi);
  35893. small->setSize (390, 390);
  35894. saveWindow (std::move (small), "-settings-midi-small.png");
  35895. }
  35896. {
  35897. // round 190bj (QA): the Apex Limiter's window content at its default size, as sized before (JUCE's ratio
  35898. // on the whole window: the status row cut off) and now
  35899. lynx::AudioEngine apexEngine (false);
  35900. lynx::Song song;
  35901. song.mixer.resize (2);
  35902. song.mixer[0].name = "Master";
  35903. song.mixer[1].name = "Insert 1";
  35904. song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::apexLimiter));
  35905. apexEngine.setSong (std::move (song));
  35906. apexEngine.dispatchPendingMessages();
  35907. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, true), prefix + "-apex-window-before190bj.png");
  35908. savePng (lynx::ProEditorWindows::windowContentForSnapshot (apexEngine, 1, 0, false), prefix + "-apex-window.png");
  35909. }
  35910. saveWindow (lynx::makePluginManagerPanel (offline, false), "-plugin-manager.png");
  35911. // round 190gg: the crash prompt and a plugin window's crash notice, with "Always run ... in a separate process"
  35912. saveWindow (lynx::PluginWindows::makeCrashPromptPanel ("Serum", false), "-plugin-crash-prompt.png");
  35913. saveWindow (lynx::PluginWindows::makeCrashNoticePanel ("Serum", true), "-plugin-crash-notice.png");
  35914. saveWindow (lynx::makeShortcutManagerPanel (false), "-shortcuts.png");
  35915. }
  35916. {
  35917. // round 84: New project, Clip properties, Arrangements, Plugin performance monitor, Touch keyboard
  35918. saveWindow (lynx::makeNewProjectPanel(), "-new-project.png");
  35919. const auto& clips = offline.getSong().playlist;
  35920. for (int i = 0; i < (int) clips.size(); ++i)
  35921. if (clips[(std::size_t) i].kind == lynx::ClipKind::pattern)
  35922. {
  35923. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i, (i + 1) % (int) clips.size() }), "-clip-properties.png");
  35924. break;
  35925. }
  35926. for (int i = 0; i < (int) clips.size(); ++i)
  35927. if (clips[(std::size_t) i].kind == lynx::ClipKind::audio)
  35928. {
  35929. saveWindow (lynx::makeClipPropertiesPanel (offline, i, { i }), "-clip-properties-audio.png");
  35930. break;
  35931. }
  35932. if (offline.getSong().arrangements.size() < 2)
  35933. offline.editSong ([] (lynx::Song& s) {
  35934. const auto current = s.currentArrangement;
  35935. s.addArrangement ("Radio edit", true);
  35936. s.addArrangement ("Intro loop");
  35937. s.selectArrangement (current);
  35938. }, false);
  35939. saveWindow (lynx::makeArrangementsPanel (offline), "-arrangements.png");
  35940. saveWindow (lynx::makePluginMonitorPanel (offline), "-plugin-monitor.png");
  35941. saveWindow (lynx::makeTouchKeyboardPanel (offline), "-touch-keyboard.png");
  35942. }
  35943. {
  35944. // round 142: the Newtone / Newtime editors on a synthetic sung line (A3 B3 C4 · E4), one note moved
  35945. const auto wav = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-newtone.wav");
  35946. {
  35947. juce::AudioBuffer<float> line (1, 44100 * 2);
  35948. const double hz[] = { 220.0, 246.94, 261.63, 0.0, 329.63 };
  35949. double ph = 0.0;
  35950. for (int i = 0; i < line.getNumSamples(); ++i)
  35951. {
  35952. const auto f0 = hz[std::min (4, i / 17640)];
  35953. 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;
  35954. float v = 0.0f;
  35955. for (int h = 1; f0 > 0.0 && h < 8; ++h)
  35956. v += (float) (0.3 / h * std::sin (h * ph));
  35957. line.setSample (0, i, v);
  35958. }
  35959. wav.deleteFile();
  35960. juce::WavAudioFormat format;
  35961. std::unique_ptr<juce::OutputStream> out (wav.createOutputStream().release());
  35962. if (auto* w = out != nullptr ? format.createWriterFor (out.get(), 44100.0, 1, 16, {}, 0) : nullptr)
  35963. {
  35964. out.release();
  35965. std::unique_ptr<juce::AudioFormatWriter> writer (w);
  35966. writer->writeFromAudioSampleBuffer (line, 0, line.getNumSamples());
  35967. }
  35968. }
  35969. if (const auto sample = offline.getSampleLibrary().load (wav.getFullPathName()))
  35970. {
  35971. auto notes = lynx::newtonefx::analyseNotes (*sample);
  35972. if (notes.pitches.size() > 1)
  35973. notes.pitches[1].shift = 2.0;
  35974. lynx::newtonefx::WarpMap warp;
  35975. warp.frames = (std::int64_t) sample->frames();
  35976. warp.markers = { { 22050, 33075 } };
  35977. int at = 0;
  35978. offline.editSong ([&] (lynx::Song& song) {
  35979. if (song.mixer.size() < 2)
  35980. song.mixer.resize (2);
  35981. auto& fx = song.mixer[1].effects;
  35982. auto tone = lynx::makeEffectSlot (lynx::EffectKind::newtone);
  35983. tone.samplePath = wav.getFullPathName().toStdString();
  35984. tone.state = lynx::newtonefx::writeNative (notes);
  35985. auto time = lynx::makeEffectSlot (lynx::EffectKind::newtime);
  35986. time.samplePath = tone.samplePath;
  35987. time.state = lynx::newtonefx::writeWarp (warp);
  35988. at = (int) fx.size();
  35989. fx.push_back (tone);
  35990. fx.push_back (time);
  35991. }, false);
  35992. saveWindow (lynx::makeNewtoneEditor (offline, 1, at), "-newtone.png");
  35993. saveWindow (lynx::makeNewtoneEditor (offline, 1, at + 1), "-newtime.png");
  35994. offline.editSong ([at] (lynx::Song& song) {
  35995. auto& fx = song.mixer[1].effects;
  35996. fx.erase (fx.begin() + at, fx.begin() + at + 2);
  35997. }, false);
  35998. }
  35999. }
  36000. if (! offline.getSong().automations.empty())
  36001. {
  36002. auto editor = lynx::makeAutomationEditor (offline, 0);
  36003. editor->setSize (760, 300);
  36004. saveWindow (std::move (editor), "-automation.png");
  36005. // round 177b: the same clip in FL's LFO mode: FL's defaults, then one shaped state (the UI gate pairs)
  36006. const auto before = offline.getSong().automations[0].lfo;
  36007. const auto lfoShot = [&offline, &saveWindow] (std::function<void (lynx::AutomationLfo&)> set, const char* suffix) {
  36008. offline.editSong ([&set] (lynx::Song& song) {
  36009. auto& lfo = song.automations[0].lfo;
  36010. lfo = lynx::AutomationLfo {};
  36011. lfo.on = true;
  36012. set (lfo);
  36013. }, false);
  36014. auto lfoEditor = lynx::makeAutomationEditor (offline, 0);
  36015. lfoEditor->setSize (760, 346);
  36016. saveWindow (std::move (lfoEditor), suffix);
  36017. };
  36018. lfoShot ([] (lynx::AutomationLfo&) {}, "-automation-lfo.png");
  36019. lfoShot ([] (lynx::AutomationLfo& lfo) {
  36020. // the state set through FL's own UI for the UI gate (TNS 50 %, SKEW 25 %, PW 25 %, two points), as FL saved it
  36021. lfo.tension = 64;
  36022. lfo.skew = 32;
  36023. lfo.pulseWidth = 28;
  36024. lfo.amp = { { 0, 0.6716f, 0.0f }, { (std::int64_t) (lynx::ppq * 1.4128), 0.9204f, 0.0f } };
  36025. }, "-automation-lfo-shape.png");
  36026. offline.editSong ([before] (lynx::Song& song) { song.automations[0].lfo = before; }, false);
  36027. }
  36028. // round 177b: LYNX's modulators window, with one routed modulator
  36029. {
  36030. offline.editSong ([] (lynx::Song& song) {
  36031. lynx::Modulator m;
  36032. m.name = "LFO 1";
  36033. m.shape = lynx::ModShape::triangle;
  36034. m.routes = { { { lynx::AutomationTargetKind::mixerVolume, 1, 0, 0 }, 0.25f }, { { lynx::AutomationTargetKind::mixerPan, 1, 0, 0 }, -0.5f } };
  36035. song.modulators.push_back (m);
  36036. lynx::Modulator r;
  36037. r.name = "LFO 2";
  36038. r.shape = lynx::ModShape::smoothRandom;
  36039. r.sync = false;
  36040. r.hz = 0.5;
  36041. song.modulators.push_back (r);
  36042. }, false);
  36043. auto mods = lynx::makeModulatorsPanel (offline);
  36044. mods->setSize (720, 360);
  36045. saveWindow (std::move (mods), "-modulators.png");
  36046. offline.editSong ([] (lynx::Song& song) { song.modulators.clear(); }, false);
  36047. }
  36048. saveWindow (lynx::makeChannelSettingsPanel (offline, 0), "-sampler.png");
  36049. // the channel window frame (REA round 143b): header strip + tabs; the Misc tab of the first channel and of a synth
  36050. saveWindow (lynx::makeChannelFrame (offline, 0), "-channel-frame.png");
  36051. saveWindow (lynx::makeChannelFrame (offline, 0, -1), "-channel-misc.png");
  36052. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  36053. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::synth)
  36054. {
  36055. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-synth.png");
  36056. saveWindow (lynx::makeChannelModulationPanel (offline, c), "-modulation.png");
  36057. break;
  36058. }
  36059. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  36060. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::controller)
  36061. {
  36062. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-controller.png");
  36063. break;
  36064. }
  36065. for (const auto kind : { lynx::InstrumentKind::sakura, lynx::InstrumentKind::drumpad })
  36066. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  36067. if (offline.getSong().channels[(std::size_t) c].instrument == kind)
  36068. {
  36069. saveWindow (lynx::makeChannelSettingsPanel (offline, c), kind == lynx::InstrumentKind::sakura ? "-sakura.png" : "-drumpad.png");
  36070. break;
  36071. }
  36072. // round 180c: Fruity Slicer's editor
  36073. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  36074. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fruityslicer)
  36075. {
  36076. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fruityslicer.png");
  36077. // rounds 190f / 190m: its Envelope / instrument page, one picture per target
  36078. saveWindow (lynx::makeChannelFrame (offline, c, 1), "-fruityslicer-envelope.png");
  36079. for (const auto& [target, name] : std::vector<std::pair<int, const char*>> { { 0, "panning" }, { 2, "modx" }, { 3, "mody" }, { 4, "pitch" } })
  36080. {
  36081. auto frame = lynx::makeChannelFrame (offline, c, 1);
  36082. lynx::showFlVoiceTarget (*frame, target);
  36083. saveWindow (std::move (frame), juce::String ("-fruityslicer-envelope-") + name + ".png");
  36084. }
  36085. break;
  36086. }
  36087. // round 190r: Slicex's editor
  36088. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  36089. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::slicex)
  36090. {
  36091. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-slicex.png");
  36092. break;
  36093. }
  36094. // round 190q: FPC's editor
  36095. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  36096. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::fpc)
  36097. {
  36098. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-fpc.png");
  36099. break;
  36100. }
  36101. // round 190hz: DirectWave's editor
  36102. for (int c = 0; c < (int) offline.getSong().channels.size(); ++c)
  36103. if (offline.getSong().channels[(std::size_t) c].instrument == lynx::InstrumentKind::directwave)
  36104. {
  36105. saveWindow (lynx::makeChannelSettingsPanel (offline, c), "-directwave.png");
  36106. break;
  36107. }
  36108. // parametric EQ: the one with the most pronounced curve (in an imported .flp, with FL's settings)
  36109. {
  36110. int bestTrack = -1, bestSlot = -1;
  36111. double bestShape = -1.0;
  36112. const auto& mixer = offline.getSong().mixer;
  36113. for (int t = 0; t < (int) mixer.size(); ++t)
  36114. for (int s = 0; s < (int) mixer[(std::size_t) t].effects.size(); ++s)
  36115. if (const auto& fx = mixer[(std::size_t) t].effects[(std::size_t) s]; fx.kind == lynx::EffectKind::parametricEq)
  36116. {
  36117. double shape = 0.0;
  36118. for (double hz = 30.0; hz < 18000.0; hz *= 1.5)
  36119. shape += std::abs (lynx::peq::responseDb (fx.params, 48000.0, hz));
  36120. if (shape > bestShape)
  36121. {
  36122. bestShape = shape;
  36123. bestTrack = t;
  36124. bestSlot = s;
  36125. }
  36126. }
  36127. if (bestTrack >= 0)
  36128. saveWindow (lynx::makeParametricEqEditor (offline, bestTrack, bestSlot), "-peq.png");
  36129. }
  36130. // Note inspector for the Piano Roll's notes (its selection, or all of the channel's notes)
  36131. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot())
  36132. saveWindow (std::move (inspector), "-noteinspector.png");
  36133. if (auto inspector = ui.getPianoRollForSnapshot().makeNoteInspectorForSnapshot (true))
  36134. saveWindow (std::move (inspector), "-noteinspector-one.png");
  36135. // workflow P2: note tool dialogs (they preview on the pattern; each one puts the notes back when destroyed)
  36136. {
  36137. auto& roll = ui.getPianoRollForSnapshot();
  36138. const std::pair<lynx::NoteTool, const char*> tools[] = { { lynx::NoteTool::strum, "-tool-strum.png" },
  36139. { lynx::NoteTool::arpeggiate, "-tool-arpeggiate.png" },
  36140. { lynx::NoteTool::flip, "-tool-flip.png" },
  36141. { lynx::NoteTool::randomise, "-tool-randomise.png" },
  36142. { lynx::NoteTool::scaleLevels, "-tool-scalelevels.png" },
  36143. { lynx::NoteTool::limit, "-tool-limit.png" },
  36144. { lynx::NoteTool::quantize, "-tool-quantize.png" },
  36145. { lynx::NoteTool::chop, "-tool-chop.png" },
  36146. { lynx::NoteTool::flam, "-tool-flam.png" },
  36147. { lynx::NoteTool::lfo, "-tool-lfo.png" },
  36148. { lynx::NoteTool::claw, "-tool-claw.png" },
  36149. { lynx::NoteTool::articulate, "-tool-articulate.png" },
  36150. { lynx::NoteTool::riffMachine, "-tool-riff.png" },
  36151. { lynx::NoteTool::chordProgression, "-tool-chords.png" } };
  36152. for (const auto& [tool, name] : tools)
  36153. saveWindow (lynx::makeNoteToolPanel (offline, tool, roll.noteIndicesForSnapshot(), roll.gridForSnapshot()), name);
  36154. }
  36155. // round 83: the event editor, with sample events on the selected channel's volume (removed afterwards)
  36156. {
  36157. const lynx::AutomationTarget volume { lynx::AutomationTargetKind::channelVolume, offline.getSelectedChannel() };
  36158. const auto before = offline.getSong().patterns[(std::size_t) offline.getSong().currentPattern].events;
  36159. offline.editSong ([&] (lynx::Song& s) {
  36160. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], volume);
  36161. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.2f, 0.9f, lynx::ticksPerStep);
  36162. lynx::prtools::LfoOptions lfo;
  36163. lfo.startSpeed = 7 * 4096; // one beat
  36164. lynx::eventedit::applyLfo (lane, lynx::ppq * 2, lynx::ppq * 4, lfo, lynx::ticksPerStep);
  36165. }, false);
  36166. saveWindow (lynx::makeEventEditor (offline, volume), "-eventeditor.png");
  36167. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  36168. // issue #86: the same editor on the Tempo target, with the project's own Tempo events (a sample ramp if none)
  36169. const lynx::AutomationTarget tempo { lynx::AutomationTargetKind::tempo, 0 };
  36170. offline.editSong ([&] (lynx::Song& s) {
  36171. auto& lane = lynx::eventedit::laneFor (s.patterns[(std::size_t) s.currentPattern], tempo);
  36172. if (lane.events.empty())
  36173. lynx::eventedit::line (lane, 0, lynx::ppq * 2, 0.05f, 0.11f, lynx::ticksPerStep);
  36174. }, false);
  36175. saveWindow (lynx::makeEventEditor (offline, tempo), "-eventeditor-tempo.png");
  36176. {
  36177. auto compact = lynx::makeEventEditor (offline, tempo); // the toolbar in a small window
  36178. compact->setSize (640, 300);
  36179. saveWindow (std::move (compact), "-eventeditor-tempo-small.png");
  36180. auto narrowest = lynx::makeEventEditor (offline, tempo); // the tool window's lower limit
  36181. narrowest->setSize (400, 300);
  36182. saveWindow (std::move (narrowest), "-eventeditor-tempo-narrowest.png");
  36183. }
  36184. offline.editSong ([&] (lynx::Song& s) { s.patterns[(std::size_t) s.currentPattern].events = before; }, false);
  36185. }
  36186. // round 86: the audio editor with a synthetic drum loop (markers, a region, a loop), waveform and spectrogram,
  36187. // and its menu items (-audioeditor-menu.txt)
  36188. {
  36189. namespace ae = lynx::audioedit;
  36190. ae::Document d;
  36191. d.title = "Drum loop";
  36192. d.audio.sampleRate = 44100.0;
  36193. const auto frames = (std::size_t) (44100 * 2);
  36194. d.audio.channels.assign (2, std::vector<float> (frames, 0.0f));
  36195. std::uint32_t seed = 7;
  36196. for (int hit = 0; hit < 8; ++hit)
  36197. {
  36198. const auto at = (std::size_t) hit * frames / 8;
  36199. const auto kick = hit % 2 == 0;
  36200. double phase = 0.0;
  36201. for (std::size_t i = 0; i < 12000 && at + i < frames; ++i)
  36202. {
  36203. seed = seed * 1664525u + 1013904223u;
  36204. const auto noise = (float) (seed >> 8) / 16777216.0f - 0.5f;
  36205. const auto t = (double) i / 44100.0;
  36206. phase += 2.0 * 3.141592653589793 * (kick ? 45.0 + 160.0 * std::exp (-t * 30.0) : 190.0) / 44100.0;
  36207. const auto body = (float) std::sin (phase) * (float) std::exp (-t * (kick ? 9.0 : 22.0));
  36208. const auto v = kick ? 0.85f * body : 0.35f * body + 0.6f * noise * (float) std::exp (-t * 18.0);
  36209. d.audio.channels[0][at + i] += v;
  36210. d.audio.channels[1][at + i] += kick ? v : v * 0.8f + 0.1f * noise * (float) std::exp (-t * 30.0);
  36211. }
  36212. }
  36213. ae::addMarker (d, (std::int64_t) frames / 8, "Snare");
  36214. ae::addRegion (d, { (std::int64_t) frames / 2, (std::int64_t) frames * 3 / 4 }, "Fill");
  36215. ae::setLoop (d, { 0, (std::int64_t) frames });
  36216. auto wave = lynx::makeAudioEditorForSnapshot (offline, d, false);
  36217. juce::File (prefix + "-audioeditor-menu.txt").replaceWithText (lynx::audioEditorMenuForSnapshot (*wave).joinIntoString ("\n") + "\n");
  36218. saveWindow (std::move (wave), "-audioeditor.png");
  36219. saveWindow (lynx::makeAudioEditorForSnapshot (offline, d, true), "-audioeditor-spectrum.png");
  36220. }
  36221. // warp markers (round 175a, M3): the audio editor of the first audio clip whose channel has warp markers,
  36222. // opened as the Playlist opens it, with its warp lane
  36223. {
  36224. const auto& song = offline.getSong();
  36225. for (int i = 0; i < (int) song.playlist.size(); ++i)
  36226. {
  36227. const auto& c = song.playlist[(std::size_t) i];
  36228. if (c.kind == lynx::ClipKind::audio && juce::isPositiveAndBelow (c.channel, (int) song.channels.size())
  36229. && song.channels[(std::size_t) c.channel].sampler.warp.size() >= 3)
  36230. {
  36231. if (auto panel = lynx::makeAudioEditorPanel (offline, c.channel, i, true))
  36232. saveWindow (std::move (panel), "-audioeditor-warp.png");
  36233. break;
  36234. }
  36235. }
  36236. }
  36237. // the tempo tapper after five steady taps (round 132)
  36238. saveWindow (lynx::makeTempoTapperForSnapshot (offline, 5, 128.0), "-tempotapper.png");
  36239. // the Channel Rack's piano-roll view (round 132)
  36240. ui.selectTabForSnapshot (0);
  36241. ui.getRackForSnapshot().setPianoRollView (true);
  36242. offline.dispatchPendingMessages();
  36243. saveSnapshot (ui, prefix + "-rack-pianoroll-view.png");
  36244. ui.getRackForSnapshot().setPianoRollView (false);
  36245. // the Channel Rack with the step graph lane (velocity), and the Euclidean fill window
  36246. ui.selectTabForSnapshot (0);
  36247. ui.getRackForSnapshot().setGraphLevelForSnapshot (0);
  36248. offline.dispatchPendingMessages();
  36249. saveSnapshot (ui, prefix + "-rack-graph.png");
  36250. ui.getRackForSnapshot().setGraphLevelForSnapshot (1);
  36251. saveSnapshot (ui, prefix + "-rack-graph-pan.png");
  36252. // FL's Note pitch, Shift and Repeat lanes (issue #208)
  36253. ui.getRackForSnapshot().setGraphLevelForSnapshot ((int) lynx::notetools::Level::notePitch);
  36254. saveSnapshot (ui, prefix + "-rack-graph-pitch.png");
  36255. ui.getRackForSnapshot().setGraphLevelForSnapshot ((int) lynx::notetools::Level::shift);
  36256. saveSnapshot (ui, prefix + "-rack-graph-shift.png");
  36257. ui.getRackForSnapshot().setGraphLevelForSnapshot ((int) lynx::notetools::Level::repeat);
  36258. saveSnapshot (ui, prefix + "-rack-graph-repeat.png");
  36259. ui.getRackForSnapshot().toggleGraphLanes();
  36260. saveWindow (ui.getRackForSnapshot().makeEuclideanPanel (0), "-euclidean.png");
  36261. // the Mixer with three inserts selected and one armed for recording
  36262. ui.selectTabForSnapshot (3);
  36263. if (offline.getSong().mixer.size() > 4)
  36264. {
  36265. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({ 1, 2, 3 }, 2);
  36266. offline.setInsertArmed (3, true);
  36267. offline.dispatchPendingMessages();
  36268. saveSnapshot (ui, prefix + "-mixer-multi.png");
  36269. // the armed insert with an audio input (its input row in the side panel, the level bar on the strip)
  36270. offline.editSong ([] (lynx::Song& s) { s.mixer[3].inputChannel = 0; });
  36271. ui.getMixerForSnapshot().selectTrack (3);
  36272. offline.dispatchPendingMessages();
  36273. saveSnapshot (ui, prefix + "-mixer-input.png");
  36274. offline.undo();
  36275. offline.setInsertArmed (3, false);
  36276. ui.getMixerForSnapshot().getStripsForSnapshot().setSelection ({}, 0);
  36277. }
  36278. // the Mixer's routing lane: an insert with sends selected (send knobs and wires)
  36279. if (offline.getSong().mixer.size() > 6)
  36280. {
  36281. int source = -1;
  36282. for (int t = 1; t < (int) offline.getSong().mixer.size() && source < 0; ++t)
  36283. if (! offline.getSong().mixer[(std::size_t) t].sends.empty())
  36284. source = t;
  36285. const auto temporary = source < 0;
  36286. if (temporary) // the demo has no sends: add two for the picture
  36287. {
  36288. source = 1;
  36289. 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); });
  36290. }
  36291. ui.getMixerForSnapshot().selectTrack (source);
  36292. offline.dispatchPendingMessages();
  36293. saveSnapshot (ui, prefix + "-mixer-sends.png");
  36294. if (temporary)
  36295. offline.editSong ([] (lynx::Song& s) { s.setRoute (1, 5, false); s.setRoute (1, 6, false); s.setRoute (4, 1, false); });
  36296. ui.getMixerForSnapshot().selectTrack (0);
  36297. }
  36298. // round 190io (issue #154 part 2): the Mixer view that lists each strip's insert effects (a LYNX view, off by
  36299. // default), with an insert selected whose sends light the route arrows
  36300. {
  36301. auto& strips = ui.getMixerForSnapshot().getStripsForSnapshot();
  36302. strips.setShowStripInserts (true);
  36303. offline.dispatchPendingMessages();
  36304. saveSnapshot (ui, prefix + "-mixer190io-inserts.png");
  36305. strips.setShowStripInserts (false);
  36306. offline.dispatchPendingMessages();
  36307. }
  36308. // the Playlist with ripple editing on
  36309. ui.selectTabForSnapshot (2);
  36310. ui.getPlaylistForSnapshot().setRipple (true);
  36311. saveSnapshot (ui, prefix + "-playlist-ripple.png");
  36312. ui.getPlaylistForSnapshot().setRipple (false);
  36313. // FL's legacy Pattern Blocks (round 170f, issue #60): the section under the clip tracks, a row per pattern
  36314. {
  36315. const auto saved = offline.getSong();
  36316. offline.editSong ([] (lynx::Song& s) {
  36317. s.patternBlocksOn = true;
  36318. while (s.patterns.size() < 5) // a few rows to show (Drums, Bass...: copies of the demo's pattern)
  36319. lynx::clonePattern (s, (int) s.patterns.size() - 1);
  36320. const auto rows = juce::jmin (6, (int) s.patterns.size());
  36321. for (int r = 0; r < rows; ++r)
  36322. lynx::patternblocks::paintRange (s, r, (std::int64_t) (r % 3) * 4 * lynx::ppq * 2,
  36323. (std::int64_t) (8 + r * 2) * 4 * lynx::ppq);
  36324. }, false);
  36325. offline.dispatchPendingMessages();
  36326. saveSnapshot (ui, prefix + "-playlist-blocks.png");
  36327. // issue #127 (PR #132 and our follow-up): the Playlist's pencil, brush and eraser on the blocks, driven
  36328. // with real mouse events on the view. One picture per tool, and the gestures' results in
  36329. // <prefix>-playlist-blocks-tools.txt ("OK", or the checks that failed).
  36330. if (auto* blocks = ui.getPlaylistForSnapshot().getBlocksViewForSnapshot())
  36331. {
  36332. juce::StringArray failed;
  36333. const auto expect = [&failed] (bool ok, const char* what) { if (! ok) failed.add (what); };
  36334. const auto bar = offline.getSong().barTicks();
  36335. offline.editSong ([bar] (lynx::Song& s) {
  36336. s.blocks.clear();
  36337. for (std::size_t r = 0; r < 4 && r < s.patterns.size(); ++r)
  36338. s.patterns[r].lengthTicks = r == 1 ? 2 * bar : bar; // row 2 holds a 2-bar pattern
  36339. }, false);
  36340. offline.dispatchPendingMessages();
  36341. const auto source = juce::Desktop::getInstance().getMainMouseSource();
  36342. const juce::ModifierKeys left (juce::ModifierKeys::leftButtonModifier), right (juce::ModifierKeys::rightButtonModifier);
  36343. juce::Point<float> pressedAt;
  36344. const auto event = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  36345. const auto at = blocks->pointForSnapshot (row, tick).toFloat();
  36346. const auto now = juce::Time::getCurrentTime();
  36347. return juce::MouseEvent (source, at, mods, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, blocks, blocks, now, pressedAt, now, 1, false);
  36348. };
  36349. const auto press = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) {
  36350. pressedAt = blocks->pointForSnapshot (row, tick).toFloat();
  36351. blocks->mouseDown (event (row, tick, mods));
  36352. };
  36353. const auto dragTo = [&] (int row, std::int64_t tick, juce::ModifierKeys mods) { blocks->mouseDrag (event (row, tick, mods)); };
  36354. const auto release = [&] (int row, std::int64_t tick) { blocks->mouseUp (event (row, tick, {})); };
  36355. // the starts of row `row`'s blocks, as "0,2,5" (bars from 0)
  36356. const auto rowBars = [&] (int row) {
  36357. juce::StringArray bars;
  36358. for (const auto& b : offline.getSong().blocks)
  36359. if (b.pattern == row)
  36360. bars.add (juce::String (b.start / bar) + (b.start % bar != 0 ? "+" : ""));
  36361. return bars.joinIntoString (",");
  36362. };
  36363. auto& tools = ui.getPlaylistForSnapshot();
  36364. // Pencil: a press on empty space places one block that follows the mouse along its row
  36365. tools.setToolForSnapshot (lynx::EditTool::pencil);
  36366. press (0, 2 * bar + 40, left);
  36367. expect (rowBars (0) == "2", "pencil: a press places one block");
  36368. dragTo (2, 5 * bar + 40, left); // (over another row: the block stays in its own)
  36369. release (2, 5 * bar + 40);
  36370. expect (rowBars (0) == "5" && rowBars (2).isEmpty(), "pencil: the placed block follows the drag in its row");
  36371. // a 2-bar block grabbed by its second bar keeps that bar under the mouse (it used to jump a bar)
  36372. press (1, 1 * bar + 40, left);
  36373. release (1, 1 * bar + 40);
  36374. expect (rowBars (1) == "1", "pencil: a click places the 2-bar block");
  36375. press (1, 2 * bar + 40, left);
  36376. dragTo (1, 2 * bar + bar / 2, left);
  36377. expect (rowBars (1) == "1", "move: a small move on the grabbed bar leaves the block in place");
  36378. dragTo (1, 4 * bar + 40, left);
  36379. release (1, 4 * bar + 40);
  36380. expect (rowBars (1) == "3", "move: the grabbed bar stays under the mouse");
  36381. offline.dispatchPendingMessages();
  36382. saveSnapshot (ui, prefix + "-playlist-blocks-pencil.png");
  36383. // Brush: a drag over empty space paints a run; a press on a block moves it
  36384. tools.setToolForSnapshot (lynx::EditTool::brush);
  36385. press (2, 0, left);
  36386. dragTo (2, 3 * bar + 40, left);
  36387. release (2, 3 * bar + 40);
  36388. expect (rowBars (2) == "0,1,2,3", "brush: a drag paints a run");
  36389. press (2, 3 * bar + 40, left);
  36390. dragTo (2, 6 * bar + 40, left);
  36391. release (2, 6 * bar + 40);
  36392. expect (rowBars (2) == "0,1,2,6", "brush: a press on a block moves it");
  36393. offline.dispatchPendingMessages();
  36394. saveSnapshot (ui, prefix + "-playlist-blocks-brush.png");
  36395. // Eraser, and the right button with any tool: only the blocks under the mouse, row by row
  36396. offline.editSong ([bar] (lynx::Song& s) {
  36397. for (int r = 0; r < 4 && r < (int) s.patterns.size(); ++r)
  36398. lynx::patternblocks::place (s, r, 8 * bar);
  36399. }, false);
  36400. offline.dispatchPendingMessages();
  36401. expect (rowBars (0) == "5,8" && rowBars (3) == "8", "eraser: the column is set up");
  36402. saveSnapshot (ui, prefix + "-playlist-blocks-eraser-before.png");
  36403. tools.setToolForSnapshot (lynx::EditTool::eraser);
  36404. press (0, 8 * bar + 40, left);
  36405. expect (rowBars (0) == "5" && rowBars (1) == "3,8" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8",
  36406. "eraser: a click takes only the block under the mouse");
  36407. dragTo (1, 8 * bar + 60, left); // down one row: that row's block goes too, the rows below stay
  36408. release (1, 8 * bar + 60);
  36409. expect (rowBars (1) == "3" && rowBars (2) == "0,1,2,6,8" && rowBars (3) == "8", "eraser: the drag erases the rows it crosses, no others");
  36410. tools.setToolForSnapshot (lynx::EditTool::pencil);
  36411. press (3, 8 * bar + 40, right);
  36412. release (3, 8 * bar + 40);
  36413. expect (rowBars (3).isEmpty() && rowBars (2) == "0,1,2,6,8", "right click: erases only the block under the mouse");
  36414. offline.dispatchPendingMessages();
  36415. saveSnapshot (ui, prefix + "-playlist-blocks-eraser.png");
  36416. juce::File (prefix + "-playlist-blocks-tools.txt").replaceWithText (failed.isEmpty() ? juce::String ("OK\n") : "ERROR\n" + failed.joinIntoString ("\n") + "\n");
  36417. }
  36418. offline.editSong ([saved] (lynx::Song& s) { s = saved; }, false);
  36419. offline.dispatchPendingMessages();
  36420. }
  36421. // quick-add palette, and the Browser searching
  36422. saveWindow (ui.makeQuickAddForSnapshot(), "-quickadd.png");
  36423. ui.showDesktopForSnapshot (false);
  36424. ui.getBrowserForSnapshot().setSearchForSnapshot ("kick");
  36425. offline.dispatchPendingMessages();
  36426. saveSnapshot (ui, prefix + "-browser-search.png");
  36427. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  36428. ui.getBrowserForSnapshot().selectFirstSampleForSnapshot(); // the tree with a sample selected and its waveform
  36429. offline.dispatchPendingMessages();
  36430. saveSnapshot (ui, prefix + "-browser-tree.png");
  36431. // the Browser's PROJECT tab: the patterns, generators and audio files of the project in their colours
  36432. ui.getBrowserForSnapshot().showProjectForSnapshot();
  36433. offline.dispatchPendingMessages();
  36434. saveSnapshot (ui, prefix + "-browser-project.png");
  36435. ui.getBrowserForSnapshot().showPluginDatabaseForSnapshot(); // round 142: the Plugin database's FL engines
  36436. offline.dispatchPendingMessages();
  36437. saveSnapshot (ui, prefix + "-browser-plugins.png");
  36438. // round 190bf (fl190be Q1): the Plugin database's right-click menus, a folder's and an entry's (FL's System group)
  36439. saveMenus (juce::StringArray { "Plugin database: folder", "Plugin database: entry" }, ui.getBrowserForSnapshot().pluginDatabaseMenusForSnapshot(),
  36440. prefix + "-browser190bf-menus.png");
  36441. ui.getBrowserForSnapshot().setTab (lynx::BrowserComponent::allTab);
  36442. saveWindow (ui.getBrowserForSnapshot().makeFoldersPanelForSnapshot(), "-browser-folders.png"); // round 164
  36443. {
  36444. // round 164: the content filter leaves out the folders with nothing to list (a small library)
  36445. const auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-library");
  36446. lib.deleteRecursively();
  36447. for (const auto* path : { "Drums/Kicks/kick 1.wav", "Drums/Kicks/kick 2.wav", "Drums/snare.wav", "Keys/pad.sf2", "Presets/Synth/lead.fst",
  36448. "Projects/beat.flp", "Projects/MIDI/chords.mid", "Notes/readme.txt", "Empty/Nothing/.keep" })
  36449. lib.getChildFile (path).create();
  36450. ui.showDesktopForSnapshot (false);
  36451. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  36452. offline.dispatchPendingMessages();
  36453. saveSnapshot (ui, prefix + "-browser164-all.png");
  36454. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::samples);
  36455. offline.dispatchPendingMessages();
  36456. saveSnapshot (ui, prefix + "-browser164-samples.png");
  36457. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::projects);
  36458. offline.dispatchPendingMessages();
  36459. saveSnapshot (ui, prefix + "-browser164-projects.png");
  36460. lib.deleteRecursively();
  36461. ui.getBrowserForSnapshot().resetViewForSnapshot();
  36462. }
  36463. {
  36464. // round 190as: "Find similar samples" on a small library of kicks, hats and pads (LYNX_SNAPSHOT_SIMILAR =
  36465. // "<folder>|<file>" lists a real folder instead)
  36466. auto lib = juce::File::getSpecialLocation (juce::File::tempDirectory).getChildFile ("lynx-snapshot-similar");
  36467. auto query = lib.getChildFile ("Drums/Kicks/Kick 2.wav");
  36468. const auto real = juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_SIMILAR", {});
  36469. const auto made = real.isEmpty();
  36470. if (made)
  36471. {
  36472. lib.deleteRecursively();
  36473. juce::Random random (190);
  36474. const auto write = [&] (const juce::String& path, char kind, int v) {
  36475. const auto rate = 44100.0;
  36476. const auto frames = (int) (rate * (kind == 'k' ? 0.35 : kind == 'h' ? 0.09 : 2.5));
  36477. juce::AudioBuffer<float> audio (1, frames);
  36478. double phase = 0.0;
  36479. float last = 0.0f;
  36480. for (int i = 0; i < frames; ++i)
  36481. {
  36482. const auto t = i / rate;
  36483. float x = 0.0f;
  36484. if (kind == 'k')
  36485. {
  36486. phase += juce::MathConstants<double>::twoPi * ((46.0 + 3.0 * v) + 150.0 * std::exp (-t * 35.0)) / rate;
  36487. x = (float) (std::sin (phase) * std::exp (-t * (8.0 + v)));
  36488. }
  36489. else if (kind == 'h')
  36490. {
  36491. const auto n = random.nextFloat() * 2.0f - 1.0f;
  36492. x = (n - last) * 0.5f * (float) std::exp (-t * (50.0 + 12.0 * v));
  36493. last = n;
  36494. }
  36495. else
  36496. {
  36497. const auto base = 220.0 * std::pow (2.0, v / 12.0);
  36498. x = (float) (0.25 * std::min (1.0, t / 0.4) * std::min (1.0, (2.5 - t) / 0.5)
  36499. * (std::sin (juce::MathConstants<double>::twoPi * base * t) + std::sin (juce::MathConstants<double>::twoPi * base * 1.5 * t)));
  36500. }
  36501. audio.setSample (0, i, 0.8f * x);
  36502. }
  36503. const auto file = lib.getChildFile (path);
  36504. file.getParentDirectory().createDirectory();
  36505. juce::WavAudioFormat wav;
  36506. if (auto out = file.createOutputStream())
  36507. if (auto writer = std::unique_ptr<juce::AudioFormatWriter> (wav.createWriterFor (out.release(), rate, 1, 16, {}, 0)))
  36508. writer->writeFromAudioSampleBuffer (audio, 0, frames);
  36509. };
  36510. for (int v = 1; v <= 5; ++v)
  36511. {
  36512. write ("Drums/Kicks/Kick " + juce::String (v) + ".wav", 'k', v);
  36513. write ("Drums/Hats/Hat " + juce::String (v) + ".wav", 'h', v);
  36514. write ("Keys/Pad " + juce::String (v) + ".wav", 'p', v);
  36515. }
  36516. }
  36517. else
  36518. {
  36519. lib = juce::File (real.upToFirstOccurrenceOf ("|", false, false));
  36520. query = juce::File (real.fromFirstOccurrenceOf ("|", false, false));
  36521. }
  36522. ui.showDesktopForSnapshot (false);
  36523. ui.getBrowserForSnapshot().showFilterForSnapshot (lib, lynx::browserview::ContentFilter::all);
  36524. ui.getBrowserForSnapshot().findSimilarForSnapshot (query, lib);
  36525. offline.dispatchPendingMessages();
  36526. saveSnapshot (ui, prefix + "-browser-similar.png");
  36527. ui.getBrowserForSnapshot().setSearchForSnapshot ({});
  36528. if (made)
  36529. lib.deleteRecursively();
  36530. ui.getBrowserForSnapshot().resetViewForSnapshot();
  36531. }
  36532. // the undo history after a few edits
  36533. offline.editSong ([] (lynx::Song& s) { s.bpm += 1.0; });
  36534. offline.editSong ([] (lynx::Song& s) { if (! s.channels.empty()) s.channels[0].muted = ! s.channels[0].muted; });
  36535. offline.editSong ([] (lynx::Song& s) { if (! s.patterns.empty()) s.patterns[(std::size_t) s.currentPattern].notes.push_back ({}); });
  36536. offline.undo();
  36537. saveWindow (lynx::makeHistoryPanel (offline), "-history.png");
  36538. // spectral waveforms: a synthetic beat (kick, hats, a chord, a noise riser) as audio clips in spectral
  36539. // colours, zoomed in, classic and stereo; the same file in the Sampler editor and the Browser preview
  36540. {
  36541. const juce::File wav (prefix + "-wavedemo.wav");
  36542. writeWaveDemo (wav, offline.getSong().bpm);
  36543. const auto path = wav.getFullPathName();
  36544. const auto pathUtf8 = path.toStdString();
  36545. int samplerChannel = -1, firstTrack = 0;
  36546. offline.editSong ([&] (lynx::Song& s) {
  36547. for (const auto& clip : s.playlist)
  36548. firstTrack = std::max (firstTrack, clip.track + 1);
  36549. lynx::ChannelDef audio;
  36550. audio.name = "Beat (audio)";
  36551. audio.instrument = lynx::InstrumentKind::audioClip;
  36552. audio.samplePath = pathUtf8;
  36553. s.channels.push_back (audio);
  36554. const auto audioChannel = (int) s.channels.size() - 1;
  36555. lynx::ChannelDef sampler = audio;
  36556. sampler.name = "Beat (sampler)";
  36557. sampler.instrument = lynx::InstrumentKind::sampler;
  36558. sampler.sampler.regionStart = 0.06f;
  36559. sampler.sampler.regionEnd = 0.94f;
  36560. s.channels.push_back (sampler);
  36561. samplerChannel = (int) s.channels.size() - 1;
  36562. const auto bar = s.barTicks();
  36563. const auto whole = (std::int64_t) std::llround (8.0 * s.bpm / 60.0 * lynx::ppq);
  36564. lynx::Clip clip;
  36565. clip.kind = lynx::ClipKind::audio;
  36566. clip.channel = audioChannel;
  36567. clip.track = firstTrack;
  36568. clip.length = whole;
  36569. s.playlist.push_back (clip);
  36570. clip.track = firstTrack + 1; // a slice of it, later in the song
  36571. clip.start = bar;
  36572. clip.offset = bar;
  36573. clip.length = 2 * bar;
  36574. s.playlist.push_back (clip);
  36575. // taller rows for the audio (tracks can be resized: P18)
  36576. if ((int) s.playlistTracks.size() < firstTrack + 2)
  36577. s.playlistTracks.resize ((std::size_t) firstTrack + 2);
  36578. s.playlistTracks[(std::size_t) firstTrack].height = 80;
  36579. s.playlistTracks[(std::size_t) firstTrack + 1].height = 60;
  36580. });
  36581. offline.dispatchPendingMessages();
  36582. auto& cache = *lynx::ui::WaveformCache::getInstance();
  36583. cache.find (path, [&offline, path] { return offline.getSampleLibrary().load (path); });
  36584. cache.waitUntilIdle (30000);
  36585. ui.selectTabForSnapshot (2);
  36586. auto& playlist = ui.getPlaylistForSnapshot();
  36587. playlist.setTimeSelectionForSnapshot (0, 0);
  36588. {
  36589. // the Playlist alone (the floating Channel Rack would cover the clips)
  36590. auto saveSnapshot = [&playlist] (juce::Component&, const juce::String& file) { saveArea (playlist, playlist.getLocalBounds(), file); };
  36591. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  36592. saveSnapshot (ui, prefix + "-playlist-audio.png");
  36593. playlist.setViewForSnapshot (1400.0, 0, std::max (0, firstTrack - 3));
  36594. saveSnapshot (ui, prefix + "-playlist-audio-zoom.png");
  36595. lynx::ui::WaveformCache::stereo = true;
  36596. saveSnapshot (ui, prefix + "-playlist-audio-stereo.png");
  36597. lynx::ui::WaveformCache::stereo = false;
  36598. lynx::ui::WaveformCache::spectral = true;
  36599. playlist.setViewForSnapshot (180.0, 0, std::max (0, firstTrack - 3));
  36600. saveSnapshot (ui, prefix + "-playlist-audio-spectral.png");
  36601. lynx::ui::WaveformCache::spectral = false;
  36602. playlist.setViewForSnapshot (40.0, 0, 0);
  36603. saveSnapshot (ui, prefix + "-playlist-audio-far.png");
  36604. // LYNX_SNAPSHOT_AUDIO=a.wav;b.wav...: real audio as clips (default-height tracks, one tall,
  36605. // a fade, a reversed copy), at three zoom levels
  36606. if (const auto files = juce::StringArray::fromTokens (juce::SystemStats::getEnvironmentVariable ("LYNX_SNAPSHOT_AUDIO", {}), ";", "");
  36607. ! files.isEmpty())
  36608. {
  36609. const auto realTrack = firstTrack + 2;
  36610. std::vector<juce::String> paths;
  36611. for (const auto& f : files)
  36612. if (juce::File (f.trim()).existsAsFile())
  36613. paths.push_back (f.trim());
  36614. offline.editSong ([&] (lynx::Song& s) {
  36615. const auto bar = s.barTicks();
  36616. const std::uint32_t colours[] = { 0, 0xffd9a441, 0xff6fb36a, 0xffb06fd0, 0xff5fb7c9, 0xffd06f6f };
  36617. for (std::size_t i = 0; i < paths.size(); ++i)
  36618. {
  36619. lynx::ChannelDef audio;
  36620. audio.name = juce::File (paths[i]).getFileNameWithoutExtension().toStdString();
  36621. audio.instrument = lynx::InstrumentKind::audioClip;
  36622. audio.samplePath = paths[i].toStdString();
  36623. audio.colour = colours[i % 6];
  36624. audio.sampler.stretchBeats = i % 2 == 0 ? 16.0f : 0.0f; // fitted to 4 bars, or as recorded
  36625. audio.sampler.keepPitch = true;
  36626. s.channels.push_back (audio);
  36627. lynx::Clip clip;
  36628. clip.kind = lynx::ClipKind::audio;
  36629. clip.channel = (int) s.channels.size() - 1;
  36630. clip.track = realTrack + (int) i;
  36631. clip.length = 4 * bar;
  36632. clip.fadeIn = i == 1 ? bar / 2 : 0;
  36633. s.playlist.push_back (clip);
  36634. clip.start = 4 * bar;
  36635. clip.fadeIn = 0;
  36636. clip.fadeOut = i == 0 ? bar : 0;
  36637. s.playlist.push_back (clip);
  36638. }
  36639. if ((int) s.playlistTracks.size() < realTrack + (int) paths.size())
  36640. s.playlistTracks.resize ((std::size_t) realTrack + paths.size());
  36641. if (! paths.empty())
  36642. s.playlistTracks[(std::size_t) realTrack].height = 90;
  36643. });
  36644. offline.dispatchPendingMessages();
  36645. for (const auto& path2 : paths)
  36646. cache.find (path2, [&offline, path2] { return offline.getSampleLibrary().load (path2); });
  36647. cache.waitUntilIdle (60000);
  36648. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  36649. saveSnapshot (ui, prefix + "-playlist-real.png");
  36650. playlist.setViewForSnapshot (700.0, 0, std::max (0, realTrack - 1));
  36651. saveSnapshot (ui, prefix + "-playlist-real-zoom.png");
  36652. playlist.setViewForSnapshot (2400.0, 0, std::max (0, realTrack - 1));
  36653. saveSnapshot (ui, prefix + "-playlist-real-close.png");
  36654. playlist.setViewForSnapshot (50.0, 0, std::max (0, realTrack - 4));
  36655. saveSnapshot (ui, prefix + "-playlist-real-far.png");
  36656. // the clip menu of the first real clip
  36657. if (const auto menu = playlist.getClipMenuForSnapshot ((int) offline.getSong().playlist.size() - (int) paths.size() * 2); menu.getNumItems() > 0)
  36658. saveMenus (juce::StringArray { "Audio clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-audio.png");
  36659. if (const auto menu = playlist.getClipMenuForSnapshot (0); menu.getNumItems() > 0)
  36660. saveMenus (juce::StringArray { "Pattern clip" }, std::vector<juce::PopupMenu> { menu }, prefix + "-clip-menu-pattern.png");
  36661. // the clip menu's actions, run through the menu itself; results in -clip-actions.txt
  36662. {
  36663. juce::StringArray log;
  36664. auto clipOf = [&offline] (const std::string& channelName, int nth) {
  36665. const auto& sg = offline.getSong();
  36666. for (int i = 0; i < (int) sg.playlist.size(); ++i)
  36667. {
  36668. const auto& c = sg.playlist[(std::size_t) i];
  36669. if (c.kind == lynx::ClipKind::audio && c.channel >= 0 && sg.channels[(std::size_t) c.channel].name == channelName && nth-- == 0)
  36670. return i;
  36671. }
  36672. return -1;
  36673. };
  36674. std::function<bool (const juce::PopupMenu&, const juce::String&)> run = [&run] (const juce::PopupMenu& m, const juce::String& text) {
  36675. for (juce::PopupMenu::MenuItemIterator it (m); it.next();)
  36676. {
  36677. auto& item = it.getItem();
  36678. if (item.subMenu != nullptr && run (*item.subMenu, text))
  36679. return true;
  36680. // (without the menu mnemonic's mark: FL's underlined letters, round 190dz)
  36681. if (item.text.removeCharacters (juce::String::charToString (1)).startsWith (text) && item.isEnabled && item.action)
  36682. {
  36683. item.action();
  36684. return true;
  36685. }
  36686. }
  36687. return false;
  36688. };
  36689. auto act = [&] (const std::string& name, int nth, const juce::String& text) {
  36690. const auto clip = clipOf (name, nth);
  36691. const auto ok = clip >= 0 && run (playlist.getClipMenuForSnapshot (clip), text);
  36692. offline.dispatchPendingMessages();
  36693. return ok;
  36694. };
  36695. auto channelOf = [&] (const std::string& name) -> const lynx::ChannelDef* {
  36696. for (const auto& c : offline.getSong().channels)
  36697. if (c.name == name)
  36698. return &c;
  36699. return nullptr;
  36700. };
  36701. auto check = [&log] (const juce::String& what, bool ok) { log.add ((ok ? "OK " : "FAIL ") + what); };
  36702. const auto names = [&] { std::vector<std::string> n; for (auto& p2 : paths) n.push_back (juce::File (p2).getFileNameWithoutExtension().toStdString()); return n; }();
  36703. if (names.size() >= 4)
  36704. {
  36705. const auto channelsBefore = offline.getSong().channels.size();
  36706. check ("Reverse", act (names[2], 0, lynx::tr ("Reverse")) && channelOf (names[2])->sampler.reverse);
  36707. offline.undo();
  36708. offline.dispatchPendingMessages();
  36709. check ("Reverse undone", ! channelOf (names[2])->sampler.reverse);
  36710. act (names[2], 0, lynx::tr ("Reverse"));
  36711. check ("Make unique", act (names[3], 1, lynx::tr ("Make unique")) && offline.getSong().channels.size() == channelsBefore + 1
  36712. && channelOf (names[3] + " #2") != nullptr);
  36713. check ("Fit to tempo, resample", act (names[1], 0, lynx::tr ("Fit to tempo, resample ({0})", { juce::String() }).upToFirstOccurrenceOf ("(", false, false))
  36714. && channelOf (names[1])->sampler.stretchBeats > 0.0f && ! channelOf (names[1])->sampler.keepPitch);
  36715. const auto gainBefore = offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain;
  36716. check ("Normalize", act (names[0], 1, lynx::tr ("Normalize"))
  36717. && offline.getSong().playlist[(std::size_t) clipOf (names[0], 1)].gain != gainBefore);
  36718. const auto clipsBefore = offline.getSong().playlist.size();
  36719. check ("Split here", act (names[3], 0, lynx::tr ("Split here")) && offline.getSong().playlist.size() == clipsBefore + 1);
  36720. check ("Mute", act (names[0], 0, lynx::tr ("Mute")) && offline.getSong().playlist[(std::size_t) clipOf (names[0], 0)].muted);
  36721. check ("Copy + Paste here", act (names[0], 0, lynx::tr ("Copy")) && act (names[0], 1, lynx::tr ("Paste here"))
  36722. && offline.getSong().playlist.size() == clipsBefore + 2);
  36723. check ("Delete", act (names[0], 2, lynx::tr ("Delete")) && offline.getSong().playlist.size() == clipsBefore + 1);
  36724. check ("Chop to grid", act (names[3], 0, lynx::tr ("Chop to grid")) && offline.getSong().playlist.size() > clipsBefore + 1);
  36725. }
  36726. playlist.setViewForSnapshot (160.0, 0, std::max (0, realTrack - 4));
  36727. saveSnapshot (ui, prefix + "-playlist-real-actions.png");
  36728. juce::File (prefix + "-clip-actions.txt").replaceWithText (log.joinIntoString ("\n") + "\n");
  36729. }
  36730. }
  36731. }
  36732. saveWindow (lynx::makeChannelSettingsPanel (offline, samplerChannel), "-sampler-wave.png");
  36733. ui.showDesktopForSnapshot (false);
  36734. ui.getBrowserForSnapshot().showPreviewForSnapshot (wav);
  36735. saveSnapshot (ui, prefix + "-browser-preview.png");
  36736. }
  36737. }
  36738. // round 165o: every Label / button / tick box whose text the drawing squeezes below its minimum scale or cuts
  36739. // (an ellipsis), per language: `LYNX --lang de --snapshot shots/de` -> shots/de-textfit.txt
  36740. juce::File (prefix + "-textfit.txt").replaceWithText (textFitLog().joinIntoString ("\n") + "\n");
  36741. juce::LookAndFeel::setDefaultLookAndFeel (nullptr);
  36742. quit();
  36743. }
  36744. // --snapshot: 8 s of a synthetic stereo beat whose parts sit in different bands (kick = low, chord = mid,
  36745. // hats and the noise riser = high), to show the spectral waveform colours
  36746. #include "BrowserShot190iz.inc" // round 190iz
  36747. #include "LynxModelShot190ni.inc" // round 190ni
  36748. #include "UndoGesture190jv.inc" // round 190jv
  36749. #include "TrimShot190jv.inc" // round 190jv
  36750. #include "PrChordShot190kd.inc" // round 190kd
  36751. #include "ModalShot190mc.inc" // round 190mc
  36752. #include "KeysShot190nu.inc" // round chord2_190nu
  36753. #include "SectionsShot190ol.inc" // round 190ol (research190oe P1 / P6)
  36754. #include "PrShot190jv.inc" // round 190jv
  36755. #include "HostPlay190ll.inc" // round 190ll (issue #199)
  36756. #include "IssuesShot190ll.inc" // round 190ll (issues #200, #201, #203)
  36757. #include "SimpleGbShot190ke.inc" // round 190ke
  36758. #include "LoopShot190kf.inc" // round gaps190kf
  36759. #include "QaRest190lcShot.inc" // rollup 0.1.30 step 7 (round 190lc)
  36760. #include "LoopInfoShot190kx.inc" // round 190kx
  36761. static void writeWaveDemo (const juce::File& file, double bpm)
  36762. {
  36763. constexpr double rate = 44100.0;
  36764. const auto frames = (int) (8.0 * rate);
  36765. juce::AudioBuffer<float> buffer (2, frames);
  36766. buffer.clear();
  36767. auto* l = buffer.getWritePointer (0);
  36768. auto* r = buffer.getWritePointer (1);
  36769. const auto beat = 60.0 / juce::jlimit (40.0, 300.0, bpm);
  36770. std::uint32_t noise = 0x9e3779b9u;
  36771. auto white = [&noise] {
  36772. noise ^= noise << 13;
  36773. noise ^= noise >> 17;
  36774. noise ^= noise << 5;
  36775. return (float) (noise & 0xffffff) / (float) 0x800000 - 1.0f;
  36776. };
  36777. float previous = 0.0f;
  36778. for (int i = 0; i < frames; ++i)
  36779. {
  36780. const auto t = i / rate;
  36781. const auto inBeat = std::fmod (t, beat);
  36782. const auto bar = (int) (t / (beat * 4.0));
  36783. float left = 0.0f, right = 0.0f;
  36784. // kick on every beat: a falling sine
  36785. {
  36786. const auto phase = 2.0 * juce::MathConstants<double>::pi * (48.0 * inBeat + 4.0 * (1.0 - std::exp (-inBeat * 30.0)));
  36787. const auto k = (float) (std::sin (phase) * std::exp (-inBeat * 7.0)) * 0.85f;
  36788. left += k;
  36789. right += k;
  36790. }
  36791. // hats on the off-beats: high-passed noise bursts, a little to the right
  36792. {
  36793. const auto h = std::fmod (t + beat * 0.5, beat);
  36794. const auto n = white();
  36795. const auto hp = (n - previous) * 0.5f;
  36796. previous = n;
  36797. const auto hat = hp * (float) std::exp (-h * 45.0) * 0.55f;
  36798. left += hat * 0.6f;
  36799. right += hat;
  36800. }
  36801. // a chord in the second and third bars (mid band)
  36802. if (bar == 1 || bar == 2)
  36803. {
  36804. const auto env = (float) std::min (1.0, std::min (t - beat * 4.0, beat * 12.0 - t) * 8.0);
  36805. float chord = 0.0f;
  36806. for (const auto hz : { 523.25, 659.25, 783.99 })
  36807. chord += (float) (std::sin (2.0 * juce::MathConstants<double>::pi * hz * t) + 0.3 * std::sin (4.0 * juce::MathConstants<double>::pi * hz * t));
  36808. left += chord * 0.09f * std::max (0.0f, env);
  36809. right += chord * 0.09f * std::max (0.0f, env);
  36810. }
  36811. // a white-noise riser over the last two seconds (high band)
  36812. if (t > 6.0)
  36813. {
  36814. const auto rise = (float) ((t - 6.0) / 2.0);
  36815. left += white() * 0.4f * rise * rise;
  36816. right += white() * 0.4f * rise * rise;
  36817. }
  36818. l[i] = left;
  36819. r[i] = right;
  36820. }
  36821. buffer.applyGain (0.9f / juce::jmax (1.0e-6f, buffer.getMagnitude (0, frames)));
  36822. file.deleteFile();
  36823. juce::WavAudioFormat wav;
  36824. if (std::unique_ptr<juce::AudioFormatWriter> writer { wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0) })
  36825. writer->writeFromAudioSampleBuffer (buffer, 0, frames);
  36826. }
  36827. // the menu bar's menus side by side, drawn with the LookAndFeel as they appear when opened
  36828. static void saveMenus (lynx::MainComponent& ui, const juce::String& path)
  36829. {
  36830. const auto names = ui.getMenuNamesForSnapshot();
  36831. std::vector<juce::PopupMenu> source;
  36832. for (int m = 0; m < names.size(); ++m)
  36833. source.push_back (ui.getMenuForSnapshot (m));
  36834. saveMenus (names, source, path);
  36835. }
  36836. // menus side by side, each under its name, in the columns JUCE shows them in: its own column breaks, or (round 190je,
  36837. // cmake/LynxPatchJuce.cmake fix 40) the split of a menu taller than 70 % of a 1080 px screen
  36838. static void saveMenus (const juce::StringArray& names, const std::vector<juce::PopupMenu>& source, const juce::String& path)
  36839. {
  36840. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  36841. struct Row
  36842. {
  36843. const juce::PopupMenu::Item* item;
  36844. int height;
  36845. };
  36846. struct Laid
  36847. {
  36848. juce::PopupMenu menu;
  36849. std::vector<std::vector<Row>> columns;
  36850. std::vector<int> widths;
  36851. int width = 0, height = 0;
  36852. };
  36853. std::vector<Laid> menus;
  36854. menus.reserve ((std::size_t) names.size());
  36855. const auto border = lf.getPopupMenuBorderSize();
  36856. const auto separatorWidth = lf.getPopupMenuColumnSeparatorWidthWithOptions (juce::PopupMenu::Options());
  36857. for (int m = 0; m < names.size(); ++m)
  36858. {
  36859. menus.push_back (Laid { source[(std::size_t) m] });
  36860. auto& laid = menus.back();
  36861. std::vector<Row> rows;
  36862. std::vector<lynx::themes::MenuRow> shape;
  36863. std::vector<int> breaks;
  36864. for (juce::PopupMenu::MenuItemIterator it (laid.menu); it.next();)
  36865. {
  36866. const auto& item = it.getItem();
  36867. int w = 0, h = 0;
  36868. if (item.customComponent != nullptr)
  36869. item.customComponent->getIdealSize (w, h); // (a title band: its own height, as JUCE asks it)
  36870. else
  36871. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  36872. if (item.isSectionHeader) h += h / 2; // as JUCE does
  36873. rows.push_back ({ &item, h });
  36874. shape.push_back ({ h, item.isSeparator, item.isSectionHeader });
  36875. if (item.shouldBreakAfter)
  36876. breaks.push_back ((int) rows.size() - 1);
  36877. }
  36878. if (breaks.empty())
  36879. if (const auto at = lynx::themes::tallMenuBreak (shape, 1080 * 7 / 10); at >= 0)
  36880. breaks.push_back (at);
  36881. laid.columns.emplace_back();
  36882. laid.widths.push_back (160);
  36883. for (int i = 0; i < (int) rows.size(); ++i)
  36884. {
  36885. const auto& item = *rows[(std::size_t) i].item;
  36886. int w = 0, h = 0;
  36887. if (item.customComponent != nullptr)
  36888. item.customComponent->getIdealSize (w, h);
  36889. else
  36890. lf.getIdealPopupMenuItemSize (item.text, item.isSeparator, item.isSectionHeader ? -1 : 0, w, h);
  36891. if (item.shortcutKeyDescription.isNotEmpty() || item.text.containsChar ('\t'))
  36892. w += 90;
  36893. laid.columns.back().push_back (rows[(std::size_t) i]);
  36894. laid.widths.back() = juce::jmax (laid.widths.back(), w + 10);
  36895. if (std::find (breaks.begin(), breaks.end(), i) != breaks.end() && i + 1 < (int) rows.size())
  36896. {
  36897. laid.columns.emplace_back();
  36898. laid.widths.push_back (160);
  36899. }
  36900. }
  36901. laid.width = (int) (laid.columns.size() - 1) * separatorWidth;
  36902. for (std::size_t c = 0; c < laid.columns.size(); ++c)
  36903. {
  36904. laid.width += laid.widths[c];
  36905. int h = 2 * border;
  36906. for (const auto& row : laid.columns[c])
  36907. h += row.height;
  36908. laid.height = juce::jmax (laid.height, h);
  36909. }
  36910. }
  36911. int totalWidth = 16, totalHeight = 0;
  36912. for (const auto& l : menus)
  36913. {
  36914. totalWidth += l.width + 16;
  36915. totalHeight = juce::jmax (totalHeight, l.height + 32);
  36916. }
  36917. auto image = lynx::shot::canvas (totalWidth, totalHeight);
  36918. {
  36919. juce::Graphics g (image);
  36920. lynx::shot::logical (g);
  36921. g.fillAll (lynx::theme::colour::bg1);
  36922. int x = 16;
  36923. bool first = true;
  36924. for (int m = 0; m < (int) menus.size(); ++m)
  36925. {
  36926. const auto& l = menus[(std::size_t) m];
  36927. g.setColour (lynx::theme::colour::textSecondary);
  36928. g.setFont (lynx::theme::font (lynx::theme::type::small, true));
  36929. g.drawText (names[m], x, 0, l.width, 24, juce::Justification::centredLeft);
  36930. {
  36931. juce::Graphics::ScopedSaveState state (g);
  36932. g.reduceClipRegion (x, 24, l.width, l.height);
  36933. g.setOrigin (x, 24);
  36934. lf.drawPopupMenuBackground (g, l.width, l.height);
  36935. int columnX = 0;
  36936. for (std::size_t c = 0; c < l.columns.size(); ++c)
  36937. {
  36938. int y = border;
  36939. for (const auto& row : l.columns[c])
  36940. {
  36941. const auto& item = *row.item;
  36942. 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),
  36943. row.height);
  36944. auto text = item.text, shortcut = item.shortcutKeyDescription;
  36945. if (text.containsChar ('\t'))
  36946. {
  36947. shortcut = text.fromFirstOccurrenceOf ("\t", false, false);
  36948. text = text.upToFirstOccurrenceOf ("\t", false, false);
  36949. }
  36950. if (item.isSectionHeader)
  36951. lf.drawPopupMenuSectionHeader (g, r, text);
  36952. else if (item.customComponent != nullptr)
  36953. {
  36954. juce::Graphics::ScopedSaveState itemState (g);
  36955. g.setOrigin (r.getPosition());
  36956. item.customComponent->setSize (r.getWidth(), r.getHeight());
  36957. item.customComponent->paintEntireComponent (g, false);
  36958. }
  36959. else
  36960. lf.drawPopupMenuItem (g, r, item.isSeparator, item.isEnabled, first && ! item.isSeparator && m == 0, item.isTicked,
  36961. item.subMenu != nullptr, text, shortcut, item.image.get(), nullptr);
  36962. first = false;
  36963. y += row.height;
  36964. }
  36965. columnX += l.widths[c];
  36966. if (c + 1 < l.columns.size())
  36967. {
  36968. lf.drawPopupMenuColumnSeparatorWithOptions (g, juce::Rectangle<int> (columnX, border, separatorWidth, l.height - 2 * border),
  36969. juce::PopupMenu::Options());
  36970. columnX += separatorWidth;
  36971. }
  36972. }
  36973. }
  36974. x += l.width + 16;
  36975. }
  36976. }
  36977. const auto file = lynx::shot::file (juce::File (path));
  36978. file.deleteFile();
  36979. juce::PNGImageFormat png;
  36980. if (auto out = file.createOutputStream())
  36981. png.writeImageToStream (image, *out);
  36982. }
  36983. static void writePng (const juce::Image& image, const juce::String& path)
  36984. {
  36985. const auto file = lynx::shot::file (juce::File (path));
  36986. file.deleteFile();
  36987. juce::PNGImageFormat png;
  36988. if (auto out = file.createOutputStream())
  36989. png.writeImageToStream (image, *out);
  36990. }
  36991. // the splash screen: one settled frame, and a strip of frames through its animation
  36992. static void saveSplashFrames (const juce::String& prefix)
  36993. {
  36994. lynx::SplashScreen splash;
  36995. splash.setStatus (lynx::tr ("Loading the workspace..."));
  36996. splash.setTimeForSnapshot (1.6);
  36997. writePng (lynx::shot::snapshot (splash), prefix + "-splash.png");
  36998. const double times[] = { 0.10, 0.22, 0.29, 0.40, 0.58, 0.75, 1.00, 1.30 };
  36999. const auto w = lynx::SplashScreen::width / 2, h = lynx::SplashScreen::height / 2;
  37000. auto strip = lynx::shot::canvas (4 * (w + 8) + 8, 2 * (h + 8) + 8);
  37001. {
  37002. juce::Graphics g (strip);
  37003. lynx::shot::logical (g);
  37004. g.fillAll (lynx::theme::colour::bg1);
  37005. for (int i = 0; i < 8; ++i)
  37006. {
  37007. splash.setTimeForSnapshot (times[i]);
  37008. const auto frame = lynx::shot::snapshot (splash);
  37009. g.drawImage (frame, 8 + (i % 4) * (w + 8), 8 + (i / 4) * (h + 8), w, h, 0, 0, frame.getWidth(), frame.getHeight());
  37010. }
  37011. }
  37012. writePng (strip, prefix + "-splash-frames.png");
  37013. }
  37014. // every icon at 16, 20 and 24 px (at `scale`, e.g. 1.5 for a 150% display), in the toolbar's
  37015. // colours: at rest, hovered and switched on
  37016. // round 190je (design190ia G1): one state sheet per button kind: idle, hover, pressed, on, disabled, as the one state rule
  37017. // draws them (core/ThemePalette.h buttonLook); the menu rows in both menu styles
  37018. static void saveStateSheet (const juce::String& path, float scale)
  37019. {
  37020. using namespace lynx;
  37021. scale *= shot::scale();
  37022. auto& lf = juce::LookAndFeel::getDefaultLookAndFeel();
  37023. const int labelWidth = 220, cellW = 120, cellH = 40, columns = 5;
  37024. const juce::String heads[] = { "idle", "hover", "pressed", "on", "disabled" };
  37025. enum Kind { text, iconFilled, iconOnce, iconSwitch, iconSwitchOwn, tick, radio, combo, tab, menuDark, menuFl, kinds };
  37026. const char* names[] = { "Text button", "Icon button (filled)", "Toolbar icon (acts once)", "Toolbar switch", "Toolbar switch (own colours)",
  37027. "Tick box", "Radio choice", "Combo box", "Tab", "Menu item (LYNX dark)", "Menu item (FL classic)" };
  37028. const auto w = labelWidth + columns * cellW + 16, h = 30 + kinds * cellH + 16;
  37029. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  37030. {
  37031. juce::Graphics g (image);
  37032. g.addTransform (juce::AffineTransform::scale (scale));
  37033. g.fillAll (theme::colour::bg3);
  37034. g.setFont (theme::font (theme::type::small, true));
  37035. g.setColour (theme::colour::textSecondary);
  37036. for (int c = 0; c < columns; ++c)
  37037. g.drawText (heads[c], labelWidth + c * cellW, 6, cellW, 20, juce::Justification::centred);
  37038. const auto styleBefore = theme::menus::style();
  37039. for (int k = 0; k < kinds; ++k)
  37040. {
  37041. const auto y = 30 + k * cellH;
  37042. g.setFont (theme::font (theme::type::small));
  37043. g.setColour (theme::colour::textPrimary);
  37044. g.drawText (names[k], 8, y, labelWidth - 12, cellH, juce::Justification::centredLeft);
  37045. for (int c = 0; c < columns; ++c)
  37046. {
  37047. const auto hover = c == 1, down = c == 2, on = c == 3, disabled = c == 4;
  37048. const juce::Rectangle<int> cell (labelWidth + c * cellW, y, cellW, cellH);
  37049. juce::Graphics::ScopedSaveState state (g);
  37050. g.reduceClipRegion (cell);
  37051. switch (k)
  37052. {
  37053. case text:
  37054. {
  37055. juce::TextButton b ("Export");
  37056. b.setSize (96, 26);
  37057. b.setToggleState (on, juce::dontSendNotification);
  37058. b.setEnabled (! disabled);
  37059. g.setOrigin (cell.getX() + 12, cell.getY() + 7);
  37060. lf.drawButtonBackground (g, b, b.findColour (on ? juce::TextButton::buttonOnColourId : juce::TextButton::buttonColourId), hover, down);
  37061. lf.drawButtonText (g, b, hover, down);
  37062. break;
  37063. }
  37064. case iconFilled:
  37065. case iconOnce:
  37066. case iconSwitch:
  37067. case iconSwitchOwn:
  37068. {
  37069. IconButton b ("state", k == iconFilled ? Icon::plus : k == iconOnce ? Icon::save : Icon::metronome);
  37070. b.setFlat (k != iconFilled);
  37071. if (k == iconSwitch)
  37072. b.setToggleLook (true);
  37073. if (k == iconSwitchOwn)
  37074. {
  37075. b.setOnColour (theme::colour::bg6);
  37076. b.setIconColourWhenOn (theme::colour::accent);
  37077. }
  37078. b.setSize (k == iconFilled ? 34 : 30, 30);
  37079. b.setToggleState (on, juce::dontSendNotification);
  37080. b.setEnabled (! disabled);
  37081. g.setOrigin (cell.getX() + 12, cell.getY() + 5);
  37082. b.paintButton (g, hover, down);
  37083. break;
  37084. }
  37085. case tick:
  37086. case radio:
  37087. {
  37088. juce::ToggleButton b (k == tick ? "Snap to grid" : "Pattern");
  37089. if (k == radio)
  37090. b.getProperties().set ("lynxRadio", true);
  37091. b.setSize (110, 24);
  37092. b.setToggleState (on, juce::dontSendNotification);
  37093. b.setEnabled (! disabled);
  37094. g.setOrigin (cell.getX() + 6, cell.getY() + 8);
  37095. lf.drawToggleButton (g, b, hover, down);
  37096. break;
  37097. }
  37098. case combo:
  37099. {
  37100. if (hover || down || on) // (a combo box's hover comes from the mouse itself: --uitest covers it)
  37101. break;
  37102. juce::ComboBox b;
  37103. b.setSize (100, 24);
  37104. b.setEnabled (! disabled);
  37105. g.setOrigin (cell.getX() + 10, cell.getY() + 8);
  37106. lf.drawComboBox (g, 100, 24, false, 0, 0, 0, 0, b);
  37107. g.setColour (disabled ? theme::colour::textDisabled : theme::colour::textPrimary);
  37108. g.setFont (lf.getComboBoxFont (b));
  37109. g.drawText ("1/16 step", 6, 0, 70, 24, juce::Justification::centredLeft);
  37110. break;
  37111. }
  37112. case tab:
  37113. {
  37114. if (disabled)
  37115. break;
  37116. juce::TabbedButtonBar bar (juce::TabbedButtonBar::TabsAtTop);
  37117. bar.setSize (220, 32);
  37118. bar.addTab ("Audio", theme::colour::bg2, -1);
  37119. bar.addTab ("MIDI", theme::colour::bg2, -1);
  37120. bar.setCurrentTabIndex (on ? 1 : 0, false);
  37121. auto* tabButton = bar.getTabButton (1);
  37122. tabButton->setBounds (0, 0, 100, 32);
  37123. g.setOrigin (cell.getX() + 10, cell.getY() + 4);
  37124. g.setColour (theme::colour::bg1);
  37125. g.fillRect (0, 0, 100, 32);
  37126. lf.drawTabButton (*tabButton, g, hover, down);
  37127. break;
  37128. }
  37129. case menuDark:
  37130. case menuFl:
  37131. {
  37132. if (down)
  37133. break;
  37134. theme::menus::setStyle (k == menuFl ? themes::MenuStyle::flClassic : themes::MenuStyle::lynxDark);
  37135. g.setOrigin (cell.getX() + 4, cell.getY() + 8);
  37136. lf.drawPopupMenuBackground (g, 112, 25);
  37137. lf.drawPopupMenuItem (g, { 2, 2, 108, 21 }, false, ! disabled, hover, on, false, theme::mnemonic ("Open", 'O'), "Ctrl+O", nullptr, nullptr);
  37138. theme::menus::setStyle (styleBefore);
  37139. break;
  37140. }
  37141. default:
  37142. break;
  37143. }
  37144. }
  37145. }
  37146. }
  37147. writePng (image, path);
  37148. }
  37149. static void saveIconSheet (const juce::String& path, float scale)
  37150. {
  37151. scale *= lynx::shot::scale();
  37152. const int sizes[] = { 16, 20, 24 };
  37153. const int cell = 34, columns = 3 * 3, labelWidth = 110;
  37154. const auto w = labelWidth + columns * cell + 16, h = lynx::iconCount * cell + 16;
  37155. juce::Image image (juce::Image::ARGB, juce::roundToInt ((float) w * scale), juce::roundToInt ((float) h * scale), true);
  37156. {
  37157. juce::Graphics g (image); // (drawing is flushed when it goes out of scope)
  37158. g.addTransform (juce::AffineTransform::scale (scale));
  37159. g.fillAll (lynx::theme::colour::bg3);
  37160. g.setFont (lynx::theme::font (lynx::theme::type::small));
  37161. for (int i = 1; i < lynx::iconCount; ++i)
  37162. {
  37163. const auto y = 8 + (i - 1) * cell;
  37164. g.setColour (lynx::theme::colour::textDisabled);
  37165. g.drawText (juce::String (i), 8, y, labelWidth - 8, cell, juce::Justification::centredLeft);
  37166. for (int v = 0; v < 3; ++v)
  37167. for (int s = 0; s < 3; ++s)
  37168. {
  37169. const juce::Rectangle<float> box ((float) (labelWidth + (v * 3 + s) * cell), (float) y, (float) cell, (float) cell);
  37170. const auto bg = v == 2 ? lynx::theme::colour::accent : v == 1 ? lynx::theme::colour::bg5 : lynx::theme::colour::bg3;
  37171. g.setColour (bg);
  37172. g.fillRoundedRectangle (box.reduced (2.0f), 4.0f);
  37173. const auto fg = v == 2 ? lynx::theme::colour::onAccent : v == 1 ? lynx::theme::colour::textPrimary
  37174. : lynx::theme::colour::textSecondary.brighter (0.25f);
  37175. lynx::icons::draw (g, (lynx::Icon) i, box.withSizeKeepingCentre ((float) sizes[s], (float) sizes[s]), fg);
  37176. }
  37177. }
  37178. }
  37179. writePng (image, path);
  37180. }
  37181. // a part of a component (e.g. the main toolbar)
  37182. static void saveArea (juce::Component& c, juce::Rectangle<int> area, const juce::String& path)
  37183. {
  37184. const auto file = lynx::shot::file (juce::File (path));
  37185. file.deleteFile();
  37186. juce::PNGImageFormat png;
  37187. if (auto out = file.createOutputStream())
  37188. png.writeImageToStream (lynx::shot::snapshot (c, area), *out);
  37189. }
  37190. static void savePng (const juce::Image& image, const juce::String& path)
  37191. {
  37192. const auto file = lynx::shot::file (juce::File (path));
  37193. file.deleteFile();
  37194. juce::PNGImageFormat png;
  37195. if (auto out = file.createOutputStream())
  37196. png.writeImageToStream (image, *out);
  37197. }
  37198. // -toolbar-tips.png: the top of the window with the bubbles of a few controls as they appear under the
  37199. // mouse; -tips-sheet.png: every quick tip of the window, to check names, shortcuts and translations
  37200. static void saveQuickTips (lynx::MainComponent& ui, const juce::String& prefix)
  37201. {
  37202. const auto tips = ui.getQuickTipsForSnapshot();
  37203. const auto top = juce::Rectangle<int> (0, 0, ui.getWidth(), juce::jmin (ui.getHeight(), ui.getToolbarBoundsForSnapshot().getHeight() + 72));
  37204. auto image = lynx::shot::snapshot (ui, top);
  37205. {
  37206. juce::Graphics g (image);
  37207. lynx::shot::logical (g);
  37208. const juce::String shown[] = { lynx::tr ("Pattern mode"), lynx::tr ("Play"), lynx::tr ("Metronome"), lynx::tr ("Mixer"), lynx::tr ("Save project"),
  37209. lynx::tr ("Window options"), lynx::tr ("Close") };
  37210. std::vector<juce::Rectangle<int>> used;
  37211. for (const auto& [area, tip] : tips)
  37212. {
  37213. const auto name = tip.upToFirstOccurrenceOf ("\t", false, false);
  37214. if (std::find (std::begin (shown), std::end (shown), name) == std::end (shown))
  37215. continue;
  37216. const auto bubble = lynx::ui::quickTipBounds (tip, area, top);
  37217. if (std::any_of (used.begin(), used.end(), [&] (const auto& r) { return r.intersects (bubble); }))
  37218. continue;
  37219. used.push_back (bubble);
  37220. g.setColour (juce::Colours::white.withAlpha (0.075f)); // the hovered control
  37221. g.fillRoundedRectangle (area.toFloat().reduced (0.5f), lynx::theme::radius::md);
  37222. lynx::ui::paintQuickTip (g, bubble.toFloat(), tip);
  37223. }
  37224. }
  37225. savePng (image, prefix + "-toolbar-tips.png");
  37226. // the sheet: bubbles in rows
  37227. const int width = 900;
  37228. int x = 12, y = 12;
  37229. std::vector<std::pair<juce::Rectangle<int>, juce::String>> placed;
  37230. for (const auto& [area, tip] : tips)
  37231. {
  37232. auto r = lynx::ui::quickTipSize (tip);
  37233. if (x + r.getWidth() > width - 12)
  37234. {
  37235. x = 12;
  37236. y += r.getHeight() + 10;
  37237. }
  37238. placed.emplace_back (r.withPosition (x, y), tip);
  37239. x += r.getWidth() + 10;
  37240. }
  37241. auto sheet = lynx::shot::canvas (width, y + 20 + 12);
  37242. {
  37243. juce::Graphics g (sheet);
  37244. lynx::shot::logical (g);
  37245. g.fillAll (lynx::theme::colour::bg3);
  37246. for (const auto& [r, tip] : placed)
  37247. lynx::ui::paintQuickTip (g, r.toFloat(), tip);
  37248. }
  37249. savePng (sheet, prefix + "-tips-sheet.png");
  37250. }
  37251. static juce::StringArray& textFitLog()
  37252. {
  37253. static juce::StringArray log;
  37254. return log;
  37255. }
  37256. // drawFittedText would shrink `text` below `minScale` or cut it: fewer visible glyphs than the text has
  37257. static bool textIsCut (const juce::Font& font, const juce::String& text, juce::Rectangle<int> area, int maxLines, float minScale)
  37258. {
  37259. if (text.trim().isEmpty() || area.getWidth() <= 4 || area.getHeight() <= 4)
  37260. return false;
  37261. auto visible = [] (juce::GlyphArrangement& ga) {
  37262. int n = 0;
  37263. for (int i = 0; i < ga.getNumGlyphs(); ++i)
  37264. n += ga.getGlyph (i).isWhitespace() ? 0 : 1;
  37265. return n;
  37266. };
  37267. juce::GlyphArrangement fitted, full;
  37268. fitted.addFittedText (font, text, 0.0f, 0.0f, (float) area.getWidth(), (float) area.getHeight(), juce::Justification::centredLeft,
  37269. juce::jmax (1, maxLines), minScale);
  37270. full.addLineOfText (font, text, 0.0f, 0.0f);
  37271. return visible (fitted) < visible (full);
  37272. }
  37273. // walks the visible components under `root` and logs the texts that don't fit (labels, text buttons, tick boxes)
  37274. static void checkTextFit (juce::Component& root, const juce::String& where)
  37275. {
  37276. std::function<void (juce::Component&)> visit = [&] (juce::Component& c) {
  37277. if (! c.isVisible() || c.getWidth() <= 0 || c.getHeight() <= 0)
  37278. return;
  37279. juce::String text;
  37280. bool cut = false;
  37281. if (auto* label = dynamic_cast<juce::Label*> (&c); label != nullptr && ! label->isBeingEdited())
  37282. {
  37283. const auto font = label->getLookAndFeel().getLabelFont (*label);
  37284. const auto area = label->getBorderSize().subtractedFrom (label->getLocalBounds());
  37285. text = label->getText();
  37286. cut = textIsCut (font, text, area, juce::jmax (1, (int) ((float) area.getHeight() / font.getHeight())),
  37287. label->getMinimumHorizontalScale());
  37288. }
  37289. else if (auto* toggle = dynamic_cast<juce::ToggleButton*> (&c))
  37290. {
  37291. const auto tick = juce::jmin (16.0f, (float) c.getHeight() - 4.0f);
  37292. text = toggle->getButtonText();
  37293. cut = textIsCut (juce::Font (lynx::theme::font (juce::jmin ((float) lynx::theme::type::body, (float) c.getHeight() * 0.75f))), text,
  37294. c.getLocalBounds().withTrimmedLeft (juce::roundToInt (tick) + 8).withTrimmedRight (2), 2, 0.85f);
  37295. }
  37296. else if (auto* button = dynamic_cast<juce::TextButton*> (&c);
  37297. button != nullptr && (int) button->getProperties().getWithDefault (lynx::theme::LookAndFeel::iconProperty, 0) == 0)
  37298. {
  37299. text = button->getButtonText();
  37300. cut = textIsCut (button->getLookAndFeel().getTextButtonFont (*button, button->getHeight()), text,
  37301. button->getLocalBounds().reduced (juce::jmin (8, button->getWidth() / 6), 0), 2, 0.85f);
  37302. }
  37303. if (cut)
  37304. {
  37305. juce::String path;
  37306. for (auto* p = &c; p != nullptr && p != &root; p = p->getParentComponent())
  37307. if (p->getName().isNotEmpty())
  37308. path = p->getName() + (path.isEmpty() ? "" : "/") + path;
  37309. const auto line = where + " | " + juce::String (c.getWidth()) + "x" + juce::String (c.getHeight()) + " | " + text.replace ("\n", "\\n")
  37310. + (path.isEmpty() ? juce::String() : " | " + path);
  37311. textFitLog().addIfNotAlreadyThere (line);
  37312. }
  37313. for (auto* child : c.getChildren())
  37314. visit (*child);
  37315. };
  37316. visit (root);
  37317. }
  37318. static void saveSnapshot (juce::Component& c, const juce::String& path)
  37319. {
  37320. checkTextFit (c, juce::File (path).getFileNameWithoutExtension());
  37321. const auto file = lynx::shot::file (juce::File (path));
  37322. file.deleteFile();
  37323. juce::PNGImageFormat png;
  37324. if (auto out = file.createOutputStream())
  37325. png.writeImageToStream (lynx::shot::snapshot (c), *out);
  37326. }
  37327. class MainWindow final : public juce::DocumentWindow
  37328. {
  37329. public:
  37330. MainWindow (const juce::String& name, lynx::AudioEngine& engine)
  37331. : DocumentWindow (name, lynx::theme::window, DocumentWindow::allButtons, false)
  37332. {
  37333. probeEngine = &engine;
  37334. // (round 190hd) one desktop window, made with the native title bar: before, JUCE made one with its own title
  37335. // bar and setUsingNativeTitleBar made it again (~20-35 ms each, the Direct2D context included)
  37336. setUsingNativeTitleBar (true);
  37337. addToDesktop();
  37338. setIcon (lynx::logoImage());
  37339. startupTrace.mark (" window: its desktop window (native title bar), icon");
  37340. content = new lynx::MainComponent (engine);
  37341. setContentOwned (content, true);
  37342. startupTrace.mark (" window: content set");
  37343. setResizable (true, true);
  37344. setResizeLimits (800, 400, 10000, 10000);
  37345. // ~88% of the main display's usable area (at least the UI's design size, but never larger than the
  37346. // display: the AppImage catalog test runs on an 800x600 screen)
  37347. if (const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay())
  37348. {
  37349. const auto area = display->userArea;
  37350. const auto fit = [] (int design, int available) {
  37351. return juce::jmin (available, juce::jmax (design, (int) (available * 0.88)));
  37352. };
  37353. setSize (fit (getWidth(), area.getWidth()), fit (getHeight(), area.getHeight()));
  37354. }
  37355. centreWithSize (getWidth(), getHeight());
  37356. // where it was last time (round 167v); the first start opens maximized, the Playlist filling the screen
  37357. // with the Browser at the left and the Channel Rack above it, like FL Studio's first start
  37358. const auto saved = stateFile().loadFileAsString().trim();
  37359. // (LYNX_TEST_MODE keeps the fixed-size window scripted checks expect, unless LYNX_TEST_MAXIMIZE=1)
  37360. const auto firstStart = saved.isEmpty()
  37361. && (! lynx::platform::testMode() || juce::SystemStats::getEnvironmentVariable ("LYNX_TEST_MAXIMIZE", {}) == "1");
  37362. maximiseOnReveal = firstStart || saved.startsWithIgnoreCase ("fs");
  37363. if (saved.isNotEmpty())
  37364. restoreWindowStateFromString (saved.startsWithIgnoreCase ("fs") ? saved.substring (2).trim() : saved);
  37365. }
  37366. // Shows the window (built hidden while the splash screen is up).
  37367. void reveal()
  37368. {
  37369. if (lynx::uitrace::enabled()) // LYNX_TRACE_UI: the frames per second and the longest gap in ui.log (round 173f)
  37370. watchFrames ({});
  37371. setVisible (true);
  37372. // LYNX_LOCATOR_PROBE=1 (round 190ip, measurements): a floating window with a locator moving 30 times a second
  37373. if (juce::SystemStats::getEnvironmentVariable ("LYNX_LOCATOR_PROBE", {}) == "1")
  37374. juce::Timer::callAfterDelay (1500, [e = probeEngine] {
  37375. lynx::ui::openLocatorProbe ([e] {
  37376. const auto& transport = e->getTransport();
  37377. const auto bar = (double) juce::jmax<std::int64_t> (1, e->getSong().barTicks());
  37378. return transport.playing.load() ? std::fmod (transport.positionTicks.load(), bar) / bar : -1.0;
  37379. });
  37380. });
  37381. lynx::applyWindowChrome (*this);
  37382. lynx::fitWindowOnScreen (*this); // a size saved at another UI zoom still fits (round 163)
  37383. if (maximiseOnReveal)
  37384. setFullScreen (true); // (a title-bar window: maximized, the taskbar stays)
  37385. toFront (true);
  37386. content->grabKeyboardFocus();
  37387. // issue #62: the detached panels restored with the layout (built before this window was shown): their saved
  37388. // place and above it, once the window manager has placed this one
  37389. juce::Timer::callAfterDelay (250, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  37390. if (safe != nullptr)
  37391. safe->content->restoreDetachedWindows();
  37392. });
  37393. }
  37394. // Runs `then` once, right after the window's next frame (round 190go: the audio device opens behind the
  37395. // window's first frame, not before it); at the latest after 300 ms (a window that paints nothing: minimised).
  37396. void whenPainted (std::function<void()> then)
  37397. {
  37398. afterPaint = std::move (then);
  37399. afterPaintPosted = false;
  37400. repaint();
  37401. juce::Timer::callAfterDelay (300, [safe = juce::Component::SafePointer<MainWindow> (this)] {
  37402. if (safe != nullptr)
  37403. safe->runAfterPaint();
  37404. });
  37405. }
  37406. void runAfterPaint()
  37407. {
  37408. if (auto then = std::exchange (afterPaint, nullptr))
  37409. then();
  37410. }
  37411. // The window's place and maximized state for the next start (main-window.txt in the settings folder).
  37412. void saveState() { stateFile().replaceWithText (getWindowStateAsString()); }
  37413. static juce::File stateFile() { return lynx::PluginHost::settingsFolder().getChildFile ("main-window.txt"); }
  37414. void openFile (const juce::File& file) { content->openFile (file); }
  37415. lynx::MainComponent& getContent() { return *content; }
  37416. void showSetupWizard() { content->showSetupWizard(); }
  37417. void confirmDiscard (std::function<void()> then) { content->confirmDiscard (std::move (then)); }
  37418. void closeButtonPressed() override { JUCEApplication::getInstance()->systemRequestedQuit(); }
  37419. // Every frame the window paints, with its dirty area (ui/FrameProbe.h; --uiperf, LYNX_TRACE_UI). The trace keeps
  37420. // counting when --uiperf watches too.
  37421. void watchFrames (std::function<void (double, juce::Rectangle<int>)> callback)
  37422. {
  37423. if (probe == nullptr)
  37424. {
  37425. probe = std::make_unique<lynx::ui::FrameProbe>();
  37426. Component::addAndMakeVisible (*probe); // (ResizableWindow hides the plain overload)
  37427. probe->setBounds (getLocalBounds());
  37428. }
  37429. probe->onFrame = [callback = std::move (callback)] (double now, juce::Rectangle<int> area) {
  37430. if (lynx::uitrace::enabled())
  37431. lynx::uitrace::frame (now);
  37432. if (callback)
  37433. callback (now, area);
  37434. };
  37435. }
  37436. void resized() override
  37437. {
  37438. DocumentWindow::resized();
  37439. if (probe != nullptr)
  37440. probe->setBounds (getLocalBounds());
  37441. }
  37442. // --uiperf: the time of each frame the window paints (its own paint, then every child's, up to the last)
  37443. std::function<void (double)> onFrame;
  37444. void paint (juce::Graphics& g) override
  37445. {
  37446. if (onFrame)
  37447. frameStart = juce::Time::getMillisecondCounterHiRes();
  37448. DocumentWindow::paint (g);
  37449. }
  37450. void paintOverChildren (juce::Graphics& g) override
  37451. {
  37452. DocumentWindow::paintOverChildren (g);
  37453. if (afterPaint != nullptr && ! std::exchange (afterPaintPosted, true)) // (the frame is presented first)
  37454. juce::MessageManager::callAsync ([safe = juce::Component::SafePointer<MainWindow> (this)] {
  37455. if (safe != nullptr)
  37456. safe->runAfterPaint();
  37457. });
  37458. if (onFrame && frameStart > 0.0)
  37459. onFrame (juce::Time::getMillisecondCounterHiRes() - frameStart);
  37460. frameStart = 0.0;
  37461. }
  37462. private:
  37463. lynx::MainComponent* content = nullptr; // owned by the window
  37464. std::unique_ptr<lynx::ui::FrameProbe> probe; // (on top of the content; see watchFrames)
  37465. double frameStart = 0.0;
  37466. bool maximiseOnReveal = false;
  37467. std::function<void()> afterPaint; // (whenPainted)
  37468. lynx::AudioEngine* probeEngine = nullptr; // (LYNX_LOCATOR_PROBE)
  37469. bool afterPaintPosted = false;
  37470. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
  37471. };
  37472. lynx::theme::LookAndFeel lookAndFeel;
  37473. std::unique_ptr<lynx::AudioEngine> engine;
  37474. std::unique_ptr<lynx::RemoteControl> remoteControl;
  37475. std::unique_ptr<juce::XmlElement> savedDeviceState; // --rtstress: the user's device before this run's --type/--buffer
  37476. // Hidden test mode --asiodll "<driver.dll>[|{CLSID}]" (REA round 97): an ASIO driver loaded straight from its file,
  37477. // without registering it, listed as the driver type "ASIO driver file". True when one was added.
  37478. bool addDriverFileDeviceType()
  37479. {
  37480. const auto args = juce::JUCEApplication::getCommandLineParameterArray();
  37481. const auto i = args.indexOf ("--asiodll");
  37482. if (i < 0 || i + 1 >= args.size() || engine == nullptr)
  37483. return false;
  37484. auto& devices = engine->getDeviceManager();
  37485. devices.getAvailableDeviceTypes(); // creates the standard types first
  37486. for (auto* t : devices.getAvailableDeviceTypes())
  37487. if (t->getTypeName() == lynx::dllAsioTypeName)
  37488. return true;
  37489. auto type = lynx::makeDllAsioDeviceType (args[i + 1].unquoted());
  37490. if (type == nullptr)
  37491. return false;
  37492. devices.addAudioDeviceType (std::move (type));
  37493. return true;
  37494. }
  37495. void restoreSavedDeviceState()
  37496. {
  37497. if (engine != nullptr)
  37498. engine->restoreAudioDeviceState (savedDeviceState.get());
  37499. }
  37500. std::unique_ptr<MainWindow> mainWindow;
  37501. std::unique_ptr<juce::Timer> perf; // --uiperf
  37502. std::unique_ptr<lynx::StartupSplash> splash;
  37503. static constexpr double landingSeconds = 1.05; // the logo's drop (SplashScreen::remainingDuration's `landing`)
  37504. std::shared_future<std::pair<juce::Image, double>> graphicsDeviceJob; // (round 190hd) holds the graphics device
  37505. bool graphicsDeviceMarked = false, windowRevealed = false;
  37506. std::future<std::shared_ptr<const lynx::SampleData>> startupSampleJob; // (round 190go: the built-in start-up sound)
  37507. bool startedAfterWindow = false, startupSoundPlayed = false;
  37508. double splashDuration = lynx::SplashScreen::minimumDuration; // seconds of its clock (round 121: from the process start)
  37509. lynx::StartupOptions startupOptions;
  37510. juce::File fileToOpen;
  37511. bool startupFileHandled = false;
  37512. bool startWithoutPlugins = false; // --no-plugins project.lynx (round 190ap)
  37513. juce::File openTimeReport; // --opentime
  37514. int openTimeIdleSeconds = 10;
  37515. };
  37516. START_JUCE_APPLICATION (LynxApplication)